Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions lib/ModelingToolkitTearing/src/reassemble.jl
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,16 @@ function generate_system_equations!(state::TearingState, neweqs::Vector{Equation
else
var = substitute(fullvars[iv], total_sub)
eq = var ~ rhs
# `var` becomes observed. `contract_variables` recovers the incidence
# of an observed variable from its matched equation, but `var` is
# solved from the whole block, so make every other equation
# incident on `iv` also incident on the variables of the solution.
for e in copy(𝑑neighbors(graph, iv))
e == ieq && continue
for v in new_incidence
add_edge!(graph, e, v)
end
end
push!(eq_generator.solved_eqs, eq)
push!(eq_generator.solved_vars, iv)
block_vars[j] = var
Expand Down
35 changes: 35 additions & 0 deletions lib/ModelingToolkitTearing/test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -808,6 +808,41 @@ end
@test Set(unknowns(sys)) == Set([e, c, d])
end

@testset "Inline linear SCCs keep the incidence of variables they make observed" begin
# The jacobian sparsity of a torn system is read off the tearing graph. A variable
# solved by an inline linear SCC and made observed must leave behind its dependencies
# in the equations that use it, e.g. `D(x) ~ xˍt` with `xˍt` a function of `x` and `y`.
@variables x(t) y(t)
@variables z(t)[1:3]
A = [1 0.3 0.2; 0.1 1 0.4; 0.2 0.1 1]
cases = [
[D(x) + 0.5D(y) ~ y - x, D(y) + 0.5D(x) ~ x - y],
[sum(A[i, j] * D(z[j]) for j in 1:3) ~ -z[i] + z[mod1(i + 1, 3)]^2 for i in 1:3],
]
# `analytical_linear_scc_limit = 0` sends blocks larger than 1x1 through `LinearSolve`
@testset "case $i, analytical_linear_scc_limit = $limit" for (i, eqs) in enumerate(cases), limit in (0, 2)
ralg = MTKTearing.DefaultReassembleAlgorithm(;
inline_linear_sccs = true, analytical_linear_scc_limit = limit
)
sys = mtkcompile(System(eqs, t; name = :sys); reassemble_alg = ralg)
@test !isempty(observed(sys))
if i == 2 && limit == 0
@test !isempty(inline_linear_systems(sys))
end
S = MTKBase.jacobian_sparsity(sys)
prob = ODEProblem(
sys, Dict(u => 0.3 for u in unknowns(sys)), (0.0, 1.0); build_initializeprob = false
)
u = collect(range(0.5, 1.5; length = length(prob.u0)))
J = ForwardDiff.jacobian(u) do u
du = similar(u)
prob.f(du, u, prob.p, 0.1)
du
end
@test all(S .| iszero.(J))
end
end

@testset "`TearingState` ignores `MTK.HOMOTOPY_LAMBDA`" begin
@variables x(t)
@named sys = System([D(x) ~ x * MTKBase.HOMOTOPY_LAMBDA], t, [x], [])
Expand Down
Loading