Skip to content

Commit bb9b488

Browse files
Merge pull request #70 from JuliaComputing/as/strict-inline-scc
fix: use strict form of `linear_expansion` in inline linear SCC pass
2 parents 03d1ef2 + 5ee49ad commit bb9b488

2 files changed

Lines changed: 29 additions & 6 deletions

File tree

lib/ModelingToolkitTearing/src/reassemble.jl

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -565,15 +565,24 @@ function get_linear_scc_linsol(state::TearingState, alg_eqs::Vector{Int},
565565
# Substitute solved differential equations
566566
resid = Symbolics.fixpoint_sub(
567567
resid, total_sub, MTKBase.Shift; maxiters = max(2length(total_sub), 10))
568-
# Standard `linear_expansion`-based process
569-
for (varidx, var) in enumerate(vars)
570-
a, resid, islinear = Symbolics.linear_expansion(resid, var)
568+
b[eqidx] = resid
569+
end
570+
571+
for (varidx, var) in enumerate(vars)
572+
lex = Symbolics.LinearExpander(var; strict = true)
573+
for (eqidx, resid) in enumerate(b)
574+
p, q, islinear = lex(resid)
571575
islinear || return nothing
572-
A[eqidx, varidx] = a
576+
A[eqidx, varidx] = p
577+
b[eqidx] = q
573578
end
574-
# `-` is important! `b` is on the other side of the equality.
575-
b[eqidx] = -resid
576579
end
580+
581+
# `-` is important! `b` is on the other side of the equality.
582+
for i in eachindex(b)
583+
b[i] = -b[i]
584+
end
585+
577586
if N <= analytical_linear_scc_limit && _check_allow_symbolic_parameter(
578587
state, A, allow_symbolic, allow_parameter
579588
)

lib/ModelingToolkitTearing/test/runtests.jl

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,3 +155,17 @@ end
155155
# variables is removed from `ts.structure.graph`. This would cause incorrect values in `linear_subsys_adjmat!`
156156
@test coeffs == [-1]
157157
end
158+
159+
@testset "Inline linear SCC uses strict form of `linear_expansion`" begin
160+
@variables x(t) y(t) z(t) w(t) p(t)
161+
# Without strict form, the `ifelse` is considered linear in `z`
162+
@test_nowarn @mtkcompile sys = System(
163+
[
164+
D(x) ~ 2x + t
165+
y + 2z + 3w ~ 4
166+
2y + 4ifelse(z < 0, 2z, 3z) + 7w ~ 12
167+
3y - 2z + 5w ~ 13
168+
D(p) ~ 2y + 3w + z
169+
], t
170+
) reassemble_alg = MTKTearing.DefaultReassembleAlgorithm(; inline_linear_sccs = true)
171+
end

0 commit comments

Comments
 (0)