diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e770afd4c6..1cd61197a9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,8 +1,6 @@ name: CI on: pull_request: - branches: - - master paths-ignore: - 'docs/**' push: diff --git a/Project.toml b/Project.toml index dca1dcd386..7582ff9f8c 100644 --- a/Project.toml +++ b/Project.toml @@ -1,7 +1,7 @@ name = "ModelingToolkit" uuid = "961ee093-0014-501f-94e3-6117800e7a78" authors = ["Yingbo Ma ", "Chris Rackauckas and contributors"] -version = "8.75.0" +version = "8.76.0" [deps] AbstractTrees = "1520ce14-60c1-5f80-bbc7-55ef81b5835c" @@ -99,7 +99,7 @@ SparseArrays = "1" SpecialFunctions = "0.7, 0.8, 0.9, 0.10, 1.0, 2" StaticArrays = "0.10, 0.11, 0.12, 1.0" SymbolicIndexingInterface = "0.3.1" -SymbolicUtils = "1.0" +SymbolicUtils = "1.0 - 1.5.1" Symbolics = "5.7" URIs = "1" UnPack = "0.1, 1.0" diff --git a/docs/make.jl b/docs/make.jl index dd8e766b67..08cd1130aa 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -16,7 +16,7 @@ mathengine = MathJax3(Dict(:loader => Dict("load" => ["[tex]/require", "[tex]/ma "ams", "autoload", "mathtools", - "require", + "require" ]))) makedocs(sitename = "ModelingToolkit.jl", diff --git a/docs/pages.jl b/docs/pages.jl index 9d49c477ec..6fe332986a 100644 --- a/docs/pages.jl +++ b/docs/pages.jl @@ -10,7 +10,8 @@ pages = [ "tutorials/parameter_identifiability.md", "tutorials/bifurcation_diagram_computation.md", "tutorials/domain_connections.md"], - "Examples" => Any["Basic Examples" => Any["examples/higher_order.md", + "Examples" => Any[ + "Basic Examples" => Any["examples/higher_order.md", "examples/spring_mass.md", "examples/modelingtoolkitize_index_reduction.md", "examples/parsing.md"], @@ -35,5 +36,5 @@ pages = [ "systems/DiscreteSystem.md", "systems/PDESystem.md"], "comparison.md", - "internals.md", + "internals.md" ] diff --git a/docs/src/basics/Composition.md b/docs/src/basics/Composition.md index 6171b545a5..4a96a0d3b9 100644 --- a/docs/src/basics/Composition.md +++ b/docs/src/basics/Composition.md @@ -22,7 +22,7 @@ function decay(; name) @variables x(t) f(t) D = Differential(t) ODESystem([ - D(x) ~ -a * x + f, + D(x) ~ -a * x + f ]; name = name) end @@ -32,8 +32,9 @@ end @parameters t D = Differential(t) -connected = compose(ODESystem([decay2.f ~ decay1.x - D(decay1.f) ~ 0], t; name = :connected), decay1, decay2) +connected = compose( + ODESystem([decay2.f ~ decay1.x + D(decay1.f) ~ 0], t; name = :connected), decay1, decay2) equations(connected) @@ -52,10 +53,10 @@ Now we can solve the system: ```@example composition x0 = [decay1.x => 1.0 - decay1.f => 0.0 - decay2.x => 1.0] + decay1.f => 0.0 + decay2.x => 1.0] p = [decay1.a => 0.1 - decay2.a => 0.2] + decay2.a => 0.2] using DifferentialEquations prob = ODEProblem(simplified_sys, x0, (0.0, 100.0), p) @@ -96,7 +97,7 @@ in their namespaced form. For example: ```julia u0 = [x => 2.0 - subsys.x => 2.0] + subsys.x => 2.0] ``` Note that any default values within the given subcomponent will be @@ -210,7 +211,9 @@ N = S + I + R @named ieqn = ODESystem([D(I) ~ β * S * I / N - γ * I]) @named reqn = ODESystem([D(R) ~ γ * I]) -sir = compose(ODESystem([ +sir = compose( + ODESystem( + [ S ~ ieqn.S, I ~ seqn.I, R ~ ieqn.R, @@ -218,11 +221,17 @@ sir = compose(ODESystem([ seqn.I ~ ieqn.I, seqn.R ~ reqn.R, ieqn.R ~ reqn.R, - reqn.I ~ ieqn.I], t, [S, I, R], [β, γ], + reqn.I ~ ieqn.I], + t, + [S, I, R], + [β, γ], defaults = [seqn.β => β - ieqn.β => β - ieqn.γ => γ - reqn.γ => γ], name = :sir), seqn, ieqn, reqn) + ieqn.β => β + ieqn.γ => γ + reqn.γ => γ], name = :sir), + seqn, + ieqn, + reqn) ``` Note that the states are forwarded by an equality relationship, while @@ -244,7 +253,7 @@ u0 = [seqn.S => 990.0, reqn.R => 0.0] p = [β => 0.5 - γ => 0.25] + γ => 0.25] tspan = (0.0, 40.0) prob = ODEProblem(sireqn_simple, u0, tspan, p, jac = true) diff --git a/docs/src/basics/Events.md b/docs/src/basics/Events.md index bed148f4ef..79e3e5321e 100644 --- a/docs/src/basics/Events.md +++ b/docs/src/basics/Events.md @@ -69,7 +69,7 @@ function UnitMassWithFriction(k; name) @variables t x(t)=0 v(t)=0 D = Differential(t) eqs = [D(x) ~ v - D(v) ~ sin(t) - k * sign(v)] + D(v) ~ sin(t) - k * sign(v)] ODESystem(eqs, t; continuous_events = [v ~ 0], name) # when v = 0 there is a discontinuity end @named m = UnitMassWithFriction(0.7) @@ -94,7 +94,7 @@ root_eqs = [x ~ 0] # the event happens at the ground x(t) = 0 affect = [v ~ -v] # the effect is that the velocity changes sign @named ball = ODESystem([D(x) ~ v - D(v) ~ -9.8], t; continuous_events = root_eqs => affect) # equation => affect + D(v) ~ -9.8], t; continuous_events = root_eqs => affect) # equation => affect ball = structural_simplify(ball) @@ -114,13 +114,14 @@ Multiple events? No problem! This example models a bouncing ball in 2D that is e D = Differential(t) continuous_events = [[x ~ 0] => [vx ~ -vx] - [y ~ -1.5, y ~ 1.5] => [vy ~ -vy]] + [y ~ -1.5, y ~ 1.5] => [vy ~ -vy]] -@named ball = ODESystem([ +@named ball = ODESystem( + [ D(x) ~ vx, D(y) ~ vy, D(vx) ~ -9.8 - 0.1vx, # gravity + some small air resistance - D(vy) ~ -0.1vy, + D(vy) ~ -0.1vy ], t; continuous_events) ball = structural_simplify(ball) @@ -189,7 +190,7 @@ affect interface: sts = @variables x(t), v(t) par = @parameters g = 9.8 bb_eqs = [D(x) ~ v - D(v) ~ -g] + D(v) ~ -g] function bb_affect!(integ, u, p, ctx) integ.u[u.v] = -integ.u[u.v] diff --git a/docs/src/basics/Linearization.md b/docs/src/basics/Linearization.md index 5dc207db02..34f980774f 100644 --- a/docs/src/basics/Linearization.md +++ b/docs/src/basics/Linearization.md @@ -26,8 +26,8 @@ using ModelingToolkit D = Differential(t) eqs = [u ~ kp * (r - y) # P controller - D(x) ~ -x + u # First-order plant - y ~ x] # Output equation + D(x) ~ -x + u # First-order plant + y ~ x] # Output equation @named sys = ODESystem(eqs, t) matrices, simplified_sys = linearize(sys, [r], [y]) # Linearize from r to y diff --git a/docs/src/basics/Variable_metadata.md b/docs/src/basics/Variable_metadata.md index aa0d579383..000acf22c5 100644 --- a/docs/src/basics/Variable_metadata.md +++ b/docs/src/basics/Variable_metadata.md @@ -142,7 +142,7 @@ Dₜ = Differential(t) @parameters T [tunable = true, bounds = (0, Inf)] @parameters k [tunable = true, bounds = (0, Inf)] eqs = [Dₜ(x) ~ (-x + k * u) / T # A first-order system with time constant T and gain k - y ~ x] + y ~ x] sys = ODESystem(eqs, t, name = :tunable_first_order) ``` diff --git a/docs/src/examples/parsing.md b/docs/src/examples/parsing.md index 47d5321a4e..fb7c064127 100644 --- a/docs/src/examples/parsing.md +++ b/docs/src/examples/parsing.md @@ -7,8 +7,8 @@ symbolic forms from that? For example, say we had the following system we wanted ```@example parsing ex = [:(y ~ x) - :(y ~ -2x + 3 / z) - :(z ~ 2)] + :(y ~ -2x + 3 / z) + :(z ~ 2)] ``` We can use the function `parse_expr_to_symbolic` from Symbolics.jl to generate the symbolic diff --git a/docs/src/examples/spring_mass.md b/docs/src/examples/spring_mass.md index eafd8269ea..771b181442 100644 --- a/docs/src/examples/spring_mass.md +++ b/docs/src/examples/spring_mass.md @@ -26,7 +26,7 @@ end function connect_spring(spring, a, b) [spring.x ~ norm(scalarize(a .- b)) - scalarize(spring.dir .~ scalarize(a .- b))] + scalarize(spring.dir .~ scalarize(a .- b))] end function spring_force(spring) @@ -43,7 +43,7 @@ g = [0.0, -9.81] @named spring = Spring(k = k, l = l) eqs = [connect_spring(spring, mass.pos, center) - scalarize(D.(mass.v) .~ spring_force(spring) / mass.m .+ g)] + scalarize(D.(mass.v) .~ spring_force(spring) / mass.m .+ g)] @named _model = ODESystem(eqs, t, [spring.x; spring.dir; mass.pos], []) @named model = compose(_model, mass, spring) @@ -96,7 +96,7 @@ We now define functions that help construct the equations for a mass-spring syst ```@example component function connect_spring(spring, a, b) [spring.x ~ norm(scalarize(a .- b)) - scalarize(spring.dir .~ scalarize(a .- b))] + scalarize(spring.dir .~ scalarize(a .- b))] end ``` @@ -125,7 +125,7 @@ We can now create the equations describing this system, by connecting `spring` t ```@example component eqs = [connect_spring(spring, mass.pos, center) - scalarize(D.(mass.v) .~ spring_force(spring) / mass.m .+ g)] + scalarize(D.(mass.v) .~ spring_force(spring) / mass.m .+ g)] ``` Finally, we can build the model using these equations and components. diff --git a/docs/src/examples/tearing_parallelism.md b/docs/src/examples/tearing_parallelism.md index 1a79603528..7efadbb93f 100644 --- a/docs/src/examples/tearing_parallelism.md +++ b/docs/src/examples/tearing_parallelism.md @@ -32,7 +32,7 @@ function ConstantVoltage(; name, V = 1.0) @named n = Pin() @parameters V = V eqs = [V ~ p.v - n.v - 0 ~ p.i + n.i] + 0 ~ p.i + n.i] compose(ODESystem(eqs, t, [], [V], name = name), p, n) end @@ -48,10 +48,10 @@ function HeatingResistor(; name, R = 1.0, TAmbient = 293.15, alpha = 1.0) @variables v(t) RTherm(t) @parameters R=R TAmbient=TAmbient alpha=alpha eqs = [RTherm ~ R * (1 + alpha * (h.T - TAmbient)) - v ~ p.i * RTherm - h.Q_flow ~ -v * p.i # -LossPower - v ~ p.v - n.v - 0 ~ p.i + n.i] + v ~ p.i * RTherm + h.Q_flow ~ -v * p.i # -LossPower + v ~ p.v - n.v + 0 ~ p.i + n.i] compose(ODESystem(eqs, t, [v, RTherm], [R, TAmbient, alpha], name = name), p, n, h) end @@ -61,7 +61,7 @@ function HeatCapacitor(; name, rho = 8050, V = 1, cp = 460, TAmbient = 293.15) C = rho * V * cp @named h = HeatPort() eqs = [ - D(h.T) ~ h.Q_flow / C, + D(h.T) ~ h.Q_flow / C ] compose(ODESystem(eqs, t, [], [rho, V, cp], name = name), h) @@ -73,8 +73,8 @@ function Capacitor(; name, C = 1.0) @variables v(t) = 0.0 @parameters C = C eqs = [v ~ p.v - n.v - 0 ~ p.i + n.i - D(v) ~ p.i / C] + 0 ~ p.i + n.i + D(v) ~ p.i / C] compose(ODESystem(eqs, t, [v], [C], name = name), p, n) end @@ -85,9 +85,9 @@ function parallel_rc_model(i; name, source, ground, R, C) heat_capacitor = HeatCapacitor(name = Symbol(:heat_capacitor, i)) rc_eqs = [connect(source.p, resistor.p) - connect(resistor.n, capacitor.p) - connect(capacitor.n, source.n, ground.g) - connect(resistor.h, heat_capacitor.h)] + connect(resistor.n, capacitor.p) + connect(capacitor.n, source.n, ground.g) + connect(resistor.h, heat_capacitor.h)] compose(ODESystem(rc_eqs, t, name = Symbol(name, i)), [resistor, capacitor, source, ground, heat_capacitor]) @@ -113,7 +113,7 @@ end; @variables E(t) = 0.0 eqs = [ D(E) ~ sum(((i, sys),) -> getproperty(sys, Symbol(:resistor, i)).h.Q_flow, - enumerate(rc_systems)), + enumerate(rc_systems)) ] @named _big_rc = ODESystem(eqs, t, [E], []) @named big_rc = compose(_big_rc, rc_systems) @@ -155,7 +155,8 @@ ts = TearingState(expand_connections(big_rc)) inc_org = BipartiteGraphs.incidence_matrix(ts.structure.graph) blt_org = StructuralTransformations.sorted_incidence_matrix(ts, only_algeqs = true, only_algvars = true) -blt_reduced = StructuralTransformations.sorted_incidence_matrix(ModelingToolkit.get_tearing_state(sys), +blt_reduced = StructuralTransformations.sorted_incidence_matrix( + ModelingToolkit.get_tearing_state(sys), only_algeqs = true, only_algvars = true) ``` diff --git a/docs/src/tutorials/acausal_components.md b/docs/src/tutorials/acausal_components.md index 508912c860..4c3d6fc3d9 100644 --- a/docs/src/tutorials/acausal_components.md +++ b/docs/src/tutorials/acausal_components.md @@ -102,7 +102,7 @@ end @mtkbuild rc_model = RCModel(resistor.R = 2.0) u0 = [ - rc_model.capacitor.v => 0.0, + rc_model.capacitor.v => 0.0 ] prob = ODEProblem(rc_model, u0, (0, 10.0)) sol = solve(prob) @@ -316,7 +316,7 @@ This is done as follows: ```@example acausal u0 = [rc_model.capacitor.v => 0.0 - rc_model.capacitor.p.i => 0.0] + rc_model.capacitor.p.i => 0.0] prob = ODEProblem(rc_model, u0, (0, 10.0)) sol = solve(prob) diff --git a/docs/src/tutorials/domain_connections.md b/docs/src/tutorials/domain_connections.md index 1912d60048..3514fe8fe7 100644 --- a/docs/src/tutorials/domain_connections.md +++ b/docs/src/tutorials/domain_connections.md @@ -46,7 +46,7 @@ The fluid medium setter for `HydralicPort` may be defined as `HydraulicFluid` wi end eqs = [ - dm ~ 0, + dm ~ 0 ] ODESystem(eqs, t, vars, pars; name, defaults = [dm => 0]) @@ -88,8 +88,8 @@ end p = port.p eqs = [D(rho) ~ drho - rho ~ port.ρ * (1 + p / port.β) - dm ~ drho * vol] + rho ~ port.ρ * (1 + p / port.β) + dm ~ drho * vol] ODESystem(eqs, t, vars, pars; name, systems) end @@ -108,7 +108,7 @@ When the system is defined we can generate a fluid component and connect it to t end eqs = [connect(fluid, src.port) - connect(src.port, vol.port)] + connect(src.port, vol.port)] ODESystem(eqs, t, [], []; systems, name) end @@ -162,10 +162,10 @@ If we have a more complicated system, for example a hydraulic actuator, with a s end eqs = [D(x) ~ dx - D(dx) ~ ddx - mass * ddx ~ (port_a.p - port_b.p) * area - port_a.dm ~ +(port_a.ρ) * dx * area - port_b.dm ~ -(port_b.ρ) * dx * area] + D(dx) ~ ddx + mass * ddx ~ (port_a.p - port_b.p) * area + port_a.dm ~ +(port_a.ρ) * dx * area + port_b.dm ~ -(port_b.ρ) * dx * area] ODESystem(eqs, t, vars, pars; name, systems) end @@ -186,9 +186,9 @@ A system with 2 different fluids is defined and connected to each separate domai end eqs = [connect(fluid_a, src_a.port) - connect(fluid_b, src_b.port) - connect(src_a.port, act.port_a) - connect(src_b.port, act.port_b)] + connect(fluid_b, src_b.port) + connect(src_a.port, act.port_a) + connect(src_b.port, act.port_b)] ODESystem(eqs, t, [], []; systems, name) end @@ -218,9 +218,9 @@ After running `structural_simplify()` on `actsys2`, the defaults will show that end eqs = [connect(fluid, src_a.port) - connect(fluid, src_b.port) - connect(src_a.port, act.port_a) - connect(src_b.port, act.port_b)] + connect(fluid, src_b.port) + connect(src_a.port, act.port_a) + connect(src_b.port, act.port_b)] ODESystem(eqs, t, [], []; systems, name) end @@ -254,7 +254,7 @@ In some cases a component will be defined with 2 connectors of the same domain, end eqs = [port_a.dm ~ (port_a.p - port_b.p) * K - 0 ~ port_a.dm + port_b.dm] + 0 ~ port_a.dm + port_b.dm] ODESystem(eqs, t, [], pars; systems, name) end @@ -274,8 +274,8 @@ Adding the `Restrictor` to the original system example will cause a break in the end eqs = [connect(fluid, src.port) - connect(src.port, res.port_a) - connect(res.port_b, vol.port)] + connect(src.port, res.port_a) + connect(res.port_b, vol.port)] ODESystem(eqs, t, [], []; systems, name) end @@ -316,8 +316,8 @@ To ensure that the `Restrictor` component does not disrupt the domain network, t end eqs = [domain_connect(port_a, port_b) # <-- connect the domain network - port_a.dm ~ (port_a.p - port_b.p) * K - 0 ~ port_a.dm + port_b.dm] + port_a.dm ~ (port_a.p - port_b.p) * K + 0 ~ port_a.dm + port_b.dm] ODESystem(eqs, t, [], pars; systems, name) end diff --git a/docs/src/tutorials/nonlinear.md b/docs/src/tutorials/nonlinear.md index 9b8ea954ce..b198c8ffcb 100644 --- a/docs/src/tutorials/nonlinear.md +++ b/docs/src/tutorials/nonlinear.md @@ -23,8 +23,8 @@ guess = [x => 1.0, z => 0.0] ps = [σ => 10.0 - ρ => 26.0 - β => 8 / 3] + ρ => 26.0 + β => 8 / 3] prob = NonlinearProblem(ns, guess, ps) sol = solve(prob, NewtonRaphson()) diff --git a/docs/src/tutorials/optimization.md b/docs/src/tutorials/optimization.md index b4ee03141b..8c109904b8 100644 --- a/docs/src/tutorials/optimization.md +++ b/docs/src/tutorials/optimization.md @@ -46,9 +46,9 @@ Next, the actual `OptimizationProblem` can be created. At this stage, an initial ```@example rosenbrock_2d u0 = [x => 1.0 - y => 2.0] + y => 2.0] p = [a => 1.0 - b => 100.0] + b => 100.0] prob = OptimizationProblem(sys, u0, p, grad = true, hess = true) solve(prob, GradientDescent()) @@ -66,11 +66,11 @@ end @parameters a=1 b=100 loss = (a - x)^2 + b * (y - x^2)^2 cons = [ - x^2 + y^2 ≲ 1, + x^2 + y^2 ≲ 1 ] @named sys = OptimizationSystem(loss, [x, y], [a, b], constraints = cons) u0 = [x => 0.14 - y => 0.14] + y => 0.14] prob = OptimizationProblem(sys, u0, grad = true, hess = true, cons_j = true, cons_h = true) solve(prob, IPNewton()) ``` diff --git a/docs/src/tutorials/programmatically_generating.md b/docs/src/tutorials/programmatically_generating.md index ca11243c84..9620d73042 100644 --- a/docs/src/tutorials/programmatically_generating.md +++ b/docs/src/tutorials/programmatically_generating.md @@ -21,7 +21,7 @@ using Symbolics @variables t x(t) y(t) # Define variables D = Differential(t) # Define a differential operator eqs = [D(x) ~ y - D(y) ~ x] # Define an array of equations + D(y) ~ x] # Define an array of equations ``` ## The Non-DSL (non-`@mtkmodel`) Way of Defining an ODESystem diff --git a/docs/src/tutorials/stochastic_diffeq.md b/docs/src/tutorials/stochastic_diffeq.md index aa81449313..9b835ec9b1 100644 --- a/docs/src/tutorials/stochastic_diffeq.md +++ b/docs/src/tutorials/stochastic_diffeq.md @@ -28,13 +28,13 @@ noiseeqs = [0.1 * x, u0map = [ x => 1.0, y => 0.0, - z => 0.0, + z => 0.0 ] parammap = [ σ => 10.0, β => 26.0, - ρ => 2.33, + ρ => 2.33 ] prob = SDEProblem(de, u0map, (0.0, 100.0), parammap) diff --git a/examples/electrical_components.jl b/examples/electrical_components.jl index 2c829a6b38..ce0b2e67d7 100644 --- a/examples/electrical_components.jl +++ b/examples/electrical_components.jl @@ -18,8 +18,8 @@ end @named n = Pin() sts = @variables v(t)=1.0 i(t)=1.0 eqs = [v ~ p.v - n.v - 0 ~ p.i + n.i - i ~ p.i] + 0 ~ p.i + n.i + i ~ p.i] compose(ODESystem(eqs, t, sts, []; name = name), p, n) end @@ -28,7 +28,7 @@ end @unpack v, i = oneport ps = @parameters R = R eqs = [ - v ~ i * R, + v ~ i * R ] extend(ODESystem(eqs, t, [], ps; name = name), oneport) end @@ -39,7 +39,7 @@ end ps = @parameters C = C D = Differential(t) eqs = [ - D(v) ~ i / C, + D(v) ~ i / C ] extend(ODESystem(eqs, t, [], ps; name = name), oneport) end @@ -49,7 +49,7 @@ end @unpack v = oneport ps = @parameters V = V eqs = [ - V ~ v, + V ~ v ] extend(ODESystem(eqs, t, [], ps; name = name), oneport) end @@ -60,7 +60,7 @@ end ps = @parameters L = L D = Differential(t) eqs = [ - D(i) ~ v / L, + D(i) ~ v / L ] extend(ODESystem(eqs, t, [], ps; name = name), oneport) end @@ -77,10 +77,10 @@ end @variables v(t) RTherm(t) @parameters R=R TAmbient=TAmbient alpha=alpha eqs = [RTherm ~ R * (1 + alpha * (h.T - TAmbient)) - v ~ p.i * RTherm - h.Q_flow ~ -v * p.i # -LossPower - v ~ p.v - n.v - 0 ~ p.i + n.i] + v ~ p.i * RTherm + h.Q_flow ~ -v * p.i # -LossPower + v ~ p.v - n.v + 0 ~ p.i + n.i] compose(ODESystem(eqs, t, [v, RTherm], [R, TAmbient, alpha], name = name), p, n, h) end @@ -91,7 +91,7 @@ end @named h = HeatPort() D = Differential(t) eqs = [ - D(h.T) ~ h.Q_flow / C, + D(h.T) ~ h.Q_flow / C ] compose(ODESystem(eqs, t, [], [rho, V, cp], name = name), h) diff --git a/examples/rc_model.jl b/examples/rc_model.jl index 3bdef087f9..158436d980 100644 --- a/examples/rc_model.jl +++ b/examples/rc_model.jl @@ -9,9 +9,9 @@ V = 1.0 @named ground = Ground() rc_eqs = [connect(source.p, resistor.p) - connect(resistor.n, capacitor.p) - connect(capacitor.n, source.n) - connect(capacitor.n, ground.g)] + connect(resistor.n, capacitor.p) + connect(capacitor.n, source.n) + connect(capacitor.n, ground.g)] @named rc_model = ODESystem(rc_eqs, t) rc_model = compose(rc_model, [resistor, capacitor, source, ground]) diff --git a/examples/serial_inductor.jl b/examples/serial_inductor.jl index 54d460d923..302df32c17 100644 --- a/examples/serial_inductor.jl +++ b/examples/serial_inductor.jl @@ -7,10 +7,10 @@ include("electrical_components.jl") @named ground = Ground() eqs = [connect(source.p, resistor.p) - connect(resistor.n, inductor1.p) - connect(inductor1.n, inductor2.p) - connect(source.n, inductor2.n) - connect(inductor2.n, ground.g)] + connect(resistor.n, inductor1.p) + connect(inductor1.n, inductor2.p) + connect(source.n, inductor2.n) + connect(inductor2.n, ground.g)] @named ll_model = ODESystem(eqs, t) ll_model = compose(ll_model, [source, resistor, inductor1, inductor2, ground]) @@ -23,11 +23,11 @@ ll_model = compose(ll_model, [source, resistor, inductor1, inductor2, ground]) @named ground = Ground() eqs = [connect(source.p, inductor1.p) - connect(inductor1.n, resistor1.p) - connect(inductor1.n, resistor2.p) - connect(resistor1.n, resistor2.n) - connect(resistor2.n, inductor2.p) - connect(source.n, inductor2.n) - connect(inductor2.n, ground.g)] + connect(inductor1.n, resistor1.p) + connect(inductor1.n, resistor2.p) + connect(resistor1.n, resistor2.n) + connect(resistor2.n, inductor2.p) + connect(source.n, inductor2.n) + connect(inductor2.n, ground.g)] @named ll2_model = ODESystem(eqs, t) ll2_model = compose(ll2_model, [source, resistor1, resistor2, inductor1, inductor2, ground]) diff --git a/ext/MTKBifurcationKitExt.jl b/ext/MTKBifurcationKitExt.jl index 34a22d8a51..085b3f0215 100644 --- a/ext/MTKBifurcationKitExt.jl +++ b/ext/MTKBifurcationKitExt.jl @@ -40,10 +40,12 @@ struct ObservableRecordFromSolution{S, T} subs_vals_params = Pair.(parameters(nsys), p_vals) # Gets the (base) substitution values for observables. subs_vals_obs = [obs.lhs => substitute(obs.rhs, - [subs_vals_states; subs_vals_params]) for obs in observed(nsys)] + [subs_vals_states; subs_vals_params]) + for obs in observed(nsys)] # Sometimes observables depend on other observables, hence we make a second update to this vector. subs_vals_obs = [obs.lhs => substitute(obs.rhs, - [subs_vals_states; subs_vals_params; subs_vals_obs]) for obs in observed(nsys)] + [subs_vals_states; subs_vals_params; subs_vals_obs]) + for obs in observed(nsys)] # During the bifurcation process, the value of some states, parameters, and observables may vary (and are calculated in each step). Those that are not are stored in this vector subs_vals = [subs_vals_states; subs_vals_params; subs_vals_obs] @@ -68,7 +70,8 @@ function (orfs::ObservableRecordFromSolution)(x, p) # Updates the observable values (in subs_vals). for (obs_idx, obs_eq) in enumerate(orfs.obs_eqs) - orfs.subs_vals[orfs.param_end_idxs + obs_idx] = orfs.subs_vals[orfs.param_end_idxs + obs_idx][1] => substitute(obs_eq.rhs, + orfs.subs_vals[orfs.param_end_idxs + obs_idx] = orfs.subs_vals[orfs.param_end_idxs + obs_idx][1] => substitute( + obs_eq.rhs, orfs.subs_vals) end diff --git a/ext/MTKDeepDiffsExt.jl b/ext/MTKDeepDiffsExt.jl index ced00b3515..a24a638d32 100644 --- a/ext/MTKDeepDiffsExt.jl +++ b/ext/MTKDeepDiffsExt.jl @@ -2,11 +2,11 @@ module MTKDeepDiffsExt using DeepDiffs, ModelingToolkit using ModelingToolkit.BipartiteGraphs: Label, - BipartiteAdjacencyList, unassigned, - HighlightInt + BipartiteAdjacencyList, unassigned, + HighlightInt using ModelingToolkit: SystemStructure, - MatchedSystemStructure, - SystemStructurePrintMatrix + MatchedSystemStructure, + SystemStructurePrintMatrix """ A utility struct for displaying the difference between two HighlightInts. @@ -93,11 +93,13 @@ function Base.show(io::IO, l::BipartiteAdjacencyListDiff) end) print(IOContext(io, :typeinfo => typeof(highlighted)), highlighted) elseif new_nonempty === true - printstyled(io, map(l.new.u) do i + printstyled( + io, map(l.new.u) do i HighlightInt(i, :nothing, i === l.new.match) end, color = :light_green) elseif old_nonempty === true - printstyled(io, map(l.old.u) do i + printstyled( + io, map(l.old.u) do i HighlightInt(i, :nothing, i === l.old.match) end, color = :light_red) elseif old_nonempty !== nothing || new_nonempty !== nothing diff --git a/src/ModelingToolkit.jl b/src/ModelingToolkit.jl index eb58ba14a2..30e78de838 100644 --- a/src/ModelingToolkit.jl +++ b/src/ModelingToolkit.jl @@ -39,9 +39,9 @@ using PrecompileTools, Reexport export independent_variables, states, parameters import SymbolicUtils import SymbolicUtils: istree, arguments, operation, similarterm, promote_symtype, - Symbolic, isadd, ismul, ispow, issym, FnType, - @rule, Rewriters, substitute, metadata, BasicSymbolic, - Sym, Term + Symbolic, isadd, ismul, ispow, issym, FnType, + @rule, Rewriters, substitute, metadata, BasicSymbolic, + Sym, Term using SymbolicUtils.Code import SymbolicUtils.Code: toexpr import SymbolicUtils.Rewriters: Chain, Postwalk, Prewalk, Fixpoint @@ -53,17 +53,17 @@ using PrecompileTools, Reexport using Symbolics using Symbolics: degree using Symbolics: _parse_vars, value, @derivatives, get_variables, - exprs_occur_in, solve_for, build_expr, unwrap, wrap, - VariableSource, getname, variable, Connection, connect, - NAMESPACE_SEPARATOR, set_scalar_metadata, setdefaultval + exprs_occur_in, solve_for, build_expr, unwrap, wrap, + VariableSource, getname, variable, Connection, connect, + NAMESPACE_SEPARATOR, set_scalar_metadata, setdefaultval import Symbolics: rename, get_variables!, _solve, hessian_sparsity, - jacobian_sparsity, isaffine, islinear, _iszero, _isone, - tosymbol, lower_varname, diff2term, var_from_nested_derivative, - BuildTargets, JuliaTarget, StanTarget, CTarget, MATLABTarget, - ParallelForm, SerialForm, MultithreadedForm, build_function, - rhss, lhss, prettify_expr, gradient, - jacobian, hessian, derivative, sparsejacobian, sparsehessian, - substituter, scalarize, getparent + jacobian_sparsity, isaffine, islinear, _iszero, _isone, + tosymbol, lower_varname, diff2term, var_from_nested_derivative, + BuildTargets, JuliaTarget, StanTarget, CTarget, MATLABTarget, + ParallelForm, SerialForm, MultithreadedForm, build_function, + rhss, lhss, prettify_expr, gradient, + jacobian, hessian, derivative, sparsejacobian, sparsehessian, + substituter, scalarize, getparent import DiffEqBase: @add_kwonly import OrdinaryDiffEq @@ -181,12 +181,12 @@ PrecompileTools.@compile_workload begin end export AbstractTimeDependentSystem, - AbstractTimeIndependentSystem, - AbstractMultivariateSystem + AbstractTimeIndependentSystem, + AbstractMultivariateSystem export ODESystem, - ODEFunction, ODEFunctionExpr, ODEProblemExpr, convert_system, - add_accumulations, System + ODEFunction, ODEFunctionExpr, ODEProblemExpr, convert_system, + add_accumulations, System export DAEFunctionExpr, DAEProblemExpr export SDESystem, SDEFunction, SDEFunctionExpr, SDEProblemExpr export SystemStructure @@ -203,9 +203,9 @@ export alias_elimination, flatten export connect, domain_connect, @connector, Connection, Flow, Stream, instream export @component, @mtkmodel, @mtkbuild export isinput, isoutput, getbounds, hasbounds, getguess, hasguess, isdisturbance, - istunable, getdist, hasdist, - tunable_parameters, isirreducible, getdescription, hasdescription, isbinaryvar, - isintegervar + istunable, getdist, hasdist, + tunable_parameters, isirreducible, getdescription, hasdescription, isbinaryvar, + isintegervar export ode_order_lowering, dae_order_lowering, liouville_transform export PDESystem export Differential, expand_derivatives, @derivatives @@ -213,11 +213,11 @@ export Equation, ConstrainedEquation export Term, Sym export SymScope, LocalScope, ParentScope, DelayParentScope, GlobalScope export independent_variable, equations, controls, - observed, structure, full_equations + observed, structure, full_equations export structural_simplify, expand_connections, linearize, linearization_function export DiscreteSystem, - DiscreteProblem, DiscreteProblemExpr, DiscreteFunction, - DiscreteFunctionExpr + DiscreteProblem, DiscreteProblemExpr, DiscreteFunction, + DiscreteFunctionExpr export calculate_jacobian, generate_jacobian, generate_function export calculate_control_jacobian, generate_control_jacobian diff --git a/src/bipartite_graph.jl b/src/bipartite_graph.jl index 6b73628007..52eb2f8cb1 100644 --- a/src/bipartite_graph.jl +++ b/src/bipartite_graph.jl @@ -3,12 +3,12 @@ module BipartiteGraphs import ModelingToolkit: complete export BipartiteEdge, BipartiteGraph, DiCMOBiGraph, Unassigned, unassigned, - Matching, ResidualCMOGraph, InducedCondensationGraph, maximal_matching, - construct_augmenting_path!, MatchedCondensationGraph + Matching, ResidualCMOGraph, InducedCondensationGraph, maximal_matching, + construct_augmenting_path!, MatchedCondensationGraph export 𝑠vertices, 𝑑vertices, has_𝑠vertex, has_𝑑vertex, 𝑠neighbors, 𝑑neighbors, - 𝑠edges, 𝑑edges, nsrcs, ndsts, SRC, DST, set_neighbors!, invview, - delete_srcs!, delete_dsts! + 𝑠edges, 𝑑edges, nsrcs, ndsts, SRC, DST, set_neighbors!, invview, + delete_srcs!, delete_dsts! using DocStringExtensions using UnPack @@ -778,14 +778,14 @@ end function Graphs.outneighbors(mcg::MatchedCondensationGraph, cc::Integer) Iterators.flatten((mcg.scc_assignment[v′] - for v′ in outneighbors(mcg.graph, v) if mcg.scc_assignment[v′] != cc) - for v in mcg.sccs[cc]) + for v′ in outneighbors(mcg.graph, v) if mcg.scc_assignment[v′] != cc) + for v in mcg.sccs[cc]) end function Graphs.inneighbors(mcg::MatchedCondensationGraph, cc::Integer) Iterators.flatten((mcg.scc_assignment[v′] - for v′ in inneighbors(mcg.graph, v) if mcg.scc_assignment[v′] != cc) - for v in mcg.sccs[cc]) + for v′ in inneighbors(mcg.graph, v) if mcg.scc_assignment[v′] != cc) + for v in mcg.sccs[cc]) end """ @@ -811,8 +811,8 @@ end function _neighbors(icg::InducedCondensationGraph, cc::Integer) Iterators.flatten(Iterators.flatten(icg.graph.fadjlist[vsrc] - for vsrc in icg.graph.badjlist[v]) - for v in icg.sccs[cc]) + for vsrc in icg.graph.badjlist[v]) + for v in icg.sccs[cc]) end function Graphs.outneighbors(icg::InducedCondensationGraph, v::Integer) diff --git a/src/inputoutput.jl b/src/inputoutput.jl index 5a9a354b38..1a70098d88 100644 --- a/src/inputoutput.jl +++ b/src/inputoutput.jl @@ -18,9 +18,9 @@ function outputs(sys) rhss = [eq.rhs for eq in o] lhss = [eq.lhs for eq in o] unique([filter(isoutput, states(sys)) - filter(isoutput, parameters(sys)) - filter(x -> istree(x) && isoutput(x), rhss) # observed can return equations with complicated expressions, we are only looking for single Terms - filter(x -> istree(x) && isoutput(x), lhss)]) + filter(isoutput, parameters(sys)) + filter(x -> istree(x) && isoutput(x), rhss) # observed can return equations with complicated expressions, we are only looking for single Terms + filter(x -> istree(x) && isoutput(x), lhss)]) end """ @@ -413,7 +413,7 @@ function add_input_disturbance(sys, dist::DisturbanceModel, inputs = nothing) end eqs = [dsys.input.u[1] ~ d - dist.input ~ u + dsys.output.u[1]] + dist.input ~ u + dsys.output.u[1]] augmented_sys = ODESystem(eqs, t, systems = [dsys], name = gensym(:outer)) augmented_sys = extend(augmented_sys, sys) diff --git a/src/structural_transformation/StructuralTransformations.jl b/src/structural_transformation/StructuralTransformations.jl index 7289df4232..45ac4cbe54 100644 --- a/src/structural_transformation/StructuralTransformations.jl +++ b/src/structural_transformation/StructuralTransformations.jl @@ -11,36 +11,37 @@ using SymbolicUtils: similarterm, istree using ModelingToolkit using ModelingToolkit: ODESystem, AbstractSystem, var_from_nested_derivative, Differential, - states, equations, vars, Symbolic, diff2term, value, - operation, arguments, Sym, Term, simplify, solve_for, - isdiffeq, isdifferential, isirreducible, - empty_substitutions, get_substitutions, - get_tearing_state, get_iv, independent_variables, - has_tearing_state, defaults, InvalidSystemException, - ExtraEquationsSystemException, - ExtraVariablesSystemException, - get_postprocess_fbody, vars!, - IncrementalCycleTracker, add_edge_checked!, topological_sort, - invalidate_cache!, Substitutions, get_or_construct_tearing_state, - filter_kwargs, lower_varname, setio, SparseMatrixCLIL, - fast_substitute, get_fullvars, has_equations, observed + states, equations, vars, Symbolic, diff2term, value, + operation, arguments, Sym, Term, simplify, solve_for, + isdiffeq, isdifferential, isirreducible, + empty_substitutions, get_substitutions, + get_tearing_state, get_iv, independent_variables, + has_tearing_state, defaults, InvalidSystemException, + ExtraEquationsSystemException, + ExtraVariablesSystemException, + get_postprocess_fbody, vars!, + IncrementalCycleTracker, add_edge_checked!, topological_sort, + invalidate_cache!, Substitutions, get_or_construct_tearing_state, + filter_kwargs, lower_varname, setio, SparseMatrixCLIL, + fast_substitute, get_fullvars, has_equations, observed using ModelingToolkit.BipartiteGraphs import .BipartiteGraphs: invview, complete import ModelingToolkit: var_derivative!, var_derivative_graph! using Graphs using ModelingToolkit: algeqs, EquationsView, - SystemStructure, TransformationState, TearingState, structural_simplify!, - isdiffvar, isdervar, isalgvar, isdiffeq, algeqs, is_only_discrete, - dervars_range, diffvars_range, algvars_range, - DiffGraph, complete!, - get_fullvars, system_subset + SystemStructure, TransformationState, TearingState, + structural_simplify!, + isdiffvar, isdervar, isalgvar, isdiffeq, algeqs, is_only_discrete, + dervars_range, diffvars_range, algvars_range, + DiffGraph, complete!, + get_fullvars, system_subset using ModelingToolkit.DiffEqBase using ModelingToolkit.StaticArrays using RuntimeGeneratedFunctions: @RuntimeGeneratedFunction, - RuntimeGeneratedFunctions, - drop_expr + RuntimeGeneratedFunctions, + drop_expr RuntimeGeneratedFunctions.init(@__MODULE__) @@ -52,8 +53,8 @@ export tearing, partial_state_selection, dae_index_lowering, check_consistency export dummy_derivative export build_torn_function, build_observed_function, ODAEProblem export sorted_incidence_matrix, - pantelides!, tearing_reassemble, find_solvables!, - linear_subsys_adjmat! + pantelides!, tearing_reassemble, find_solvables!, + linear_subsys_adjmat! export tearing_assignments, tearing_substitution export torn_system_jacobian_sparsity export full_equations diff --git a/src/structural_transformation/codegen.jl b/src/structural_transformation/codegen.jl index 1123420a87..c3272afe12 100644 --- a/src/structural_transformation/codegen.jl +++ b/src/structural_transformation/codegen.jl @@ -194,8 +194,9 @@ function gen_nlsolve!(is_not_prepended_assignment, eqs, vars, u0map::AbstractDic funex = MakeArray(rhss, SVector) pre = get_preprocess_constants(rhss) end - f = Func([DestructuredArgs(vars, inbounds = !checkbounds) - DestructuredArgs(params, inbounds = !checkbounds)], + f = Func( + [DestructuredArgs(vars, inbounds = !checkbounds) + DestructuredArgs(params, inbounds = !checkbounds)], [], pre(Let(needed_assignments[inner_idxs], funex, @@ -219,8 +220,8 @@ function gen_nlsolve!(is_not_prepended_assignment, eqs, vars, u0map::AbstractDic end nlsolve_expr = Assignment[preassignments - fname ← drop_expr(@RuntimeGeneratedFunction(f)) - DestructuredArgs(vars, inbounds = !checkbounds) ← solver_call] + fname ← drop_expr(@RuntimeGeneratedFunction(f)) + DestructuredArgs(vars, inbounds = !checkbounds) ← solver_call] nlsolve_expr end @@ -244,7 +245,8 @@ function build_torn_function(sys; state = get_or_construct_tearing_state(sys) fullvars = state.fullvars var_eq_matching, var_sccs = algebraic_variables_scc(state) - condensed_graph = MatchedCondensationGraph(DiCMOBiGraph{true}(complete(state.structure.graph), + condensed_graph = MatchedCondensationGraph( + DiCMOBiGraph{true}(complete(state.structure.graph), complete(var_eq_matching)), var_sccs) toporder = topological_sort_by_dfs(condensed_graph) @@ -305,15 +307,17 @@ function build_torn_function(sys; cpre = get_preprocess_constants(rhss) pre2 = x -> pre(cpre(x)) - expr = SymbolicUtils.Code.toexpr(Func([out - DestructuredArgs(states, - inbounds = !checkbounds) - DestructuredArgs(parameters(sys), - inbounds = !checkbounds) - independent_variables(sys)], + expr = SymbolicUtils.Code.toexpr( + Func( + [out + DestructuredArgs(states, + inbounds = !checkbounds) + DestructuredArgs(parameters(sys), + inbounds = !checkbounds) + independent_variables(sys)], [], pre2(Let([torn_expr; - assignments[is_not_prepended_assignment]], + assignments[is_not_prepended_assignment]], funbody, false))), sol_states) @@ -345,7 +349,8 @@ function build_torn_function(sys; end end - ODEFunction{true, SciMLBase.AutoSpecialize}(drop_expr(@RuntimeGeneratedFunction(expr)), + ODEFunction{true, SciMLBase.AutoSpecialize}( + drop_expr(@RuntimeGeneratedFunction(expr)), sparsity = jacobian_sparsity ? torn_system_with_nlsolve_jacobian_sparsity(state, var_eq_matching, @@ -464,7 +469,7 @@ function build_observed_function(state, ts, var_eq_matching, var_sccs, for iscc in subset torn_vars_idxs = Int[var for var in var_sccs[iscc] - if var_eq_matching[var] !== unassigned] + if var_eq_matching[var] !== unassigned] isempty(torn_vars_idxs) || push!(nested_torn_vars_idxs, torn_vars_idxs) end torn_eqs = [[eqs[var_eq_matching[i]] for i in idxs] @@ -489,18 +494,22 @@ function build_observed_function(state, ts, var_eq_matching, var_sccs, end pre = get_postprocess_fbody(sys) cpre = get_preprocess_constants([obs[1:maxidx]; - isscalar ? ts[1] : MakeArray(ts, output_type)]) + isscalar ? ts[1] : MakeArray(ts, output_type)]) pre2 = x -> pre(cpre(x)) - ex = Code.toexpr(Func([DestructuredArgs(unknown_states, inbounds = !checkbounds) - DestructuredArgs(parameters(sys), inbounds = !checkbounds) - independent_variables(sys)], + ex = Code.toexpr( + Func( + [DestructuredArgs(unknown_states, inbounds = !checkbounds) + DestructuredArgs(parameters(sys), inbounds = !checkbounds) + independent_variables(sys)], [], - pre2(Let([collect(Iterators.flatten(solves)) - assignments[is_not_prepended_assignment] - map(eq -> eq.lhs ← eq.rhs, obs[1:maxidx]) - subs], + pre2(Let( + [collect(Iterators.flatten(solves)) + assignments[is_not_prepended_assignment] + map(eq -> eq.lhs ← eq.rhs, obs[1:maxidx]) + subs], isscalar ? ts[1] : MakeArray(ts, output_type), - false))), sol_states) + false))), + sol_states) expression ? ex : drop_expr(@RuntimeGeneratedFunction(ex)) end diff --git a/src/structural_transformation/pantelides.jl b/src/structural_transformation/pantelides.jl index 6b79cdc8b6..5f076a1cb3 100644 --- a/src/structural_transformation/pantelides.jl +++ b/src/structural_transformation/pantelides.jl @@ -54,7 +54,7 @@ function pantelides_reassemble(state::TearingState, var_eq_matching) end rhs = ModelingToolkit.expand_derivatives(D(eq.rhs)) substitution_dict = Dict(x.lhs => x.rhs - for x in out_eqs if x !== nothing && x.lhs isa Symbolic) + for x in out_eqs if x !== nothing && x.lhs isa Symbolic) sub_rhs = substitute(rhs, substitution_dict) out_eqs[diff] = lhs ~ sub_rhs end @@ -131,7 +131,8 @@ function pantelides!(state::TransformationState; finalize = true, maxiters = 800 ecolor = falses(neqs) var_eq_matching = Matching(nvars) neqs′ = neqs - nnonemptyeqs = count(eq -> !isempty(𝑠neighbors(graph, eq)) && eq_to_diff[eq] === nothing, + nnonemptyeqs = count( + eq -> !isempty(𝑠neighbors(graph, eq)) && eq_to_diff[eq] === nothing, 1:neqs′) varwhitelist = computed_highest_diff_variables(state.structure) diff --git a/src/structural_transformation/partial_state_selection.jl b/src/structural_transformation/partial_state_selection.jl index 8ba4892fd9..4a8f7d9b55 100644 --- a/src/structural_transformation/partial_state_selection.jl +++ b/src/structural_transformation/partial_state_selection.jl @@ -49,7 +49,8 @@ function pss_graph_modia!(structure::SystemStructure, maximal_top_matching, varl maxeqlevel = maximum(map(x -> inv_eqlevel[x], eqs)) maxvarlevel = level = maximum(map(x -> inv_varlevel[x], vars)) old_level_vars = () - ict = IncrementalCycleTracker(DiCMOBiGraph{true}(graph, + ict = IncrementalCycleTracker( + DiCMOBiGraph{true}(graph, complete(Matching(ndsts(graph)))); dir = :in) @@ -102,8 +103,9 @@ function pss_graph_modia!(structure::SystemStructure, maximal_top_matching, varl end if level != 0 - remaining_vars = collect(v for v in to_tear_vars - if var_eq_matching[v] === unassigned) + remaining_vars = collect(v + for v in to_tear_vars + if var_eq_matching[v] === unassigned) if !isempty(remaining_vars) remaining_eqs = setdiff(to_tear_eqs, assigned_eqs) nlsolve_matching = maximal_matching(graph, @@ -175,7 +177,8 @@ function dummy_derivative_graph!(state::TransformationState, jac = nothing; dummy_derivative_graph!(state.structure, var_eq_matching, jac, state_priority, log) end -function dummy_derivative_graph!(structure::SystemStructure, var_eq_matching, jac = nothing, +function dummy_derivative_graph!( + structure::SystemStructure, var_eq_matching, jac = nothing, state_priority = nothing, ::Val{log} = Val(false)) where {log} @unpack eq_to_diff, var_to_diff, graph = structure diff_to_eq = invview(eq_to_diff) diff --git a/src/structural_transformation/symbolics_tearing.jl b/src/structural_transformation/symbolics_tearing.jl index 3839e77622..36c08c56a2 100644 --- a/src/structural_transformation/symbolics_tearing.jl +++ b/src/structural_transformation/symbolics_tearing.jl @@ -438,7 +438,8 @@ function tearing_reassemble(state::TearingState, var_eq_matching; if isdervar(iv) order, lv = var_order(iv) dx = D(lower_varname(fullvars[lv], idep, order - 1)) - eq = dx ~ ModelingToolkit.fixpoint_sub(Symbolics.solve_for(neweqs[ieq], + eq = dx ~ ModelingToolkit.fixpoint_sub( + Symbolics.solve_for(neweqs[ieq], fullvars[iv]), total_sub) for e in 𝑑neighbors(graph, iv) @@ -465,8 +466,9 @@ function tearing_reassemble(state::TearingState, var_eq_matching; @warn "Tearing: solving $eq for $var is singular!" else rhs = -b / a - neweq = var ~ ModelingToolkit.fixpoint_sub(simplify ? - Symbolics.simplify(rhs) : rhs, + neweq = var ~ ModelingToolkit.fixpoint_sub( + simplify ? + Symbolics.simplify(rhs) : rhs, total_sub) push!(subeqs, neweq) push!(solved_equations, ieq) @@ -495,8 +497,8 @@ function tearing_reassemble(state::TearingState, var_eq_matching; end solved_variables_set = BitSet(solved_variables) invvarsperm = [diff_vars; - setdiff!(setdiff(1:ndsts(graph), diff_vars_set), - solved_variables_set)] + setdiff!(setdiff(1:ndsts(graph), diff_vars_set), + solved_variables_set)] varsperm = zeros(Int, ndsts(graph)) for (i, v) in enumerate(invvarsperm) varsperm[v] = i @@ -542,7 +544,7 @@ function tearing_reassemble(state::TearingState, var_eq_matching; @set! sys.eqs = neweqs @set! sys.states = Any[v for (i, v) in enumerate(fullvars) - if diff_to_var[i] === nothing && ispresent(i)] + if diff_to_var[i] === nothing && ispresent(i)] @set! sys.substitutions = Substitutions(subeqs, deps) obs_sub = dummy_sub diff --git a/src/structural_transformation/utils.jl b/src/structural_transformation/utils.jl index ff9ef2f82a..a195733176 100644 --- a/src/structural_transformation/utils.jl +++ b/src/structural_transformation/utils.jl @@ -88,7 +88,7 @@ function check_consistency(state::TransformationState, orig_inputs) # This is defined to check if Pantelides algorithm terminates. For more # details, check the equation (15) of the original paper. extended_graph = (@set graph.fadjlist = Vector{Int}[graph.fadjlist; - map(collect, edges(var_to_diff))]) + map(collect, edges(var_to_diff))]) extended_var_eq_matching = maximal_matching(extended_graph) unassigned_var = [] @@ -345,8 +345,9 @@ function reordered_matrix(sys, torn_matching) append!(J, js) end - e_residual = setdiff([max_matching[v] - for v in vars if max_matching[v] !== unassigned], e_solved) + e_residual = setdiff( + [max_matching[v] + for v in vars if max_matching[v] !== unassigned], e_solved) for er in e_residual isdiffeq(eqs[er]) && continue ii += 1 diff --git a/src/systems/abstractsystem.jl b/src/systems/abstractsystem.jl index 7406a5746f..c66f788bdb 100644 --- a/src/systems/abstractsystem.jl +++ b/src/systems/abstractsystem.jl @@ -156,7 +156,8 @@ Base.nameof(sys::AbstractSystem) = getfield(sys, :name) #Deprecated function independent_variable(sys::AbstractSystem) - Base.depwarn("`independent_variable` is deprecated. Use `get_iv` or `independent_variables` instead.", + Base.depwarn( + "`independent_variable` is deprecated. Use `get_iv` or `independent_variables` instead.", :independent_variable) isdefined(sys, :iv) ? getfield(sys, :iv) : nothing end @@ -213,7 +214,8 @@ function SymbolicIndexingInterface.variable_index(sys::AbstractSystem, sym::Symb if idx !== nothing return idx elseif count('₊', string(sym)) == 1 - return findfirst(isequal(sym), Symbol.(sys.name, :₊, getname.(variable_symbols(sys)))) + return findfirst( + isequal(sym), Symbol.(sys.name, :₊, getname.(variable_symbols(sys)))) end return nothing end @@ -255,7 +257,8 @@ function SymbolicIndexingInterface.parameter_index(sys::AbstractSystem, sym::Sym if idx !== nothing return idx elseif count('₊', string(sym)) == 1 - return findfirst(isequal(sym), Symbol.(sys.name, :₊, getname.(parameter_symbols(sys)))) + return findfirst( + isequal(sym), Symbol.(sys.name, :₊, getname.(parameter_symbols(sys)))) end return nothing end @@ -313,44 +316,44 @@ function complete(sys::AbstractSystem) end for prop in [:eqs - :tag - :noiseeqs - :iv - :states - :ps - :tspan - :name - :var_to_name - :ctrls - :defaults - :observed - :tgrad - :jac - :ctrl_jac - :Wfact - :Wfact_t - :systems - :structure - :op - :constraints - :controls - :loss - :bcs - :domain - :ivs - :dvs - :connector_type - :connections - :preface - :torn_matching - :tearing_state - :substitutions - :metadata - :gui_metadata - :discrete_subsystems - :unknown_states - :split_idxs - :parent] + :tag + :noiseeqs + :iv + :states + :ps + :tspan + :name + :var_to_name + :ctrls + :defaults + :observed + :tgrad + :jac + :ctrl_jac + :Wfact + :Wfact_t + :systems + :structure + :op + :constraints + :controls + :loss + :bcs + :domain + :ivs + :dvs + :connector_type + :connections + :preface + :torn_matching + :tearing_state + :substitutions + :metadata + :gui_metadata + :discrete_subsystems + :unknown_states + :split_idxs + :parent] fname1 = Symbol(:get_, prop) fname2 = Symbol(:has_, prop) @eval begin @@ -435,7 +438,8 @@ end function getvar(sys::AbstractSystem, name::Symbol; namespace = !iscomplete(sys)) systems = get_systems(sys) if isdefined(sys, name) - Base.depwarn("`sys.name` like `sys.$name` is deprecated. Use getters like `get_$name` instead.", + Base.depwarn( + "`sys.name` like `sys.$name` is deprecated. Use getters like `get_$name` instead.", "sys.$name") return getfield(sys, name) elseif !isempty(systems) @@ -592,7 +596,7 @@ namespace_controls(sys::AbstractSystem) = controls(sys, controls(sys)) function namespace_defaults(sys) defs = defaults(sys) Dict((isparameter(k) ? parameters(sys, k) : states(sys, k)) => namespace_expr(v, sys) - for (k, v) in pairs(defs)) + for (k, v) in pairs(defs)) end function namespace_equations(sys::AbstractSystem, ivs = independent_variables(sys)) @@ -690,9 +694,9 @@ function observed(sys::AbstractSystem) obs = get_observed(sys) systems = get_systems(sys) [obs; - reduce(vcat, - (map(o -> namespace_equation(o, s), observed(s)) for s in systems), - init = Equation[])] + reduce(vcat, + (map(o -> namespace_equation(o, s), observed(s)) for s in systems), + init = Equation[])] end Base.@deprecate default_u0(x) defaults(x) false @@ -726,9 +730,9 @@ function equations(sys::AbstractSystem) return eqs else eqs = Equation[eqs; - reduce(vcat, - namespace_equations.(get_systems(sys)); - init = Equation[])] + reduce(vcat, + namespace_equations.(get_systems(sys)); + init = Equation[])] return eqs end end @@ -999,8 +1003,10 @@ function Base.show(io::IO, mime::MIME"text/plain", sys::AbstractSystem) val = get(defs, s, nothing) if val !== nothing print(io, " [defaults to ") - show(IOContext(io, :compact => true, :limit => true, - :displaysize => (1, displaysize(io)[2])), val) + show( + IOContext(io, :compact => true, :limit => true, + :displaysize => (1, displaysize(io)[2])), + val) print(io, "]") end description = getdescription(s) @@ -1025,8 +1031,10 @@ function Base.show(io::IO, mime::MIME"text/plain", sys::AbstractSystem) val = get(defs, s, nothing) if val !== nothing print(io, " [defaults to ") - show(IOContext(io, :compact => true, :limit => true, - :displaysize => (1, displaysize(io)[2])), val) + show( + IOContext(io, :compact => true, :limit => true, + :displaysize => (1, displaysize(io)[2])), + val) print(io, "]") end description = getdescription(s) @@ -1508,7 +1516,8 @@ where `x` are differential state variables, `z` algebraic variables, `u` inputs function linearize_symbolic(sys::AbstractSystem, inputs, outputs; simplify = false, allow_input_derivatives = false, kwargs...) - sys, diff_idxs, alge_idxs, input_idxs = io_preprocessing(sys, inputs, outputs; simplify, + sys, diff_idxs, alge_idxs, input_idxs = io_preprocessing( + sys, inputs, outputs; simplify, kwargs...) sts = states(sys) t = get_iv(sys) @@ -1549,9 +1558,9 @@ function linearize_symbolic(sys::AbstractSystem, inputs, error("g_z not invertible, this indicates that the DAE is of index > 1.") gzgx = -(gz \ g_x) A = [f_x f_z - gzgx*f_x gzgx*f_z] + gzgx*f_x gzgx*f_z] B = [f_u - gzgx * f_u] # The cited paper has zeros in the bottom block, see derivation in https://github.com/SciML/ModelingToolkit.jl/pull/1691 for the correct formula + gzgx * f_u] # The cited paper has zeros in the bottom block, see derivation in https://github.com/SciML/ModelingToolkit.jl/pull/1691 for the correct formula C = [h_x h_z] Bs = -(gz \ g_u) # This equation differ from the cited paper, the paper is likely wrong since their equaiton leads to a dimension mismatch. @@ -1598,12 +1607,14 @@ function markio!(state, orig_inputs, inputs, outputs; check = true) if check ikeys = keys(filter(!last, inputset)) if !isempty(ikeys) - error("Some specified inputs were not found in system. The following variables were not found ", + error( + "Some specified inputs were not found in system. The following variables were not found ", ikeys) end end check && (all(values(outputset)) || - error("Some specified outputs were not found in system. The following Dict indicates the found variables ", + error( + "Some specified outputs were not found in system. The following Dict indicates the found variables ", outputset)) state, orig_inputs end @@ -1736,9 +1747,9 @@ function linearize(sys, lin_fun; t = 0.0, op = Dict(), allow_input_derivatives = error("g_z not invertible, this indicates that the DAE is of index > 1.") gzgx = -(gz \ g_x) A = [f_x f_z - gzgx*f_x gzgx*f_z] + gzgx*f_x gzgx*f_z] B = [f_u - gzgx * f_u] # The cited paper has zeros in the bottom block, see derivation in https://github.com/SciML/ModelingToolkit.jl/pull/1691 for the correct formula + gzgx * f_u] # The cited paper has zeros in the bottom block, see derivation in https://github.com/SciML/ModelingToolkit.jl/pull/1691 for the correct formula C = [h_x h_z] Bs = -(gz \ g_u) # This equation differ from the cited paper, the paper is likely wrong since their equaiton leads to a dimension mismatch. diff --git a/src/systems/alias_elimination.jl b/src/systems/alias_elimination.jl index 3ddb88f77b..939ce27d28 100644 --- a/src/systems/alias_elimination.jl +++ b/src/systems/alias_elimination.jl @@ -102,10 +102,10 @@ function alias_elimination!(state::TearingState; kwargs...) @set! mm.nparentrows = nsrcs(graph) @set! mm.row_cols = eltype(mm.row_cols)[mm.row_cols[i] for (i, eq) in enumerate(mm.nzrows) - if old_to_new_eq[eq] > 0] + if old_to_new_eq[eq] > 0] @set! mm.row_vals = eltype(mm.row_vals)[mm.row_vals[i] for (i, eq) in enumerate(mm.nzrows) - if old_to_new_eq[eq] > 0] + if old_to_new_eq[eq] > 0] @set! mm.nzrows = Int[old_to_new_eq[eq] for eq in mm.nzrows if old_to_new_eq[eq] > 0] for old_ieq in to_expand diff --git a/src/systems/callbacks.jl b/src/systems/callbacks.jl index b97112e9e8..bc523d879e 100644 --- a/src/systems/callbacks.jl +++ b/src/systems/callbacks.jl @@ -138,10 +138,10 @@ function continuous_events(sys::AbstractSystem) systems = get_systems(sys) cbs = [obs; - reduce(vcat, - (map(o -> namespace_callback(o, s), continuous_events(s)) - for s in systems), - init = SymbolicContinuousCallback[])] + reduce(vcat, + (map(o -> namespace_callback(o, s), continuous_events(s)) + for s in systems), + init = SymbolicContinuousCallback[])] filter(!isempty, cbs) end @@ -232,9 +232,9 @@ function discrete_events(sys::AbstractSystem) obs = get_discrete_events(sys) systems = get_systems(sys) cbs = [obs; - reduce(vcat, - (map(o -> namespace_callback(o, s), discrete_events(s)) for s in systems), - init = SymbolicDiscreteCallback[])] + reduce(vcat, + (map(o -> namespace_callback(o, s), discrete_events(s)) for s in systems), + init = SymbolicDiscreteCallback[])] cbs end @@ -249,8 +249,11 @@ function add_integrator_header(integrator = gensym(:MTKIntegrator), out = :u) end function condition_header(integrator = gensym(:MTKIntegrator)) - expr -> Func([expr.args[1], expr.args[2], - DestructuredArgs(expr.args[3:end], integrator, inds = [:p])], [], expr.body) + expr -> Func( + [expr.args[1], expr.args[2], + DestructuredArgs(expr.args[3:end], integrator, inds = [:p])], + [], + expr.body) end """ diff --git a/src/systems/clock_inference.jl b/src/systems/clock_inference.jl index 9ffeb56319..0c0b5a411b 100644 --- a/src/systems/clock_inference.jl +++ b/src/systems/clock_inference.jl @@ -187,12 +187,14 @@ function generate_discrete_affect(syss, inputs, continuous_id, id_to_clock; output_type = SVector) ni = length(input) ns = length(states(sys)) - disc = Func([ + disc = Func( + [ out, DestructuredArgs(states(sys)), DestructuredArgs(appended_parameters), - get_iv(sys), - ], [], + get_iv(sys) + ], + [], let_block) cont_to_disc_idxs = (offset + 1):(offset += ni) input_offset = offset diff --git a/src/systems/connectors.jl b/src/systems/connectors.jl index 42ad27fb2b..d3299be9c2 100644 --- a/src/systems/connectors.jl +++ b/src/systems/connectors.jl @@ -353,7 +353,8 @@ function generate_connection_set!(connectionsets, domain_csets, if !isempty(extra_states) @set! sys.states = [get_states(sys); extra_states] end - @set! sys.systems = map(s -> generate_connection_set!(connectionsets, domain_csets, s, + @set! sys.systems = map( + s -> generate_connection_set!(connectionsets, domain_csets, s, find, replace, renamespace(namespace, s)), subsys) @@ -497,9 +498,11 @@ function expand_instream(csets::AbstractVector{<:ConnectionSet}, sys::AbstractSy tol = 1e-8) subsys = get_systems(sys) # post order traversal - @set! sys.systems = map(s -> expand_instream(csets, s, + @set! sys.systems = map( + s -> expand_instream(csets, s, renamespace(namespace, nameof(s)), - namespace; debug, tol), subsys) + namespace; debug, tol), + subsys) subsys = get_systems(sys) if debug diff --git a/src/systems/diffeqs/abstractodesystem.jl b/src/systems/diffeqs/abstractodesystem.jl index f79859da57..7309df5202 100644 --- a/src/systems/diffeqs/abstractodesystem.jl +++ b/src/systems/diffeqs/abstractodesystem.jl @@ -747,6 +747,7 @@ function ODEFunctionExpr{iip}(sys::AbstractODESystem, dvs = states(sys), $_jac M = $_M ODEFunction{$iip}($fsym, + sys = $sys, jac = $jacsym, tgrad = $tgradsym, mass_matrix = M, @@ -1133,7 +1134,8 @@ function DiffEqBase.SDDEProblem{iip}(sys::AbstractODESystem, u0map = [], else noise_rate_prototype = zeros(eltype(u0), size(noiseeqs)) end - SDDEProblem{iip}(f, f.g, u0, h, tspan, p; noise_rate_prototype = + SDDEProblem{iip}(f, f.g, u0, h, tspan, p; + noise_rate_prototype = noise_rate_prototype, kwargs1..., kwargs...) end diff --git a/src/systems/diffeqs/odesystem.jl b/src/systems/diffeqs/odesystem.jl index 77975c91d9..b61b00a6c8 100644 --- a/src/systems/diffeqs/odesystem.jl +++ b/src/systems/diffeqs/odesystem.jl @@ -201,7 +201,8 @@ function ODESystem(deqs::AbstractVector{<:Equation}, iv, dvs, ps; dvs′ = filter(x -> !isdelay(x, iv), dvs′) if !(isempty(default_u0) && isempty(default_p)) - Base.depwarn("`default_u0` and `default_p` are deprecated. Use `defaults` instead.", + Base.depwarn( + "`default_u0` and `default_p` are deprecated. Use `defaults` instead.", :ODESystem, force = true) end defaults = todict(defaults) diff --git a/src/systems/diffeqs/sdesystem.jl b/src/systems/diffeqs/sdesystem.jl index e584857fd8..0afe0bbe68 100644 --- a/src/systems/diffeqs/sdesystem.jl +++ b/src/systems/diffeqs/sdesystem.jl @@ -171,7 +171,8 @@ function SDESystem(deqs::AbstractVector{<:Equation}, neqs::AbstractArray, iv, dv throw(ArgumentError("System names must be unique.")) end if !(isempty(default_u0) && isempty(default_p)) - Base.depwarn("`default_u0` and `default_p` are deprecated. Use `defaults` instead.", + Base.depwarn( + "`default_u0` and `default_p` are deprecated. Use `defaults` instead.", :SDESystem, force = true) end defaults = todict(defaults) @@ -531,7 +532,8 @@ function SDEFunctionExpr{iip}(sys::SDESystem, dvs = states(sys), end if Wfact - tmp_Wfact, tmp_Wfact_t = generate_factorized_W(sys, dvs, ps; expression = Val{true}, + tmp_Wfact, tmp_Wfact_t = generate_factorized_W( + sys, dvs, ps; expression = Val{true}, kwargs...) _Wfact = tmp_Wfact[idx] _Wfact_t = tmp_Wfact_t[idx] diff --git a/src/systems/discrete_system/discrete_system.jl b/src/systems/discrete_system/discrete_system.jl index 0363d17687..0dc0d62943 100644 --- a/src/systems/discrete_system/discrete_system.jl +++ b/src/systems/discrete_system/discrete_system.jl @@ -141,7 +141,8 @@ function DiscreteSystem(eqs::AbstractVector{<:Equation}, iv, dvs, ps; ctrl′ = value.(controls) if !(isempty(default_u0) && isempty(default_p)) - Base.depwarn("`default_u0` and `default_p` are deprecated. Use `defaults` instead.", + Base.depwarn( + "`default_u0` and `default_p` are deprecated. Use `defaults` instead.", :DiscreteSystem, force = true) end defaults = todict(defaults) diff --git a/src/systems/jumps/jumpsystem.jl b/src/systems/jumps/jumpsystem.jl index 9509582b1d..1bf553bed0 100644 --- a/src/systems/jumps/jumpsystem.jl +++ b/src/systems/jumps/jumpsystem.jl @@ -102,7 +102,8 @@ struct JumpSystem{U <: ArrayPartition} <: AbstractTimeDependentSystem """ complete::Bool - function JumpSystem{U}(tag, ap::U, iv, states, ps, var_to_name, observed, name, systems, + function JumpSystem{U}( + tag, ap::U, iv, states, ps, var_to_name, observed, name, systems, defaults, connector_type, devents, metadata = nothing, gui_metadata = nothing, complete = false; @@ -153,7 +154,8 @@ function JumpSystem(eqs, iv, states, ps; end end if !(isempty(default_u0) && isempty(default_p)) - Base.depwarn("`default_u0` and `default_p` are deprecated. Use `defaults` instead.", + Base.depwarn( + "`default_u0` and `default_p` are deprecated. Use `defaults` instead.", :JumpSystem, force = true) end defaults = todict(defaults) @@ -490,7 +492,7 @@ end function (ratemap::JumpSysMajParamMapper{ U, V, - W, + W })(params) where {U <: AbstractArray, V <: AbstractArray, W} updateparams!(ratemap, params) diff --git a/src/systems/model_parsing.jl b/src/systems/model_parsing.jl index 4a8d73652c..044263da1b 100644 --- a/src/systems/model_parsing.jl +++ b/src/systems/model_parsing.jl @@ -831,12 +831,14 @@ end function parse_conditional_model_statements(comps, dict, eqs, exprs, kwargs, mod, ps, vs, component_blk, equations_blk, parameter_blk, variable_blk) parameter_blk !== nothing && - parse_variables!(exprs.args, ps, dict, mod, :(begin + parse_variables!( + exprs.args, ps, dict, mod, :(begin $parameter_blk end), :parameters, kwargs) variable_blk !== nothing && - parse_variables!(exprs.args, vs, dict, mod, :(begin + parse_variables!( + exprs.args, vs, dict, mod, :(begin $variable_blk end), :variables, kwargs) diff --git a/src/systems/nonlinear/nonlinearsystem.jl b/src/systems/nonlinear/nonlinearsystem.jl index 0eca0ce7d3..fb37e9a1e7 100644 --- a/src/systems/nonlinear/nonlinearsystem.jl +++ b/src/systems/nonlinear/nonlinearsystem.jl @@ -124,7 +124,8 @@ function NonlinearSystem(eqs, states, ps; for x in scalarize(eqs)] if !(isempty(default_u0) && isempty(default_p)) - Base.depwarn("`default_u0` and `default_p` are deprecated. Use `defaults` instead.", + Base.depwarn( + "`default_u0` and `default_p` are deprecated. Use `defaults` instead.", :NonlinearSystem, force = true) end sysnames = nameof.(systems) @@ -205,7 +206,7 @@ end function hessian_sparsity(sys::NonlinearSystem) [hessian_sparsity(eq.rhs, - states(sys)) for eq in equations(sys)] + states(sys)) for eq in equations(sys)] end """ diff --git a/src/systems/optimization/constraints_system.jl b/src/systems/optimization/constraints_system.jl index 46def83701..fa2a6cd249 100644 --- a/src/systems/optimization/constraints_system.jl +++ b/src/systems/optimization/constraints_system.jl @@ -112,7 +112,8 @@ function ConstraintsSystem(constraints, states, ps; ps′ = value.(scalarize(ps)) if !(isempty(default_u0) && isempty(default_p)) - Base.depwarn("`default_u0` and `default_p` are deprecated. Use `defaults` instead.", + Base.depwarn( + "`default_u0` and `default_p` are deprecated. Use `defaults` instead.", :ConstraintsSystem, force = true) end sysnames = nameof.(systems) diff --git a/src/systems/optimization/optimizationsystem.jl b/src/systems/optimization/optimizationsystem.jl index f85ffd97b6..08ed0faf34 100644 --- a/src/systems/optimization/optimizationsystem.jl +++ b/src/systems/optimization/optimizationsystem.jl @@ -97,7 +97,8 @@ function OptimizationSystem(op, states, ps; op′ = value(scalarize(op)) if !(isempty(default_u0) && isempty(default_p)) - Base.depwarn("`default_u0` and `default_p` are deprecated. Use `defaults` instead.", + Base.depwarn( + "`default_u0` and `default_p` are deprecated. Use `defaults` instead.", :OptimizationSystem, force = true) end sysnames = nameof.(systems) @@ -227,7 +228,8 @@ function DiffEqBase.OptimizationProblem{iip}(sys::OptimizationSystem, u0map, use_union = false, kwargs...) where {iip} if haskey(kwargs, :lcons) || haskey(kwargs, :ucons) - Base.depwarn("`lcons` and `ucons` are deprecated. Specify constraints directly instead.", + Base.depwarn( + "`lcons` and `ucons` are deprecated. Specify constraints directly instead.", :OptimizationProblem, force = true) end @@ -419,7 +421,8 @@ function OptimizationProblemExpr{iip}(sys::OptimizationSystem, u0map, use_union = false, kwargs...) where {iip} if haskey(kwargs, :lcons) || haskey(kwargs, :ucons) - Base.depwarn("`lcons` and `ucons` are deprecated. Specify constraints directly instead.", + Base.depwarn( + "`lcons` and `ucons` are deprecated. Specify constraints directly instead.", :OptimizationProblem, force = true) end @@ -461,7 +464,8 @@ function OptimizationProblemExpr{iip}(sys::OptimizationSystem, u0map, f = generate_function(sys, checkbounds = checkbounds, linenumbers = linenumbers, expression = Val{true}) if grad - _grad = generate_gradient(sys, checkbounds = checkbounds, linenumbers = linenumbers, + _grad = generate_gradient( + sys, checkbounds = checkbounds, linenumbers = linenumbers, parallel = parallel, expression = Val{false})[idx] else _grad = :nothing @@ -560,7 +564,8 @@ function OptimizationProblemExpr{iip}(sys::OptimizationSystem, u0map, cons_hess_prototype = cons_hess_prototype, expr = obj_expr, cons_expr = cons_expr) - OptimizationProblem{$iip}(_f, u0, p; lb = lb, ub = ub, int = int, lcons = lcons, + OptimizationProblem{$iip}( + _f, u0, p; lb = lb, ub = ub, int = int, lcons = lcons, ucons = ucons, kwargs...) end else diff --git a/src/systems/pde/pdesystem.jl b/src/systems/pde/pdesystem.jl index f0d8ec3869..01708e01bf 100644 --- a/src/systems/pde/pdesystem.jl +++ b/src/systems/pde/pdesystem.jl @@ -132,12 +132,14 @@ end function Base.getproperty(x::PDESystem, sym::Symbol) if sym == :indvars return getfield(x, :ivs) - Base.depwarn("`sys.indvars` is deprecated, please use `get_ivs(sys)`", :getproperty, + Base.depwarn( + "`sys.indvars` is deprecated, please use `get_ivs(sys)`", :getproperty, force = true) elseif sym == :depvars return getfield(x, :dvs) - Base.depwarn("`sys.depvars` is deprecated, please use `get_dvs(sys)`", :getproperty, + Base.depwarn( + "`sys.depvars` is deprecated, please use `get_dvs(sys)`", :getproperty, force = true) else diff --git a/src/systems/systems.jl b/src/systems/systems.jl index 39a527003a..41d35eb0c1 100644 --- a/src/systems/systems.jl +++ b/src/systems/systems.jl @@ -83,8 +83,8 @@ function __structural_simplify(sys::AbstractSystem, io = nothing; simplify = fal @set! sys.eqs = new_eqs @set! sys.states = [v for (i, v) in enumerate(fullvars) - if !iszero(new_idxs[i]) && - invview(var_to_diff)[i] === nothing] + if !iszero(new_idxs[i]) && + invview(var_to_diff)[i] === nothing] # TODO: IO is not handled. ode_sys = structural_simplify(sys, io; simplify, kwargs...) eqs = equations(ode_sys) diff --git a/src/systems/systemstructure.jl b/src/systems/systemstructure.jl index 69077b452f..8842f53f0a 100644 --- a/src/systems/systemstructure.jl +++ b/src/systems/systemstructure.jl @@ -4,11 +4,11 @@ using SymbolicUtils: istree, operation, arguments, Symbolic using SymbolicUtils: quick_cancel, similarterm using ..ModelingToolkit import ..ModelingToolkit: isdiffeq, var_from_nested_derivative, vars!, flatten, - value, InvalidSystemException, isdifferential, _iszero, - isparameter, isconstant, - independent_variables, SparseMatrixCLIL, AbstractSystem, - equations, isirreducible, input_timedomain, TimeDomain, - VariableType, getvariabletype, has_equations, ODESystem + value, InvalidSystemException, isdifferential, _iszero, + isparameter, isconstant, + independent_variables, SparseMatrixCLIL, AbstractSystem, + equations, isirreducible, input_timedomain, TimeDomain, + VariableType, getvariabletype, has_equations, ODESystem using ..BipartiteGraphs import ..BipartiteGraphs: invview, complete using Graphs @@ -459,8 +459,9 @@ function Base.getindex(bgpm::SystemStructurePrintMatrix, i::Integer, j::Integer) elseif j == 6 return Label((i - 1 <= length(bgpm.var_to_diff)) ? string(i - 1) : "") elseif j == 4 - return BipartiteAdjacencyList(i - 1 <= nsrcs(bgpm.bpg) ? - 𝑠neighbors(bgpm.bpg, i - 1) : nothing, + return BipartiteAdjacencyList( + i - 1 <= nsrcs(bgpm.bpg) ? + 𝑠neighbors(bgpm.bpg, i - 1) : nothing, bgpm.highlight_graph !== nothing && i - 1 <= nsrcs(bgpm.highlight_graph) ? Set(𝑠neighbors(bgpm.highlight_graph, i - 1)) : @@ -474,8 +475,9 @@ function Base.getindex(bgpm::SystemStructurePrintMatrix, i::Integer, j::Integer) match = bgpm.var_eq_matching[i - 1] isa(match, Union{Int, Unassigned}) || (match = true) # Selected State end - return BipartiteAdjacencyList(i - 1 <= ndsts(bgpm.bpg) ? - 𝑑neighbors(bgpm.bpg, i - 1) : nothing, + return BipartiteAdjacencyList( + i - 1 <= ndsts(bgpm.bpg) ? + 𝑑neighbors(bgpm.bpg, i - 1) : nothing, bgpm.highlight_graph !== nothing && i - 1 <= ndsts(bgpm.highlight_graph) ? Set(𝑑neighbors(bgpm.highlight_graph, i - 1)) : diff --git a/src/systems/validation.jl b/src/systems/validation.jl index d3ce0ea9a4..5ddbcdbb24 100644 --- a/src/systems/validation.jl +++ b/src/systems/validation.jl @@ -211,8 +211,10 @@ function _validate(conn::Connection; info::String = "") valid end -function validate(jump::Union{ModelingToolkit.VariableRateJump, - ModelingToolkit.ConstantRateJump}, t::Symbolic; +function validate( + jump::Union{ModelingToolkit.VariableRateJump, + ModelingToolkit.ConstantRateJump}, + t::Symbolic; info::String = "") newinfo = replace(info, "eq." => "jump") _validate([jump.rate, 1 / t], ["rate", "1/t"], info = newinfo) && # Assuming the rate is per time units diff --git a/src/variables.jl b/src/variables.jl index df359354a5..f2eed9ba83 100644 --- a/src/variables.jl +++ b/src/variables.jl @@ -128,7 +128,8 @@ $(SIGNATURES) Intercept the call to `process_p_u0_symbolic` and process symbolic maps of `p` and/or `u0` if the user has `ModelingToolkit` loaded. """ -function SciMLBase.process_p_u0_symbolic(prob::Union{SciMLBase.AbstractDEProblem, +function SciMLBase.process_p_u0_symbolic( + prob::Union{SciMLBase.AbstractDEProblem, NonlinearProblem, OptimizationProblem, SciMLBase.AbstractOptimizationCache}, p, diff --git a/test/clock.jl b/test/clock.jl index 74946d21d7..d9c05258c4 100644 --- a/test/clock.jl +++ b/test/clock.jl @@ -15,13 +15,13 @@ D = Differential(t) # u(n + 1) := f(u(n)) eqs = [yd ~ Sample(t, dt)(y) - ud ~ kp * (r - yd) - r ~ 1.0 + ud ~ kp * (r - yd) + r ~ 1.0 -# plant (time continuous part) - u ~ Hold(ud) - D(x) ~ -x + u - y ~ x] + # plant (time continuous part) + u ~ Hold(ud) + D(x) ~ -x + u + y ~ x] @named sys = ODESystem(eqs) # compute equation and variables' time domains #TODO: test linearize @@ -96,21 +96,21 @@ d = Clock(t, dt) k = ShiftIndex(d) eqs = [yd ~ Sample(t, dt)(y) - ud ~ kp * (r - yd) + z(k) - r ~ 1.0 - -# plant (time continuous part) - u ~ Hold(ud) - D(x) ~ -x + u - y ~ x - z(k + 2) ~ z(k) + yd -#= -z(k + 2) ~ z(k) + yd -=> -z′(k + 1) ~ z(k) + yd -z(k + 1) ~ z′(k) -=# -] + ud ~ kp * (r - yd) + z(k) + r ~ 1.0 + + # plant (time continuous part) + u ~ Hold(ud) + D(x) ~ -x + u + y ~ x + z(k + 2) ~ z(k) + yd + #= + z(k + 2) ~ z(k) + yd + => + z′(k + 1) ~ z(k) + yd + z(k + 1) ~ z′(k) + =# + ] @named sys = ODESystem(eqs) ss = structural_simplify(sys); if VERSION >= v"1.7" @@ -157,16 +157,16 @@ dt2 = 0.2 D = Differential(t) eqs = [ -# controller (time discrete part `dt=0.1`) - yd1 ~ Sample(t, dt)(y) - ud1 ~ kp * (Sample(t, dt)(r) - yd1) - yd2 ~ Sample(t, dt2)(y) - ud2 ~ kp * (Sample(t, dt2)(r) - yd2) - -# plant (time continuous part) - u ~ Hold(ud1) + Hold(ud2) - D(x) ~ -x + u - y ~ x] + # controller (time discrete part `dt=0.1`) + yd1 ~ Sample(t, dt)(y) + ud1 ~ kp * (Sample(t, dt)(r) - yd1) + yd2 ~ Sample(t, dt2)(y) + ud2 ~ kp * (Sample(t, dt2)(r) - yd2) + + # plant (time continuous part) + u ~ Hold(ud1) + Hold(ud2) + D(x) ~ -x + u + y ~ x] @named sys = ODESystem(eqs) ci, varmap = infer_clocks(sys) @@ -196,7 +196,7 @@ function plant(; name) @variables x(t)=1 u(t)=0 y(t)=0 D = Differential(t) eqs = [D(x) ~ -x + u - y ~ x] + y ~ x] ODESystem(eqs, t; name = name) end @@ -204,7 +204,7 @@ function filt(; name) @variables x(t)=0 u(t)=0 y(t)=0 a = 1 / exp(dt) eqs = [x(k + 1) ~ a * x + (1 - a) * u(k) - y ~ x] + y ~ x] ODESystem(eqs, t, name = name) end @@ -212,7 +212,7 @@ function controller(kp; name) @variables y(t)=0 r(t)=0 ud(t)=0 yd(t)=0 @parameters kp = kp eqs = [yd ~ Sample(y) - ud ~ kp * (r - yd)] + ud ~ kp * (r - yd)] ODESystem(eqs, t; name = name) end @@ -221,9 +221,9 @@ end @named p = plant() connections = [f.u ~ -1#(t >= 1) # step input - f.y ~ c.r # filtered reference to controller reference - Hold(c.ud) ~ p.u # controller output to plant input - p.y ~ c.y] + f.y ~ c.r # filtered reference to controller reference + Hold(c.ud) ~ p.u # controller output to plant input + p.y ~ c.y] @named cl = ODESystem(connections, t, systems = [f, c, p]) @@ -249,17 +249,17 @@ dt2 = 0.2 D = Differential(t) eqs = [ -# controller (time discrete part `dt=0.1`) - yd1 ~ Sample(t, dt)(y) - ud1 ~ kp * (r - yd1) -# controller (time discrete part `dt=0.2`) - yd2 ~ Sample(t, dt2)(y) - ud2 ~ kp * (r - yd2) - -# plant (time continuous part) - u ~ Hold(ud1) + Hold(ud2) - D(x) ~ -x + u - y ~ x] + # controller (time discrete part `dt=0.1`) + yd1 ~ Sample(t, dt)(y) + ud1 ~ kp * (r - yd1) + # controller (time discrete part `dt=0.2`) + yd2 ~ Sample(t, dt2)(y) + ud2 ~ kp * (r - yd2) + + # plant (time continuous part) + u ~ Hold(ud1) + Hold(ud2) + D(x) ~ -x + u + y ~ x] @named cl = ODESystem(eqs, t) diff --git a/test/components.jl b/test/components.jl index 74950126a4..b4be975de3 100644 --- a/test/components.jl +++ b/test/components.jl @@ -47,8 +47,8 @@ sys = structural_simplify(rc_model) check_contract(sys) @test !isempty(ModelingToolkit.defaults(sys)) u0 = [capacitor.v => 0.0 - capacitor.p.i => 0.0 - resistor.v => 0.0] + capacitor.p.i => 0.0 + resistor.v => 0.0] prob = ODEProblem(sys, u0, (0, 10.0)) sol = solve(prob, Rodas4()) check_rc_sol(sol) @@ -65,16 +65,16 @@ let @named ground = Ground() rc_eqs = [connect(source.p, resistor.p) - connect(resistor.n, capacitor.p) - connect(capacitor.n, source.n) - connect(capacitor.n, ground.g)] + connect(resistor.n, capacitor.p) + connect(capacitor.n, source.n) + connect(capacitor.n, ground.g)] @named _rc_model = ODESystem(rc_eqs, t) @named rc_model = compose(_rc_model, [resistor, capacitor, source, ground]) sys = structural_simplify(rc_model) u0 = [ - capacitor.v => 0.0, + capacitor.v => 0.0 ] params = [param_r1 => 1.0, param_c1 => 1.0] @@ -88,10 +88,10 @@ let # 1478 @named resistor2 = Resistor(R = R) rc_eqs2 = [connect(source.p, resistor.p) - connect(resistor.n, resistor2.p) - connect(resistor2.n, capacitor.p) - connect(capacitor.n, source.n) - connect(capacitor.n, ground.g)] + connect(resistor.n, resistor2.p) + connect(resistor2.n, capacitor.p) + connect(capacitor.n, source.n) + connect(capacitor.n, ground.g)] @named _rc_model2 = ODESystem(rc_eqs2, t) @named rc_model2 = compose(_rc_model2, @@ -110,8 +110,8 @@ function rc_component(; name, R = 1, C = 1) @named resistor = Resistor(R = R) # test parent scope default of @named @named capacitor = Capacitor(C = ParentScope(C)) eqs = [connect(p, resistor.p); - connect(resistor.n, capacitor.p); - connect(capacitor.n, n)] + connect(resistor.n, capacitor.p); + connect(capacitor.n, n)] @named sys = ODESystem(eqs, t, [], [R, C]) compose(sys, [p, n, resistor, capacitor]; name = name) end @@ -120,8 +120,8 @@ end @named source = ConstantVoltage(V = 1) @named rc_comp = rc_component() eqs = [connect(source.p, rc_comp.p) - connect(source.n, rc_comp.n) - connect(source.n, ground.g)] + connect(source.n, rc_comp.n) + connect(source.n, ground.g)] @named sys′ = ODESystem(eqs, t) @named sys_inner_outer = compose(sys′, [ground, source, rc_comp]) @test_nowarn show(IOBuffer(), MIME"text/plain"(), sys_inner_outer) @@ -129,14 +129,14 @@ expand_connections(sys_inner_outer, debug = true) sys_inner_outer = structural_simplify(sys_inner_outer) @test !isempty(ModelingToolkit.defaults(sys_inner_outer)) u0 = [rc_comp.capacitor.v => 0.0 - rc_comp.capacitor.p.i => 0.0 - rc_comp.resistor.v => 0.0] + rc_comp.capacitor.p.i => 0.0 + rc_comp.resistor.v => 0.0] prob = ODEProblem(sys_inner_outer, u0, (0, 10.0), sparse = true) sol_inner_outer = solve(prob, Rodas4()) @test sol[capacitor.v] ≈ sol_inner_outer[rc_comp.capacitor.v] u0 = [ - capacitor.v => 0.0, + capacitor.v => 0.0 ] prob = ODAEProblem(sys, u0, (0, 10.0)) sol = solve(prob, Tsit5()) @@ -220,7 +220,7 @@ function Load(; name) @named n = Pin() @named resistor = Resistor(R = R) eqs = [connect(p, resistor.p); - connect(resistor.n, n)] + connect(resistor.n, n)] @named sys = ODESystem(eqs, t) compose(sys, [p, n, resistor]; name = name) end @@ -231,7 +231,7 @@ function Circuit(; name) @named load = Load() @named resistor = Resistor(R = R) eqs = [connect(load.p, ground.g); - connect(resistor.p, ground.g)] + connect(resistor.p, ground.g)] @named sys = ODESystem(eqs, t) compose(sys, [ground, resistor, load]; name = name) end @@ -247,9 +247,9 @@ function parallel_rc_model(i; name, source, ground, R, C) heat_capacitor = HeatCapacitor(name = Symbol(:heat_capacitor, i)) rc_eqs = [connect(source.p, resistor.p) - connect(resistor.n, capacitor.p) - connect(capacitor.n, source.n, ground.g) - connect(resistor.h, heat_capacitor.h)] + connect(resistor.n, capacitor.p) + connect(capacitor.n, source.n, ground.g) + connect(resistor.h, heat_capacitor.h)] compose(ODESystem(rc_eqs, t, name = Symbol(name, i)), [resistor, capacitor, source, ground, heat_capacitor]) @@ -266,7 +266,7 @@ end; @variables E(t) = 0.0 eqs = [ D(E) ~ sum(((i, sys),) -> getproperty(sys, Symbol(:resistor, i)).h.Q_flow, - enumerate(rc_systems)), + enumerate(rc_systems)) ] @named _big_rc = ODESystem(eqs, t, [E], []) @named big_rc = compose(_big_rc, rc_systems) @@ -279,7 +279,7 @@ function FixedResistor(; name, R = 1.0) @unpack v, i = oneport @constants R = R eqs = [ - v ~ i * R, + v ~ i * R ] extend(ODESystem(eqs, t, [], []; name = name), oneport) end @@ -287,8 +287,8 @@ capacitor = Capacitor(; name = :c1) resistor = FixedResistor(; name = :r1) ground = Ground(; name = :ground) rc_eqs = [connect(capacitor.n, resistor.p) - connect(resistor.n, capacitor.p) - connect(capacitor.n, ground.g)] + connect(resistor.n, capacitor.p) + connect(capacitor.n, ground.g)] @named _rc_model = ODESystem(rc_eqs, t) @named rc_model = compose(_rc_model, diff --git a/test/dde.jl b/test/dde.jl index 479a1a59a7..23874bb700 100644 --- a/test/dde.jl +++ b/test/dde.jl @@ -33,9 +33,9 @@ sol2 = solve(prob2, alg, reltol = 1e-7, abstol = 1e-10) tau = 1 D = Differential(t) eqs = [D(x₀) ~ (v0 / (1 + beta0 * (x₂(t - tau)^2))) * (p0 - q0) * x₀ - d0 * x₀ - D(x₁) ~ (v0 / (1 + beta0 * (x₂(t - tau)^2))) * (1 - p0 + q0) * x₀ + - (v1 / (1 + beta1 * (x₂(t - tau)^2))) * (p1 - q1) * x₁ - d1 * x₁ - D(x₂(t)) ~ (v1 / (1 + beta1 * (x₂(t - tau)^2))) * (1 - p1 + q1) * x₁ - d2 * x₂(t)] + D(x₁) ~ (v0 / (1 + beta0 * (x₂(t - tau)^2))) * (1 - p0 + q0) * x₀ + + (v1 / (1 + beta1 * (x₂(t - tau)^2))) * (p1 - q1) * x₁ - d1 * x₁ + D(x₂(t)) ~ (v1 / (1 + beta1 * (x₂(t - tau)^2))) * (1 - p1 + q1) * x₁ - d2 * x₂(t)] @named sys = System(eqs) prob = DDEProblem(sys, [x₀ => 1.0, x₁ => 1.0, x₂(t) => 1.0], diff --git a/test/direct.jl b/test/direct.jl index fd0db24d38..b7b18f14cc 100644 --- a/test/direct.jl +++ b/test/direct.jl @@ -20,7 +20,7 @@ canonequal(a, b) = isequal(simplify(a), simplify(b)) [ -sin(x) * cos(cos(x)), x / hypot(x, no_der(x)) + - no_der(x) * Differential(x)(no_der(x)) / hypot(x, no_der(x)), + no_der(x) * Differential(x)(no_der(x)) / hypot(x, no_der(x)) ]) @register_symbolic intfun(x)::Int @@ -31,8 +31,8 @@ eqs = [σ * (y - x), x * y - β * z] simpexpr = [:($(*)(σ, $(+)(y, $(*)(-1, x)))) - :($(+)($(*)(x, $(+)(ρ, $(*)(-1, z))), $(*)(-1, y))) - :($(+)($(*)(x, y), $(*)(-1, z, β)))] + :($(+)($(*)(x, $(+)(ρ, $(*)(-1, z))), $(*)(-1, y))) + :($(+)($(*)(x, y), $(*)(-1, z, β)))] σ, β, ρ = 2 // 3, 3 // 4, 4 // 5 x, y, z = 6 // 7, 7 // 8, 8 // 9 diff --git a/test/discretesystem.jl b/test/discretesystem.jl index e8b2a0114d..12fee727c9 100644 --- a/test/discretesystem.jl +++ b/test/discretesystem.jl @@ -31,7 +31,7 @@ syss = structural_simplify(sys) for df in [ DiscreteFunction(sys, [S, I, R], [c, nsteps, δt, β, γ]), - eval(DiscreteFunctionExpr(sys, [S, I, R], [c, nsteps, δt, β, γ])), + eval(DiscreteFunctionExpr(sys, [S, I, R], [c, nsteps, δt, β, γ])) ] # iip @@ -117,7 +117,7 @@ D2 = Difference(t; dt = 2) # Equations eqs = [ D1(x(t)) ~ 0.4x(t) + 0.3x(t - 1.5) + 0.1x(t - 3), - D2(y(t)) ~ 0.3y(t) + 0.7y(t - 2) + 0.1z * h, + D2(y(t)) ~ 0.3y(t) + 0.7y(t - 2) + 0.1z * h ] # System @@ -129,9 +129,9 @@ eqs2, max_delay = ModelingToolkit.linearize_eqs(sys; return_max_delay = true) @test max_delay[Symbolics.operation(Symbolics.value(y(t)))] ≈ 2 linearized_eqs = [eqs - x(t - 3.0) ~ x(t - 1.5) - x(t - 1.5) ~ x(t) - y(t - 2.0) ~ y(t)] + x(t - 3.0) ~ x(t - 1.5) + x(t - 1.5) ~ x(t) + y(t - 2.0) ~ y(t)] @test all(eqs2 .== linearized_eqs) # observed variable handling @@ -186,8 +186,8 @@ RHS2 = RHS defs = Dict{Any, Any}(s => v for (s, v) in zip(ss, vv)) preface = [Assignment(dummy_var, SetArray(true, term(getfield, wf, Meta.quot(:u)), us)) - Assignment(dummy_var, SetArray(true, term(getfield, wf, Meta.quot(:p)), ps)) - Assignment(buffer, term(wf, t))] + Assignment(dummy_var, SetArray(true, term(getfield, wf, Meta.quot(:p)), ps)) + Assignment(buffer, term(wf, t))] eqs = map(1:length(us)) do i Δ(us[i]) ~ dummy_identity(buffer[i], us[i]) end diff --git a/test/domain_connectors.jl b/test/domain_connectors.jl index 3f42808664..c12b1ba67c 100644 --- a/test/domain_connectors.jl +++ b/test/domain_connectors.jl @@ -36,7 +36,7 @@ end end eqs = [ - dm ~ 0, + dm ~ 0 ] ODESystem(eqs, t, vars, pars; name, defaults = [dm => 0]) @@ -54,7 +54,7 @@ function FixedPressure(; p, name) end eqs = [ - port.p ~ p, + port.p ~ p ] ODESystem(eqs, t, vars, pars; name, systems) @@ -80,8 +80,8 @@ function FixedVolume(; vol, p_int, name) p = port.p eqs = [D(rho) ~ drho - rho ~ port.ρ * (1 + p / port.β) - dm ~ drho * vol] + rho ~ port.ρ * (1 + p / port.β) + dm ~ drho * vol] ODESystem(eqs, t, vars, pars; name, systems) end @@ -119,9 +119,9 @@ function Valve2Port(; p_s_int, p_r_int, p_int, name) # eqs = [domain_connect(port, HS, HR) - port.dm ~ -ifelse(x >= 0, +flow(Δp̃_s), -flow(Δp̃_r)) - HS.dm ~ ifelse(x >= 0, port.dm, 0) - HR.dm ~ ifelse(x < 0, port.dm, 0)] + port.dm ~ -ifelse(x >= 0, +flow(Δp̃_s), -flow(Δp̃_r)) + HS.dm ~ ifelse(x >= 0, port.dm, 0) + HR.dm ~ ifelse(x < 0, port.dm, 0)] ODESystem(eqs, t, vars, pars; name, systems) end @@ -137,10 +137,10 @@ function System(; name) vol = FixedVolume(; vol = 0.1, p_int = 100) end eqs = [domain_connect(fluid, src.port) - connect(src.port, valve.HS) - connect(rtn.port, valve.HR) - connect(vol.port, valve.port) - valve.x ~ sin(2π * t * 10)] + connect(src.port, valve.HS) + connect(rtn.port, valve.HR) + connect(vol.port, valve.port) + valve.x ~ sin(2π * t * 10)] return ODESystem(eqs, t, vars, pars; systems, name) end diff --git a/test/error_handling.jl b/test/error_handling.jl index 6c330bcbf9..59aa6b79a1 100644 --- a/test/error_handling.jl +++ b/test/error_handling.jl @@ -10,9 +10,8 @@ function UnderdefinedConstantVoltage(; name, V = 1.0) @named n = Pin() @parameters V eqs = [ - V ~ p.v - n.v, - # Remove equation - # 0 ~ p.i + n.i + V ~ p.v - n.v # Remove equation + # 0 ~ p.i + n.i ] ODESystem(eqs, t, [], [V], systems = [p, n], defaults = Dict(V => val), name = name) end @@ -24,9 +23,9 @@ function OverdefinedConstantVoltage(; name, V = 1.0, I = 1.0) @named n = Pin() @parameters V I eqs = [V ~ p.v - n.v - # Overdefine p.i and n.i - n.i ~ I - p.i ~ I] + # Overdefine p.i and n.i + n.i ~ I + p.i ~ I] ODESystem(eqs, t, [], [V], systems = [p, n], defaults = Dict(V => val, I => val2), name = name) end @@ -39,16 +38,16 @@ V = 1.0 @named source = UnderdefinedConstantVoltage(V = V) rc_eqs = [connect(source.p, resistor.p) - connect(resistor.n, capacitor.p) - connect(capacitor.n, source.n)] + connect(resistor.n, capacitor.p) + connect(capacitor.n, source.n)] @named rc_model = ODESystem(rc_eqs, t, systems = [resistor, capacitor, source]) @test_throws ModelingToolkit.ExtraVariablesSystemException structural_simplify(rc_model) @named source2 = OverdefinedConstantVoltage(V = V, I = V / R) rc_eqs2 = [connect(source2.p, resistor.p) - connect(resistor.n, capacitor.p) - connect(capacitor.n, source2.n)] + connect(resistor.n, capacitor.p) + connect(capacitor.n, source2.n)] @named rc_model2 = ODESystem(rc_eqs2, t, systems = [resistor, capacitor, source2]) @test_throws ModelingToolkit.ExtraEquationsSystemException structural_simplify(rc_model2) diff --git a/test/extensions/bifurcationkit.jl b/test/extensions/bifurcationkit.jl index 53c7369485..612bf888ae 100644 --- a/test/extensions/bifurcationkit.jl +++ b/test/extensions/bifurcationkit.jl @@ -85,7 +85,8 @@ let all([b.x ≈ b.param for b in bif_dia.γ.branch]) # Tests that we get two Hopf bifurcations at the correct positions. - hopf_points = sort(getfield.(filter(sp -> sp.type == :hopf, bif_dia.γ.specialpoint), + hopf_points = sort( + getfield.(filter(sp -> sp.type == :hopf, bif_dia.γ.specialpoint), :x); by = x -> x[1]) @test length(hopf_points) == 2 diff --git a/test/funcaffect.jl b/test/funcaffect.jl index bb953988b5..bd08f371af 100644 --- a/test/funcaffect.jl +++ b/test/funcaffect.jl @@ -39,7 +39,7 @@ cb1 = ModelingToolkit.SymbolicContinuousCallback([t ~ zr], (affect1!, [], [], [1 # named tuple sys1 = ODESystem(eqs, t, [u], [], name = :sys, discrete_events = [ - [4.0] => (f = affect1!, sts = [u], pars = [], ctx = nothing), + [4.0] => (f = affect1!, sts = [u], pars = [], ctx = nothing) ]) @test sys == sys1 @@ -95,7 +95,7 @@ end @named sys = ODESystem(eqs, t, [u], [a], discrete_events = [ - [4.0, 8.0] => (affect3!, [u], [a => :b], nothing), + [4.0, 8.0] => (affect3!, [u], [a => :b], nothing) ]) prob = ODEProblem(sys, [u => 10.0], (0, 10.0)) @@ -110,12 +110,12 @@ i8 = findfirst(==(8.0), sol[:t]) @test_throws ErrorException ODESystem(eqs, t, [u], [a], discrete_events = [ [4.0, 8.0] => (affect3!, [u, v => :u], [a], - nothing), + nothing) ]; name = :sys) @test_nowarn ODESystem(eqs, t, [u], [a], discrete_events = [ - [4.0, 8.0] => (affect3!, [u], [a => :u], nothing), + [4.0, 8.0] => (affect3!, [u], [a => :u], nothing) ]; name = :sys) @named resistor = ODESystem(D(v) ~ v, t, [v], []) @@ -126,7 +126,8 @@ function affect4!(integ, u, p, ctx) ctx[1] += 1 @test u.resistor₊v == 1 end -s1 = compose(ODESystem(Equation[], t, [], [], name = :s1, +s1 = compose( + ODESystem(Equation[], t, [], [], name = :s1, discrete_events = 1.0 => (affect4!, [resistor.v], [], ctx)), resistor) s2 = structural_simplify(s1) @@ -144,14 +145,14 @@ end @named rc_model = ODESystem(rc_eqs, t, continuous_events = [ [capacitor.v ~ 0.3] => (affect5!, [capacitor.v], - [capacitor.C => :C], nothing), + [capacitor.C => :C], nothing) ]) rc_model = compose(rc_model, [resistor, capacitor, source, ground]) sys = structural_simplify(rc_model) u0 = [capacitor.v => 0.0 - capacitor.p.i => 0.0 - resistor.v => 0.0] + capacitor.p.i => 0.0 + resistor.v => 0.0] prob = ODEProblem(sys, u0, (0, 10.0)) sol = solve(prob, Rodas4()) @@ -170,9 +171,10 @@ function Capacitor2(; name, C = 1.0) ps = @parameters C = C D = Differential(t) eqs = [ - D(v) ~ i / C, + D(v) ~ i / C ] - extend(ODESystem(eqs, t, [], ps; name = name, + extend( + ODESystem(eqs, t, [], ps; name = name, continuous_events = [[v ~ 0.3] => (affect6!, [v], [C], nothing)]), oneport) end @@ -180,17 +182,17 @@ end @named capacitor2 = Capacitor2(C = C) rc_eqs2 = [connect(source.p, resistor.p) - connect(resistor.n, capacitor2.p) - connect(capacitor2.n, source.n) - connect(capacitor2.n, ground.g)] + connect(resistor.n, capacitor2.p) + connect(capacitor2.n, source.n) + connect(capacitor2.n, ground.g)] @named rc_model2 = ODESystem(rc_eqs2, t) rc_model2 = compose(rc_model2, [resistor, capacitor2, source, ground]) sys2 = structural_simplify(rc_model2) u0 = [capacitor2.v => 0.0 - capacitor2.p.i => 0.0 - resistor.v => 0.0] + capacitor2.p.i => 0.0 + resistor.v => 0.0] prob2 = ODEProblem(sys2, u0, (0, 10.0)) sol2 = solve(prob2, Rodas4()) @@ -264,7 +266,7 @@ sol_ = solve(prob_, Tsit5(), callback = cb_) sts = @variables y(t), v(t) par = @parameters g = 9.8 bb_eqs = [D(y) ~ v - D(v) ~ -g] + D(v) ~ -g] function bb_affect!(integ, u, p, ctx) integ.u[u.v] = -integ.u[u.v] @@ -272,7 +274,7 @@ end @named bb_model = ODESystem(bb_eqs, t, sts, par, continuous_events = [ - [y ~ zr] => (bb_affect!, [v], [], nothing), + [y ~ zr] => (bb_affect!, [v], [], nothing) ]) bb_sys = structural_simplify(bb_model) diff --git a/test/input_output_handling.jl b/test/input_output_handling.jl index 249a94e9d0..05e994c932 100644 --- a/test/input_output_handling.jl +++ b/test/input_output_handling.jl @@ -1,7 +1,7 @@ using ModelingToolkit, Symbolics, Test using ModelingToolkit: get_namespace, has_var, inputs, outputs, is_bound, bound_inputs, - unbound_inputs, bound_outputs, unbound_outputs, isinput, isoutput, - ExtraVariablesSystemException + unbound_inputs, bound_outputs, unbound_outputs, isinput, isoutput, + ExtraVariablesSystemException @variables t xx(t) some_input(t) [input = true] D = Differential(t) @@ -129,9 +129,9 @@ t = ModelingToolkitStandardLibrary.Mechanical.Rotational.t @named torque = Torque(; use_support = false) @variables y(t) = 0 eqs = [connect(torque.flange, inertia1.flange_a) - connect(inertia1.flange_b, spring.flange_a, damper.flange_a) - connect(inertia2.flange_a, spring.flange_b, damper.flange_b) - y ~ inertia2.w + torque.tau.u] + connect(inertia1.flange_b, spring.flange_a, damper.flange_a) + connect(inertia2.flange_a, spring.flange_b, damper.flange_b) + y ~ inertia2.w + torque.tau.u] model = ODESystem(eqs, t; systems = [torque, inertia1, inertia2, spring, damper], name = :name) model_outputs = [inertia1.w, inertia2.w, inertia1.phi, inertia2.phi] @@ -159,7 +159,7 @@ end @variables t x(t)=0 u(t)=0 [input = true] D = Differential(t) eqs = [ - D(x) ~ -x + u, + D(x) ~ -x + u ] @named sys = ODESystem(eqs) @@ -182,7 +182,7 @@ function Mass(; name, m = 1.0, p = 0, v = 0) ps = @parameters m = m sts = @variables pos(t)=p vel(t)=v eqs = [D(pos) ~ vel - y ~ pos] + y ~ pos] ODESystem(eqs, t, [pos, vel, y], ps; name) end @@ -219,8 +219,8 @@ c = 10 @named sd = SpringDamper(; k, c) eqs = [connect_sd(sd, mass1, mass2) - D(mass1.vel) ~ (sd_force(sd) + u) / mass1.m - D(mass2.vel) ~ (-sd_force(sd)) / mass2.m] + D(mass1.vel) ~ (sd_force(sd) + u) / mass1.m + D(mass2.vel) ~ (-sd_force(sd)) / mass2.m] @named _model = ODESystem(eqs, t) @named model = compose(_model, mass1, mass2, sd); @@ -228,7 +228,8 @@ f, dvs, ps = ModelingToolkit.generate_control_function(model, simplify = true) @test length(dvs) == 4 @test length(ps) == length(parameters(model)) p = ModelingToolkit.varmap_to_vars(ModelingToolkit.defaults(model), ps) -x = ModelingToolkit.varmap_to_vars(merge(ModelingToolkit.defaults(model), +x = ModelingToolkit.varmap_to_vars( + merge(ModelingToolkit.defaults(model), Dict(D.(states(model)) .=> 0.0)), dvs) u = [rand()] out = f[1](x, u, p, 1) @@ -268,8 +269,8 @@ c = 10 # Damping coefficient function SystemModel(u = nothing; name = :model) eqs = [connect(torque.flange, inertia1.flange_a) - connect(inertia1.flange_b, spring.flange_a, damper.flange_a) - connect(inertia2.flange_a, spring.flange_b, damper.flange_b)] + connect(inertia1.flange_b, spring.flange_a, damper.flange_a) + connect(inertia2.flange_a, spring.flange_b, damper.flange_b)] if u !== nothing push!(eqs, connect(torque.tau, u.output)) return @named model = ODESystem(eqs, t; @@ -279,7 +280,7 @@ function SystemModel(u = nothing; name = :model) inertia2, spring, damper, - u, + u ]) end ODESystem(eqs, t; systems = [torque, inertia1, inertia2, spring, damper], name) @@ -321,8 +322,8 @@ y₁, y₂, y₃ = x u1, u2 = u k₁, k₂, k₃ = 1, 1, 1 eqs = [D(y₁) ~ -k₁ * y₁ + k₃ * y₂ * y₃ + u1 - D(y₂) ~ k₁ * y₁ - k₃ * y₂ * y₃ - k₂ * y₂^2 + u2 - y₁ + y₂ + y₃ ~ 1] + D(y₂) ~ k₁ * y₁ - k₃ * y₂ * y₃ - k₂ * y₂^2 + u2 + y₁ + y₂ + y₃ ~ 1] @named sys = ODESystem(eqs, t) m_inputs = [u[1], u[2]] @@ -337,11 +338,12 @@ sys_simp, input_idxs = structural_simplify(sys, (; inputs = m_inputs, outputs = @named gain = Gain(1;) @named int = Integrator(; k = 1) @named fb = Feedback(;) -@named model = ODESystem([ +@named model = ODESystem( + [ connect(c.output, fb.input1), connect(fb.input2, int.output), connect(fb.output, gain.input), - connect(gain.output, int.input), + connect(gain.output, int.input) ], t, systems = [int, gain, c, fb]) @@ -372,7 +374,7 @@ matrices, ssys = linearize(augmented_sys, [ augmented_sys.u, augmented_sys.input.u[2], - augmented_sys.d, + augmented_sys.d ], outs) @test matrices.A ≈ [A [1; 0]; zeros(1, 2) -0.001] @test matrices.B == I diff --git a/test/inversemodel.jl b/test/inversemodel.jl index 0d18e899aa..9fcbcc158a 100644 --- a/test/inversemodel.jl +++ b/test/inversemodel.jl @@ -145,7 +145,7 @@ sol = solve(prob, Rodas5P()) # plot(sol, idxs=[model.tank.xc, model.tank.xT, model.controller.ctr_output.u], layout=3, sp=[1 2 3]) # hline!([prob[cm.ref.k]], label="ref", sp=1) -@test sol(tspan[2], idxs = cm.tank.xc)≈ getp(prob, cm.ref.k)(prob) atol=1e-2 # Test that the inverse model led to the correct reference +@test sol(tspan[2], idxs = cm.tank.xc)≈getp(prob, cm.ref.k)(prob) atol=1e-2 # Test that the inverse model led to the correct reference Sf, simplified_sys = Blocks.get_sensitivity_function(model, :y) # This should work without providing an operating opint containing a dummy derivative x, p = ModelingToolkit.get_u0_p(simplified_sys, op) diff --git a/test/linalg.jl b/test/linalg.jl index 6bfbfebb09..be6fb39b1b 100644 --- a/test/linalg.jl +++ b/test/linalg.jl @@ -3,25 +3,25 @@ using LinearAlgebra using Test A = [0 1 1 2 2 1 1 2 1 2 - 0 1 -1 -3 -2 2 1 -5 0 -5 - 0 1 2 2 1 1 2 1 1 2 - 0 1 1 1 2 1 1 2 2 1 - 0 2 1 2 2 2 2 1 1 1 - 0 1 1 1 2 2 1 1 2 1 - 0 2 1 2 2 1 2 1 1 2 - 0 1 7 17 14 2 1 19 4 23 - 0 1 -1 -3 -2 1 1 -4 0 -5 - 0 1 1 2 2 1 1 2 2 2] + 0 1 -1 -3 -2 2 1 -5 0 -5 + 0 1 2 2 1 1 2 1 1 2 + 0 1 1 1 2 1 1 2 2 1 + 0 2 1 2 2 2 2 1 1 1 + 0 1 1 1 2 2 1 1 2 1 + 0 2 1 2 2 1 2 1 1 2 + 0 1 7 17 14 2 1 19 4 23 + 0 1 -1 -3 -2 1 1 -4 0 -5 + 0 1 1 2 2 1 1 2 2 2] N = ModelingToolkit.nullspace(A) @test size(N, 2) == 3 @test rank(N) == 3 @test iszero(A * N) A = [0 1 2 0 1 0; - 0 0 0 0 0 1; - 0 0 0 0 0 1; - 1 0 1 2 0 1; - 0 0 0 2 1 0] + 0 0 0 0 0 1; + 0 0 0 0 0 1; + 1 0 1 2 0 1; + 0 0 0 2 1 0] col_order = Int[] N = ModelingToolkit.nullspace(A; col_order) colspan = A[:, col_order[1:4]] # rank is 4 diff --git a/test/linearize.jl b/test/linearize.jl index d77793275c..641c8f389b 100644 --- a/test/linearize.jl +++ b/test/linearize.jl @@ -7,8 +7,8 @@ using ModelingToolkit, Test D = Differential(t) eqs = [u ~ kp * (r - y) - D(x) ~ -x + u - y ~ x] + D(x) ~ -x + u + y ~ x] @named sys = ODESystem(eqs, t) @@ -50,7 +50,7 @@ function plant(; name) @variables u(t)=0 y(t)=0 D = Differential(t) eqs = [D(x) ~ -x + u - y ~ x] + y ~ x] ODESystem(eqs, t; name = name) end @@ -59,7 +59,7 @@ function filt_(; name) @variables u(t)=0 [input = true] D = Differential(t) eqs = [D(x) ~ -2 * x + u - y ~ x] + y ~ x] ODESystem(eqs, t, name = name) end @@ -67,7 +67,7 @@ function controller(kp; name) @variables y(t)=0 r(t)=0 u(t)=0 @parameters kp = kp eqs = [ - u ~ kp * (r - y), + u ~ kp * (r - y) ] ODESystem(eqs, t; name = name) end @@ -77,8 +77,8 @@ end @named p = plant() connections = [f.y ~ c.r # filtered reference to controller reference - c.u ~ p.u # controller output to plant input - p.y ~ c.y] + c.u ~ p.u # controller output to plant input + p.y ~ c.y] @named cl = ODESystem(connections, t, systems = [f, c, p]) @@ -138,19 +138,19 @@ if VERSION >= v"1.8" @test_throws "Some specified inputs were not found" linearize(pid, [ pid.reference.u, - pid.measurement.u, + pid.measurement.u ], [ctr_output.u]) @test_throws "Some specified outputs were not found" linearize(pid, [ reference.u, - measurement.u, + measurement.u ], [pid.ctr_output.u]) else # v1.6 does not have the feature to match error message @test_throws ErrorException linearize(pid, [ pid.reference.u, - pid.measurement.u, + pid.measurement.u ], [ctr_output.u]) @test_throws ErrorException linearize(pid, [reference.u, measurement.u], @@ -165,8 +165,8 @@ function saturation(; y_max, y_min = y_max > 0 ? -y_max : -Inf, name) @parameters y_max=y_max y_min=y_min ie = ModelingToolkit.IfElse.ifelse eqs = [ - # The equation below is equivalent to y ~ clamp(u, y_min, y_max) - y ~ ie(u > y_max, y_max, ie((y_min < u) & (u < y_max), u, y_min)), + # The equation below is equivalent to y ~ clamp(u, y_min, y_max) + y ~ ie(u > y_max, y_max, ie((y_min < u) & (u < y_max), u, y_min)) ] ODESystem(eqs, t, name = name) end @@ -216,8 +216,8 @@ if VERSION >= v"1.8" @named force = Force(use_support = false) eqs = [connect(link1.TX1, cart.flange) - connect(cart.flange, force.flange) - connect(link1.TY1, fixed.flange)] + connect(cart.flange, force.flange) + connect(link1.TY1, fixed.flange)] @named model = ODESystem(eqs, t, [], []; systems = [link1, cart, force, fixed]) def = ModelingToolkit.defaults(model) diff --git a/test/mass_matrix.jl b/test/mass_matrix.jl index 1e54f58ef1..fd1288a787 100644 --- a/test/mass_matrix.jl +++ b/test/mass_matrix.jl @@ -12,8 +12,8 @@ eqs = [D(y[1]) ~ -k[1] * y[1] + k[3] * y[2] * y[3], @test_throws ArgumentError ODESystem(eqs, y[1]) M = calculate_massmatrix(sys) @test M == [1 0 0 - 0 1 0 - 0 0 0] + 0 1 0 + 0 0 0] f = ODEFunction(sys) prob_mm = ODEProblem(f, [1.0, 0.0, 0.0], (0.0, 1e5), (0.04, 3e7, 1e4)) diff --git a/test/model_parsing.jl b/test/model_parsing.jl index 7b07425532..137c5c1cd1 100644 --- a/test/model_parsing.jl +++ b/test/model_parsing.jl @@ -1,6 +1,7 @@ using ModelingToolkit, Test using ModelingToolkit: get_gui_metadata, get_systems, get_connector_type, - get_ps, getdefault, getname, scalarize, VariableDescription, RegularConnector + get_ps, getdefault, getname, scalarize, VariableDescription, + RegularConnector using URIs: URI using Distributions using Unitful @@ -397,17 +398,17 @@ end @test all([ if_in_sys.eq ~ 0, if_in_sys.eq ~ 1, - if_in_sys.eq ~ 4, + if_in_sys.eq ~ 4 ] .∈ [equations(if_in_sys)]) @test all([ elseif_in_sys.eq ~ 0, elseif_in_sys.eq ~ 2, - elseif_in_sys.eq ~ 5, + elseif_in_sys.eq ~ 5 ] .∈ [equations(elseif_in_sys)]) @test all([ else_in_sys.eq ~ 0, else_in_sys.eq ~ 3, - else_in_sys.eq ~ 5, + else_in_sys.eq ~ 5 ] .∈ [equations(else_in_sys)]) @test getdefault(if_in_sys.eq) == 1 @@ -484,11 +485,11 @@ end @test nameof.(get_systems(else_out_sys)) == [:else_sys, :default_sys] @test Equation[if_out_sys.if_parameter ~ 0 - if_out_sys.default_parameter ~ 0] == equations(if_out_sys) + if_out_sys.default_parameter ~ 0] == equations(if_out_sys) @test Equation[elseif_out_sys.elseif_parameter ~ 0 - elseif_out_sys.default_parameter ~ 0] == equations(elseif_out_sys) + elseif_out_sys.default_parameter ~ 0] == equations(elseif_out_sys) @test Equation[else_out_sys.else_parameter ~ 0 - else_out_sys.default_parameter ~ 0] == equations(else_out_sys) + else_out_sys.default_parameter ~ 0] == equations(else_out_sys) @mtkmodel TernaryBranchingOutsideTheBlock begin @structural_parameters begin diff --git a/test/modelingtoolkitize.jl b/test/modelingtoolkitize.jl index 517977f99f..610ff9c83c 100644 --- a/test/modelingtoolkitize.jl +++ b/test/modelingtoolkitize.jl @@ -76,9 +76,9 @@ i₀ = 0.075 # fraction of initial infected people in every age class ## regional contact matrix regional_all_contact_matrix = [3.45536 0.485314 0.506389 0.123002; - 0.597721 2.11738 0.911374 0.323385; - 0.906231 1.35041 1.60756 0.67411; - 0.237902 0.432631 0.726488 0.979258] # 4x4 contact matrix + 0.597721 2.11738 0.911374 0.323385; + 0.906231 1.35041 1.60756 0.67411; + 0.237902 0.432631 0.726488 0.979258] # 4x4 contact matrix ## regional population stratified by age N = [723208, 874150, 1330993, 1411928] # array of 4 elements, each of which representing the absolute amount of population in the corresponding age class. @@ -105,7 +105,7 @@ function SIRD_ac!(du, u, p, t) 0.003 / 100, 0.004 / 100, (0.015 + 0.030 + 0.064 + 0.213 + 0.718) / (5 * 100), - (2.384 + 8.466 + 12.497 + 1.117) / (4 * 100), + (2.384 + 8.466 + 12.497 + 1.117) / (4 * 100) ] δ = vcat(repeat([δ₁], 1), repeat([δ₂], 1), repeat([δ₃], 1), repeat([δ₄], 4 - 1 - 1 - 1)) diff --git a/test/nonlinearsystem.jl b/test/nonlinearsystem.jl index 0d1fcf90da..66bdb8d915 100644 --- a/test/nonlinearsystem.jl +++ b/test/nonlinearsystem.jl @@ -93,17 +93,19 @@ eqs1 = [ 0 ~ σ * (y - x) * h + F, 0 ~ x * (ρ - z) - u, 0 ~ x * y - β * z, - 0 ~ x + y - z - u, + 0 ~ x + y - z - u ] lorenz = name -> NonlinearSystem(eqs1, [x, y, z, u, F], [σ, ρ, β], name = name) lorenz1 = lorenz(:lorenz1) @test_throws ArgumentError NonlinearProblem(lorenz1, zeros(5)) lorenz2 = lorenz(:lorenz2) -@named connected = NonlinearSystem([s ~ a + lorenz1.x - lorenz2.y ~ s * h - lorenz1.F ~ lorenz2.u - lorenz2.F ~ lorenz1.u], [s, a], [], +@named connected = NonlinearSystem( + [s ~ a + lorenz1.x + lorenz2.y ~ s * h + lorenz1.F ~ lorenz2.u + lorenz2.F ~ lorenz1.u], + [s, a], [], systems = [lorenz1, lorenz2]) @test_nowarn alias_elimination(connected) @@ -154,10 +156,10 @@ end @parameters a b @variables x y eqs1 = [ - 0 ~ a * x, + 0 ~ a * x ] eqs2 = [ - 0 ~ b * y, + 0 ~ b * y ] @named sys1 = NonlinearSystem(eqs1, [x], [a]) @@ -184,9 +186,9 @@ RHS2 = RHS @variables t @variables v1(t) v2(t) i1(t) i2(t) eq = [v1 ~ sin(2pi * t * h) - v1 - v2 ~ i1 - v2 ~ i2 - i1 ~ i2] + v1 - v2 ~ i1 + v2 ~ i2 + i1 ~ i2] @named sys = ODESystem(eq) @test length(equations(structural_simplify(sys))) == 0 @@ -249,9 +251,9 @@ end D = Differential(t) eqs = [dx ~ a * x - b * x * y - dy ~ -c * y + d * x * y - D(x) ~ dx - D(y) ~ dy] + dy ~ -c * y + d * x * y + D(x) ~ dx + D(y) ~ dy] @named sys = ODESystem(eqs, t, vars, pars) diff --git a/test/odaeproblem.jl b/test/odaeproblem.jl index c2de571cb0..8caf9c3133 100644 --- a/test/odaeproblem.jl +++ b/test/odaeproblem.jl @@ -13,9 +13,9 @@ function Segment(; name) @named n = Pin() # bottom eqs = [connect(p1, R.p) - connect(R.n, p2, r.p) - connect(r.n, C.p) - connect(C.n, n)] + connect(R.n, p2, r.p) + connect(r.n, C.p) + connect(C.n, n)] return ODESystem(eqs, t, [], []; name = name, @@ -33,9 +33,9 @@ function Strip(; name) @named n = Pin() # bottom eqs = [connect(p1, segments[1].p1) - connect(p2, segments[end].p2) - [connect(n, seg.n) for seg in segments]... - [connect(segments[i].p2, segments[i + 1].p1) for i in 1:(num_segments - 1)]...] + connect(p2, segments[end].p2) + [connect(n, seg.n) for seg in segments]... + [connect(segments[i].p2, segments[i + 1].p1) for i in 1:(num_segments - 1)]...] return ODESystem(eqs, t, [], []; name, systems = [p1, p2, n, segments...]) @@ -49,8 +49,8 @@ end @named strip = Strip() rc_eqs = [connect(c.output, source.V) - connect(source.p, strip.p1, strip.p2) - connect(strip.n, source.n, ground.g)] + connect(source.p, strip.p1, strip.p2) + connect(strip.n, source.n, ground.g)] @named rc_model = ODESystem(rc_eqs, t, systems = [strip, c, source, ground]) sys = structural_simplify(rc_model) diff --git a/test/odesystem.jl b/test/odesystem.jl index c4a09b6ecd..ba8696a106 100644 --- a/test/odesystem.jl +++ b/test/odesystem.jl @@ -27,8 +27,8 @@ ssort(eqs) = sort(eqs, by = string) @test isequal(ssort(parameters(subed)), [k, β, ρ]) @test isequal(equations(subed), [D(x) ~ k * (y - x) - D(y) ~ (ρ - z) * x - y - D(z) ~ x * y - β * κ * z]) + D(y) ~ (ρ - z) * x - y + D(z) ~ x * y - β * κ * z]) @named des[1:3] = ODESystem(eqs) @test length(unique(x -> ModelingToolkit.get_tag(x), des)) == 1 @test eval(toexpr(de)) == de @@ -53,8 +53,11 @@ jacfun = eval(jac_expr[2]) for f in [ ODEFunction(de, [x, y, z], [σ, ρ, β], tgrad = true, jac = true), - eval(ODEFunctionExpr(de, [x, y, z], [σ, ρ, β], tgrad = true, jac = true)), + eval(ODEFunctionExpr(de, [x, y, z], [σ, ρ, β], tgrad = true, jac = true)) ] + # system + @test f.sys === de + # iip du = zeros(3) u = collect(1:3) @@ -149,20 +152,21 @@ D3 = Differential(t)^3 D2 = Differential(t)^2 @variables u(t) uˍtt(t) uˍt(t) xˍt(t) eqs = [D3(u) ~ 2(D2(u)) + D(u) + D(x) + 1 - D2(x) ~ D(x) + 2] + D2(x) ~ D(x) + 2] @named de = ODESystem(eqs) de1 = ode_order_lowering(de) lowered_eqs = [D(uˍtt) ~ 2uˍtt + uˍt + xˍt + 1 - D(xˍt) ~ xˍt + 2 - D(uˍt) ~ uˍtt - D(u) ~ uˍt - D(x) ~ xˍt] + D(xˍt) ~ xˍt + 2 + D(uˍt) ~ uˍtt + D(u) ~ uˍt + D(x) ~ xˍt] #@test de1 == ODESystem(lowered_eqs) # issue #219 -@test all(isequal.([ModelingToolkit.var_from_nested_derivative(eq.lhs)[1] - for eq in equations(de1)], +@test all(isequal.( + [ModelingToolkit.var_from_nested_derivative(eq.lhs)[1] + for eq in equations(de1)], states(@named lowered = ODESystem(lowered_eqs)))) test_diffeq_inference("first-order transform", de1, t, [uˍtt, xˍt, uˍt, u, x], []) @@ -305,8 +309,8 @@ for (prob, atol) in [(prob1, 1e-12), (prob2, 1e-12), (prob3, 1e-12)] end du0 = [D(y₁) => -0.04 - D(y₂) => 0.04 - D(y₃) => 0.0] + D(y₂) => 0.04 + D(y₃) => 0.0] prob4 = DAEProblem(sys, du0, u0, tspan, p2) prob5 = eval(DAEProblemExpr(sys, du0, u0, tspan, p2)) for prob in [prob4, prob5] @@ -344,18 +348,18 @@ D = Differential(t) asys = add_accumulations(sys) @variables accumulation_x(t) accumulation_y(t) accumulation_z(t) eqs = [0 ~ x + z - 0 ~ x - y - D(accumulation_x) ~ x - D(accumulation_y) ~ y - D(accumulation_z) ~ z - D(x) ~ y] + 0 ~ x - y + D(accumulation_x) ~ x + D(accumulation_y) ~ y + D(accumulation_z) ~ z + D(x) ~ y] @test ssort(equations(asys)) == ssort(eqs) @variables ac(t) asys = add_accumulations(sys, [ac => (x + y)^2]) eqs = [0 ~ x + z - 0 ~ x - y - D(ac) ~ (x + y)^2 - D(x) ~ y] + 0 ~ x - y + D(ac) ~ (x + y)^2 + D(x) ~ y] @test ssort(equations(asys)) == ssort(eqs) sys2 = ode_order_lowering(sys) @@ -368,7 +372,7 @@ D = Differential(t) eqs = [ D(x1) ~ -x1, - 0 ~ x1 - x2, + 0 ~ x1 - x2 ] @named sys = ODESystem(eqs, t) @test isequal(ModelingToolkit.get_iv(sys), t) @@ -410,7 +414,7 @@ pars = [] vars = @variables((u1,)) der = Differential(t) eqs = [ - der(u1) ~ 1, + der(u1) ~ 1 ] @test_throws ArgumentError ODESystem(eqs, t, vars, pars, name = :foo) @@ -422,7 +426,7 @@ vars = @variables((u1(t),)) @parameters w der = Differential(w) eqs = [ - der(u1) ~ t, + der(u1) ~ t ] @test_throws ArgumentError ModelingToolkit.ODESystem(eqs, t, vars, pars, name = :foo) @@ -482,7 +486,7 @@ sts = @variables x(t)[1:3]=[1, 2, 3.0] y(t)=1.0 ps = @parameters p[1:3] = [1, 2, 3] D = Differential(t) eqs = [collect(D.(x) .~ x) - D(y) ~ norm(collect(x)) * y - x[1]] + D(y) ~ norm(collect(x)) * y - x[1]] @named sys = ODESystem(eqs, t, [sts...;], [ps...;]) sys = structural_simplify(sys) @test isequal(@nonamespace(sys.x), x) @@ -508,9 +512,9 @@ sol = solve(prob, Tsit5()) Δ = Difference(t; dt = 0.1) U = DiscreteUpdate(t; dt = 0.1) eqs = [δ(x) ~ a * x - b * x * y - δ(y) ~ -c * y + d * x * y - Δ(x) ~ y - U(y) ~ x + 1] + δ(y) ~ -c * y + d * x * y + Δ(x) ~ y + U(y) ~ x + 1] @named de = ODESystem(eqs, t, [x, y], [a, b, c, d]) @test generate_difference_cb(de) isa ModelingToolkit.DiffEqCallbacks.DiscreteCallback @@ -568,7 +572,7 @@ using ModelingToolkit: hist D = Differential(t) xₜ₋₁ = hist(x, t - 1) eqs = [D(x) ~ x * y - D(y) ~ y * x - xₜ₋₁] + D(y) ~ y * x - xₜ₋₁] @named sys = ODESystem(eqs, t) # register @@ -615,7 +619,7 @@ D = Differential(t) eqs = [ D(x) ~ 0.1x + 0.9y, D(y) ~ 0.5x + 0.5y, - z ~ α * x - β * y, + z ~ α * x - β * y ] @named sys = ODESystem(eqs, t, [x, y, z], [α, β]) @@ -668,8 +672,8 @@ eqs[end] = D(D(z)) ~ α * x - β * y defs = Dict{Any, Any}(s => v for (s, v) in zip(ss, vv)) preface = [Assignment(dummy_var, SetArray(true, term(getfield, wf, Meta.quot(:u)), us)) - Assignment(dummy_var, SetArray(true, term(getfield, wf, Meta.quot(:p)), ps)) - Assignment(buffer, term(wf, t))] + Assignment(dummy_var, SetArray(true, term(getfield, wf, Meta.quot(:p)), ps)) + Assignment(buffer, term(wf, t))] eqs = map(1:length(us)) do i D(us[i]) ~ dummy_identity(buffer[i], us[i]) end @@ -688,8 +692,8 @@ let @variables y(t) = 0 @parameters k = 1 eqs = [D(x[1]) ~ x[2] - D(x[2]) ~ -x[1] - 0.5 * x[2] + k - y ~ 0.9 * x[1] + x[2]] + D(x[2]) ~ -x[1] - 0.5 * x[2] + k + y ~ 0.9 * x[1] + x[2]] @named sys = ODESystem(eqs, t, vcat(x, [y]), [k], defaults = Dict(x .=> 0)) sys = structural_simplify(sys) @@ -773,8 +777,8 @@ let D = Differential(t) eqs = [D(q) ~ -p / L - F - D(p) ~ q / C - 0 ~ q / C - R * F] + D(p) ~ q / C + 0 ~ q / C - R * F] @named sys = ODESystem(eqs, t) @test length(equations(structural_simplify(sys))) == 2 @@ -797,7 +801,7 @@ let eqs2 = [ D2(y2) ~ x2 * (rho - z2) - y2, D2(x2) ~ sigma * (y2 - x2), - D2(z2) ~ x2 * y2 - beta * z2, + D2(z2) ~ x2 * y2 - beta * z2 ] # array u @@ -809,7 +813,7 @@ let eqs4 = [ D2(y2) ~ x2 * (rho - z2) - y2, D2(x2) ~ sigma * (y2 - x2), - D2(z2) ~ y2 - beta * z2, # missing x2 term + D2(z2) ~ y2 - beta * z2 # missing x2 term ] @named sys1 = ODESystem(eqs) @@ -833,11 +837,11 @@ let vars = @variables sP(t) spP(t) spm(t) sph(t) pars = @parameters a b eqs = [sP ~ 1 - spP ~ sP - spm ~ a - sph ~ b - spm ~ 0 - sph ~ a] + spP ~ sP + spm ~ a + sph ~ b + spm ~ 0 + sph ~ a] @named sys = ODESystem(eqs, t, vars, pars) @test_throws ModelingToolkit.ExtraEquationsSystemException structural_simplify(sys) end @@ -858,9 +862,9 @@ let Dt = Differential(t) eqs = [Differential(t)(u[2]) - 1.1u[1] ~ 0 - Differential(t)(u[3]) - 1.1u[2] ~ 0 - u[1] ~ 0.0 - u[4] ~ 0.0] + Differential(t)(u[3]) - 1.1u[2] ~ 0 + u[1] ~ 0.0 + u[4] ~ 0.0] ps = [] @@ -957,7 +961,7 @@ let sys_simp = structural_simplify(sys_con) D = Differential(t) true_eqs = [D(sys.x) ~ sys.v - D(sys.v) ~ ctrl.kv * sys.v + ctrl.kx * sys.x] + D(sys.v) ~ ctrl.kv * sys.v + ctrl.kx * sys.x] @test isequal(full_equations(sys_simp), true_eqs) end @@ -981,7 +985,7 @@ let ∂t = Differential(t) eqs = [∂t(Q) ~ 0.2P - ∂t(P) ~ -80.0sin(Q)] + ∂t(P) ~ -80.0sin(Q)] @test_throws ArgumentError @named sys = ODESystem(eqs) end @@ -990,8 +994,8 @@ end D = Differential(t) eqs = [D(q) ~ -p / L - F - D(p) ~ q / C - 0 ~ q / C - R * F] + D(p) ~ q / C + 0 ~ q / C - R * F] testdict = Dict([:name => "test"]) @named sys = ODESystem(eqs, t, metadata = testdict) @test get_metadata(sys) == testdict @@ -1000,7 +1004,7 @@ testdict = Dict([:name => "test"]) ∂t = Differential(t) eqs = [∂t(Q) ~ 1 / sin(P) - ∂t(P) ~ log(-cos(Q))] + ∂t(P) ~ log(-cos(Q))] @named sys = ODESystem(eqs, t, [P, Q], []) sys = debug_system(sys); prob = ODEProblem(sys, [], (0, 1.0)); diff --git a/test/optimizationsystem.jl b/test/optimizationsystem.jl index 2dbf9f08ed..a13b6c4cea 100644 --- a/test/optimizationsystem.jl +++ b/test/optimizationsystem.jl @@ -1,5 +1,5 @@ using ModelingToolkit, SparseArrays, Test, Optimization, OptimizationOptimJL, - OptimizationMOI, Ipopt, AmplNLWriter, Ipopt_jll + OptimizationMOI, Ipopt, AmplNLWriter, Ipopt_jll using ModelingToolkit: get_metadata @testset "basic" begin @@ -32,15 +32,15 @@ using ModelingToolkit: get_metadata @test sparse_prob.f.hess_prototype.colptr == hess_sparsity.colptr u0 = [sys1.x => 1.0 - sys1.y => 2.0 - sys2.x => 3.0 - sys2.y => 4.0 - z => 5.0] + sys1.y => 2.0 + sys2.x => 3.0 + sys2.y => 4.0 + z => 5.0] p = [sys1.a => 6.0 - sys1.b => 7.0 - sys2.a => 8.0 - sys2.b => 9.0 - β => 10.0] + sys1.b => 7.0 + sys2.a => 8.0 + sys2.b => 9.0 + β => 10.0] prob = OptimizationProblem(combinedsys, u0, p, grad = true, hess = true, cons_j = true, cons_h = true) @@ -54,7 +54,7 @@ end @parameters a b loss = (a - x)^2 + b * (y - x^2)^2 cons = [ - x^2 + y^2 ≲ 1.0, + x^2 + y^2 ≲ 1.0 ] @named sys = OptimizationSystem(loss, [x, y], [a, b], constraints = cons) @@ -77,8 +77,8 @@ end @parameters a b loss = (a - x)^2 + b * z^2 cons = [1.0 ~ x^2 + y^2 - z ~ y - x^2 - z^2 + y^2 ≲ 1.0] + z ~ y - x^2 + z^2 + y^2 ≲ 1.0] @named sys = OptimizationSystem(loss, [x, y, z], [a, b], constraints = cons) sys = structural_simplify(sys) prob = OptimizationProblem(sys, [x => 0.0, y => 0.0, z => 0.0], [a => 1.0, b => 1.0], @@ -142,10 +142,10 @@ end o1 = (x - a)^2 o2 = (y - 1 / 2)^2 c1 = [ - x ~ 1, + x ~ 1 ] c2 = [ - y ~ 1, + y ~ 1 ] sys1 = OptimizationSystem(o1, [x], [a], name = :sys1, constraints = c1) sys2 = OptimizationSystem(o2, [y], [], name = :sys2, constraints = c2) @@ -183,7 +183,7 @@ end sys1 = OptimizationSystem(loss, [x, y], [a, b], name = :sys1) cons = [ - x^2 + y^2 ≲ 1.0, + x^2 + y^2 ≲ 1.0 ] sys2 = OptimizationSystem(loss, [x, y], [a, b], name = :sys2, constraints = cons) @@ -194,15 +194,15 @@ end name = :combinedsys) u0 = [sys1.x => 1.0 - sys1.y => 2.0 - sys2.x => 3.0 - sys2.y => 4.0 - z => 5.0] + sys1.y => 2.0 + sys2.x => 3.0 + sys2.y => 4.0 + z => 5.0] p = [sys1.a => 6.0 - sys1.b => 7.0 - sys2.a => 8.0 - sys2.b => 9.0 - β => 10.0] + sys1.b => 7.0 + sys2.a => 8.0 + sys2.b => 9.0 + β => 10.0] prob = OptimizationProblem(combinedsys, u0, p, grad = true, hess = true, cons_j = true, cons_h = true) @@ -227,7 +227,7 @@ end @variables x o1 = (x - 1)^2 c1 = [ - x ~ 1, + x ~ 1 ] testdict = Dict(["test" => 1]) sys1 = OptimizationSystem(o1, [x], [], name = :sys1, constraints = c1, @@ -240,7 +240,7 @@ end @named sys = OptimizationSystem(x[1] + x[2], [x...], []; constraints = [ 1.0 ≲ x[1]^2 + x[2]^2, - x[1]^2 + x[2]^2 ≲ 2.0, + x[1]^2 + x[2]^2 ≲ 2.0 ]) prob = OptimizationProblem(sys, [x[1] => 2.0, x[2] => 0.0], [], grad = true, @@ -267,7 +267,7 @@ end @parameters α₁ α₂ loss = (α₁ - x₁)^2 + α₂ * (x₂ - x₁^2)^2 cons = [ - x₁^2 + x₂^2 ≲ 1.0, + x₁^2 + x₂^2 ≲ 1.0 ] sys1 = OptimizationSystem(loss, [x₁, x₂], [α₁, α₂], name = :sys1, constraints = cons) @@ -301,5 +301,5 @@ end prob = OptimizationProblem(sys, [x => 0.0, y => 0.0], [a => 1.0, b => 100.0]) @test prob.f.expr isa Symbolics.Symbolic @test all(prob.f.cons_expr[i].lhs isa Symbolics.Symbolic - for i in 1:length(prob.f.cons_expr)) + for i in 1:length(prob.f.cons_expr)) end diff --git a/test/reduction.jl b/test/reduction.jl index 0b58c2de43..73de52f23b 100644 --- a/test/reduction.jl +++ b/test/reduction.jl @@ -3,19 +3,19 @@ using ModelingToolkit: topsort_equations @variables t x(t) y(t) z(t) k(t) eqs = [x ~ y + z - z ~ 2 - y ~ 2z + k] + z ~ 2 + y ~ 2z + k] sorted_eq = topsort_equations(eqs, [x, y, z, k]) ref_eq = [z ~ 2 - y ~ 2z + k - x ~ y + z] + y ~ 2z + k + x ~ y + z] @test ref_eq == sorted_eq @test_throws ArgumentError topsort_equations([x ~ y + z - z ~ 2 - y ~ 2z + x], [x, y, z, k]) + z ~ 2 + y ~ 2z + x], [x, y, z, k]) @parameters t σ ρ β @variables x(t) y(t) z(t) a(t) u(t) F(t) @@ -24,10 +24,10 @@ D = Differential(t) test_equal(a, b) = @test isequal(a, b) || isequal(simplify(a), simplify(b)) eqs = [D(x) ~ σ * (y - x) - D(y) ~ x * (ρ - z) - y + β - 0 ~ z - x + y - 0 ~ a + z - u ~ z + a] + D(y) ~ x * (ρ - z) - y + β + 0 ~ z - x + y + 0 ~ a + z + u ~ z + a] lorenz1 = ODESystem(eqs, t, name = :lorenz1) @@ -37,7 +37,7 @@ show(io, MIME("text/plain"), lorenz1_aliased); str = String(take!(io)); @test all(s -> occursin(s, str), ["lorenz1", "States (2)", "Parameters (3)"]) reduced_eqs = [D(x) ~ σ * (y - x) - D(y) ~ β + (ρ - z) * x - y] + D(y) ~ β + (ρ - z) * x - y] #test_equal.(equations(lorenz1_aliased), reduced_eqs) @test isempty(setdiff(states(lorenz1_aliased), [x, y, z])) #test_equal.(observed(lorenz1_aliased), [u ~ 0 @@ -51,7 +51,7 @@ eqs1 = [ D(x) ~ σ * (y - x) + F, D(y) ~ x * (ρ - z) - u, D(z) ~ x * y - β * z, - u ~ x + y - z, + u ~ x + y - z ] lorenz = name -> ODESystem(eqs1, t, name = name) @@ -60,10 +60,12 @@ state = TearingState(lorenz1) @test isempty(setdiff(state.fullvars, [D(x), F, y, x, D(y), u, z, D(z)])) lorenz2 = lorenz(:lorenz2) -@named connected = ODESystem([s ~ a + lorenz1.x - lorenz2.y ~ s - lorenz1.u ~ lorenz2.F - lorenz2.u ~ lorenz1.F], t, systems = [lorenz1, lorenz2]) +@named connected = ODESystem( + [s ~ a + lorenz1.x + lorenz2.y ~ s + lorenz1.u ~ lorenz2.F + lorenz2.u ~ lorenz1.F], + t, systems = [lorenz1, lorenz2]) @test length(Base.propertynames(connected)) == 10 @test isequal((@nonamespace connected.lorenz1.x), x) __x = x @@ -81,39 +83,39 @@ reduced_system2 = structural_simplify(tearing_substitution(structural_simplify(t @test isequal(observed(reduced_system), observed(reduced_system2)) @test setdiff(states(reduced_system), [s - a - lorenz1.x - lorenz1.y - lorenz1.z - lorenz1.u - lorenz2.x - lorenz2.y - lorenz2.z - lorenz2.u]) |> isempty + a + lorenz1.x + lorenz1.y + lorenz1.z + lorenz1.u + lorenz2.x + lorenz2.y + lorenz2.z + lorenz2.u]) |> isempty @test setdiff(parameters(reduced_system), [lorenz1.σ - lorenz1.ρ - lorenz1.β - lorenz2.σ - lorenz2.ρ - lorenz2.β]) |> isempty + lorenz1.ρ + lorenz1.β + lorenz2.σ + lorenz2.ρ + lorenz2.β]) |> isempty @test length(equations(reduced_system)) == 6 pp = [lorenz1.σ => 10 - lorenz1.ρ => 28 - lorenz1.β => 8 / 3 - lorenz2.σ => 10 - lorenz2.ρ => 28 - lorenz2.β => 8 / 3] + lorenz1.ρ => 28 + lorenz1.β => 8 / 3 + lorenz2.σ => 10 + lorenz2.ρ => 28 + lorenz2.β => 8 / 3] u0 = [lorenz1.x => 1.0 - lorenz1.y => 0.0 - lorenz1.z => 0.0 - s => 0.0 - lorenz2.x => 1.0 - lorenz2.y => 0.0 - lorenz2.z => 0.0] + lorenz1.y => 0.0 + lorenz1.z => 0.0 + s => 0.0 + lorenz2.x => 1.0 + lorenz2.y => 0.0 + lorenz2.z => 0.0] prob1 = ODEProblem(reduced_system, u0, (0.0, 100.0), pp) solve(prob1, Rodas5()) @@ -131,12 +133,12 @@ let @parameters k_P pc = ODESystem(Equation[u_c ~ k_P * y_c], t, name = :pc) connections = [pc.u_c ~ ol.u - pc.y_c ~ ol.y] + pc.y_c ~ ol.y] @named connected = ODESystem(connections, t, systems = [ol, pc]) @test equations(connected) isa Vector{Equation} reduced_sys = structural_simplify(connected) ref_eqs = [D(ol.x) ~ ol.a * ol.x + ol.b * ol.u - 0 ~ pc.k_P * ol.y - ol.u] + 0 ~ pc.k_P * ol.y - ol.u] #@test ref_eqs == equations(reduced_sys) end @@ -156,15 +158,15 @@ end @variables u1(t) u2(t) u3(t) @parameters p eqs = [u1 ~ u2 - u3 ~ u1 + u2 + p - u3 ~ hypot(u1, u2) * p] + u3 ~ u1 + u2 + p + u3 ~ hypot(u1, u2) * p] @named sys = NonlinearSystem(eqs, [u1, u2, u3], [p]) reducedsys = structural_simplify(sys) @test length(observed(reducedsys)) == 2 u0 = [u1 => 1 - u2 => 1 - u3 => 0.3] + u2 => 1 + u3 => 0.3] pp = [2] nlprob = NonlinearProblem(reducedsys, u0, pp) reducedsol = solve(nlprob, NewtonRaphson()) @@ -189,10 +191,10 @@ sys = structural_simplify(sys′) D = Differential(t) eqs = [D(E) ~ k₋₁ * C - k₁ * E * S - D(C) ~ k₁ * E * S - k₋₁ * C - k₂ * C - D(S) ~ k₋₁ * C - k₁ * E * S - D(P) ~ k₂ * C - E₀ ~ E + C] + D(C) ~ k₁ * E * S - k₋₁ * C - k₂ * C + D(S) ~ k₋₁ * C - k₁ * E * S + D(P) ~ k₂ * C + E₀ ~ E + C] @named sys = ODESystem(eqs, t, [E, C, S, P], [k₁, k₂, k₋₁, E₀]) @test_throws ModelingToolkit.ExtraEquationsSystemException structural_simplify(sys) @@ -203,8 +205,8 @@ params = collect(@parameters y1(t) y2(t)) sts = collect(@variables x(t) u1(t) u2(t)) D = Differential(t) eqs = [0 ~ x + sin(u1 + u2) - D(x) ~ x + y1 - cos(x) ~ sin(y2)] + D(x) ~ x + y1 + cos(x) ~ sin(y2)] @named sys = ODESystem(eqs, t, sts, params) @test_throws ModelingToolkit.InvalidSystemException structural_simplify(sys) @@ -214,15 +216,15 @@ D = Differential(t) @variables v47(t) v57(t) v66(t) v25(t) i74(t) i75(t) i64(t) i71(t) v1(t) v2(t) eq = [v47 ~ v1 - v47 ~ sin(10t) - v57 ~ v1 - v2 - v57 ~ 10.0i64 - v66 ~ v2 - v66 ~ 5.0i74 - v25 ~ v2 - i75 ~ 0.005 * D(v25) - 0 ~ i74 + i75 - i64 - 0 ~ i64 + i71] + v47 ~ sin(10t) + v57 ~ v1 - v2 + v57 ~ 10.0i64 + v66 ~ v2 + v66 ~ 5.0i74 + v25 ~ v2 + i75 ~ 0.005 * D(v25) + 0 ~ i74 + i75 - i64 + 0 ~ i64 + i71] @named sys0 = ODESystem(eq, t) sys = structural_simplify(sys0) @@ -239,9 +241,9 @@ dvv = ModelingToolkit.value(ModelingToolkit.derivative(eq.rhs, vv)) D = Differential(t) eqs = [D(x) ~ σ * (y - x) - D(y) ~ x * (ρ - z) - y + β - 0 ~ a + z - u ~ z + a] + D(y) ~ x * (ρ - z) - y + β + 0 ~ a + z + u ~ z + a] lorenz1 = ODESystem(eqs, t, name = :lorenz1) lorenz1_reduced = structural_simplify(lorenz1) @@ -252,8 +254,8 @@ lorenz1_reduced = structural_simplify(lorenz1) vars = @variables x(t) y(t) z(t) D = Differential(t) eqs = [D(x) ~ x - D(y) ~ y - D(z) ~ t] + D(y) ~ y + D(z) ~ t] @named model = ODESystem(eqs) sys = structural_simplify(model) Js = ModelingToolkit.jacobian_sparsity(sys) @@ -264,8 +266,8 @@ Js = ModelingToolkit.jacobian_sparsity(sys) @variables t vars = @variables a(t) w(t) phi(t) eqs = [a ~ D(w) - w ~ D(phi) - w ~ sin(t)] + w ~ D(phi) + w ~ sin(t)] @named sys = ODESystem(eqs, t, vars, []) ss = alias_elimination(sys) @test isempty(observed(ss)) @@ -288,13 +290,13 @@ new_sys = alias_elimination(sys) @test isempty(observed(new_sys)) eqs = [x ~ 0 - D(x) ~ x + y] + D(x) ~ x + y] @named sys = ODESystem(eqs, t, [x, y], []) ss = structural_simplify(sys) @test isempty(equations(ss)) @test sort(string.(observed(ss))) == ["x(t) ~ 0.0" - "xˍt(t) ~ 0.0" - "y(t) ~ xˍt(t) - x(t)"] + "xˍt(t) ~ 0.0" + "y(t) ~ xˍt(t) - x(t)"] eqs = [D(D(x)) ~ -x] @named sys = ODESystem(eqs, t, [x], []) diff --git a/test/sdesystem.jl b/test/sdesystem.jl index a520a9d58e..ac1a0339e7 100644 --- a/test/sdesystem.jl +++ b/test/sdesystem.jl @@ -39,20 +39,20 @@ solexpr = solve(eval(probexpr), SRIW1(), seed = 1) @test SDEProblem(de, nothing).tspan == (0.0, 10.0) noiseeqs_nd = [0.01*x 0.01*x*y 0.02*x*z - σ 0.01*y 0.02*x*z - ρ β 0.01*z] + σ 0.01*y 0.02*x*z + ρ β 0.01*z] @named de = SDESystem(eqs, noiseeqs_nd, t, [x, y, z], [σ, ρ, β]) f = eval(generate_diffusion_function(de)[1]) @test f([1, 2, 3.0], [0.1, 0.2, 0.3], nothing) == [0.01*1 0.01*1*2 0.02*1*3 - 0.1 0.01*2 0.02*1*3 - 0.2 0.3 0.01*3] + 0.1 0.01*2 0.02*1*3 + 0.2 0.3 0.01*3] f = eval(generate_diffusion_function(de)[2]) du = ones(3, 3) f(du, [1, 2, 3.0], [0.1, 0.2, 0.3], nothing) @test du == [0.01*1 0.01*1*2 0.02*1*3 - 0.1 0.01*2 0.02*1*3 - 0.2 0.3 0.01*3] + 0.1 0.01*2 0.02*1*3 + 0.2 0.3 0.01*3] f = SDEFunction(de) prob = SDEProblem(SDEFunction(de), [1.0, 0.0, 0.0], (0.0, 100.0), (10.0, 26.0, 2.33), @@ -62,13 +62,13 @@ sol = solve(prob, EM(), dt = 0.001) u0map = [ x => 1.0, y => 0.0, - z => 0.0, + z => 0.0 ] parammap = [ σ => 10.0, β => 26.0, - ρ => 2.33, + ρ => 2.33 ] prob = SDEProblem(de, u0map, (0.0, 100.0), parammap) @@ -320,7 +320,7 @@ fdrift = eval(generate_function(sys)[1]) fdif = eval(generate_diffusion_function(sys)[1]) @test fdrift(u0, p, t) == p[1] * u0 @test fdif(u0, p, t) == [p[2]*u0[1] p[3]*u0[1] - p[4]*u0[1] p[5]*u0[2]] + p[4]*u0[1] p[5]*u0[2]] fdrift! = eval(generate_function(sys)[2]) fdif! = eval(generate_diffusion_function(sys)[2]) du = similar(u0) @@ -329,7 +329,7 @@ fdrift!(du, u0, p, t) du = similar(u0, size(prob.noise_rate_prototype)) fdif!(du, u0, p, t) @test du == [p[2]*u0[1] p[3]*u0[1] - p[4]*u0[1] p[5]*u0[2]] + p[4]*u0[1] p[5]*u0[2]] # Ito -> Strat sys2 = stochastic_integral_transform(sys, -1 // 2) @@ -337,22 +337,22 @@ fdrift = eval(generate_function(sys2)[1]) fdif = eval(generate_diffusion_function(sys2)[1]) @test fdrift(u0, p, t) ≈ [ p[1] * u0[1] - 1 // 2 * (p[2]^2 * u0[1] + p[3]^2 * u0[1]), - p[1] * u0[2] - 1 // 2 * (p[2] * p[4] * u0[1] + p[5]^2 * u0[2]), + p[1] * u0[2] - 1 // 2 * (p[2] * p[4] * u0[1] + p[5]^2 * u0[2]) ] @test fdif(u0, p, t) == [p[2]*u0[1] p[3]*u0[1] - p[4]*u0[1] p[5]*u0[2]] + p[4]*u0[1] p[5]*u0[2]] fdrift! = eval(generate_function(sys2)[2]) fdif! = eval(generate_diffusion_function(sys2)[2]) du = similar(u0) fdrift!(du, u0, p, t) @test du ≈ [ p[1] * u0[1] - 1 // 2 * (p[2]^2 * u0[1] + p[3]^2 * u0[1]), - p[1] * u0[2] - 1 // 2 * (p[2] * p[4] * u0[1] + p[5]^2 * u0[2]), + p[1] * u0[2] - 1 // 2 * (p[2] * p[4] * u0[1] + p[5]^2 * u0[2]) ] du = similar(u0, size(prob.noise_rate_prototype)) fdif!(du, u0, p, t) @test du == [p[2]*u0[1] p[3]*u0[1] - p[4]*u0[1] p[5]*u0[2]] + p[4]*u0[1] p[5]*u0[2]] # Strat -> Ito sys2 = stochastic_integral_transform(sys, 1 // 2) @@ -360,22 +360,22 @@ fdrift = eval(generate_function(sys2)[1]) fdif = eval(generate_diffusion_function(sys2)[1]) @test fdrift(u0, p, t) ≈ [ p[1] * u0[1] + 1 // 2 * (p[2]^2 * u0[1] + p[3]^2 * u0[1]), - p[1] * u0[2] + 1 // 2 * (p[2] * p[4] * u0[1] + p[5]^2 * u0[2]), + p[1] * u0[2] + 1 // 2 * (p[2] * p[4] * u0[1] + p[5]^2 * u0[2]) ] @test fdif(u0, p, t) == [p[2]*u0[1] p[3]*u0[1] - p[4]*u0[1] p[5]*u0[2]] + p[4]*u0[1] p[5]*u0[2]] fdrift! = eval(generate_function(sys2)[2]) fdif! = eval(generate_diffusion_function(sys2)[2]) du = similar(u0) fdrift!(du, u0, p, t) @test du ≈ [ p[1] * u0[1] + 1 // 2 * (p[2]^2 * u0[1] + p[3]^2 * u0[1]), - p[1] * u0[2] + 1 // 2 * (p[2] * p[4] * u0[1] + p[5]^2 * u0[2]), + p[1] * u0[2] + 1 // 2 * (p[2] * p[4] * u0[1] + p[5]^2 * u0[2]) ] du = similar(u0, size(prob.noise_rate_prototype)) fdif!(du, u0, p, t) @test du == [p[2]*u0[1] p[3]*u0[1] - p[4]*u0[1] p[5]*u0[2]] + p[4]*u0[1] p[5]*u0[2]] # non-diagonal noise: Torus -- Strat and Ito are identical u0 = rand(2) @@ -402,7 +402,7 @@ fdif = eval(generate_diffusion_function(sys)[1]) @test fdrift(u0, p, t) == 0 * u0 @test fdif(u0, p, t) == [cos(p[1])*sin(u0[1]) cos(p[1])*cos(u0[1]) -sin(p[1])*sin(u0[2]) -sin(p[1])*cos(u0[2]) - sin(p[1])*sin(u0[1]) sin(p[1])*cos(u0[1]) cos(p[1])*sin(u0[2]) cos(p[1])*cos(u0[2])] + sin(p[1])*sin(u0[1]) sin(p[1])*cos(u0[1]) cos(p[1])*sin(u0[2]) cos(p[1])*cos(u0[2])] fdrift! = eval(generate_function(sys)[2]) fdif! = eval(generate_diffusion_function(sys)[2]) du = similar(u0) @@ -412,7 +412,7 @@ du = similar(u0, size(prob.noise_rate_prototype)) fdif!(du, u0, p, t) @test du == [cos(p[1])*sin(u0[1]) cos(p[1])*cos(u0[1]) -sin(p[1])*sin(u0[2]) -sin(p[1])*cos(u0[2]) - sin(p[1])*sin(u0[1]) sin(p[1])*cos(u0[1]) cos(p[1])*sin(u0[2]) cos(p[1])*cos(u0[2])] + sin(p[1])*sin(u0[1]) sin(p[1])*cos(u0[1]) cos(p[1])*sin(u0[2]) cos(p[1])*cos(u0[2])] # Ito -> Strat sys2 = stochastic_integral_transform(sys, -1 // 2) @@ -421,7 +421,7 @@ fdif = eval(generate_diffusion_function(sys2)[1]) @test fdrift(u0, p, t) == 0 * u0 @test fdif(u0, p, t) == [cos(p[1])*sin(u0[1]) cos(p[1])*cos(u0[1]) -sin(p[1])*sin(u0[2]) -sin(p[1])*cos(u0[2]) - sin(p[1])*sin(u0[1]) sin(p[1])*cos(u0[1]) cos(p[1])*sin(u0[2]) cos(p[1])*cos(u0[2])] + sin(p[1])*sin(u0[1]) sin(p[1])*cos(u0[1]) cos(p[1])*sin(u0[2]) cos(p[1])*cos(u0[2])] fdrift! = eval(generate_function(sys2)[2]) fdif! = eval(generate_diffusion_function(sys2)[2]) du = similar(u0) @@ -431,7 +431,7 @@ du = similar(u0, size(prob.noise_rate_prototype)) fdif!(du, u0, p, t) @test du == [cos(p[1])*sin(u0[1]) cos(p[1])*cos(u0[1]) -sin(p[1])*sin(u0[2]) -sin(p[1])*cos(u0[2]) - sin(p[1])*sin(u0[1]) sin(p[1])*cos(u0[1]) cos(p[1])*sin(u0[2]) cos(p[1])*cos(u0[2])] + sin(p[1])*sin(u0[1]) sin(p[1])*cos(u0[1]) cos(p[1])*sin(u0[2]) cos(p[1])*cos(u0[2])] # Strat -> Ito sys2 = stochastic_integral_transform(sys, 1 // 2) @@ -440,7 +440,7 @@ fdif = eval(generate_diffusion_function(sys2)[1]) @test fdrift(u0, p, t) == 0 * u0 @test fdif(u0, p, t) == [cos(p[1])*sin(u0[1]) cos(p[1])*cos(u0[1]) -sin(p[1])*sin(u0[2]) -sin(p[1])*cos(u0[2]) - sin(p[1])*sin(u0[1]) sin(p[1])*cos(u0[1]) cos(p[1])*sin(u0[2]) cos(p[1])*cos(u0[2])] + sin(p[1])*sin(u0[1]) sin(p[1])*cos(u0[1]) cos(p[1])*sin(u0[2]) cos(p[1])*cos(u0[2])] fdrift! = eval(generate_function(sys2)[2]) fdif! = eval(generate_diffusion_function(sys2)[2]) du = similar(u0) @@ -450,13 +450,13 @@ du = similar(u0, size(prob.noise_rate_prototype)) fdif!(du, u0, p, t) @test du == [cos(p[1])*sin(u0[1]) cos(p[1])*cos(u0[1]) -sin(p[1])*sin(u0[2]) -sin(p[1])*cos(u0[2]) - sin(p[1])*sin(u0[1]) sin(p[1])*cos(u0[1]) cos(p[1])*sin(u0[2]) cos(p[1])*cos(u0[2])] + sin(p[1])*sin(u0[1]) sin(p[1])*cos(u0[1]) cos(p[1])*sin(u0[2]) cos(p[1])*cos(u0[2])] # issue #819 @testset "Combined system name collisions" begin @variables t eqs_short = [D(x) ~ σ * (y - x), - D(y) ~ x * (ρ - z) - y, + D(y) ~ x * (ρ - z) - y ] sys1 = SDESystem(eqs_short, noiseeqs, t, [x, y, z], [σ, ρ, β], name = :sys1) sys2 = SDESystem(eqs_short, noiseeqs, t, [x, y, z], [σ, ρ, β], name = :sys1) @@ -495,12 +495,12 @@ noiseeqs = [0.1 * x] x0 = 0.1 u0map = [ - x => x0, + x => x0 ] parammap = [ α => 1.5, - β => 1.0, + β => 1.0 ] @named de = SDESystem(eqs, noiseeqs, t, [x], [α, β], observed = [weight ~ x * 10]) @@ -536,12 +536,12 @@ end ## Standard approach # EM with 1`000 trajectories for stepsize 2^-7 u0map = [ - x => x0, + x => x0 ] parammap = [ α => 1.5, - β => 1.0, + β => 1.0 ] prob = SDEProblem(de, u0map, (0.0, 1.0), parammap) @@ -605,8 +605,8 @@ drift_eqs = [D(x) ~ σ * (y - x), D(z) ~ x * y] diffusion_eqs = [s*x 0 - s*y s*x - (s * x * z)-s * z 0] + s*y s*x + (s * x * z)-s * z 0] sys2 = SDESystem(drift_eqs, diffusion_eqs, t, sts, ps, name = :sys1) @test sys1 == sys2 diff --git a/test/serialization.jl b/test/serialization.jl index 79f6f34bdf..d8ce32feae 100644 --- a/test/serialization.jl +++ b/test/serialization.jl @@ -9,7 +9,7 @@ for prob in [ eval(ModelingToolkit.ODEProblem{false}(sys, nothing, nothing, SciMLBase.NullParameters())), eval(ModelingToolkit.ODEProblemExpr{false}(sys, nothing, nothing, - SciMLBase.NullParameters())), + SciMLBase.NullParameters())) ] _fn = tempname() diff --git a/test/split_parameters.jl b/test/split_parameters.jl index d37b9e2c13..ffbd88fe33 100644 --- a/test/split_parameters.jl +++ b/test/split_parameters.jl @@ -50,7 +50,7 @@ function Sampled(; name, data = Float64[], dt = 0.0) end eqs = [ - output.u ~ get_value(data, t, dt), + output.u ~ get_value(data, t, dt) ] return ODESystem(eqs, t, vars, pars; name, systems, @@ -62,9 +62,9 @@ vars = @variables y(t)=1 dy(t)=0 ddy(t)=0 @named int = Integrator() eqs = [y ~ src.output.u - D(y) ~ dy - D(dy) ~ ddy - connect(src.output, int.input)] + D(y) ~ dy + D(dy) ~ ddy + connect(src.output, int.input)] @named sys = ODESystem(eqs, t, vars, []; systems = [int, src]) s = complete(sys) @@ -93,8 +93,8 @@ prob′′ = remake(prob; p = [s.src.data => x]) vars = @variables y(t)=1 dy(t)=0 ddy(t)=0 pars = @parameters a=1.0 b=2.0 c=3 eqs = [D(y) ~ dy * a - D(dy) ~ ddy * b - ddy ~ sin(t) * c] + D(dy) ~ ddy * b + ddy ~ sin(t) * c] @named model = ODESystem(eqs, t, vars, pars) sys = structural_simplify(model) @@ -141,8 +141,8 @@ c = 3.0 # Damping coefficient function SystemModel(u = nothing; name = :model) eqs = [connect(torque.flange, inertia1.flange_a) - connect(inertia1.flange_b, spring.flange_a, damper.flange_a) - connect(inertia2.flange_a, spring.flange_b, damper.flange_b)] + connect(inertia1.flange_b, spring.flange_a, damper.flange_a) + connect(inertia2.flange_a, spring.flange_b, damper.flange_b)] if u !== nothing push!(eqs, connect(torque.tau, u.output)) return @named model = ODESystem(eqs, @@ -161,9 +161,9 @@ matrices, ssys = ModelingToolkit.linearize(wr(model), inputs, model_outputs) # Design state-feedback gain using LQR # Define cost matrices x_costs = [model.inertia1.w => 1.0 - model.inertia2.w => 1.0 - model.inertia1.phi => 1.0 - model.inertia2.phi => 1.0] + model.inertia2.w => 1.0 + model.inertia1.phi => 1.0 + model.inertia2.phi => 1.0] L = randn(1, 4) # Post-multiply by `C` to get the correct input to the controller # This old definition of MatrixGain will work because the parameter space does not include K (an Array term) @@ -179,8 +179,8 @@ L = randn(1, 4) # Post-multiply by `C` to get the correct input to the controlle @named add = Add(; k1 = 1.0, k2 = 1.0) # To add the control signal and the disturbance connections = [[state_feedback.input.u[i] ~ model_outputs[i] for i in 1:4] - connect(d.output, :d, add.input1) - connect(add.input2, state_feedback.output) - connect(add.output, :u, model.torque.tau)] + connect(d.output, :d, add.input1) + connect(add.input2, state_feedback.output) + connect(add.output, :u, model.torque.tau)] @named closed_loop = ODESystem(connections, t, systems = [model, state_feedback, add, d]) S = get_sensitivity(closed_loop, :u) diff --git a/test/state_selection.jl b/test/state_selection.jl index 0fb08100b1..59d23af668 100644 --- a/test/state_selection.jl +++ b/test/state_selection.jl @@ -5,9 +5,9 @@ sts = @variables x1(t) x2(t) x3(t) x4(t) params = @parameters u1(t) u2(t) u3(t) u4(t) D = Differential(t) eqs = [x1 + x2 + u1 ~ 0 - x1 + x2 + x3 + u2 ~ 0 - x1 + D(x3) + x4 + u3 ~ 0 - 2 * D(D(x1)) + D(D(x2)) + D(D(x3)) + D(x4) + u4 ~ 0] + x1 + x2 + x3 + u2 ~ 0 + x1 + D(x3) + x4 + u3 ~ 0 + 2 * D(D(x1)) + D(D(x2)) + D(D(x3)) + D(x4) + u4 ~ 0] @named sys = ODESystem(eqs, t) let dd = dummy_derivative(sys) @@ -32,10 +32,10 @@ end D = Differential(t) eqs = [D(x) ~ σ * (y - x) - D(y) ~ x * (ρ - z) - y + β - 0 ~ z - x + y - 0 ~ a + z - u ~ z + a] + D(y) ~ x * (ρ - z) - y + β + 0 ~ z - x + y + 0 ~ a + z + u ~ z + a] lorenz1 = ODESystem(eqs, t, name = :lorenz1) let al1 = alias_elimination(lorenz1) @@ -65,7 +65,7 @@ let @named fluid_port = Fluid_port() ps = @parameters p=p T_back=T_back eqs = [fluid_port.p ~ p - fluid_port.T ~ T_back] + fluid_port.T ~ T_back] compose(ODESystem(eqs, t, [], ps; name = name), fluid_port) end @@ -74,9 +74,9 @@ let @named return_port = Fluid_port() # expected to receive from connected pipe -> m>0 ps = @parameters delta_p=delta_p T_feed=T_feed eqs = [supply_port.m ~ -return_port.m - supply_port.p ~ return_port.p + delta_p - supply_port.T ~ instream(supply_port.T) - return_port.T ~ T_feed] + supply_port.p ~ return_port.p + delta_p + supply_port.T ~ instream(supply_port.T) + return_port.T ~ T_feed] compose(ODESystem(eqs, t, [], ps; name = name), [supply_port, return_port]) end @@ -85,9 +85,9 @@ let @named return_port = Fluid_port() # expected to feed connected pipe -> m<0 ps = @parameters T_return = T_return eqs = [supply_port.m ~ -return_port.m - supply_port.p ~ return_port.p # zero pressure loss for now - supply_port.T ~ instream(supply_port.T) - return_port.T ~ T_return] + supply_port.p ~ return_port.p # zero pressure loss for now + supply_port.T ~ instream(supply_port.T) + return_port.T ~ T_return] compose(ODESystem(eqs, t, [], ps; name = name), [supply_port, return_port]) end @@ -97,11 +97,11 @@ let ps = @parameters L=L d=d rho=rho f=f N=N sts = @variables v(t)=0.0 dp_z(t)=0.0 eqs = [fluid_port_a.m ~ -fluid_port_b.m - fluid_port_a.T ~ instream(fluid_port_a.T) - fluid_port_b.T ~ fluid_port_a.T - v * pi * d^2 / 4 * rho ~ fluid_port_a.m - dp_z ~ abs(v) * v * 0.5 * rho * L / d * f # pressure loss - D(v) * rho * L ~ (fluid_port_a.p - fluid_port_b.p - dp_z)] + fluid_port_a.T ~ instream(fluid_port_a.T) + fluid_port_b.T ~ fluid_port_a.T + v * pi * d^2 / 4 * rho ~ fluid_port_a.m + dp_z ~ abs(v) * v * 0.5 * rho * L / d * f # pressure loss + D(v) * rho * L ~ (fluid_port_a.p - fluid_port_b.p - dp_z)] compose(ODESystem(eqs, t, sts, ps; name = name), [fluid_port_a, fluid_port_b]) end function System(; name, L = 10.0) @@ -113,17 +113,18 @@ let subs = [compensator, source, substation, supply_pipe, return_pipe] ps = @parameters L = L eqs = [connect(compensator.fluid_port, source.supply_port) - connect(source.supply_port, supply_pipe.fluid_port_a) - connect(supply_pipe.fluid_port_b, substation.supply_port) - connect(substation.return_port, return_pipe.fluid_port_b) - connect(return_pipe.fluid_port_a, source.return_port)] + connect(source.supply_port, supply_pipe.fluid_port_a) + connect(supply_pipe.fluid_port_b, substation.supply_port) + connect(substation.return_port, return_pipe.fluid_port_b) + connect(return_pipe.fluid_port_a, source.return_port)] compose(ODESystem(eqs, t, [], ps; name = name), subs) end @named system = System(L = 10) @unpack supply_pipe, return_pipe = system sys = structural_simplify(system) - u0 = [system.supply_pipe.v => 0.1, system.return_pipe.v => 0.1, D(supply_pipe.v) => 0.0, + u0 = [ + system.supply_pipe.v => 0.1, system.return_pipe.v => 0.1, D(supply_pipe.v) => 0.0, D(return_pipe.fluid_port_a.m) => 0.0, D(supply_pipe.fluid_port_a.m) => 0.0] prob1 = ODEProblem(sys, u0, (0.0, 10.0), []) @@ -159,19 +160,19 @@ let D = Differential(t) eqs = [p_1 ~ 1.2e5 - p_2 ~ 1e5 - u_1 ~ 10 - mo_1 ~ u_1 * rho_1 - mo_2 ~ u_2 * rho_2 - mo_3 ~ u_3 * rho_3 - Ek_1 ~ rho_1 * u_1 * u_1 - Ek_2 ~ rho_2 * u_2 * u_2 - Ek_3 ~ rho_3 * u_3 * u_3 - rho_1 ~ p_1 / 273.11 / 300 - rho_2 ~ (p_1 + p_2) * 0.5 / 273.11 / 300 - rho_3 ~ p_2 / 273.11 / 300 - D(rho_2) ~ (mo_1 - mo_3) / dx - D(mo_2) ~ (Ek_1 - Ek_3 + p_1 - p_2) / dx - f / 2 / pipe_D * u_2 * u_2] + p_2 ~ 1e5 + u_1 ~ 10 + mo_1 ~ u_1 * rho_1 + mo_2 ~ u_2 * rho_2 + mo_3 ~ u_3 * rho_3 + Ek_1 ~ rho_1 * u_1 * u_1 + Ek_2 ~ rho_2 * u_2 * u_2 + Ek_3 ~ rho_3 * u_3 * u_3 + rho_1 ~ p_1 / 273.11 / 300 + rho_2 ~ (p_1 + p_2) * 0.5 / 273.11 / 300 + rho_3 ~ p_2 / 273.11 / 300 + D(rho_2) ~ (mo_1 - mo_3) / dx + D(mo_2) ~ (Ek_1 - Ek_3 + p_1 - p_2) / dx - f / 2 / pipe_D * u_2 * u_2] @named trans = ODESystem(eqs, t) @@ -182,17 +183,17 @@ let rho = 1.2 * ones(n) u0 = [p_1 => 1.2e5 - p_2 => 1e5 - u_1 => 0 - u_2 => 0.1 - u_3 => 0.2 - rho_1 => 1.1 - rho_2 => 1.2 - rho_3 => 1.3 - mo_1 => 0 - mo_2 => 1 - mo_3 => 2 - Ek_3 => 3] + p_2 => 1e5 + u_1 => 0 + u_2 => 0.1 + u_3 => 0.2 + rho_1 => 1.1 + rho_2 => 1.2 + rho_3 => 1.3 + mo_1 => 0 + mo_2 => 1 + mo_3 => 2 + Ek_3 => 3] prob1 = ODEProblem(sys, u0, (0.0, 0.1)) prob2 = ODAEProblem(sys, u0, (0.0, 0.1)) @test solve(prob1, FBDF()).retcode == ReturnCode.Success @@ -240,15 +241,15 @@ let D = Differential(t) defs = [p1 => p_1f_0 - p2 => p_2f_0 - rho1 => density * (1 + p_1f_0 / bulk) - rho2 => density * (1 + p_2f_0 / bulk) - V1 => l_1f * A_1f - V2 => l_2f * A_2f - D(p1) => dp1 - D(p2) => dp2 - D(w) => dw - D(dw) => ddw] + p2 => p_2f_0 + rho1 => density * (1 + p_1f_0 / bulk) + rho2 => density * (1 + p_2f_0 / bulk) + V1 => l_1f * A_1f + V2 => l_2f * A_2f + D(p1) => dp1 + D(p2) => dp2 + D(w) => dw + D(dw) => ddw] # equations ------------------------------------------------------------------ # sqrt -> log as a hack @@ -258,25 +259,25 @@ let Δp2 = p2 eqs = [+flow(xm, Δp1) ~ rho1 * dV1 + drho1 * V1 - 0 ~ IfElse.ifelse(w > 0.5, - (0) - (rho2 * dV2 + drho2 * V2), - (-flow(xm, Δp2)) - (rho2 * dV2 + drho2 * V2)) - V1 ~ (l_1f + w) * A_1f - V2 ~ (l_2f - w) * A_2f - dV1 ~ +dw * A_1f - dV2 ~ -dw * A_2f - rho1 ~ density * (1.0 + p1 / bulk) - rho2 ~ density * (1.0 + p2 / bulk) - drho1 ~ density * (dp1 / bulk) - drho2 ~ density * (dp2 / bulk) - D(p1) ~ dp1 - D(p2) ~ dp2 - D(w) ~ dw - D(dw) ~ ddw - xf ~ 20e-3 * (1 - cos(2 * π * 5 * t)) - 0 ~ IfElse.ifelse(w > 0.5, - (m_total * ddw) - (p1 * A_1f - p2 * A_2f - damp * dw), - (m_total * ddw) - (p1 * A_1f - p2 * A_2f))] + 0 ~ IfElse.ifelse(w > 0.5, + (0) - (rho2 * dV2 + drho2 * V2), + (-flow(xm, Δp2)) - (rho2 * dV2 + drho2 * V2)) + V1 ~ (l_1f + w) * A_1f + V2 ~ (l_2f - w) * A_2f + dV1 ~ +dw * A_1f + dV2 ~ -dw * A_2f + rho1 ~ density * (1.0 + p1 / bulk) + rho2 ~ density * (1.0 + p2 / bulk) + drho1 ~ density * (dp1 / bulk) + drho2 ~ density * (dp2 / bulk) + D(p1) ~ dp1 + D(p2) ~ dp2 + D(w) ~ dw + D(dw) ~ ddw + xf ~ 20e-3 * (1 - cos(2 * π * 5 * t)) + 0 ~ IfElse.ifelse(w > 0.5, + (m_total * ddw) - (p1 * A_1f - p2 * A_2f - damp * dw), + (m_total * ddw) - (p1 * A_1f - p2 * A_2f))] # ---------------------------------------------------------------------------- # solution ------------------------------------------------------------------- diff --git a/test/stream_connectors.jl b/test/stream_connectors.jl index 8a7facb09f..b14c2661be 100644 --- a/test/stream_connectors.jl +++ b/test/stream_connectors.jl @@ -124,13 +124,13 @@ end @named sink = MassFlowSource_h(m_flow_in = -0.01, h_in = 400e3) eqns = [connect(n1m1.port_a, pipe.port_a) - connect(pipe.port_b, sink.port)] + connect(pipe.port_b, sink.port)] @named sys = ODESystem(eqns, t) eqns = [domain_connect(fluid, n1m1.port_a) - connect(n1m1.port_a, pipe.port_a) - connect(pipe.port_b, sink.port)] + connect(n1m1.port_a, pipe.port_a) + connect(pipe.port_b, sink.port)] @named n1m1Test = ODESystem(eqns, t, [], []; systems = [fluid, n1m1, pipe, sink]) @@ -138,42 +138,42 @@ eqns = [domain_connect(fluid, n1m1.port_a) @unpack source, port_a = n1m1 ssort(eqs) = sort(eqs, by = string) @test ssort(equations(expand_connections(n1m1))) == ssort([0 ~ port_a.m_flow - 0 ~ source.port1.m_flow - port_a.m_flow - source.port1.P ~ port_a.P - source.port1.P ~ source.P - source.port1.h_outflow ~ port_a.h_outflow - source.port1.h_outflow ~ source.h]) + 0 ~ source.port1.m_flow - port_a.m_flow + source.port1.P ~ port_a.P + source.port1.P ~ source.P + source.port1.h_outflow ~ port_a.h_outflow + source.port1.h_outflow ~ source.h]) @unpack port_a, port_b = pipe @test ssort(equations(expand_connections(pipe))) == ssort([0 ~ -port_a.m_flow - port_b.m_flow - 0 ~ port_a.m_flow - 0 ~ port_b.m_flow - port_a.P ~ port_b.P - port_a.h_outflow ~ instream(port_b.h_outflow) - port_b.h_outflow ~ instream(port_a.h_outflow)]) + 0 ~ port_a.m_flow + 0 ~ port_b.m_flow + port_a.P ~ port_b.P + port_a.h_outflow ~ instream(port_b.h_outflow) + port_b.h_outflow ~ instream(port_a.h_outflow)]) @test ssort(equations(expand_connections(sys))) == ssort([0 ~ n1m1.port_a.m_flow + pipe.port_a.m_flow - 0 ~ pipe.port_b.m_flow + sink.port.m_flow - n1m1.port_a.P ~ pipe.port_a.P - pipe.port_b.P ~ sink.port.P]) + 0 ~ pipe.port_b.m_flow + sink.port.m_flow + n1m1.port_a.P ~ pipe.port_a.P + pipe.port_b.P ~ sink.port.P]) @test ssort(equations(expand_connections(n1m1Test))) == ssort([0 ~ -pipe.port_a.m_flow - pipe.port_b.m_flow - 0 ~ n1m1.source.port1.m_flow - n1m1.port_a.m_flow - 0 ~ n1m1.port_a.m_flow + pipe.port_a.m_flow - 0 ~ pipe.port_b.m_flow + sink.port.m_flow - fluid.m_flow ~ 0 - n1m1.port_a.P ~ pipe.port_a.P - n1m1.source.port1.P ~ n1m1.port_a.P - n1m1.source.port1.P ~ n1m1.source.P - n1m1.source.port1.h_outflow ~ n1m1.port_a.h_outflow - n1m1.source.port1.h_outflow ~ n1m1.source.h - pipe.port_a.P ~ pipe.port_b.P - pipe.port_a.h_outflow ~ sink.port.h_outflow - pipe.port_b.P ~ sink.port.P - pipe.port_b.h_outflow ~ n1m1.port_a.h_outflow - sink.port.P ~ sink.P - sink.port.h_outflow ~ sink.h_in - sink.port.m_flow ~ -sink.m_flow_in]) + 0 ~ n1m1.source.port1.m_flow - n1m1.port_a.m_flow + 0 ~ n1m1.port_a.m_flow + pipe.port_a.m_flow + 0 ~ pipe.port_b.m_flow + sink.port.m_flow + fluid.m_flow ~ 0 + n1m1.port_a.P ~ pipe.port_a.P + n1m1.source.port1.P ~ n1m1.port_a.P + n1m1.source.port1.P ~ n1m1.source.P + n1m1.source.port1.h_outflow ~ n1m1.port_a.h_outflow + n1m1.source.port1.h_outflow ~ n1m1.source.h + pipe.port_a.P ~ pipe.port_b.P + pipe.port_a.h_outflow ~ sink.port.h_outflow + pipe.port_b.P ~ sink.port.P + pipe.port_b.h_outflow ~ n1m1.port_a.h_outflow + sink.port.P ~ sink.P + sink.port.h_outflow ~ sink.h_in + sink.port.m_flow ~ -sink.m_flow_in]) # N1M2 model and test code. function N1M2(; name, @@ -201,7 +201,7 @@ end @named sink2 = MassFlowSource_h(m_flow_in = -0.01, h_in = 400e3) eqns = [connect(n1m2.port_a, sink1.port) - connect(n1m2.port_b, sink2.port)] + connect(n1m2.port_b, sink2.port)] @named sys = ODESystem(eqns, t) @named n1m2Test = compose(sys, n1m2, sink1, sink2) @@ -214,9 +214,9 @@ eqns = [connect(n1m2.port_a, sink1.port) @named sink2 = MassFlowSource_h(m_flow_in = -0.01, h_in = 400e3) eqns = [connect(n1m2.port_a, pipe1.port_a) - connect(pipe1.port_b, sink1.port) - connect(n1m2.port_b, pipe2.port_a) - connect(pipe2.port_b, sink2.port)] + connect(pipe1.port_b, sink1.port) + connect(n1m2.port_b, pipe2.port_a) + connect(pipe2.port_b, sink2.port)] @named sys = ODESystem(eqns, t) @named n1m2AltTest = compose(sys, n1m2, pipe1, pipe2, sink1, sink2) @@ -245,7 +245,7 @@ end @named sink = SmallBoundary_Ph(P_in = 1e6, h_in = 400e3) eqns = [connect(source.port, n2m2.port_a) - connect(n2m2.port_b, sink.port1)] + connect(n2m2.port_b, sink.port1)] @named sys = ODESystem(eqns, t) @named n2m2Test = compose(sys, n2m2, source, sink) @@ -257,11 +257,11 @@ eqns = [connect(source.port, n2m2.port_a) @named sys = ODESystem([connect(sp1, sp2)], t) sys_exp = expand_connections(compose(sys, [sp1, sp2])) @test ssort(equations(sys_exp)) == ssort([0 ~ -sp1.m_flow - sp2.m_flow - 0 ~ sp1.m_flow - 0 ~ sp2.m_flow - sp1.P ~ sp2.P - sp1.h_outflow ~ ModelingToolkit.instream(sp2.h_outflow) - sp2.h_outflow ~ ModelingToolkit.instream(sp1.h_outflow)]) + 0 ~ sp1.m_flow + 0 ~ sp2.m_flow + sp1.P ~ sp2.P + sp1.h_outflow ~ ModelingToolkit.instream(sp2.h_outflow) + sp2.h_outflow ~ ModelingToolkit.instream(sp1.h_outflow)]) # array var @connector function VecPin(; name) @@ -276,14 +276,14 @@ end @named simple = ODESystem([connect(vp1, vp2, vp3)], t) sys = expand_connections(compose(simple, [vp1, vp2, vp3])) @test ssort(equations(sys)) == ssort([0 .~ collect(vp1.i) - 0 .~ collect(vp2.i) - 0 .~ collect(vp3.i) - vp1.v[1] ~ vp2.v[1] - vp1.v[2] ~ vp2.v[2] - vp1.v[1] ~ vp3.v[1] - vp1.v[2] ~ vp3.v[2] - 0 ~ -vp1.i[1] - vp2.i[1] - vp3.i[1] - 0 ~ -vp1.i[2] - vp2.i[2] - vp3.i[2]]) + 0 .~ collect(vp2.i) + 0 .~ collect(vp3.i) + vp1.v[1] ~ vp2.v[1] + vp1.v[2] ~ vp2.v[2] + vp1.v[1] ~ vp3.v[1] + vp1.v[2] ~ vp3.v[2] + 0 ~ -vp1.i[1] - vp2.i[1] - vp3.i[1] + 0 ~ -vp1.i[2] - vp2.i[2] - vp3.i[2]]) @connector function VectorHeatPort(; name, N = 100, T0 = 0.0, Q0 = 0.0) @variables (T(t))[1:N]=T0 (Q(t))[1:N]=Q0 [connect = Flow] @@ -335,7 +335,7 @@ end # equations --------------------------- eqs = [ - dm ~ 0, + dm ~ 0 ] ODESystem(eqs, t, vars, pars; name) @@ -355,7 +355,7 @@ function StepSource(; P, name) # equations --------------------------- eqs = [ - H.p ~ p_int * (t > 0.01), + H.p ~ p_int * (t > 0.01) ] ODESystem(eqs, t, vars, pars; name, systems) @@ -385,9 +385,9 @@ function StaticVolume(; P, V, name) # equations --------------------------- eqs = [D(vrho) ~ drho - vrho ~ rho_0 * (1 + p / H.bulk) - H.p ~ p - H.dm ~ drho * V] + vrho ~ rho_0 * (1 + p / H.bulk) + H.p ~ p + H.dm ~ drho * V] ODESystem(eqs, t, vars, pars; name, systems, defaults = [vrho => rho_0 * (1 + p_int / H.bulk)]) @@ -409,8 +409,8 @@ function PipeBase(; P, R, name) # equations --------------------------- eqs = [HA.p - HB.p ~ HA.dm * resistance / HA.viscosity - 0 ~ HA.dm + HB.dm - domain_connect(HA, HB)] + 0 ~ HA.dm + HB.dm + domain_connect(HA, HB)] ODESystem(eqs, t, vars, pars; name, systems) end @@ -432,7 +432,7 @@ function Pipe(; P, R, name) end eqs = [connect(v1.H, p12.HA, HA) - connect(v2.H, p12.HB, HB)] + connect(v2.H, p12.HB, HB)] ODESystem(eqs, t, vars, pars; name, systems) end @@ -456,11 +456,11 @@ function TwoFluidSystem(; name) # equations --------------------------- eqs = [connect(fluid_a, source_a.H) - connect(source_a.H, pipe_a.HA) - connect(pipe_a.HB, volume_a.H) - connect(fluid_b, source_b.H) - connect(source_b.H, pipe_b.HA) - connect(pipe_b.HB, volume_b.H)] + connect(source_a.H, pipe_a.HA) + connect(pipe_a.HB, volume_a.H) + connect(fluid_b, source_b.H) + connect(source_b.H, pipe_b.HA) + connect(pipe_b.HB, volume_b.H)] ODESystem(eqs, t, vars, pars; name, systems) end @@ -495,10 +495,10 @@ function OneFluidSystem(; name) # equations --------------------------- eqs = [connect(fluid, source_a.H, source_b.H) - connect(source_a.H, pipe_a.HA) - connect(pipe_a.HB, volume_a.H) - connect(source_b.H, pipe_b.HA) - connect(pipe_b.HB, volume_b.H)] + connect(source_a.H, pipe_a.HA) + connect(pipe_a.HB, volume_a.H) + connect(source_b.H, pipe_b.HA) + connect(pipe_b.HB, volume_b.H)] ODESystem(eqs, t, vars, pars; name, systems) end diff --git a/test/structural_transformation/index_reduction.jl b/test/structural_transformation/index_reduction.jl index e6f7534e58..2ce2fd0bf4 100644 --- a/test/structural_transformation/index_reduction.jl +++ b/test/structural_transformation/index_reduction.jl @@ -105,12 +105,12 @@ u0 = [ D(y) => 0.0, x => 1.0, y => 0.0, - T => 0.0, + T => 0.0 ] p = [ L => 1.0, - g => 9.8, + g => 9.8 ] prob_auto = ODEProblem(new_sys, u0, (0.0, 10.0), p) @@ -144,11 +144,11 @@ let sys = structural_simplify(pendulum2) D(D(y)) => 0.0, x => sqrt(2) / 2, y => sqrt(2) / 2, - T => 0.0, + T => 0.0 ] p = [ L => 1.0, - g => 9.8, + g => 9.8 ] prob_auto = ODEProblem(sys, u0, (0.0, 0.5), p) diff --git a/test/structural_transformation/tearing.jl b/test/structural_transformation/tearing.jl index b2e4b846d6..4165c6df37 100644 --- a/test/structural_transformation/tearing.jl +++ b/test/structural_transformation/tearing.jl @@ -17,7 +17,7 @@ eqs = [ 0 ~ u2 - cos(u1), 0 ~ u3 - hypot(u1, u2), 0 ~ u4 - hypot(u2, u3), - 0 ~ u5 - hypot(u4, u1), + 0 ~ u5 - hypot(u4, u1) ] @named sys = NonlinearSystem(eqs, [u1, u2, u3, u4, u5], []) state = TearingState(sys) @@ -49,15 +49,15 @@ find_solvables!(state) int2var = Dict(eachindex(fullvars) .=> fullvars) graph2vars(graph) = map(is -> Set(map(i -> int2var[i], is)), graph.fadjlist) @test graph2vars(graph) == [Set([u1, u5]) - Set([u1, u2]) - Set([u1, u3, u2]) - Set([u4, u3, u2]) - Set([u4, u1, u5])] + Set([u1, u2]) + Set([u1, u3, u2]) + Set([u4, u3, u2]) + Set([u4, u1, u5])] @test graph2vars(solvable_graph) == [Set([u1]) - Set([u2]) - Set([u3]) - Set([u4]) - Set([u5])] + Set([u2]) + Set([u3]) + Set([u4]) + Set([u5])] state = TearingState(tearing(sys)) let sss = state.structure @@ -102,10 +102,10 @@ let state = TearingState(sys) torn_matching = tearing(state) S = StructuralTransformations.reordered_matrix(sys, torn_matching) @test S == [1 0 0 0 1 - 1 1 0 0 0 - 1 1 1 0 0 - 0 1 1 1 0 - 1 0 0 1 1] + 1 1 0 0 0 + 1 1 1 0 0 + 0 1 1 1 0 + 1 0 0 1 1] end # unknowns: u5 @@ -133,7 +133,7 @@ sol = solve(prob, NewtonRaphson()) eqs = [ 0 ~ x - y, 0 ~ z + y, - 0 ~ x + z, + 0 ~ x + z ] @named nlsys = NonlinearSystem(eqs, [x, y, z], []) @@ -148,8 +148,8 @@ using ModelingToolkit, OrdinaryDiffEq, BenchmarkTools @variables x(t) y(t) z(t) D = Differential(t) eqs = [D(x) ~ z * h - 0 ~ x - y - 0 ~ sin(z) + y - p * t] + 0 ~ x - y + 0 ~ sin(z) + y - p * t] @named daesys = ODESystem(eqs, t) newdaesys = structural_simplify(daesys) @test equations(newdaesys) == [D(x) ~ z; 0 ~ y + sin(z) - p * t] @@ -173,7 +173,8 @@ sol1 = solve(prob, Tsit5()) sol2 = solve(ODEProblem{false}((u, p, t) -> [-asin(u[1] - pr * t)], [1.0], (0, 1.0), - 0.2), Tsit5(), tstops = sol1.t, adaptive = false) + 0.2), + Tsit5(), tstops = sol1.t, adaptive = false) @test Array(sol1)≈Array(sol2) atol=1e-5 @test sol1[x] == first.(sol1.u) @@ -190,8 +191,8 @@ function Translational_Mass(; name, m = 1.0) ps = @parameters m = m D = Differential(t) eqs = [D(s) ~ v - D(v) ~ a - m * a ~ 0.0] + D(v) ~ a + m * a ~ 0.0] ODESystem(eqs, t, sts, ps; name = name) end @@ -209,7 +210,7 @@ calculate_tgrad(ms_model) # Mass starts with velocity = 1 u0 = [mass.s => 0.0 - mass.v => 1.0] + mass.v => 1.0] sys = structural_simplify(ms_model) @test ModelingToolkit.get_jac(sys)[] === ModelingToolkit.EMPTY_JAC diff --git a/test/symbolic_events.jl b/test/symbolic_events.jl index 4620fbaddb..1f97b474a8 100644 --- a/test/symbolic_events.jl +++ b/test/symbolic_events.jl @@ -1,7 +1,7 @@ using ModelingToolkit, OrdinaryDiffEq, StochasticDiffEq, JumpProcesses, Test using ModelingToolkit: SymbolicContinuousCallback, - SymbolicContinuousCallbacks, NULL_AFFECT, - get_callback + SymbolicContinuousCallbacks, NULL_AFFECT, + get_callback using StableRNGs rng = StableRNG(12345) @@ -128,7 +128,7 @@ fsys = flatten(sys) SymbolicContinuousCallback(Equation[x ~ 2], NULL_AFFECT) @test all(ModelingToolkit.continuous_events(sys2) .== [ SymbolicContinuousCallback(Equation[x ~ 2], NULL_AFFECT), - SymbolicContinuousCallback(Equation[sys.x ~ 1], NULL_AFFECT), + SymbolicContinuousCallback(Equation[sys.x ~ 1], NULL_AFFECT) ]) @test isequal(equations(getfield(sys2, :continuous_events))[1], x ~ 2) @@ -204,7 +204,7 @@ root_eqs = [x ~ 0] affect = [v ~ -v] @named ball = ODESystem([D(x) ~ v - D(v) ~ -9.8], t, continuous_events = root_eqs => affect) + D(v) ~ -9.8], t, continuous_events = root_eqs => affect) @test getfield(ball, :continuous_events)[] == SymbolicContinuousCallback(Equation[x ~ 0], Equation[v ~ -v]) @@ -223,12 +223,13 @@ sol = solve(prob, Tsit5()) D = Differential(t) continuous_events = [[x ~ 0] => [vx ~ -vx] - [y ~ -1.5, y ~ 1.5] => [vy ~ -vy]] + [y ~ -1.5, y ~ 1.5] => [vy ~ -vy]] -@named ball = ODESystem([D(x) ~ vx - D(y) ~ vy - D(vx) ~ -9.8 - D(vy) ~ -0.01vy], t; continuous_events) +@named ball = ODESystem( + [D(x) ~ vx + D(y) ~ vy + D(vx) ~ -9.8 + D(vy) ~ -0.01vy], t; continuous_events) ball = structural_simplify(ball) @@ -259,13 +260,13 @@ sol = solve(prob, Tsit5()) ## Test multi-variable affect # in this test, there are two variables affected by a single event. continuous_events = [ - [x ~ 0] => [vx ~ -vx, vy ~ -vy], + [x ~ 0] => [vx ~ -vx, vy ~ -vy] ] @named ball = ODESystem([D(x) ~ vx - D(y) ~ vy - D(vx) ~ -1 - D(vy) ~ 0], t; continuous_events) + D(y) ~ vy + D(vx) ~ -1 + D(vy) ~ 0], t; continuous_events) ball = structural_simplify(ball) @@ -284,8 +285,8 @@ sol = solve(prob, Tsit5()) # tests that it works for ODAESystem @variables vs(t) v(t) vmeasured(t) eq = [vs ~ sin(2pi * t) - D(v) ~ vs - v - D(vmeasured) ~ 0.0] + D(v) ~ vs - v + D(vmeasured) ~ 0.0] ev = [sin(20pi * t) ~ 0.0] => [vmeasured ~ v] @named sys = ODESystem(eq, continuous_events = ev) sys = structural_simplify(sys) @@ -329,8 +330,8 @@ sd_force(sd) = -sd.spring.k * sd.spring.x - sd.damper.c * sd.damper.vel @named sd = SpringDamper(; k = 1000, c = 10) function Model(u, d = 0) eqs = [connect_sd(sd, mass1, mass2) - Dₜ(mass1.vel) ~ (sd_force(sd) + u) / mass1.m - Dₜ(mass2.vel) ~ (-sd_force(sd) + d) / mass2.m] + Dₜ(mass1.vel) ~ (sd_force(sd) + u) / mass1.m + Dₜ(mass2.vel) ~ (-sd_force(sd) + d) / mass2.m] @named _model = ODESystem(eqs, t; observed = [y ~ mass2.pos]) @named model = compose(_model, mass1, mass2, sd) end diff --git a/test/symbolic_indexing_interface.jl b/test/symbolic_indexing_interface.jl index 2acb04c986..3d0ab8f7c1 100644 --- a/test/symbolic_indexing_interface.jl +++ b/test/symbolic_indexing_interface.jl @@ -8,11 +8,13 @@ eqs = [D(x) ~ a * y + t, D(y) ~ b * t] @test all(is_variable.((odesys,), [x, y, 1, 2, :x, :y])) @test all(.!is_variable.((odesys,), [a, b, t, 3, 0, :a, :b])) -@test variable_index.((odesys,), [x, y, a, b, t, 1, 2, :x, :y, :a, :b]) == [1, 2, nothing, nothing, nothing, 1, 2, 1, 2, nothing, nothing] +@test variable_index.((odesys,), [x, y, a, b, t, 1, 2, :x, :y, :a, :b]) == + [1, 2, nothing, nothing, nothing, 1, 2, 1, 2, nothing, nothing] @test isequal(variable_symbols(odesys), [x, y]) @test all(is_parameter.((odesys,), [a, b, 1, 2, :a, :b])) @test all(.!is_parameter.((odesys,), [x, y, t, 3, 0, :x, :y])) -@test parameter_index.((odesys,), [x, y, a, b, t, 1, 2, :x, :y, :a, :b]) == [nothing, nothing, 1, 2, nothing, 1, 2, nothing, nothing, 1, 2] +@test parameter_index.((odesys,), [x, y, a, b, t, 1, 2, :x, :y, :a, :b]) == + [nothing, nothing, 1, 2, nothing, 1, 2, nothing, nothing, 1, 2] @test isequal(parameter_symbols(odesys), [a, b]) @test all(is_independent_variable.((odesys,), [t, :t])) @test all(.!is_independent_variable.((odesys,), [x, y, a, :x, :y, :a])) @@ -23,10 +25,10 @@ eqs = [D(x) ~ a * y + t, D(y) ~ b * t] @variables x y z @parameters σ ρ β -eqs = [0 ~ σ*(y-x), - 0 ~ x*(ρ-z)-y, - 0 ~ x*y - β*z] -@named ns = NonlinearSystem(eqs, [x,y,z],[σ,ρ,β]) +eqs = [0 ~ σ * (y - x), + 0 ~ x * (ρ - z) - y, + 0 ~ x * y - β * z] +@named ns = NonlinearSystem(eqs, [x, y, z], [σ, ρ, β]) @test !is_time_dependent(ns) @@ -37,20 +39,20 @@ Dtt = Differential(t)^2 Dt = Differential(t) #2D PDE -C=1 -eq = Dtt(u(t,x)) ~ C^2*Dxx(u(t,x)) +C = 1 +eq = Dtt(u(t, x)) ~ C^2 * Dxx(u(t, x)) # Initial and boundary conditions -bcs = [u(t,0) ~ 0.,# for all t > 0 - u(t,1) ~ 0.,# for all t > 0 - u(0,x) ~ x*(1. - x), #for all 0 < x < 1 - Dt(u(0,x)) ~ 0. ] #for all 0 < x < 1] +bcs = [u(t, 0) ~ 0.0,# for all t > 0 + u(t, 1) ~ 0.0,# for all t > 0 + u(0, x) ~ x * (1.0 - x), #for all 0 < x < 1 + Dt(u(0, x)) ~ 0.0] #for all 0 < x < 1] # Space and time domains -domains = [t ∈ (0.0,1.0), - x ∈ (0.0,1.0)] +domains = [t ∈ (0.0, 1.0), + x ∈ (0.0, 1.0)] -@named pde_system = PDESystem(eq,bcs,domains,[t,x],[u]) +@named pde_system = PDESystem(eq, bcs, domains, [t, x], [u]) @test pde_system.ps == SciMLBase.NullParameters() @test parameter_symbols(pde_system) == [] diff --git a/test/symbolic_parameters.jl b/test/symbolic_parameters.jl index 1df6782faf..be048e8bdd 100644 --- a/test/symbolic_parameters.jl +++ b/test/symbolic_parameters.jl @@ -12,12 +12,12 @@ eqs = [0 ~ σ * (y - x), par = [ σ => 1, ρ => 0.1 + σ, - β => ρ * 1.1, + β => ρ * 1.1 ] u0 = [ x => u, y => σ, # default u0 from default p - z => u - 0.1, + z => u - 0.1 ] ns = NonlinearSystem(eqs, [x, y, z], [σ, ρ, β], name = :ns, defaults = [par; u0]) ns.y = u * 1.1 @@ -60,10 +60,10 @@ der = Differential(t) eqs = [der(x) ~ x] @named sys = ODESystem(eqs, t, vars, [x0]) pars = [ - x0 => 10.0, + x0 => 10.0 ] initialValues = [ - x => x0, + x => x0 ] tspan = (0.0, 1.0) problem = ODEProblem(sys, initialValues, tspan, pars) diff --git a/test/test_variable_metadata.jl b/test/test_variable_metadata.jl index 4e75f1f56c..2455273bdd 100644 --- a/test/test_variable_metadata.jl +++ b/test/test_variable_metadata.jl @@ -48,7 +48,7 @@ Dₜ = Differential(t) @parameters k [tunable = true, bounds = (0, Inf)] @parameters k2 eqs = [Dₜ(x) ~ (-k2 * x + k * u) / T - y ~ x] + y ~ x] sys = ODESystem(eqs, t, name = :tunable_first_order) p = tunable_parameters(sys) diff --git a/test/units.jl b/test/units.jl index 9abe428cd2..295c71227f 100644 --- a/test/units.jl +++ b/test/units.jl @@ -40,7 +40,7 @@ D = Differential(t) @test MT.get_unit(t^2) == u"ms^2" eqs = [D(E) ~ P - E / τ - 0 ~ P] + 0 ~ P] @test MT.validate(eqs) @named sys = ODESystem(eqs) @@ -51,7 +51,7 @@ eqs = [D(E) ~ P - E / τ @test_throws MT.ArgumentError ODESystem(eqs, t, [E, P, t], [τ], name = :sys) ODESystem(eqs, t, [E, P, t], [τ], name = :sys, checks = MT.CheckUnits) eqs = [D(E) ~ P - E / τ - 0 ~ P + E * τ] + 0 ~ P + E * τ] @test_throws MT.ValidationError ODESystem(eqs, name = :sys, checks = MT.CheckAll) @test_throws MT.ValidationError ODESystem(eqs, name = :sys, checks = true) ODESystem(eqs, name = :sys, checks = MT.CheckNone) @@ -105,7 +105,7 @@ ODESystem(eqs, name = :sys) δ = Differential(t) D = Difference(t; dt = 0.1u"s") eqs = [ - δ(x) ~ a * x, + δ(x) ~ a * x ] de = ODESystem(eqs, t, [x], [a], name = :sys) @@ -113,7 +113,7 @@ de = ODESystem(eqs, t, [x], [a], name = :sys) @parameters a [unit = u"kg"^-1] @variables x [unit = u"kg"] eqs = [ - 0 ~ a * x, + 0 ~ a * x ] @named nls = NonlinearSystem(eqs, [x], [a]) @@ -122,7 +122,7 @@ eqs = [ @variables t [unit = u"ms"] E(t) [unit = u"kJ"] P(t) [unit = u"MW"] D = Differential(t) eqs = [D(E) ~ P - E / τ - P ~ Q] + P ~ Q] noiseeqs = [0.1u"MW", 0.1u"MW"] @@ -130,12 +130,12 @@ noiseeqs = [0.1u"MW", # With noise matrix noiseeqs = [0.1u"MW" 0.1u"MW" - 0.1u"MW" 0.1u"MW"] + 0.1u"MW" 0.1u"MW"] @named sys = SDESystem(eqs, noiseeqs, t, [P, E], [τ, Q]) # Invalid noise matrix noiseeqs = [0.1u"MW" 0.1u"MW" - 0.1u"MW" 0.1u"s"] + 0.1u"MW" 0.1u"s"] @test !MT.validate(eqs, noiseeqs) # Non-trivial simplifications @@ -166,7 +166,7 @@ sys_simple = structural_simplify(sys) #Jump System @parameters β [unit = u"(mol^2*s)^-1"] γ [unit = u"(mol*s)^-1"] t [unit = u"s"] jumpmol [ - unit = u"mol", + unit = u"mol" ] @variables S(t) [unit = u"mol"] I(t) [unit = u"mol"] R(t) [unit = u"mol"] rate₁ = β * S * I diff --git a/test/variable_scope.jl b/test/variable_scope.jl index 2049f0fd69..9e183830ad 100644 --- a/test/variable_scope.jl +++ b/test/variable_scope.jl @@ -20,9 +20,9 @@ ie = ParentScope(1 / e) @test getmetadata(arguments(value(ie))[2], SymScope) === ParentScope(LocalScope()) eqs = [0 ~ a - 0 ~ b - 0 ~ c - 0 ~ d] + 0 ~ b + 0 ~ c + 0 ~ d] @named sub4 = NonlinearSystem(eqs, [a, b, c, d], []) @named sub3 = NonlinearSystem(eqs, [a, b, c, d], []) @named sub2 = NonlinearSystem([], [], [], systems = [sub3, sub4]) @@ -38,7 +38,8 @@ names = ModelingToolkit.getname.(states(sys)) @named foo = NonlinearSystem(eqs, [a, b, c, d], []) @named bar = NonlinearSystem(eqs, [a, b, c, d], []) -@test ModelingToolkit.getname(ModelingToolkit.namespace_expr(ModelingToolkit.namespace_expr(b, +@test ModelingToolkit.getname(ModelingToolkit.namespace_expr( + ModelingToolkit.namespace_expr(b, foo), bar)) == Symbol("bar₊b") @@ -53,11 +54,11 @@ end @parameters t a b c d e f p = [a - ParentScope(b) - ParentScope(ParentScope(c)) - DelayParentScope(d) - DelayParentScope(e, 2) - GlobalScope(f)] + ParentScope(b) + ParentScope(ParentScope(c)) + DelayParentScope(d) + DelayParentScope(e, 2) + GlobalScope(f)] level0 = ODESystem(Equation[], t, [], p; name = :level0) level1 = ODESystem(Equation[], t, [], []; name = :level1) ∘ level0 diff --git a/test/variable_utils.jl b/test/variable_utils.jl index 3de486e6d8..851779e208 100644 --- a/test/variable_utils.jl +++ b/test/variable_utils.jl @@ -17,8 +17,8 @@ new = (((1 / β - 1) + δ) / γ)^(1 / (γ - 1)) # Continuous using ModelingToolkit: isdifferential, isdifference, vars, difference_vars, - collect_difference_variables, collect_differential_variables, - collect_ivs + collect_difference_variables, collect_differential_variables, + collect_ivs @variables t u(t) y(t) D = Differential(t) eq = D(y) ~ u @@ -54,7 +54,7 @@ function UnitDelay(dt; name) @variables u(t)=0.0 [input = true] y(t)=0.0 [output = true] z = Difference(t; dt = dt, update = true) eqs = [ - z(y) ~ u, + z(y) ~ u ] DiscreteSystem(eqs, t, name = name) end