Skip to content

Commit c18079a

Browse files
Merge pull request #1030 from SciML/nonlinear_jac
Cache nonlinear solve jacobians
2 parents b9e78dd + 5fdbd89 commit c18079a

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

src/systems/nonlinear/nonlinearsystem.jl

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,11 @@ struct NonlinearSystem <: AbstractSystem
2727
ps::Vector
2828
observed::Vector{Equation}
2929
"""
30+
Jacobian matrix. Note: this field will not be defined until
31+
[`calculate_jacobian`](@ref) is called on the system.
32+
"""
33+
jac::RefValue{Any}
34+
"""
3035
Name: the name of the system
3136
"""
3237
name::Symbol
@@ -61,9 +66,10 @@ function NonlinearSystem(eqs, states, ps;
6166
if !(isempty(default_u0) && isempty(default_p))
6267
Base.depwarn("`default_u0` and `default_p` are deprecated. Use `defaults` instead.", :NonlinearSystem, force=true)
6368
end
69+
jac = RefValue{Any}(Matrix{Num}(undef, 0, 0))
6470
defaults = todict(defaults)
6571
defaults = Dict(value(k) => value(v) for (k, v) in pairs(defaults))
66-
NonlinearSystem(eqs, value.(states), value.(ps), observed, name, systems, defaults, nothing, connection_type)
72+
NonlinearSystem(eqs, value.(states), value.(ps), observed, jac, name, systems, defaults, nothing, connection_type)
6773
end
6874

6975
function calculate_jacobian(sys::NonlinearSystem;sparse=false,simplify=false)
@@ -74,6 +80,7 @@ function calculate_jacobian(sys::NonlinearSystem;sparse=false,simplify=false)
7480
else
7581
jac = jacobian(rhs, vals, simplify=simplify)
7682
end
83+
get_jac(sys)[] = jac
7784
return jac
7885
end
7986

test/nonlinearsystem.jl

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,3 +107,14 @@ prob = ODEProblem(sys, [subsys.x => 1, subsys.z => 2.0], (0, 1.0), [subsys.σ=>1
107107
sol = solve(prob, Rodas5())
108108
@test sol[subsys.x] + sol[subsys.y] - sol[subsys.z] sol[subsys.u]
109109
@test_throws ArgumentError convert_system(ODESystem, sys, t)
110+
111+
@parameters t σ ρ β
112+
@variables x y z
113+
114+
# Define a nonlinear system
115+
eqs = [0 ~ σ*(y-x),
116+
0 ~ x*-z)-y,
117+
0 ~ x*y - β*z]
118+
ns = NonlinearSystem(eqs, [x,y,z], [σ,ρ,β])
119+
np = NonlinearProblem(ns, [0,0,0], [1,2,3], jac=true, sparse=true)
120+
@test ModelingToolkit.get_jac(ns)[] isa SparseMatrixCSC

0 commit comments

Comments
 (0)