Skip to content

Commit 5130987

Browse files
committed
Add locally_structure_simplify!
1 parent c61aeba commit 5130987

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

src/systems/alias_elimination.jl

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,84 @@ function alias_elimination_2(sys)
180180
)
181181
end
182182

183+
iszeroterm(v_types, v) = v_types[v] == 0
184+
isirreducible(v_types, v) = v_types[v] == KEEP
185+
isalias(v_types, v) = v_types[v] > 0 && !isirreducible(v_types, v)
186+
alias(v_types, v) = v_types[v]
187+
negalias(v_types, v) = -v_types[v]
188+
189+
function locally_structure_simplify!(
190+
(vars, coeffs),
191+
invvarassoc, v_null, v_types
192+
)
193+
while length(vars) > 1 && any(!isequal(KEEP), (v_types[v] in @view vars[2:end]))
194+
for vj in 2:length(vars)
195+
v = vars[vj]
196+
if isirreducible(v_types, v)
197+
continue
198+
elseif iszeroterm(v_types, v)
199+
deleteat!(vars, vj)
200+
deleteat!(coeffs, vj)
201+
break
202+
else
203+
coeff = coeffs[vj]
204+
if isalias(v_types, v)
205+
v = alias(v_types, v)
206+
else
207+
v = negalias(v_types, v)
208+
coeff = -coeff
209+
end
183210

211+
has_v = false
212+
for vi in 2:length(vars)
213+
(vi !== vj && vars[vi] == v) || continue
214+
has_v = true
215+
c = (coeffs[vi] += coeff)
216+
if c == 0
217+
if vi < vj
218+
deleteat!(vars, [vi, vj])
219+
deleteat!(coeffs, [vi, vj])
220+
else
221+
deleteat!(vars, [vj, vi])
222+
deleteat!(coeffs, [vj, vi])
223+
end
224+
end
225+
break
226+
end # for vi
227+
228+
if has_v
229+
break
230+
else
231+
vars[vj] = v
232+
coeffs[vj] = coeff
233+
end # if
234+
end # else
235+
end # for
236+
end # while
237+
238+
v = first(vars)
239+
if invvarassoc[v] == 0
240+
if length(nvars) == 1
241+
push!(v_null, v)
242+
v_types[v] = 0
243+
empty!(vars); empty!(coeffs)
244+
return true
245+
elseif length(vars) == 2 && abs(coeffs[1]) == abs(coeffs[2])
246+
if (coeffs[1] > 0 && coeffs[2] < 0) || (coeffs[1] < 0 && coeffs[2] > 0)
247+
# positive alias
248+
push!(v_null, v)
249+
v_types[v] = vars[2]
250+
else
251+
# negative alias
252+
push!(v_null, v)
253+
v_types[v] = -vars[2]
254+
end
255+
empty!(vars); empty!(coeffs)
256+
return true
257+
end
258+
end
259+
return false
260+
end
184261

185262
"""
186263
$(SIGNATURES)

0 commit comments

Comments
 (0)