diff --git a/lib/ModelingToolkitTearing/src/reassemble.jl b/lib/ModelingToolkitTearing/src/reassemble.jl index 9c16768..a92eb88 100644 --- a/lib/ModelingToolkitTearing/src/reassemble.jl +++ b/lib/ModelingToolkitTearing/src/reassemble.jl @@ -921,6 +921,10 @@ function get_linear_scc_linsol(state::TearingState, alg_eqs::Vector{Int}, b[eqidx] = subber(resid) end + # `lex` checks linearity in one unknown at a time, so a product of two unknowns of the + # linear system (`x * y`) passes for both and leaves one of them in the other's + # coefficient. The system is only linear if no coefficient contains these unknowns. + linsys_vars = Set{SymbolicT}(vars[vars_mask]) for (varidx, var) in enumerate(vars) vars_mask[varidx] || continue lex = MTKBase.get_linear_expander_for!(sys, var, true) @@ -929,6 +933,7 @@ function get_linear_scc_linsol(state::TearingState, alg_eqs::Vector{Int}, Graphs.has_edge(graph, BipartiteEdge(alg_eqs[eqidx], alg_vars[varidx])) || continue p, q, islinear = lex(resid) islinear || return nothing + SU.query(in(linsys_vars), p) && return nothing if !SU._iszero(p) # We're iterating in increasing `varidx` (column index) so we can just `push!` push!(A.row_cols[eqidx], varidx) diff --git a/lib/ModelingToolkitTearing/test/runtests.jl b/lib/ModelingToolkitTearing/test/runtests.jl index 942a715..702152c 100644 --- a/lib/ModelingToolkitTearing/test/runtests.jl +++ b/lib/ModelingToolkitTearing/test/runtests.jl @@ -344,6 +344,18 @@ end ) reassemble_alg = MTKTearing.DefaultReassembleAlgorithm(; inline_linear_sccs = true) end +@testset "Inline linear SCC is not used when two SCC unknowns are multiplied" begin + @variables x(t) y(t) z(t) + # The SCC `(y, z)` is linear in `y` and in `z` separately, but not jointly. + eqs = [D(x) ~ y - x, z ~ 2 - y, 0 ~ z * y + y - x] + reassemble_alg = MTKTearing.DefaultReassembleAlgorithm(; inline_linear_sccs = true) + @mtkcompile sys = System(eqs, t) reassemble_alg = reassemble_alg + @test isempty(inline_linear_systems(sys)) + @mtkcompile refsys = System(eqs, t) + @test isequal(equations(sys), equations(refsys)) + @test isequal(observed(sys), observed(refsys)) +end + @testset "`system_subset(::SystemStructure)` subsets `.state_priorities`" begin @variables x(t) y(t) [state_priority = 2] z(t) [state_priority = 5] @named sys = System([D(x) ~ x, D(y) ~ y, D(z) ~ z], t)