From 6f95e5c172be44a91eea1f0272c104dadeefa93d Mon Sep 17 00:00:00 2001 From: Aayush Sabharwal Date: Thu, 25 Jan 2024 18:38:51 +0530 Subject: [PATCH 1/3] refactor: rename states to unknowns, and related changes - also some bug fixes --- docs/src/basics/AbstractSystem.md | 8 +- docs/src/basics/Linearization.md | 2 +- .../modelingtoolkitize_index_reduction.md | 8 +- docs/src/systems/JumpSystem.md | 2 +- docs/src/systems/NonlinearSystem.md | 2 +- docs/src/systems/ODESystem.md | 2 +- docs/src/systems/OptimizationSystem.md | 2 +- docs/src/systems/SDESystem.md | 2 +- ext/MTKBifurcationKitExt.jl | 12 +-- src/ModelingToolkit.jl | 3 +- src/inputoutput.jl | 8 +- .../StructuralTransformations.jl | 2 +- src/structural_transformation/codegen.jl | 8 +- src/structural_transformation/pantelides.jl | 2 +- .../symbolics_tearing.jl | 2 +- src/systems/abstractsystem.jl | 78 +++++++++---------- src/systems/callbacks.jl | 20 ++--- src/systems/clock_inference.jl | 8 +- src/systems/connectors.jl | 46 +++++------ src/systems/dependency_graphs.jl | 20 ++--- src/systems/diffeqs/abstractodesystem.jl | 70 ++++++++--------- src/systems/diffeqs/basic_transformations.jl | 2 +- src/systems/diffeqs/first_order_transform.jl | 8 +- src/systems/diffeqs/modelingtoolkitize.jl | 2 +- src/systems/diffeqs/odesystem.jl | 32 ++++---- src/systems/diffeqs/sdesystem.jl | 48 ++++++------ .../discrete_system/discrete_system.jl | 26 +++---- src/systems/jumps/jumpsystem.jl | 34 ++++---- src/systems/nonlinear/initializesystem.jl | 2 +- src/systems/nonlinear/nonlinearsystem.jl | 52 ++++++------- .../optimization/constraints_system.jl | 28 +++---- .../optimization/optimizationsystem.jl | 44 +++++------ src/systems/systems.jl | 4 +- src/systems/systemstructure.jl | 4 +- src/systems/unit_check.jl | 4 +- src/systems/validation.jl | 4 +- src/variables.jl | 8 +- test/components.jl | 6 +- test/dde.jl | 2 +- test/domain_connectors.jl | 4 +- test/extensions/Project.toml | 3 +- test/input_output_handling.jl | 6 +- test/jacobiansparsity.jl | 2 +- test/jumpsystem.jl | 2 +- test/linearize.jl | 8 +- test/log.txt | 2 + test/modelingtoolkitize.jl | 6 +- test/nonlinearsystem.jl | 14 ++-- test/odesystem.jl | 20 ++--- test/optimizationsystem.jl | 4 +- test/reduction.jl | 14 ++-- test/runtests.jl | 48 ++++++------ test/sdesystem.jl | 2 +- test/state_selection.jl | 6 +- .../index_reduction.jl | 2 +- test/structural_transformation/tearing.jl | 2 +- test/symbolic_parameters.jl | 4 +- test/test_variable_metadata.jl | 2 +- test/variable_scope.jl | 2 +- 59 files changed, 385 insertions(+), 385 deletions(-) create mode 100644 test/log.txt diff --git a/docs/src/basics/AbstractSystem.md b/docs/src/basics/AbstractSystem.md index 89bb17d8a1..feebf8ffdc 100644 --- a/docs/src/basics/AbstractSystem.md +++ b/docs/src/basics/AbstractSystem.md @@ -38,18 +38,18 @@ same keyword arguments, which are: Each `AbstractSystem` has lists of variables in context, such as distinguishing parameters vs states. In addition, an `AbstractSystem` can also hold other -`AbstractSystem` types. Direct accessing of the values, such as `sys.states`, -gives the immediate list, while the accessor functions `states(sys)` gives the +`AbstractSystem` types. Direct accessing of the values, such as `sys.unknowns`, +gives the immediate list, while the accessor functions `unknowns(sys)` gives the total set, which includes that of all systems held inside. The values which are common to all `AbstractSystem`s are: - `equations(sys)`: All equations that define the system and its subsystems. - - `states(sys)`: All the states in the system and its subsystems. + - `unknowns(sys)`: All the unknowns in the system and its subsystems. - `parameters(sys)`: All parameters of the system and its subsystems. - `nameof(sys)`: The name of the current-level system. - `get_eqs(sys)`: Equations that define the current-level system. - - `get_states(sys)`: States that are in the current-level system. + - `get_unknowns(sys)`: States that are in the current-level system. - `get_ps(sys)`: Parameters that are in the current-level system. - `get_systems(sys)`: Subsystems of the current-level system. diff --git a/docs/src/basics/Linearization.md b/docs/src/basics/Linearization.md index 5dc207db02..bf5c48f1bf 100644 --- a/docs/src/basics/Linearization.md +++ b/docs/src/basics/Linearization.md @@ -38,7 +38,7 @@ The named tuple `matrices` contains the matrices of the linear statespace repres ```@example LINEARIZE using ModelingToolkit: inputs, outputs -[states(simplified_sys); inputs(simplified_sys); outputs(simplified_sys)] +[unknowns(simplified_sys); inputs(simplified_sys); outputs(simplified_sys)] ``` ## Operating point diff --git a/docs/src/examples/modelingtoolkitize_index_reduction.md b/docs/src/examples/modelingtoolkitize_index_reduction.md index 5d673d7b3e..fc6876d942 100644 --- a/docs/src/examples/modelingtoolkitize_index_reduction.md +++ b/docs/src/examples/modelingtoolkitize_index_reduction.md @@ -32,7 +32,7 @@ traced_sys = modelingtoolkitize(pendulum_prob) pendulum_sys = structural_simplify(dae_index_lowering(traced_sys)) prob = ODAEProblem(pendulum_sys, [], tspan) sol = solve(prob, Tsit5(), abstol = 1e-8, reltol = 1e-8) -plot(sol, idxs = states(traced_sys)) +plot(sol, idxs = unknowns(traced_sys)) ``` ## Explanation @@ -154,10 +154,10 @@ prob = ODEProblem(pendulum_sys, Pair[], tspan) sol = solve(prob, Rodas4()) using Plots -plot(sol, idxs = states(traced_sys)) +plot(sol, idxs = unknowns(traced_sys)) ``` -Note that plotting using `states(traced_sys)` is done so that any +Note that plotting using `unknowns(traced_sys)` is done so that any variables which are symbolically eliminated, or any variable reordering done for enhanced parallelism/performance, still show up in the resulting plot and the plot is shown in the same order as the original numerical @@ -173,7 +173,7 @@ traced_sys = modelingtoolkitize(pendulum_prob) pendulum_sys = structural_simplify(dae_index_lowering(traced_sys)) prob = ODAEProblem(pendulum_sys, Pair[], tspan) sol = solve(prob, Tsit5(), abstol = 1e-8, reltol = 1e-8) -plot(sol, idxs = states(traced_sys)) +plot(sol, idxs = unknowns(traced_sys)) ``` And there you go: this has transformed the model from being too hard to diff --git a/docs/src/systems/JumpSystem.md b/docs/src/systems/JumpSystem.md index b066dbfc44..fda0cd6f53 100644 --- a/docs/src/systems/JumpSystem.md +++ b/docs/src/systems/JumpSystem.md @@ -9,7 +9,7 @@ JumpSystem ## Composition and Accessor Functions - `get_eqs(sys)` or `equations(sys)`: The equations that define the jump system. - - `get_states(sys)` or `states(sys)`: The set of states in the jump system. + - `get_unknowns(sys)` or `unknowns(sys)`: The set of unknowns in the jump system. - `get_ps(sys)` or `parameters(sys)`: The parameters of the jump system. - `get_iv(sys)`: The independent variable of the jump system. diff --git a/docs/src/systems/NonlinearSystem.md b/docs/src/systems/NonlinearSystem.md index dfdb8db508..06d587b1b9 100644 --- a/docs/src/systems/NonlinearSystem.md +++ b/docs/src/systems/NonlinearSystem.md @@ -9,7 +9,7 @@ NonlinearSystem ## Composition and Accessor Functions - `get_eqs(sys)` or `equations(sys)`: The equations that define the nonlinear system. - - `get_states(sys)` or `states(sys)`: The set of states in the nonlinear system. + - `get_unknowns(sys)` or `unknowns(sys)`: The set of unknowns in the nonlinear system. - `get_ps(sys)` or `parameters(sys)`: The parameters of the nonlinear system. - `get_u0_p(sys, u0map, parammap)` Numeric arrays for the initial condition and parameters given `var => value` maps. diff --git a/docs/src/systems/ODESystem.md b/docs/src/systems/ODESystem.md index f79263436f..3f9a4dc45e 100644 --- a/docs/src/systems/ODESystem.md +++ b/docs/src/systems/ODESystem.md @@ -9,7 +9,7 @@ ODESystem ## Composition and Accessor Functions - `get_eqs(sys)` or `equations(sys)`: The equations that define the ODE. - - `get_states(sys)` or `states(sys)`: The set of states in the ODE. + - `get_unknowns(sys)` or `unknowns(sys)`: The set of unknowns in the ODE. - `get_ps(sys)` or `parameters(sys)`: The parameters of the ODE. - `get_iv(sys)`: The independent variable of the ODE. - `get_u0_p(sys, u0map, parammap)` Numeric arrays for the initial condition and parameters given `var => value` maps. diff --git a/docs/src/systems/OptimizationSystem.md b/docs/src/systems/OptimizationSystem.md index 499febf65f..bcc8b21de7 100644 --- a/docs/src/systems/OptimizationSystem.md +++ b/docs/src/systems/OptimizationSystem.md @@ -9,7 +9,7 @@ OptimizationSystem ## Composition and Accessor Functions - `get_op(sys)`: The objective to be minimized. - - `get_states(sys)` or `states(sys)`: The set of states for the optimization. + - `get_unknowns(sys)` or `unknowns(sys)`: The set of unknowns for the optimization. - `get_ps(sys)` or `parameters(sys)`: The parameters for the optimization. - `get_constraints(sys)` or `constraints(sys)`: The constraints for the optimization. diff --git a/docs/src/systems/SDESystem.md b/docs/src/systems/SDESystem.md index 5e4dc958c0..455f79689e 100644 --- a/docs/src/systems/SDESystem.md +++ b/docs/src/systems/SDESystem.md @@ -16,7 +16,7 @@ sde = SDESystem(ode, noiseeqs) ## Composition and Accessor Functions - `get_eqs(sys)` or `equations(sys)`: The equations that define the SDE. - - `get_states(sys)` or `states(sys)`: The set of states in the SDE. + - `get_unknowns(sys)` or `unknowns(sys)`: The set of unknowns in the SDE. - `get_ps(sys)` or `parameters(sys)`: The parameters of the SDE. - `get_iv(sys)`: The independent variable of the SDE. diff --git a/ext/MTKBifurcationKitExt.jl b/ext/MTKBifurcationKitExt.jl index fbaf8e44a8..7174f56c8b 100644 --- a/ext/MTKBifurcationKitExt.jl +++ b/ext/MTKBifurcationKitExt.jl @@ -30,12 +30,12 @@ struct ObservableRecordFromSolution{S, T} p_vals) where {S, T} obs_eqs = observed(nsys) target_obs_idx = findfirst(isequal(plot_var, eq.lhs) for eq in observed(nsys)) - state_end_idxs = length(states(nsys)) + state_end_idxs = length(unknowns(nsys)) param_end_idxs = state_end_idxs + length(parameters(nsys)) bif_par_idx = state_end_idxs + bif_idx # Gets the (base) substitution values for states. - subs_vals_states = Pair.(states(nsys), u0_vals) + subs_vals_states = Pair.(unknowns(nsys), u0_vals) # Gets the (base) substitution values for parameters. subs_vals_params = Pair.(parameters(nsys), p_vals) # Gets the (base) substitution values for observables. @@ -95,7 +95,7 @@ function BifurcationKit.BifurcationProblem(nsys::NonlinearSystem, # Converts the input state guess. u0_bif_vals = ModelingToolkit.varmap_to_vars(u0_bif, - states(nsys); + unknowns(nsys); defaults = nsys.defaults) p_vals = ModelingToolkit.varmap_to_vars(ps, parameters(nsys); defaults = nsys.defaults) @@ -103,8 +103,8 @@ function BifurcationKit.BifurcationProblem(nsys::NonlinearSystem, bif_idx = findfirst(isequal(bif_par), parameters(nsys)) if !isnothing(plot_var) # If the plot var is a normal state. - if any(isequal(plot_var, var) for var in states(nsys)) - plot_idx = findfirst(isequal(plot_var), states(nsys)) + if any(isequal(plot_var, var) for var in unknowns(nsys)) + plot_idx = findfirst(isequal(plot_var), unknowns(nsys)) record_from_solution = (x, p) -> x[plot_idx] # If the plot var is an observed state. @@ -134,7 +134,7 @@ end # When input is a ODESystem. function BifurcationKit.BifurcationProblem(osys::ODESystem, args...; kwargs...) nsys = NonlinearSystem([0 ~ eq.rhs for eq in equations(osys)], - states(osys), + unknowns(osys), parameters(osys); name = nameof(osys)) return BifurcationKit.BifurcationProblem(nsys, args...; kwargs...) diff --git a/src/ModelingToolkit.jl b/src/ModelingToolkit.jl index b0197245f9..57a4a74af3 100644 --- a/src/ModelingToolkit.jl +++ b/src/ModelingToolkit.jl @@ -36,7 +36,7 @@ using PrecompileTools, Reexport using RecursiveArrayTools using SymbolicIndexingInterface - export independent_variables, states, parameters + export independent_variables, unknowns, parameters import SymbolicUtils import SymbolicUtils: istree, arguments, operation, similarterm, promote_symtype, Symbolic, isadd, ismul, ispow, issym, FnType, @@ -196,7 +196,6 @@ export ODEProblem, SDEProblem export NonlinearFunction, NonlinearFunctionExpr export NonlinearProblem, BlockNonlinearProblem, NonlinearProblemExpr export OptimizationProblem, OptimizationProblemExpr, constraints -export AutoModelingToolkit export SteadyStateProblem, SteadyStateProblemExpr export JumpProblem, DiscreteProblem export NonlinearSystem, OptimizationSystem, ConstraintsSystem diff --git a/src/inputoutput.jl b/src/inputoutput.jl index 5a9a354b38..45330aaea9 100644 --- a/src/inputoutput.jl +++ b/src/inputoutput.jl @@ -5,7 +5,7 @@ using Symbolics: get_variables Return all variables that mare marked as inputs. See also [`unbound_inputs`](@ref) See also [`bound_inputs`](@ref), [`unbound_inputs`](@ref) """ -inputs(sys) = [filter(isinput, states(sys)); filter(isinput, parameters(sys))] +inputs(sys) = [filter(isinput, unknowns(sys)); filter(isinput, parameters(sys))] """ outputs(sys) @@ -17,7 +17,7 @@ function outputs(sys) o = observed(sys) rhss = [eq.rhs for eq in o] lhss = [eq.lhs for eq in o] - unique([filter(isoutput, states(sys)) + unique([filter(isoutput, unknowns(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)]) @@ -205,7 +205,7 @@ function generate_control_function(sys::AbstractODESystem, inputs = unbound_inpu sys, _ = io_preprocessing(sys, inputs, []; simplify, kwargs...) - dvs = states(sys) + dvs = unknowns(sys) ps = parameters(sys) ps = setdiff(ps, inputs) if disturbance_inputs !== nothing @@ -300,7 +300,7 @@ function inputs_to_parameters!(state::TransformationState, io) @set! sys.eqs = isempty(input_to_parameters) ? equations(sys) : fast_substitute(equations(sys), input_to_parameters) - @set! sys.states = setdiff(states(sys), keys(input_to_parameters)) + @set! sys.unknowns = setdiff(unknowns(sys), keys(input_to_parameters)) ps = parameters(sys) if io !== nothing diff --git a/src/structural_transformation/StructuralTransformations.jl b/src/structural_transformation/StructuralTransformations.jl index 7289df4232..5c20554d08 100644 --- a/src/structural_transformation/StructuralTransformations.jl +++ b/src/structural_transformation/StructuralTransformations.jl @@ -11,7 +11,7 @@ using SymbolicUtils: similarterm, istree using ModelingToolkit using ModelingToolkit: ODESystem, AbstractSystem, var_from_nested_derivative, Differential, - states, equations, vars, Symbolic, diff2term, value, + unknowns, equations, vars, Symbolic, diff2term, value, operation, arguments, Sym, Term, simplify, solve_for, isdiffeq, isdifferential, isirreducible, empty_substitutions, get_substitutions, diff --git a/src/structural_transformation/codegen.jl b/src/structural_transformation/codegen.jl index 1123420a87..3f11ed049f 100644 --- a/src/structural_transformation/codegen.jl +++ b/src/structural_transformation/codegen.jl @@ -298,7 +298,7 @@ function build_torn_function(sys; rhss) states = Any[fullvars[i] for i in states_idxs] - @set! sys.unknown_states = states + @set! sys.solved_unknowns = states syms = map(Symbol, states) pre = get_postprocess_fbody(sys) @@ -410,9 +410,9 @@ function build_observed_function(state, ts, var_eq_matching, var_sccs, required_algvars = Set(intersect(algvars, vars)) obs = observed(sys) observed_idx = Dict(x.lhs => i for (i, x) in enumerate(obs)) - namespaced_to_obs = Dict(states(sys, x.lhs) => x.lhs for x in obs) - namespaced_to_sts = Dict(states(sys, x) => x for x in states(sys)) - sts = Set(states(sys)) + namespaced_to_obs = Dict(unknowns(sys, x.lhs) => x.lhs for x in obs) + namespaced_to_sts = Dict(unknowns(sys, x) => x for x in unknowns(sys)) + sts = Set(unknowns(sys)) # FIXME: This is a rather rough estimate of dependencies. We assume # the expression depends on everything before the `maxidx`. diff --git a/src/structural_transformation/pantelides.jl b/src/structural_transformation/pantelides.jl index 6b79cdc8b6..a2693671ce 100644 --- a/src/structural_transformation/pantelides.jl +++ b/src/structural_transformation/pantelides.jl @@ -65,7 +65,7 @@ function pantelides_reassemble(state::TearingState, var_eq_matching) out_eqs[sort(filter(x -> x !== unassigned, var_eq_matching))])) @set! sys.eqs = final_eqs - @set! sys.states = final_vars + @set! sys.unknowns = final_vars return sys end diff --git a/src/structural_transformation/symbolics_tearing.jl b/src/structural_transformation/symbolics_tearing.jl index 3839e77622..4c7bcb68ab 100644 --- a/src/structural_transformation/symbolics_tearing.jl +++ b/src/structural_transformation/symbolics_tearing.jl @@ -540,7 +540,7 @@ function tearing_reassemble(state::TearingState, var_eq_matching; sys = state.sys @set! sys.eqs = neweqs - @set! sys.states = Any[v + @set! sys.unknowns = Any[v for (i, v) in enumerate(fullvars) if diff_to_var[i] === nothing && ispresent(i)] @set! sys.substitutions = Substitutions(subeqs, deps) diff --git a/src/systems/abstractsystem.jl b/src/systems/abstractsystem.jl index 2c9f1884fa..82f7226b02 100644 --- a/src/systems/abstractsystem.jl +++ b/src/systems/abstractsystem.jl @@ -82,7 +82,7 @@ function calculate_hessian end """ ```julia -generate_tgrad(sys::AbstractTimeDependentSystem, dvs = states(sys), ps = parameters(sys), +generate_tgrad(sys::AbstractTimeDependentSystem, dvs = unknowns(sys), ps = parameters(sys), expression = Val{true}; kwargs...) ``` @@ -93,7 +93,7 @@ function generate_tgrad end """ ```julia -generate_gradient(sys::AbstractSystem, dvs = states(sys), ps = parameters(sys), +generate_gradient(sys::AbstractSystem, dvs = unknowns(sys), ps = parameters(sys), expression = Val{true}; kwargs...) ``` @@ -104,7 +104,7 @@ function generate_gradient end """ ```julia -generate_jacobian(sys::AbstractSystem, dvs = states(sys), ps = parameters(sys), +generate_jacobian(sys::AbstractSystem, dvs = unknowns(sys), ps = parameters(sys), expression = Val{true}; sparse = false, kwargs...) ``` @@ -115,7 +115,7 @@ function generate_jacobian end """ ```julia -generate_factorized_W(sys::AbstractSystem, dvs = states(sys), ps = parameters(sys), +generate_factorized_W(sys::AbstractSystem, dvs = unknowns(sys), ps = parameters(sys), expression = Val{true}; sparse = false, kwargs...) ``` @@ -126,7 +126,7 @@ function generate_factorized_W end """ ```julia -generate_hessian(sys::AbstractSystem, dvs = states(sys), ps = parameters(sys), +generate_hessian(sys::AbstractSystem, dvs = unknowns(sys), ps = parameters(sys), expression = Val{true}; sparse = false, kwargs...) ``` @@ -137,7 +137,7 @@ function generate_hessian end """ ```julia -generate_function(sys::AbstractSystem, dvs = states(sys), ps = parameters(sys), +generate_function(sys::AbstractSystem, dvs = unknowns(sys), ps = parameters(sys), expression = Val{true}; kwargs...) ``` @@ -320,7 +320,7 @@ for prop in [:eqs :tag :noiseeqs :iv - :states + :unknowns :ps :tspan :name @@ -352,7 +352,7 @@ for prop in [:eqs :metadata :gui_metadata :discrete_subsystems - :unknown_states + :solved_unknowns :split_idxs :parent] fname1 = Symbol(:get_, prop) @@ -417,7 +417,7 @@ function Base.propertynames(sys::AbstractSystem; private = false) for s in get_systems(sys) push!(names, getname(s)) end - has_states(sys) && for s in get_states(sys) + has_unknowns(sys) && for s in get_unknowns(sys) push!(names, getname(s)) end has_ps(sys) && for s in get_ps(sys) @@ -454,7 +454,7 @@ function getvar(sys::AbstractSystem, name::Symbol; namespace = !iscomplete(sys)) v = get(avs, name, nothing) v === nothing || return namespace ? renamespace(sys, v) : v else - sts = get_states(sys) + sts = get_unknowns(sys) i = findfirst(x -> getname(x) == name, sts) if i !== nothing return namespace ? renamespace(sys, sts[i]) : sts[i] @@ -469,7 +469,7 @@ function getvar(sys::AbstractSystem, name::Symbol; namespace = !iscomplete(sys)) end end - sts = get_states(sys) + sts = get_unknowns(sys) i = findfirst(x -> getname(x) == name, sts) if i !== nothing return namespace ? renamespace(sys, sts[i]) : sts[i] @@ -493,7 +493,7 @@ function Base.setproperty!(sys::AbstractSystem, prop::Symbol, val) idx = findfirst(s -> getname(s) == prop, params); idx !== nothing) get_defaults(sys)[params[idx]] = value(val) - elseif (sts = states(sys); + elseif (sts = unknowns(sys); idx = findfirst(s -> getname(s) == prop, sts); idx !== nothing) get_defaults(sys)[sts[idx]] = value(val) @@ -589,13 +589,13 @@ function renamespace(sys, x) end end -namespace_variables(sys::AbstractSystem) = states(sys, states(sys)) +namespace_variables(sys::AbstractSystem) = unknowns(sys, unknowns(sys)) namespace_parameters(sys::AbstractSystem) = parameters(sys, parameters(sys)) 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) + Dict((isparameter(k) ? parameters(sys, k) : unknowns(sys, k)) => namespace_expr(v, sys) for (k, v) in pairs(defs)) end @@ -649,8 +649,8 @@ function namespace_expr(O, sys, n = nameof(sys); ivs = independent_variables(sys end end _nonum(@nospecialize x) = x isa Num ? x.val : x -function states(sys::AbstractSystem) - sts = get_states(sys) +function unknowns(sys::AbstractSystem) + sts = get_unknowns(sys) systems = get_systems(sys) nonunique_states = if isempty(systems) sts @@ -713,9 +713,9 @@ function defaults(sys::AbstractSystem) isempty(systems) ? defs : mapfoldr(namespace_defaults, merge, systems; init = defs) end -states(sys::Union{AbstractSystem, Nothing}, v) = renamespace(sys, v) -parameters(sys::Union{AbstractSystem, Nothing}, v) = toparam(states(sys, v)) -for f in [:states, :parameters] +unknowns(sys::Union{AbstractSystem, Nothing}, v) = renamespace(sys, v) +parameters(sys::Union{AbstractSystem, Nothing}, v) = toparam(unknowns(sys, v)) +for f in [:unknowns, :parameters] @eval function $f(sys::AbstractSystem, vs::AbstractArray) map(v -> $f(sys, v), vs) end @@ -759,13 +759,13 @@ end function islinear(sys::AbstractSystem) rhs = [eq.rhs for eq in equations(sys)] - all(islinear(r, states(sys)) for r in rhs) + all(islinear(r, unknowns(sys)) for r in rhs) end function isaffine(sys::AbstractSystem) rhs = [eq.rhs for eq in equations(sys)] - all(isaffine(r, states(sys)) for r in rhs) + all(isaffine(r, unknowns(sys)) for r in rhs) end function time_varying_as_func(x, sys::AbstractTimeDependentSystem) @@ -788,9 +788,9 @@ $(SIGNATURES) Return a list of actual states needed to be solved by solvers. """ function unknown_states(sys::AbstractSystem) - sts = states(sys) - if has_unknown_states(sys) - sts = something(get_unknown_states(sys), sts) + sts = unknowns(sys) + if has_solved_unknowns(sys) + sts = something(get_solved_unknowns(sys), sts) end return sts end @@ -887,7 +887,7 @@ function toexpr(sys::AbstractSystem) end stsname = gensym(:sts) - sts = states(sys) + sts = unknowns(sys) push_vars!(stmt, stsname, Symbol("@variables"), sts) psname = gensym(:ps) ps = parameters(sys) @@ -940,7 +940,7 @@ end # TODO: what about inputs? function n_extra_equations(sys::AbstractSystem) - isconnector(sys) && return length(get_states(sys)) + isconnector(sys) && return length(get_unknowns(sys)) sys, (csets, _) = generate_connection_set(sys) ceqs, instream_csets = generate_connection_equations_and_stream_connections(csets) n_outer_stream_variables = 0 @@ -960,7 +960,7 @@ function n_extra_equations(sys::AbstractSystem) #end #for m in get_systems(sys) # isconnector(m) || continue - # n_toplevel_unused_flows += count(x->get_connection_type(x) === Flow && !(x in toplevel_flows), get_states(m)) + # n_toplevel_unused_flows += count(x->get_connection_type(x) === Flow && !(x in toplevel_flows), get_unknowns(m)) #end nextras = n_outer_stream_variables + length(ceqs) @@ -968,7 +968,7 @@ end function Base.show(io::IO, mime::MIME"text/plain", sys::AbstractSystem) eqs = equations(sys) - vars = states(sys) + vars = unknowns(sys) nvars = length(vars) if eqs isa AbstractArray && eltype(eqs) <: Equation neqs = count(eq -> !(eq.lhs isa Connection), eqs) @@ -1397,7 +1397,7 @@ y &= h(x, z, u) \\end{aligned} ``` -where `x` are differential state variables, `z` algebraic variables, `u` inputs and `y` outputs. To obtain a linear statespace representation, see [`linearize`](@ref). The input argument `variables` is a vector defining the operating point, corresponding to `states(simplified_sys)` and `p` is a vector corresponding to the parameters of `simplified_sys`. Note: all variables in `inputs` have been converted to parameters in `simplified_sys`. +where `x` are differential state variables, `z` algebraic variables, `u` inputs and `y` outputs. To obtain a linear statespace representation, see [`linearize`](@ref). The input argument `variables` is a vector defining the operating point, corresponding to `unknowns(simplified_sys)` and `p` is a vector corresponding to the parameters of `simplified_sys`. Note: all variables in `inputs` have been converted to parameters in `simplified_sys`. The `simplified_sys` has undergone [`structural_simplify`](@ref) and had any occurring input or output variables replaced with the variables provided in arguments `inputs` and `outputs`. The states of this system also indicate the order of the states that holds for the linearized matrices. @@ -1425,7 +1425,7 @@ function linearization_function(sys::AbstractSystem, inputs, simplify, kwargs...) if zero_dummy_der - dummyder = setdiff(states(ssys), states(sys)) + dummyder = setdiff(unknowns(ssys), unknowns(sys)) defs = Dict(x => 0.0 for x in dummyder) @set! ssys.defaults = merge(defs, defaults(ssys)) op = merge(defs, op) @@ -1443,8 +1443,8 @@ function linearization_function(sys::AbstractSystem, inputs, lin_fun = let diff_idxs = diff_idxs, alge_idxs = alge_idxs, input_idxs = input_idxs, - sts = states(sys), - fun = ODEFunction{true, SciMLBase.FullSpecialize}(sys, states(sys), ps; p = p), + sts = unknowns(sys), + fun = ODEFunction{true, SciMLBase.FullSpecialize}(sys, unknowns(sys), ps; p = p), h = build_explicit_observed_function(sys, outputs), chunk = ForwardDiff.Chunk(input_idxs) @@ -1514,7 +1514,7 @@ function linearize_symbolic(sys::AbstractSystem, inputs, kwargs...) sys, diff_idxs, alge_idxs, input_idxs = io_preprocessing(sys, inputs, outputs; simplify, kwargs...) - sts = states(sys) + sts = unknowns(sys) t = get_iv(sys) p = parameters(sys) @@ -1700,7 +1700,7 @@ connections = [f.y ~ c.r # filtered reference to controller reference lsys0, ssys = linearize(cl, [f.u], [p.x]) desired_order = [f.x, p.x] -lsys = ModelingToolkit.reorder_states(lsys0, states(ssys), desired_order) +lsys = ModelingToolkit.reorder_states(lsys0, unknowns(ssys), desired_order) @assert lsys.A == [-2 0; 1 -2] @assert lsys.B == [1; 0;;] @@ -1808,8 +1808,8 @@ Example: ``` lsys, ssys = linearize(pid, [reference.u, measurement.u], [ctr_output.u]) -desired_order = [int.x, der.x] # States that are present in states(ssys) -lsys = ModelingToolkit.reorder_states(lsys, states(ssys), desired_order) +desired_order = [int.x, der.x] # States that are present in unknowns(ssys) +lsys = ModelingToolkit.reorder_states(lsys, unknowns(ssys), desired_order) ``` See also [`ModelingToolkit.similarity_transform`](@ref) @@ -1889,7 +1889,7 @@ end function Base.hash(sys::AbstractSystem, s::UInt) s = hash(nameof(sys), s) s = foldr(hash, get_systems(sys), init = s) - s = foldr(hash, get_states(sys), init = s) + s = foldr(hash, get_unknowns(sys), init = s) s = foldr(hash, get_ps(sys), init = s) if sys isa OptimizationSystem s = hash(get_op(sys), s) @@ -1924,7 +1924,7 @@ function extend(sys::AbstractSystem, basesys::AbstractSystem; name::Symbol = nam end eqs = union(get_eqs(basesys), get_eqs(sys)) - sts = union(get_states(basesys), get_states(sys)) + sts = union(get_unknowns(basesys), get_unknowns(sys)) ps = union(get_ps(basesys), get_ps(sys)) obs = union(get_observed(basesys), get_observed(sys)) cevs = union(get_continuous_events(basesys), get_continuous_events(sys)) @@ -1976,7 +1976,7 @@ returns a `Vector{Pair}` of variables set to `default` which are missing from `g function missing_variable_defaults(sys::AbstractSystem, default = 0.0) varmap = get_defaults(sys) varmap = Dict(Symbolics.diff2term(value(k)) => value(varmap[k]) for k in keys(varmap)) - missingvars = setdiff(states(sys), keys(varmap)) + missingvars = setdiff(unknowns(sys), keys(varmap)) ds = Pair[] n = length(missingvars) diff --git a/src/systems/callbacks.jl b/src/systems/callbacks.jl index b97112e9e8..9a93606d20 100644 --- a/src/systems/callbacks.jl +++ b/src/systems/callbacks.jl @@ -37,8 +37,8 @@ func(f::FunctionalAffect) = f.f context(a::FunctionalAffect) = a.ctx parameters(a::FunctionalAffect) = a.pars parameters_syms(a::FunctionalAffect) = a.pars_syms -states(a::FunctionalAffect) = a.sts -states_syms(a::FunctionalAffect) = a.sts_syms +unknowns(a::FunctionalAffect) = a.sts +unknowns_syms(a::FunctionalAffect) = a.sts_syms function Base.:(==)(a1::FunctionalAffect, a2::FunctionalAffect) isequal(a1.f, a2.f) && isequal(a1.sts, a2.sts) && isequal(a1.pars, a2.pars) && @@ -60,8 +60,8 @@ has_functional_affect(cb) = affects(cb) isa FunctionalAffect namespace_affect(affect, s) = namespace_equation(affect, s) function namespace_affect(affect::FunctionalAffect, s) FunctionalAffect(func(affect), - renamespace.((s,), states(affect)), - states_syms(affect), + renamespace.((s,), unknowns(affect)), + unknowns_syms(affect), renamespace.((s,), parameters(affect)), parameters_syms(affect), context(affect)) @@ -295,7 +295,7 @@ Notes - `expression = Val{true}`, causes the generated function to be returned as an expression. If set to `Val{false}` a `RuntimeGeneratedFunction` will be returned. - `outputidxs`, a vector of indices of the output variables which should correspond to - `states(sys)`. If provided, checks that the LHS of affect equations are variables are + `unknowns(sys)`. If provided, checks that the LHS of affect equations are variables are dropped, i.e. it is assumed these indices are correct and affect equations are well-formed. - `kwargs` are passed through to `Symbolics.build_function`. @@ -361,14 +361,14 @@ function compile_affect(eqs::Vector{Equation}, sys, dvs, ps; outputidxs = nothin end end -function generate_rootfinding_callback(sys::AbstractODESystem, dvs = states(sys), +function generate_rootfinding_callback(sys::AbstractODESystem, dvs = unknowns(sys), ps = parameters(sys); kwargs...) cbs = continuous_events(sys) isempty(cbs) && return nothing generate_rootfinding_callback(cbs, sys, dvs, ps; kwargs...) end -function generate_rootfinding_callback(cbs, sys::AbstractODESystem, dvs = states(sys), +function generate_rootfinding_callback(cbs, sys::AbstractODESystem, dvs = unknowns(sys), ps = parameters(sys); kwargs...) eqs = map(cb -> cb.eqs, cbs) num_eqs = length.(eqs) @@ -430,14 +430,14 @@ end function compile_user_affect(affect::FunctionalAffect, sys, dvs, ps; kwargs...) dvs_ind = Dict(reverse(en) for en in enumerate(dvs)) - v_inds = map(sym -> dvs_ind[sym], states(affect)) + v_inds = map(sym -> dvs_ind[sym], unknowns(affect)) ps_ind = Dict(reverse(en) for en in enumerate(ps)) p_inds = map(sym -> ps_ind[sym], parameters(affect)) # HACK: filter out eliminated symbols. Not clear this is the right thing to do # (MTK should keep these symbols) - u = filter(x -> !isnothing(x[2]), collect(zip(states_syms(affect), v_inds))) |> + u = filter(x -> !isnothing(x[2]), collect(zip(unknowns_syms(affect), v_inds))) |> NamedTuple p = filter(x -> !isnothing(x[2]), collect(zip(parameters_syms(affect), p_inds))) |> NamedTuple @@ -480,7 +480,7 @@ function generate_discrete_callback(cb, sys, dvs, ps; postprocess_affect_expr! = end end -function generate_discrete_callbacks(sys::AbstractSystem, dvs = states(sys), +function generate_discrete_callbacks(sys::AbstractSystem, dvs = unknowns(sys), ps = parameters(sys); kwargs...) has_discrete_events(sys) || return nothing symcbs = discrete_events(sys) diff --git a/src/systems/clock_inference.jl b/src/systems/clock_inference.jl index 4293b0d512..167304f0b0 100644 --- a/src/systems/clock_inference.jl +++ b/src/systems/clock_inference.jl @@ -163,7 +163,7 @@ function generate_discrete_affect(syss, inputs, continuous_id, id_to_clock; needed_cont_to_disc_obs = map(v -> arguments(v)[1], input) # TODO: filter the needed ones fullvars = Set{Any}(eq.lhs for eq in observed(sys)) - for s in states(sys) + for s in unknowns(sys) push!(fullvars, s) end needed_disc_to_cont_obs = [] @@ -175,7 +175,7 @@ function generate_discrete_affect(syss, inputs, continuous_id, id_to_clock; push!(disc_to_cont_idxs, param_to_idx[v]) end end - append!(appended_parameters, input, states(sys)) + append!(appended_parameters, input, unknowns(sys)) cont_to_disc_obs = build_explicit_observed_function(syss[continuous_id], needed_cont_to_disc_obs, throw = false, @@ -187,10 +187,10 @@ function generate_discrete_affect(syss, inputs, continuous_id, id_to_clock; expression = true, output_type = SVector) ni = length(input) - ns = length(states(sys)) + ns = length(unknowns(sys)) disc = Func([ out, - DestructuredArgs(states(sys)), + DestructuredArgs(unknowns(sys)), DestructuredArgs(appended_parameters), get_iv(sys), ], [], diff --git a/src/systems/connectors.jl b/src/systems/connectors.jl index 42ad27fb2b..81cd516cba 100644 --- a/src/systems/connectors.jl +++ b/src/systems/connectors.jl @@ -27,7 +27,7 @@ struct RegularConnector <: AbstractConnectorType end struct DomainConnector <: AbstractConnectorType end function connector_type(sys::AbstractSystem) - sts = get_states(sys) + sts = get_unknowns(sys) n_stream = 0 n_flow = 0 n_regular = 0 # state that is not input, output, stream, or flow. @@ -66,7 +66,7 @@ SymbolicUtils.promote_symtype(::typeof(instream), _) = Real isconnector(s::AbstractSystem) = has_connector_type(s) && get_connector_type(s) !== nothing function flowvar(sys::AbstractSystem) - sts = get_states(sys) + sts = get_unknowns(sys) for s in sts vtype = get_connection_type(s) vtype === Flow && return s @@ -171,8 +171,8 @@ function Base.hash(e::ConnectionElement, salt::UInt) end e.h ⊻ salt end -namespaced_var(l::ConnectionElement) = states(l, l.v) -states(l::ConnectionElement, v) = states(copy(l.sys), v) +namespaced_var(l::ConnectionElement) = unknowns(l, l.v) +unknowns(l::ConnectionElement, v) = unknowns(copy(l.sys), v) function withtrueouter(e::ConnectionElement) e.isouter && return e @@ -238,9 +238,9 @@ function connection2set!(connectionsets, namespace, ss, isouter) # domain connections don't generate any equations if domain_ss !== nothing cset = ConnectionElement[] - dv = only(states(domain_ss)) + dv = only(unknowns(domain_ss)) for (i, s) in enumerate(ss) - sts = states(s) + sts = unknowns(s) io = isouter(s) for (j, v) in enumerate(sts) vtype = get_connection_type(v) @@ -254,7 +254,7 @@ function connection2set!(connectionsets, namespace, ss, isouter) return connectionsets end s1 = first(ss) - sts1v = states(s1) + sts1v = unknowns(s1) if isframe(s1) # Multibody O = ori(s1) orientation_vars = Symbolics.unwrap.(collect(vec(O.R))) @@ -264,7 +264,7 @@ function connection2set!(connectionsets, namespace, ss, isouter) num_statevars = length(sts1) csets = [T[] for _ in 1:num_statevars] # Add 9 orientation variables if connection is between multibody frames for (i, s) in enumerate(ss) - sts = states(s) + sts = unknowns(s) if isframe(s) # Multibody O = ori(s) orientation_vars = Symbolics.unwrap.(vec(O.R)) @@ -281,7 +281,7 @@ function connection2set!(connectionsets, namespace, ss, isouter) v = first(cset).v vtype = get_connection_type(v) if domain_ss !== nothing && vtype === Flow && - (dv = only(states(domain_ss)); isequal(v, dv)) + (dv = only(unknowns(domain_ss)); isequal(v, dv)) push!(cset, T(LazyNamespace(namespace, domain_ss), dv, false)) end for k in 2:length(cset) @@ -339,7 +339,7 @@ function generate_connection_set!(connectionsets, domain_csets, for s in subsys isconnector(s) || continue is_domain_connector(s) && continue - for v in states(s) + for v in unknowns(s) Flow === get_connection_type(v) || continue push!(connectionsets, ConnectionSet([T(LazyNamespace(namespace, s), v, false)])) end @@ -351,7 +351,7 @@ function generate_connection_set!(connectionsets, domain_csets, # pre order traversal if !isempty(extra_states) - @set! sys.states = [get_states(sys); extra_states] + @set! sys.unknowns = [get_unknowns(sys); extra_states] end @set! sys.systems = map(s -> generate_connection_set!(connectionsets, domain_csets, s, find, replace, @@ -453,7 +453,7 @@ function domain_defaults(sys, domain_csets) elseif is_domain_connector(m.sys.sys) error("Domain sources $(nameof(root)) and $(nameof(m)) are connected!") else - ns_s_def = Dict(states(m.sys.sys, n) => n for (n, v) in s_def) + ns_s_def = Dict(unknowns(m.sys.sys, n) => n for (n, v) in s_def) for p in parameters(m.sys.namespace) d_p = get(ns_s_def, p, nothing) if d_p !== nothing @@ -605,11 +605,11 @@ function expand_instream(csets::AbstractVector{<:ConnectionSet}, sys::AbstractSy vtype = get_connection_type(sv) vtype === Stream || continue if n_inners == 1 && n_outers == 1 - push!(additional_eqs, states(cset[1].sys.sys, sv) ~ states(cset[2].sys.sys, sv)) + push!(additional_eqs, unknowns(cset[1].sys.sys, sv) ~ unknowns(cset[2].sys.sys, sv)) elseif n_inners == 0 && n_outers == 2 # we don't expand `instream` in this case. - v1 = states(cset[1].sys.sys, sv) - v2 = states(cset[2].sys.sys, sv) + v1 = unknowns(cset[1].sys.sys, sv) + v2 = unknowns(cset[2].sys.sys, sv) push!(additional_eqs, v1 ~ instream(v2)) push!(additional_eqs, v2 ~ instream(v1)) else @@ -617,29 +617,29 @@ function expand_instream(csets::AbstractVector{<:ConnectionSet}, sys::AbstractSy s_inners = (s for s in cset if !s.isouter) s_outers = (s for s in cset if s.isouter) for (q, oscq) in enumerate(s_outers) - sq += sum(s -> max(-states(s, fv), 0), s_inners, init = 0) + sq += sum(s -> max(-unknowns(s, fv), 0), s_inners, init = 0) for (k, s) in enumerate(s_outers) k == q && continue - f = states(s.sys.sys, fv) + f = unknowns(s.sys.sys, fv) sq += max(f, 0) end num = 0 den = 0 for s in s_inners - f = states(s.sys.sys, fv) + f = unknowns(s.sys.sys, fv) tmp = positivemax(-f, sq; tol = tol) den += tmp - num += tmp * states(s.sys.sys, sv) + num += tmp * unknowns(s.sys.sys, sv) end for (k, s) in enumerate(s_outers) k == q && continue - f = states(s.sys.sys, fv) + f = unknowns(s.sys.sys, fv) tmp = positivemax(f, sq; tol = tol) den += tmp - num += tmp * instream(states(s.sys.sys, sv)) + num += tmp * instream(unknowns(s.sys.sys, sv)) end - push!(additional_eqs, states(oscq.sys.sys, sv) ~ num / den) + push!(additional_eqs, unknowns(oscq.sys.sys, sv) ~ num / den) end end end @@ -664,7 +664,7 @@ function expand_instream(csets::AbstractVector{<:ConnectionSet}, sys::AbstractSy end function get_current_var(namespace, cele, sv) - states(renamespace(unnamespace(namespace, _getname(cele.sys.namespace)), cele.sys.sys), + unknowns(renamespace(unnamespace(namespace, _getname(cele.sys.namespace)), cele.sys.sys), sv) end diff --git a/src/systems/dependency_graphs.jl b/src/systems/dependency_graphs.jl index 68b43538b0..cb88021e95 100644 --- a/src/systems/dependency_graphs.jl +++ b/src/systems/dependency_graphs.jl @@ -1,6 +1,6 @@ """ ```julia -equation_dependencies(sys::AbstractSystem; variables = states(sys)) +equation_dependencies(sys::AbstractSystem; variables = unknowns(sys)) ``` Given an `AbstractSystem` calculate for each equation the variables it depends on. @@ -35,7 +35,7 @@ equation_dependencies(jumpsys) equation_dependencies(jumpsys, variables = parameters(jumpsys)) ``` """ -function equation_dependencies(sys::AbstractSystem; variables = states(sys)) +function equation_dependencies(sys::AbstractSystem; variables = unknowns(sys)) eqs = equations(sys) deps = Set() depeqs_to_vars = Vector{Vector}(undef, length(eqs)) @@ -67,7 +67,7 @@ Continuing the example started in [`equation_dependencies`](@ref) ```julia digr = asgraph(equation_dependencies(jumpsys), - Dict(s => i for (i, s) in enumerate(states(jumpsys)))) + Dict(s => i for (i, s) in enumerate(unknowns(jumpsys)))) ``` """ function asgraph(eqdeps, vtois) @@ -89,7 +89,7 @@ end # could be made to directly generate graph and save memory """ ```julia -asgraph(sys::AbstractSystem; variables = states(sys), +asgraph(sys::AbstractSystem; variables = unknowns(sys), variablestoids = Dict(convert(Variable, v) => i for (i, v) in enumerate(variables))) ``` @@ -98,7 +98,7 @@ to the indices of variables they depend on. Notes: - - Defaults for kwargs creating a mapping from `equations(sys)` to `states(sys)` + - Defaults for kwargs creating a mapping from `equations(sys)` to `unknowns(sys)` they depend on. - `variables` should provide the list of variables to use for generating the dependency graph. @@ -112,14 +112,14 @@ Continuing the example started in [`equation_dependencies`](@ref) digr = asgraph(jumpsys) ``` """ -function asgraph(sys::AbstractSystem; variables = states(sys), +function asgraph(sys::AbstractSystem; variables = unknowns(sys), variablestoids = Dict(v => i for (i, v) in enumerate(variables))) asgraph(equation_dependencies(sys, variables = variables), variablestoids) end """ ```julia -variable_dependencies(sys::AbstractSystem; variables = states(sys), +variable_dependencies(sys::AbstractSystem; variables = unknowns(sys), variablestoids = nothing) ``` @@ -139,7 +139,7 @@ Continuing the example of [`equation_dependencies`](@ref) variable_dependencies(jumpsys) ``` """ -function variable_dependencies(sys::AbstractSystem; variables = states(sys), +function variable_dependencies(sys::AbstractSystem; variables = unknowns(sys), variablestoids = nothing) eqs = equations(sys) vtois = isnothing(variablestoids) ? Dict(v => i for (i, v) in enumerate(variables)) : @@ -165,7 +165,7 @@ end """ ```julia -asdigraph(g::BipartiteGraph, sys::AbstractSystem; variables = states(sys), +asdigraph(g::BipartiteGraph, sys::AbstractSystem; variables = unknowns(sys), equationsfirst = true) ``` @@ -191,7 +191,7 @@ Continuing the example in [`asgraph`](@ref) dg = asdigraph(digr, jumpsys) ``` """ -function asdigraph(g::BipartiteGraph, sys::AbstractSystem; variables = states(sys), +function asdigraph(g::BipartiteGraph, sys::AbstractSystem; variables = unknowns(sys), equationsfirst = true) neqs = length(equations(sys)) nvars = length(variables) diff --git a/src/systems/diffeqs/abstractodesystem.jl b/src/systems/diffeqs/abstractodesystem.jl index 7d22cadc3b..5e2121dd59 100644 --- a/src/systems/diffeqs/abstractodesystem.jl +++ b/src/systems/diffeqs/abstractodesystem.jl @@ -22,7 +22,7 @@ function calculate_tgrad(sys::AbstractODESystem; # t + u(t)`. rhs = [detime_dvs(eq.rhs) for eq in full_equations(sys)] iv = get_iv(sys) - xs = states(sys) + xs = unknowns(sys) rule = Dict(map((x, xt) -> xt => x, detime_dvs.(xs), xs)) rhs = substitute.(rhs, Ref(rule)) tgrad = [expand_derivatives(Differential(iv)(r), simplify) for r in rhs] @@ -33,8 +33,8 @@ function calculate_tgrad(sys::AbstractODESystem; end function calculate_jacobian(sys::AbstractODESystem; - sparse = false, simplify = false, dvs = states(sys)) - if isequal(dvs, states(sys)) + sparse = false, simplify = false, dvs = unknowns(sys)) + if isequal(dvs, unknowns(sys)) cache = get_jac(sys)[] if cache isa Tuple && cache[2] == (sparse, simplify) return cache[1] @@ -51,7 +51,7 @@ function calculate_jacobian(sys::AbstractODESystem; jac = jacobian(rhs, dvs, simplify = simplify) end - if isequal(dvs, states(sys)) + if isequal(dvs, unknowns(sys)) get_jac(sys)[] = jac, (sparse, simplify) # cache Jacobian end @@ -80,7 +80,7 @@ function calculate_control_jacobian(sys::AbstractODESystem; return jac end -function generate_tgrad(sys::AbstractODESystem, dvs = states(sys), ps = parameters(sys); +function generate_tgrad(sys::AbstractODESystem, dvs = unknowns(sys), ps = parameters(sys); simplify = false, kwargs...) tgrad = calculate_tgrad(sys, simplify = simplify) pre = get_preprocess_constants(tgrad) @@ -101,7 +101,7 @@ function generate_tgrad(sys::AbstractODESystem, dvs = states(sys), ps = paramete end end -function generate_jacobian(sys::AbstractODESystem, dvs = states(sys), ps = parameters(sys); +function generate_jacobian(sys::AbstractODESystem, dvs = unknowns(sys), ps = parameters(sys); simplify = false, sparse = false, kwargs...) jac = calculate_jacobian(sys; simplify = simplify, sparse = sparse) pre = get_preprocess_constants(jac) @@ -117,21 +117,21 @@ function generate_jacobian(sys::AbstractODESystem, dvs = states(sys), ps = param end end -function generate_control_jacobian(sys::AbstractODESystem, dvs = states(sys), +function generate_control_jacobian(sys::AbstractODESystem, dvs = unknowns(sys), ps = parameters(sys); simplify = false, sparse = false, kwargs...) jac = calculate_control_jacobian(sys; simplify = simplify, sparse = sparse) return build_function(jac, dvs, ps, get_iv(sys); kwargs...) end -function generate_dae_jacobian(sys::AbstractODESystem, dvs = states(sys), +function generate_dae_jacobian(sys::AbstractODESystem, dvs = unknowns(sys), ps = parameters(sys); simplify = false, sparse = false, kwargs...) jac_u = calculate_jacobian(sys; simplify = simplify, sparse = sparse) - derivatives = Differential(get_iv(sys)).(states(sys)) + derivatives = Differential(get_iv(sys)).(unknowns(sys)) jac_du = calculate_jacobian(sys; simplify = simplify, sparse = sparse, dvs = derivatives) - dvs = states(sys) + dvs = unknowns(sys) @variables ˍ₋gamma jac = ˍ₋gamma * jac_du + jac_u pre = get_preprocess_constants(jac) @@ -139,7 +139,7 @@ function generate_dae_jacobian(sys::AbstractODESystem, dvs = states(sys), postprocess_fbody = pre, kwargs...) end -function generate_function(sys::AbstractODESystem, dvs = states(sys), ps = parameters(sys); +function generate_function(sys::AbstractODESystem, dvs = unknowns(sys), ps = parameters(sys); implicit_dae = false, ddvs = implicit_dae ? map(Differential(get_iv(sys)), dvs) : nothing, @@ -201,7 +201,7 @@ const DDE_HISTORY_FUN = Sym{Symbolics.FnType{Tuple{Any, <:Real}, Vector{Real}}}( function delay_to_function(sys::AbstractODESystem, eqs = full_equations(sys)) delay_to_function(eqs, get_iv(sys), - Dict{Any, Int}(operation(s) => i for (i, s) in enumerate(states(sys))), + Dict{Any, Int}(operation(s) => i for (i, s) in enumerate(unknowns(sys))), parameters(sys), DDE_HISTORY_FUN) end @@ -226,7 +226,7 @@ function delay_to_function(expr, iv, sts, ps, h) end end -function generate_difference_cb(sys::ODESystem, dvs = states(sys), ps = parameters(sys); +function generate_difference_cb(sys::ODESystem, dvs = unknowns(sys), ps = parameters(sys); kwargs...) eqs = equations(sys) check_operator_variables(eqs, Difference) @@ -274,7 +274,7 @@ end function calculate_massmatrix(sys::AbstractODESystem; simplify = false) eqs = [eq for eq in equations(sys) if !isdifferenceeq(eq)] - dvs = states(sys) + dvs = unknowns(sys) M = zeros(length(eqs), length(eqs)) state2idx = Dict(s => i for (i, s) in enumerate(dvs)) for (i, eq) in enumerate(eqs) @@ -297,13 +297,13 @@ function jacobian_sparsity(sys::AbstractODESystem) sparsity === nothing || return sparsity jacobian_sparsity([eq.rhs for eq in full_equations(sys)], - [dv for dv in states(sys)]) + [dv for dv in unknowns(sys)]) end function jacobian_dae_sparsity(sys::AbstractODESystem) J1 = jacobian_sparsity([eq.rhs for eq in full_equations(sys)], - [dv for dv in states(sys)]) - derivatives = Differential(get_iv(sys)).(states(sys)) + [dv for dv in unknowns(sys)]) + derivatives = Differential(get_iv(sys)).(unknowns(sys)) J2 = jacobian_sparsity([eq.rhs for eq in full_equations(sys)], [dv for dv in derivatives]) J1 + J2 @@ -316,7 +316,7 @@ end """ ```julia -DiffEqBase.ODEFunction{iip}(sys::AbstractODESystem, dvs = states(sys), +DiffEqBase.ODEFunction{iip}(sys::AbstractODESystem, dvs = unknowns(sys), ps = parameters(sys); version = nothing, tgrad = false, jac = false, @@ -342,7 +342,7 @@ function DiffEqBase.ODEFunction{false}(sys::AbstractODESystem, args...; ODEFunction{false, SciMLBase.FullSpecialize}(sys, args...; kwargs...) end -function DiffEqBase.ODEFunction{iip, specialize}(sys::AbstractODESystem, dvs = states(sys), +function DiffEqBase.ODEFunction{iip, specialize}(sys::AbstractODESystem, dvs = unknowns(sys), ps = parameters(sys), u0 = nothing; version = nothing, tgrad = false, jac = false, p = nothing, @@ -516,7 +516,7 @@ function DiffEqBase.ODEFunction{iip, specialize}(sys::AbstractODESystem, dvs = s tgrad = _tgrad === nothing ? nothing : _tgrad, mass_matrix = _M, jac_prototype = jac_prototype, - syms = collect(Symbol.(states(sys))), + syms = collect(Symbol.(unknowns(sys))), indepsym = Symbol(get_iv(sys)), paramsyms = collect(Symbol.(ps)), observed = observedfun, @@ -526,7 +526,7 @@ end """ ```julia -DiffEqBase.DAEFunction{iip}(sys::AbstractODESystem, dvs = states(sys), +DiffEqBase.DAEFunction{iip}(sys::AbstractODESystem, dvs = unknowns(sys), ps = parameters(sys); version = nothing, tgrad = false, jac = false, @@ -542,7 +542,7 @@ function DiffEqBase.DAEFunction(sys::AbstractODESystem, args...; kwargs...) DAEFunction{true}(sys, args...; kwargs...) end -function DiffEqBase.DAEFunction{iip}(sys::AbstractODESystem, dvs = states(sys), +function DiffEqBase.DAEFunction{iip}(sys::AbstractODESystem, dvs = unknowns(sys), ps = parameters(sys), u0 = nothing; ddvs = map(diff2term ∘ Differential(get_iv(sys)), dvs), version = nothing, p = nothing, @@ -598,7 +598,7 @@ function DiffEqBase.DAEFunction{iip}(sys::AbstractODESystem, dvs = states(sys), uElType = u0 === nothing ? Float64 : eltype(u0) if jac J1 = calculate_jacobian(sys, sparse = sparse) - derivatives = Differential(get_iv(sys)).(states(sys)) + derivatives = Differential(get_iv(sys)).(unknowns(sys)) J2 = calculate_jacobian(sys; sparse = sparse, dvs = derivatives) similar(J1 + J2, uElType) else @@ -622,7 +622,7 @@ function DiffEqBase.DDEFunction(sys::AbstractODESystem, args...; kwargs...) DDEFunction{true}(sys, args...; kwargs...) end -function DiffEqBase.DDEFunction{iip}(sys::AbstractODESystem, dvs = states(sys), +function DiffEqBase.DDEFunction{iip}(sys::AbstractODESystem, dvs = unknowns(sys), ps = parameters(sys), u0 = nothing; eval_module = @__MODULE__, checkbounds = false, @@ -646,7 +646,7 @@ function DiffEqBase.SDDEFunction(sys::AbstractODESystem, args...; kwargs...) SDDEFunction{true}(sys, args...; kwargs...) end -function DiffEqBase.SDDEFunction{iip}(sys::AbstractODESystem, dvs = states(sys), +function DiffEqBase.SDDEFunction{iip}(sys::AbstractODESystem, dvs = unknowns(sys), ps = parameters(sys), u0 = nothing; eval_module = @__MODULE__, checkbounds = false, @@ -673,7 +673,7 @@ end """ ```julia -ODEFunctionExpr{iip}(sys::AbstractODESystem, dvs = states(sys), +ODEFunctionExpr{iip}(sys::AbstractODESystem, dvs = unknowns(sys), ps = parameters(sys); version = nothing, tgrad = false, jac = false, @@ -694,7 +694,7 @@ end (f::ODEFunctionClosure)(u, p, t) = f.f_oop(u, p, t) (f::ODEFunctionClosure)(du, u, p, t) = f.f_iip(du, u, p, t) -function ODEFunctionExpr{iip}(sys::AbstractODESystem, dvs = states(sys), +function ODEFunctionExpr{iip}(sys::AbstractODESystem, dvs = unknowns(sys), ps = parameters(sys), u0 = nothing; version = nothing, tgrad = false, jac = false, p = nothing, @@ -751,7 +751,7 @@ function ODEFunctionExpr{iip}(sys::AbstractODESystem, dvs = states(sys), tgrad = $tgradsym, mass_matrix = M, jac_prototype = $jp_expr, - syms = $(Symbol.(states(sys))), + syms = $(Symbol.(unknowns(sys))), indepsym = $(QuoteNode(Symbol(get_iv(sys)))), paramsyms = $(Symbol.(parameters(sys))), sparsity = $(sparsity ? jacobian_sparsity(sys) : nothing), @@ -771,7 +771,7 @@ function get_u0_p(sys, use_union = true, tofloat = true, symbolic_u0 = false) - dvs = states(sys) + dvs = unknowns(sys) ps = parameters(sys) defs = defaults(sys) @@ -804,7 +804,7 @@ function process_DEProblem(constructor, sys::AbstractODESystem, u0map, parammap; u0_constructor = identity, kwargs...) eqs = equations(sys) - dvs = states(sys) + dvs = unknowns(sys) ps = parameters(sys) iv = get_iv(sys) @@ -850,7 +850,7 @@ end """ ```julia -DAEFunctionExpr{iip}(sys::AbstractODESystem, dvs = states(sys), +DAEFunctionExpr{iip}(sys::AbstractODESystem, dvs = unknowns(sys), ps = parameters(sys); version = nothing, tgrad = false, jac = false, @@ -871,7 +871,7 @@ end (f::DAEFunctionClosure)(du, u, p, t) = f.f_oop(du, u, p, t) (f::DAEFunctionClosure)(out, du, u, p, t) = f.f_iip(out, du, u, p, t) -function DAEFunctionExpr{iip}(sys::AbstractODESystem, dvs = states(sys), +function DAEFunctionExpr{iip}(sys::AbstractODESystem, dvs = unknowns(sys), ps = parameters(sys), u0 = nothing; version = nothing, tgrad = false, jac = false, p = nothing, @@ -1015,7 +1015,7 @@ function DiffEqBase.DAEProblem{iip}(sys::AbstractODESystem, du0map, u0map, tspan has_difference = has_difference, check_length, kwargs...) diffvars = collect_differential_variables(sys) - sts = states(sys) + sts = unknowns(sys) differential_vars = map(Base.Fix2(in, diffvars), sts) kwargs = filter_kwargs(kwargs) @@ -1235,7 +1235,7 @@ function DAEProblemExpr{iip}(sys::AbstractODESystem, du0map, u0map, tspan, kwargs...) linenumbers = get(kwargs, :linenumbers, true) diffvars = collect_differential_variables(sys) - sts = states(sys) + sts = unknowns(sys) differential_vars = map(Base.Fix2(in, diffvars), sts) kwargs = filter_kwargs(kwargs) kwarg_params = gen_quoted_kwargs(kwargs) @@ -1346,7 +1346,7 @@ function isisomorphic(sys1::AbstractODESystem, sys2::AbstractODESystem) iv2 = only(independent_variables(sys2)) sys1 = convert_system(ODESystem, sys1, iv2) - s1, s2 = states(sys1), states(sys2) + s1, s2 = unknowns(sys1), unknowns(sys2) p1, p2 = parameters(sys1), parameters(sys2) (length(s1) != length(s2)) || (length(p1) != length(p2)) && return false diff --git a/src/systems/diffeqs/basic_transformations.jl b/src/systems/diffeqs/basic_transformations.jl index dc48accd05..abd3388a0b 100644 --- a/src/systems/diffeqs/basic_transformations.jl +++ b/src/systems/diffeqs/basic_transformations.jl @@ -51,6 +51,6 @@ function liouville_transform(sys::AbstractODESystem) D = ModelingToolkit.Differential(t) neweq = D(trJ) ~ trJ * -tr(calculate_jacobian(sys)) neweqs = [equations(sys); neweq] - vars = [states(sys); trJ] + vars = [unknowns(sys); trJ] ODESystem(neweqs, t, vars, parameters(sys), checks = false) end diff --git a/src/systems/diffeqs/first_order_transform.jl b/src/systems/diffeqs/first_order_transform.jl index 6f039fa53f..517cdb8786 100644 --- a/src/systems/diffeqs/first_order_transform.jl +++ b/src/systems/diffeqs/first_order_transform.jl @@ -6,17 +6,17 @@ form by defining new variables which represent the N-1 derivatives. """ function ode_order_lowering(sys::ODESystem) iv = get_iv(sys) - eqs_lowered, new_vars = ode_order_lowering(equations(sys), iv, states(sys)) + eqs_lowered, new_vars = ode_order_lowering(equations(sys), iv, unknowns(sys)) @set! sys.eqs = eqs_lowered - @set! sys.states = new_vars + @set! sys.unknowns = new_vars return sys end function dae_order_lowering(sys::ODESystem) iv = get_iv(sys) - eqs_lowered, new_vars = dae_order_lowering(equations(sys), iv, states(sys)) + eqs_lowered, new_vars = dae_order_lowering(equations(sys), iv, unknowns(sys)) @set! sys.eqs = eqs_lowered - @set! sys.states = new_vars + @set! sys.unknowns = new_vars return sys end diff --git a/src/systems/diffeqs/modelingtoolkitize.jl b/src/systems/diffeqs/modelingtoolkitize.jl index c29ef022c6..424e499388 100644 --- a/src/systems/diffeqs/modelingtoolkitize.jl +++ b/src/systems/diffeqs/modelingtoolkitize.jl @@ -161,7 +161,7 @@ Generate `SDESystem`, dependent variables, and parameters from an `SDEProblem`. """ function modelingtoolkitize(prob::DiffEqBase.SDEProblem; kwargs...) prob.f isa DiffEqBase.AbstractParameterizedFunction && - return (prob.f.sys, prob.f.sys.states, prob.f.sys.ps) + return (prob.f.sys, prob.f.sys.unknowns, prob.f.sys.ps) @parameters t p = prob.p has_p = !(p isa Union{DiffEqBase.NullParameters, Nothing}) diff --git a/src/systems/diffeqs/odesystem.jl b/src/systems/diffeqs/odesystem.jl index 508cb8cfe5..93d02b6074 100644 --- a/src/systems/diffeqs/odesystem.jl +++ b/src/systems/diffeqs/odesystem.jl @@ -38,7 +38,7 @@ struct ODESystem <: AbstractODESystem N.B.: If `torn_matching !== nothing`, this includes all variables. Actual ODE states are determined by the `SelectedState()` entries in `torn_matching`. """ - states::Vector + unknowns::Vector """Parameter variables. Must not contain the independent variable.""" ps::Vector """Time span.""" @@ -47,7 +47,7 @@ struct ODESystem <: AbstractODESystem var_to_name::Any """Control parameters (some subset of `ps`).""" ctrls::Vector - """Observed states.""" + """Observed variables.""" observed::Vector{Equation} """ Time-derivative matrix. Note: this field will not be defined until @@ -138,7 +138,7 @@ struct ODESystem <: AbstractODESystem A list of actual states needed to be solved by solvers. Only used for ODAEProblem. """ - unknown_states::Union{Nothing, Vector{Any}} + solved_unknowns::Union{Nothing, Vector{Any}} """ A vector of vectors of indices for the split parameters. """ @@ -154,7 +154,7 @@ struct ODESystem <: AbstractODESystem devents, metadata = nothing, gui_metadata = nothing, tearing_state = nothing, substitutions = nothing, complete = false, - discrete_subsystems = nothing, unknown_states = nothing, + discrete_subsystems = nothing, solved_unknowns = nothing, split_idxs = nothing, parent = nothing; checks::Union{Bool, Int} = true) if checks == true || (checks & CheckComponents) > 0 check_variables(dvs, iv) @@ -170,7 +170,7 @@ struct ODESystem <: AbstractODESystem ctrl_jac, Wfact, Wfact_t, name, systems, defaults, torn_matching, connector_type, preface, cevents, devents, metadata, gui_metadata, tearing_state, substitutions, complete, discrete_subsystems, - unknown_states, split_idxs, parent) + solved_unknowns, split_idxs, parent) end end @@ -286,7 +286,7 @@ function Base.:(==)(sys1::ODESystem, sys2::ODESystem) isequal(iv1, iv2) && isequal(nameof(sys1), nameof(sys2)) && _eq_unordered(get_eqs(sys1), get_eqs(sys2)) && - _eq_unordered(get_states(sys1), get_states(sys2)) && + _eq_unordered(get_unknowns(sys1), get_unknowns(sys2)) && _eq_unordered(get_ps(sys1), get_ps(sys2)) && all(s1 == s2 for (s1, s2) in zip(get_systems(sys1), get_systems(sys2))) end @@ -298,7 +298,7 @@ function flatten(sys::ODESystem, noeqs = false) else return ODESystem(noeqs ? Equation[] : equations(sys), get_iv(sys), - states(sys), + unknowns(sys), parameters(sys), observed = observed(sys), continuous_events = continuous_events(sys), @@ -343,12 +343,12 @@ function build_explicit_observed_function(sys, ts; obs = map(x -> x.lhs ~ substitute(x.rhs, cmap), obs) end - sts = Set(states(sys)) + sts = Set(unknowns(sys)) observed_idx = Dict(x.lhs => i for (i, x) in enumerate(obs)) param_set = Set(parameters(sys)) - param_set_ns = Set(states(sys, p) for p in parameters(sys)) - namespaced_to_obs = Dict(states(sys, x.lhs) => x.lhs for x in obs) - namespaced_to_sts = Dict(states(sys, x) => x for x in states(sys)) + param_set_ns = Set(unknowns(sys, p) for p in parameters(sys)) + namespaced_to_obs = Dict(unknowns(sys, x.lhs) => x.lhs for x in obs) + namespaced_to_sts = Dict(unknowns(sys, x) => x for x in unknowns(sys)) # FIXME: This is a rather rough estimate of dependencies. We assume # the expression depends on everything before the `maxidx`. @@ -403,7 +403,7 @@ function build_explicit_observed_function(sys, ts; else ps = (DestructuredArgs(ps, inbounds = !checkbounds),) end - dvs = DestructuredArgs(states(sys), inbounds = !checkbounds) + dvs = DestructuredArgs(unknowns(sys), inbounds = !checkbounds) if inputs === nothing args = [dvs, ps..., ivs...] else @@ -446,7 +446,7 @@ function convert_system(::Type{<:ODESystem}, sys, t; name = nameof(sys)) throw(ArgumentError("`convert_system` cannot handle reduced model (i.e. observed(sys) is non-empty).")) t = value(t) varmap = Dict() - sts = states(sys) + sts = unknowns(sys) newsts = similar(sts, Any) for (i, s) in enumerate(sts) if istree(s) @@ -483,7 +483,7 @@ $(SIGNATURES) Add accumulation variables for `vars`. """ -function add_accumulations(sys::ODESystem, vars = states(sys)) +function add_accumulations(sys::ODESystem, vars = unknowns(sys)) avars = [rename(v, Symbol(:accumulation_, getname(v))) for v in vars] add_accumulations(sys, avars .=> vars) end @@ -503,11 +503,11 @@ the cumulative `x + y` and `x^2` would be added to `sys`. function add_accumulations(sys::ODESystem, vars::Vector{<:Pair}) eqs = get_eqs(sys) avars = map(first, vars) - if (ints = intersect(avars, states(sys)); !isempty(ints)) + if (ints = intersect(avars, unknowns(sys)); !isempty(ints)) error("$ints already exist in the system!") end D = Differential(get_iv(sys)) @set! sys.eqs = [eqs; Equation[D(a) ~ v[2] for (a, v) in zip(avars, vars)]] - @set! sys.states = [get_states(sys); avars] + @set! sys.unknowns = [get_unknowns(sys); avars] @set! sys.defaults = merge(get_defaults(sys), Dict(a => 0.0 for a in avars)) end diff --git a/src/systems/diffeqs/sdesystem.jl b/src/systems/diffeqs/sdesystem.jl index 5f3f9fb00f..66cc92026d 100644 --- a/src/systems/diffeqs/sdesystem.jl +++ b/src/systems/diffeqs/sdesystem.jl @@ -39,7 +39,7 @@ struct SDESystem <: AbstractODESystem """Independent variable.""" iv::BasicSymbolic{Real} """Dependent (state) variables. Must not contain the independent variable.""" - states::Vector + unknowns::Vector """Parameter variables. Must not contain the independent variable.""" ps::Vector """Time span.""" @@ -48,7 +48,7 @@ struct SDESystem <: AbstractODESystem var_to_name::Any """Control parameters (some subset of `ps`).""" ctrls::Vector - """Observed states.""" + """Observed variables.""" observed::Vector{Equation} """ Time-derivative matrix. Note: this field will not be defined until @@ -198,7 +198,7 @@ function SDESystem(deqs::AbstractVector{<:Equation}, neqs::AbstractArray, iv, dv end function SDESystem(sys::ODESystem, neqs; kwargs...) - SDESystem(equations(sys), neqs, get_iv(sys), states(sys), parameters(sys); kwargs...) + SDESystem(equations(sys), neqs, get_iv(sys), unknowns(sys), parameters(sys); kwargs...) end function Base.:(==)(sys1::SDESystem, sys2::SDESystem) @@ -209,12 +209,12 @@ function Base.:(==)(sys1::SDESystem, sys2::SDESystem) isequal(nameof(sys1), nameof(sys2)) && isequal(get_eqs(sys1), get_eqs(sys2)) && isequal(get_noiseeqs(sys1), get_noiseeqs(sys2)) && - _eq_unordered(get_states(sys1), get_states(sys2)) && + _eq_unordered(get_unknowns(sys1), get_unknowns(sys2)) && _eq_unordered(get_ps(sys1), get_ps(sys2)) && all(s1 == s2 for (s1, s2) in zip(get_systems(sys1), get_systems(sys2))) end -function generate_diffusion_function(sys::SDESystem, dvs = states(sys), +function generate_diffusion_function(sys::SDESystem, dvs = unknowns(sys), ps = parameters(sys); isdde = false, kwargs...) eqs = get_noiseeqs(sys) if isdde @@ -239,8 +239,8 @@ function stochastic_integral_transform(sys::SDESystem, correction_factor) # use the general interface if typeof(get_noiseeqs(sys)) <: Vector eqs = vcat([equations(sys)[i].lhs ~ get_noiseeqs(sys)[i] - for i in eachindex(states(sys))]...) - de = ODESystem(eqs, get_iv(sys), states(sys), parameters(sys), name = name, + for i in eachindex(unknowns(sys))]...) + de = ODESystem(eqs, get_iv(sys), unknowns(sys), parameters(sys), name = name, checks = false) jac = calculate_jacobian(de, sparse = false, simplify = false) @@ -248,12 +248,12 @@ function stochastic_integral_transform(sys::SDESystem, correction_factor) deqs = vcat([equations(sys)[i].lhs ~ equations(sys)[i].rhs + correction_factor * ∇σσ′[i] - for i in eachindex(states(sys))]...) + for i in eachindex(unknowns(sys))]...) else dimstate, m = size(get_noiseeqs(sys)) eqs = vcat([equations(sys)[i].lhs ~ get_noiseeqs(sys)[i] - for i in eachindex(states(sys))]...) - de = ODESystem(eqs, get_iv(sys), states(sys), parameters(sys), name = name, + for i in eachindex(unknowns(sys))]...) + de = ODESystem(eqs, get_iv(sys), unknowns(sys), parameters(sys), name = name, checks = false) jac = calculate_jacobian(de, sparse = false, simplify = false) @@ -261,8 +261,8 @@ function stochastic_integral_transform(sys::SDESystem, correction_factor) for k in 2:m eqs = vcat([equations(sys)[i].lhs ~ get_noiseeqs(sys)[Int(i + (k - 1) * dimstate)] - for i in eachindex(states(sys))]...) - de = ODESystem(eqs, get_iv(sys), states(sys), parameters(sys), name = name, + for i in eachindex(unknowns(sys))]...) + de = ODESystem(eqs, get_iv(sys), unknowns(sys), parameters(sys), name = name, checks = false) jac = calculate_jacobian(de, sparse = false, simplify = false) @@ -271,10 +271,10 @@ function stochastic_integral_transform(sys::SDESystem, correction_factor) deqs = vcat([equations(sys)[i].lhs ~ equations(sys)[i].rhs + correction_factor * ∇σσ′[i] - for i in eachindex(states(sys))]...) + for i in eachindex(unknowns(sys))]...) end - SDESystem(deqs, get_noiseeqs(sys), get_iv(sys), states(sys), parameters(sys), + SDESystem(deqs, get_noiseeqs(sys), get_iv(sys), unknowns(sys), parameters(sys), name = name, checks = false) end @@ -341,7 +341,7 @@ function Girsanov_transform(sys::SDESystem, u; θ0 = 1.0) # determine the adjustable parameters `d` given `u` # gradient of u with respect to states - grad = Symbolics.gradient(u, states(sys)) + grad = Symbolics.gradient(u, unknowns(sys)) noiseeqs = get_noiseeqs(sys) if noiseeqs isa Vector @@ -356,7 +356,7 @@ function Girsanov_transform(sys::SDESystem, u; θ0 = 1.0) # drift function for state is modified # θ has zero drift deqs = vcat([equations(sys)[i].lhs ~ equations(sys)[i].rhs - drift_correction[i] - for i in eachindex(states(sys))]...) + for i in eachindex(unknowns(sys))]...) deqsθ = D(θ) ~ 0 push!(deqs, deqsθ) @@ -378,7 +378,7 @@ function Girsanov_transform(sys::SDESystem, u; θ0 = 1.0) noiseeqs = [Array(noiseeqs); noiseqsθ'] end - state = [states(sys); θ] + state = [unknowns(sys); θ] # return modified SDE System SDESystem(deqs, noiseeqs, get_iv(sys), state, parameters(sys); @@ -386,7 +386,7 @@ function Girsanov_transform(sys::SDESystem, u; θ0 = 1.0) name = name, checks = false) end -function DiffEqBase.SDEFunction{iip}(sys::SDESystem, dvs = states(sys), +function DiffEqBase.SDEFunction{iip}(sys::SDESystem, dvs = unknowns(sys), ps = parameters(sys), u0 = nothing; version = nothing, tgrad = false, sparse = false, @@ -463,7 +463,7 @@ function DiffEqBase.SDEFunction{iip}(sys::SDESystem, dvs = states(sys), end end - sts = states(sys) + sts = unknowns(sys) SDEFunction{iip}(f, g, sys = sys, jac = _jac === nothing ? nothing : _jac, @@ -471,7 +471,7 @@ function DiffEqBase.SDEFunction{iip}(sys::SDESystem, dvs = states(sys), Wfact = _Wfact === nothing ? nothing : _Wfact, Wfact_t = _Wfact_t === nothing ? nothing : _Wfact_t, mass_matrix = _M, - syms = Symbol.(states(sys)), + syms = Symbol.(unknowns(sys)), indepsym = Symbol(get_iv(sys)), paramsyms = Symbol.(ps), observed = observedfun) @@ -479,7 +479,7 @@ end """ ```julia -DiffEqBase.SDEFunction{iip}(sys::SDESystem, dvs = sys.states, ps = sys.ps; +DiffEqBase.SDEFunction{iip}(sys::SDESystem, dvs = sys.unknowns, ps = sys.ps; version = nothing, tgrad = false, sparse = false, jac = false, Wfact = false, kwargs...) where {iip} ``` @@ -494,7 +494,7 @@ end """ ```julia -DiffEqBase.SDEFunctionExpr{iip}(sys::AbstractODESystem, dvs = states(sys), +DiffEqBase.SDEFunctionExpr{iip}(sys::AbstractODESystem, dvs = unknowns(sys), ps = parameters(sys); version = nothing, tgrad = false, jac = false, Wfact = false, @@ -509,7 +509,7 @@ variable and parameter vectors, respectively. """ struct SDEFunctionExpr{iip} end -function SDEFunctionExpr{iip}(sys::SDESystem, dvs = states(sys), +function SDEFunctionExpr{iip}(sys::SDESystem, dvs = unknowns(sys), ps = parameters(sys), u0 = nothing; version = nothing, tgrad = false, jac = false, Wfact = false, @@ -558,7 +558,7 @@ function SDEFunctionExpr{iip}(sys::SDESystem, dvs = states(sys), Wfact = Wfact, Wfact_t = Wfact_t, mass_matrix = M, - syms = $(Symbol.(states(sys))), + syms = $(Symbol.(unknowns(sys))), indepsym = $(Symbol(get_iv(sys))), paramsyms = $(Symbol.(parameters(sys)))) end diff --git a/src/systems/discrete_system/discrete_system.jl b/src/systems/discrete_system/discrete_system.jl index dedb7bf6b3..08875b8da9 100644 --- a/src/systems/discrete_system/discrete_system.jl +++ b/src/systems/discrete_system/discrete_system.jl @@ -34,7 +34,7 @@ struct DiscreteSystem <: AbstractTimeDependentSystem """Independent variable.""" iv::BasicSymbolic{Real} """Dependent (state) variables. Must not contain the independent variable.""" - states::Vector + unknowns::Vector """Parameter variables. Must not contain the independent variable.""" ps::Vector """Time span.""" @@ -43,7 +43,7 @@ struct DiscreteSystem <: AbstractTimeDependentSystem var_to_name::Any """Control parameters (some subset of `ps`).""" ctrls::Vector - """Observed states.""" + """Observed variables.""" observed::Vector{Equation} """ The name of the system @@ -214,7 +214,7 @@ function SciMLBase.DiscreteProblem(sys::DiscreteSystem, u0map = [], tspan = get_ eval_expression = true, use_union = false, kwargs...) - dvs = states(sys) + dvs = unknowns(sys) ps = parameters(sys) eqs = equations(sys) eqs = linearize_eqs(sys, eqs) @@ -240,10 +240,10 @@ function SciMLBase.DiscreteProblem(sys::DiscreteSystem, u0map = [], tspan = get_ end function linearize_eqs(sys, eqs = get_eqs(sys); return_max_delay = false) - unique_states = unique(operation.(states(sys))) + unique_states = unique(operation.(unknowns(sys))) max_delay = Dict(v => 0.0 for v in unique_states) - r = @rule ~t::(t -> istree(t) && any(isequal(operation(t)), operation.(states(sys))) && is_delay_var(get_iv(sys), t)) => begin + r = @rule ~t::(t -> istree(t) && any(isequal(operation(t)), operation.(unknowns(sys))) && is_delay_var(get_iv(sys), t)) => begin delay = get_delay_val(get_iv(sys), first(arguments(~t))) if delay > max_delay[operation(~t)] max_delay[operation(~t)] = delay @@ -290,7 +290,7 @@ function get_delay_val(iv, x) return -delay end -function generate_function(sys::DiscreteSystem, dvs = states(sys), ps = parameters(sys); +function generate_function(sys::DiscreteSystem, dvs = unknowns(sys), ps = parameters(sys); kwargs...) eqs = equations(sys) check_operator_variables(eqs, Difference) @@ -307,7 +307,7 @@ end """ ```julia -SciMLBase.DiscreteFunction{iip}(sys::DiscreteSystem, dvs = states(sys), +SciMLBase.DiscreteFunction{iip}(sys::DiscreteSystem, dvs = unknowns(sys), ps = parameters(sys); version = nothing, kwargs...) where {iip} @@ -330,7 +330,7 @@ function SciMLBase.DiscreteFunction{false}(sys::DiscreteSystem, args...; kwargs. end function SciMLBase.DiscreteFunction{iip, specialize}(sys::DiscreteSystem, - dvs = states(sys), + dvs = unknowns(sys), ps = parameters(sys), u0 = nothing; version = nothing, @@ -367,7 +367,7 @@ function SciMLBase.DiscreteFunction{iip, specialize}(sys::DiscreteSystem, DiscreteFunction{iip, specialize}(f; sys = sys, - syms = Symbol.(states(sys)), + syms = Symbol.(unknowns(sys)), indepsym = Symbol(get_iv(sys)), paramsyms = Symbol.(ps), observed = observedfun, @@ -376,7 +376,7 @@ end """ ```julia -DiscreteFunctionExpr{iip}(sys::DiscreteSystem, dvs = states(sys), +DiscreteFunctionExpr{iip}(sys::DiscreteSystem, dvs = unknowns(sys), ps = parameters(sys); version = nothing, kwargs...) where {iip} @@ -394,7 +394,7 @@ end (f::DiscreteFunctionClosure)(u, p, t) = f.f_oop(u, p, t) (f::DiscreteFunctionClosure)(du, u, p, t) = f.f_iip(du, u, p, t) -function DiscreteFunctionExpr{iip}(sys::DiscreteSystem, dvs = states(sys), +function DiscreteFunctionExpr{iip}(sys::DiscreteSystem, dvs = unknowns(sys), ps = parameters(sys), u0 = nothing; version = nothing, p = nothing, linenumbers = false, @@ -408,7 +408,7 @@ function DiscreteFunctionExpr{iip}(sys::DiscreteSystem, dvs = states(sys), ex = quote $_f DiscreteFunction{$iip}($fsym, - syms = $(Symbol.(states(sys))), + syms = $(Symbol.(unknowns(sys))), indepsym = $(QuoteNode(Symbol(get_iv(sys)))), paramsyms = $(Symbol.(parameters(sys)))) end @@ -427,7 +427,7 @@ function process_DiscreteProblem(constructor, sys::DiscreteSystem, u0map, paramm tofloat = !use_union, kwargs...) eqs = equations(sys) - dvs = states(sys) + dvs = unknowns(sys) ps = parameters(sys) u0, p, defs = get_u0_p(sys, u0map, parammap; tofloat, use_union) diff --git a/src/systems/jumps/jumpsystem.jl b/src/systems/jumps/jumpsystem.jl index 6fe2b503e1..2fcb131422 100644 --- a/src/systems/jumps/jumpsystem.jl +++ b/src/systems/jumps/jumpsystem.jl @@ -61,12 +61,12 @@ struct JumpSystem{U <: ArrayPartition} <: AbstractTimeDependentSystem """The independent variable, usually time.""" iv::Any """The dependent variables, representing the state of the system. Must not contain the independent variable.""" - states::Vector + unknowns::Vector """The parameters of the system. Must not contain the independent variable.""" ps::Vector """Array variables.""" var_to_name::Any - """Observed states.""" + """Observed variables.""" observed::Vector{Equation} """The name of the system.""" name::Symbol @@ -102,25 +102,25 @@ 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, unknowns, ps, var_to_name, observed, name, systems, defaults, connector_type, devents, metadata = nothing, gui_metadata = nothing, complete = false; checks::Union{Bool, Int} = true) where {U <: ArrayPartition} if checks == true || (checks & CheckComponents) > 0 - check_variables(states, iv) + check_variables(unknowns, iv) check_parameters(ps, iv) end if checks == true || (checks & CheckUnits) > 0 - u = __get_unit_type(states, ps, iv) + u = __get_unit_type(unknowns, ps, iv) check_units(u, ap, iv) end - new{U}(tag, ap, iv, states, ps, var_to_name, observed, name, systems, defaults, + new{U}(tag, ap, iv, unknowns, ps, var_to_name, observed, name, systems, defaults, connector_type, devents, metadata, gui_metadata, complete) end end -function JumpSystem(eqs, iv, states, ps; +function JumpSystem(eqs, iv, unknowns, ps; observed = Equation[], systems = JumpSystem[], default_u0 = Dict(), @@ -160,9 +160,9 @@ function JumpSystem(eqs, iv, states, ps; defaults = todict(defaults) defaults = Dict(value(k) => value(v) for (k, v) in pairs(defaults)) - states, ps = value.(states), value.(ps) + unknowns, ps = value.(unknowns), value.(ps) var_to_name = Dict() - process_variables!(var_to_name, defaults, states) + process_variables!(var_to_name, defaults, unknowns) process_variables!(var_to_name, defaults, ps) isempty(observed) || collect_var_to_name!(var_to_name, (eq.lhs for eq in observed)) (continuous_events === nothing) || @@ -170,7 +170,7 @@ function JumpSystem(eqs, iv, states, ps; disc_callbacks = SymbolicDiscreteCallbacks(discrete_events) JumpSystem{typeof(ap)}(Threads.atomic_add!(SYSTEM_COUNT, UInt(1)), - ap, value(iv), states, ps, var_to_name, observed, name, systems, + ap, value(iv), unknowns, ps, var_to_name, observed, name, systems, defaults, connector_type, disc_callbacks, metadata, gui_metadata, checks = checks) end @@ -181,7 +181,7 @@ function generate_rate_function(js::JumpSystem, rate) csubs = Dict(c => getdefault(c) for c in consts) rate = substitute(rate, csubs) end - rf = build_function(rate, states(js), parameters(js), + rf = build_function(rate, unknowns(js), parameters(js), get_iv(js), expression = Val{true}) end @@ -192,7 +192,7 @@ function generate_affect_function(js::JumpSystem, affect, outputidxs) csubs = Dict(c => getdefault(c) for c in consts) affect = substitute(affect, csubs) end - compile_affect(affect, js, states(js), parameters(js); outputidxs = outputidxs, + compile_affect(affect, js, unknowns(js), parameters(js); outputidxs = outputidxs, expression = Val{true}, checkvars = false) end @@ -297,7 +297,7 @@ function DiffEqBase.DiscreteProblem(sys::JumpSystem, u0map, tspan::Union{Tuple, checkbounds = false, use_union = true, kwargs...) - dvs = states(sys) + dvs = unknowns(sys) ps = parameters(sys) defs = defaults(sys) @@ -320,7 +320,7 @@ function DiffEqBase.DiscreteProblem(sys::JumpSystem, u0map, tspan::Union{Tuple, end end - df = DiscreteFunction{true, true}(f; syms = Symbol.(states(sys)), + df = DiscreteFunction{true, true}(f; syms = Symbol.(unknowns(sys)), indepsym = Symbol(get_iv(sys)), paramsyms = Symbol.(ps), sys = sys, observed = observedfun) @@ -353,7 +353,7 @@ function DiscreteProblemExpr{iip}(sys::JumpSystem, u0map, tspan::Union{Tuple, No parammap = DiffEqBase.NullParameters(); use_union = false, kwargs...) where {iip} - dvs = states(sys) + dvs = unknowns(sys) ps = parameters(sys) defs = defaults(sys) @@ -365,7 +365,7 @@ function DiscreteProblemExpr{iip}(sys::JumpSystem, u0map, tspan::Union{Tuple, No u0 = $u0 p = $p tspan = $tspan - df = DiscreteFunction{true, true}(f; syms = $(Symbol.(states(sys))), + df = DiscreteFunction{true, true}(f; syms = $(Symbol.(unknowns(sys))), indepsym = $(Symbol(get_iv(sys))), paramsyms = $(Symbol.(parameters(sys)))) DiscreteProblem(df, u0, tspan, p) @@ -388,7 +388,7 @@ sol = solve(jprob, SSAStepper()) """ function JumpProcesses.JumpProblem(js::JumpSystem, prob, aggregator; callback = nothing, kwargs...) - statetoid = Dict(value(state) => i for (i, state) in enumerate(states(js))) + statetoid = Dict(value(state) => i for (i, state) in enumerate(unknowns(js))) eqs = equations(js) invttype = prob.tspan[1] === nothing ? Float64 : typeof(1 / prob.tspan[2]) diff --git a/src/systems/nonlinear/initializesystem.jl b/src/systems/nonlinear/initializesystem.jl index 96119c8071..49acdf0127 100644 --- a/src/systems/nonlinear/initializesystem.jl +++ b/src/systems/nonlinear/initializesystem.jl @@ -7,7 +7,7 @@ function initializesystem(sys::ODESystem; name = nameof(sys), kwargs...) if has_parent(sys) && (parent = get_parent(sys); parent !== nothing) sys = parent end - sts, eqs = states(sys), equations(sys) + sts, eqs = unknowns(sys), equations(sys) idxs_diff = isdiffeq.(eqs) idxs_alge = .!idxs_diff diff --git a/src/systems/nonlinear/nonlinearsystem.jl b/src/systems/nonlinear/nonlinearsystem.jl index 8ed1e198f8..743000fdc3 100644 --- a/src/systems/nonlinear/nonlinearsystem.jl +++ b/src/systems/nonlinear/nonlinearsystem.jl @@ -27,12 +27,12 @@ struct NonlinearSystem <: AbstractTimeIndependentSystem """Vector of equations defining the system.""" eqs::Vector{Equation} """Unknown variables.""" - states::Vector + unknowns::Vector """Parameters.""" ps::Vector """Array variables.""" var_to_name::Any - """Observed states.""" + """Observed variables.""" observed::Vector{Equation} """ Jacobian matrix. Note: this field will not be defined until @@ -81,23 +81,23 @@ struct NonlinearSystem <: AbstractTimeIndependentSystem """ parent::Any - function NonlinearSystem(tag, eqs, states, ps, var_to_name, observed, jac, name, + function NonlinearSystem(tag, eqs, unknowns, ps, var_to_name, observed, jac, name, systems, defaults, connector_type, metadata = nothing, gui_metadata = nothing, tearing_state = nothing, substitutions = nothing, complete = false, parent = nothing; checks::Union{Bool, Int} = true) if checks == true || (checks & CheckUnits) > 0 - u = __get_unit_type(states, ps) + u = __get_unit_type(unknowns, ps) check_units(u, eqs) end - new(tag, eqs, states, ps, var_to_name, observed, jac, name, systems, defaults, + new(tag, eqs, unknowns, ps, var_to_name, observed, jac, name, systems, defaults, connector_type, metadata, gui_metadata, tearing_state, substitutions, complete, parent) end end -function NonlinearSystem(eqs, states, ps; +function NonlinearSystem(eqs, unknowns, ps; observed = [], name = nothing, default_u0 = Dict(), @@ -136,15 +136,15 @@ function NonlinearSystem(eqs, states, ps; defaults = todict(defaults) defaults = Dict{Any, Any}(value(k) => value(v) for (k, v) in pairs(defaults)) - states = scalarize(states) - states, ps = value.(states), value.(ps) + unknowns = scalarize(unknowns) + unknowns, ps = value.(unknowns), value.(ps) var_to_name = Dict() - process_variables!(var_to_name, defaults, states) + process_variables!(var_to_name, defaults, unknowns) process_variables!(var_to_name, defaults, ps) isempty(observed) || collect_var_to_name!(var_to_name, (eq.lhs for eq in observed)) NonlinearSystem(Threads.atomic_add!(SYSTEM_COUNT, UInt(1)), - eqs, states, ps, var_to_name, observed, jac, name, systems, defaults, + eqs, unknowns, ps, var_to_name, observed, jac, name, systems, defaults, connector_type, metadata, gui_metadata, checks = checks) end @@ -155,7 +155,7 @@ function calculate_jacobian(sys::NonlinearSystem; sparse = false, simplify = fal end rhs = [eq.rhs for eq in equations(sys)] - vals = [dv for dv in states(sys)] + vals = [dv for dv in unknowns(sys)] if sparse jac = sparsejacobian(rhs, vals, simplify = simplify) else @@ -165,7 +165,7 @@ function calculate_jacobian(sys::NonlinearSystem; sparse = false, simplify = fal return jac end -function generate_jacobian(sys::NonlinearSystem, vs = states(sys), ps = parameters(sys); +function generate_jacobian(sys::NonlinearSystem, vs = unknowns(sys), ps = parameters(sys); sparse = false, simplify = false, kwargs...) jac = calculate_jacobian(sys, sparse = sparse, simplify = simplify) pre = get_preprocess_constants(jac) @@ -174,7 +174,7 @@ end function calculate_hessian(sys::NonlinearSystem; sparse = false, simplify = false) rhs = [eq.rhs for eq in equations(sys)] - vals = [dv for dv in states(sys)] + vals = [dv for dv in unknowns(sys)] if sparse hess = [sparsehessian(rhs[i], vals, simplify = simplify) for i in 1:length(rhs)] else @@ -183,14 +183,14 @@ function calculate_hessian(sys::NonlinearSystem; sparse = false, simplify = fals return hess end -function generate_hessian(sys::NonlinearSystem, vs = states(sys), ps = parameters(sys); +function generate_hessian(sys::NonlinearSystem, vs = unknowns(sys), ps = parameters(sys); sparse = false, simplify = false, kwargs...) hess = calculate_hessian(sys, sparse = sparse, simplify = simplify) pre = get_preprocess_constants(hess) return build_function(hess, vs, ps; postprocess_fbody = pre, kwargs...) end -function generate_function(sys::NonlinearSystem, dvs = states(sys), ps = parameters(sys); +function generate_function(sys::NonlinearSystem, dvs = unknowns(sys), ps = parameters(sys); kwargs...) rhss = [deq.rhs for deq in equations(sys)] pre, sol_states = get_substitutions_and_solved_states(sys) @@ -201,17 +201,17 @@ end function jacobian_sparsity(sys::NonlinearSystem) jacobian_sparsity([eq.rhs for eq in equations(sys)], - states(sys)) + unknowns(sys)) end function hessian_sparsity(sys::NonlinearSystem) [hessian_sparsity(eq.rhs, - states(sys)) for eq in equations(sys)] + unknowns(sys)) for eq in equations(sys)] end """ ```julia -SciMLBase.NonlinearFunction{iip}(sys::NonlinearSystem, dvs = states(sys), +SciMLBase.NonlinearFunction{iip}(sys::NonlinearSystem, dvs = unknowns(sys), ps = parameters(sys); version = nothing, jac = false, @@ -227,7 +227,7 @@ function SciMLBase.NonlinearFunction(sys::NonlinearSystem, args...; kwargs...) NonlinearFunction{true}(sys, args...; kwargs...) end -function SciMLBase.NonlinearFunction{iip}(sys::NonlinearSystem, dvs = states(sys), +function SciMLBase.NonlinearFunction{iip}(sys::NonlinearSystem, dvs = unknowns(sys), ps = parameters(sys), u0 = nothing; version = nothing, jac = false, @@ -268,14 +268,14 @@ function SciMLBase.NonlinearFunction{iip}(sys::NonlinearSystem, dvs = states(sys jac_prototype = sparse ? similar(calculate_jacobian(sys, sparse = sparse), Float64) : nothing, - syms = Symbol.(states(sys)), + syms = Symbol.(unknowns(sys)), paramsyms = Symbol.(parameters(sys)), observed = observedfun) end """ ```julia -SciMLBase.NonlinearFunctionExpr{iip}(sys::NonlinearSystem, dvs = states(sys), +SciMLBase.NonlinearFunctionExpr{iip}(sys::NonlinearSystem, dvs = unknowns(sys), ps = parameters(sys); version = nothing, jac = false, @@ -289,7 +289,7 @@ variable and parameter vectors, respectively. """ struct NonlinearFunctionExpr{iip} end -function NonlinearFunctionExpr{iip}(sys::NonlinearSystem, dvs = states(sys), +function NonlinearFunctionExpr{iip}(sys::NonlinearSystem, dvs = unknowns(sys), ps = parameters(sys), u0 = nothing; version = nothing, tgrad = false, jac = false, @@ -315,7 +315,7 @@ function NonlinearFunctionExpr{iip}(sys::NonlinearSystem, dvs = states(sys), NonlinearFunction{$iip}(f, jac = jac, jac_prototype = $jp_expr, - syms = $(Symbol.(states(sys))), + syms = $(Symbol.(unknowns(sys))), paramsyms = $(Symbol.(parameters(sys)))) end !linenumbers ? striplines(ex) : ex @@ -332,7 +332,7 @@ function process_NonlinearProblem(constructor, sys::NonlinearSystem, u0map, para tofloat = !use_union, kwargs...) eqs = equations(sys) - dvs = states(sys) + dvs = unknowns(sys) ps = parameters(sys) u0, p, defs = get_u0_p(sys, u0map, parammap; tofloat, use_union) @@ -415,7 +415,7 @@ function flatten(sys::NonlinearSystem, noeqs = false) return sys else return NonlinearSystem(noeqs ? Equation[] : equations(sys), - states(sys), + unknowns(sys), parameters(sys), observed = observed(sys), defaults = defaults(sys), @@ -427,7 +427,7 @@ end function Base.:(==)(sys1::NonlinearSystem, sys2::NonlinearSystem) isequal(nameof(sys1), nameof(sys2)) && _eq_unordered(get_eqs(sys1), get_eqs(sys2)) && - _eq_unordered(get_states(sys1), get_states(sys2)) && + _eq_unordered(get_unknowns(sys1), get_unknowns(sys2)) && _eq_unordered(get_ps(sys1), get_ps(sys2)) && all(s1 == s2 for (s1, s2) in zip(get_systems(sys1), get_systems(sys2))) end diff --git a/src/systems/optimization/constraints_system.jl b/src/systems/optimization/constraints_system.jl index 4e4a1ed6f1..bb0e93790b 100644 --- a/src/systems/optimization/constraints_system.jl +++ b/src/systems/optimization/constraints_system.jl @@ -28,7 +28,7 @@ struct ConstraintsSystem <: AbstractTimeIndependentSystem """Vector of equations defining the system.""" constraints::Vector{Union{Equation, Inequality}} """Unknown variables.""" - states::Vector + unknowns::Vector """Parameters.""" ps::Vector """Array variables.""" @@ -70,17 +70,17 @@ struct ConstraintsSystem <: AbstractTimeIndependentSystem """ substitutions::Any - function ConstraintsSystem(tag, constraints, states, ps, var_to_name, observed, jac, + function ConstraintsSystem(tag, constraints, unknowns, ps, var_to_name, observed, jac, name, systems, defaults, connector_type, metadata = nothing, tearing_state = nothing, substitutions = nothing; checks::Union{Bool, Int} = true) if checks == true || (checks & CheckUnits) > 0 - u = __get_unit_type(states, ps) + u = __get_unit_type(unknowns, ps) check_units(u, constraints) end - new(tag, constraints, states, ps, var_to_name, observed, jac, name, systems, + new(tag, constraints, unknowns, ps, var_to_name, observed, jac, name, systems, defaults, connector_type, metadata, tearing_state, substitutions) end @@ -88,7 +88,7 @@ end equations(sys::ConstraintsSystem) = constraints(sys) # needed for Base.show -function ConstraintsSystem(constraints, states, ps; +function ConstraintsSystem(constraints, unknowns, ps; observed = [], name = nothing, default_u0 = Dict(), @@ -109,7 +109,7 @@ function ConstraintsSystem(constraints, states, ps; throw(ArgumentError("The `name` keyword must be provided. Please consider using the `@named` macro")) cstr = value.(Symbolics.canonical_form.(scalarize(constraints))) - states′ = value.(scalarize(states)) + states′ = value.(scalarize(unknowns)) ps′ = value.(scalarize(ps)) if !(isempty(default_u0) && isempty(default_p)) @@ -131,7 +131,7 @@ function ConstraintsSystem(constraints, states, ps; isempty(observed) || collect_var_to_name!(var_to_name, (eq.lhs for eq in observed)) ConstraintsSystem(Threads.atomic_add!(SYSTEM_COUNT, UInt(1)), - cstr, states, ps, var_to_name, observed, jac, name, systems, + cstr, unknowns, ps, var_to_name, observed, jac, name, systems, defaults, connector_type, metadata, checks = checks) end @@ -143,7 +143,7 @@ function calculate_jacobian(sys::ConstraintsSystem; sparse = false, simplify = f end lhss = generate_canonical_form_lhss(sys) - vals = [dv for dv in states(sys)] + vals = [dv for dv in unknowns(sys)] if sparse jac = sparsejacobian(lhss, vals, simplify = simplify) else @@ -153,7 +153,7 @@ function calculate_jacobian(sys::ConstraintsSystem; sparse = false, simplify = f return jac end -function generate_jacobian(sys::ConstraintsSystem, vs = states(sys), ps = parameters(sys); +function generate_jacobian(sys::ConstraintsSystem, vs = unknowns(sys), ps = parameters(sys); sparse = false, simplify = false, kwargs...) jac = calculate_jacobian(sys, sparse = sparse, simplify = simplify) return build_function(jac, vs, ps; kwargs...) @@ -161,7 +161,7 @@ end function calculate_hessian(sys::ConstraintsSystem; sparse = false, simplify = false) lhss = generate_canonical_form_lhss(sys) - vals = [dv for dv in states(sys)] + vals = [dv for dv in unknowns(sys)] if sparse hess = [sparsehessian(lhs, vals, simplify = simplify) for lhs in lhss] else @@ -170,13 +170,13 @@ function calculate_hessian(sys::ConstraintsSystem; sparse = false, simplify = fa return hess end -function generate_hessian(sys::ConstraintsSystem, vs = states(sys), ps = parameters(sys); +function generate_hessian(sys::ConstraintsSystem, vs = unknowns(sys), ps = parameters(sys); sparse = false, simplify = false, kwargs...) hess = calculate_hessian(sys, sparse = sparse, simplify = simplify) return build_function(hess, vs, ps; kwargs...) end -function generate_function(sys::ConstraintsSystem, dvs = states(sys), ps = parameters(sys); +function generate_function(sys::ConstraintsSystem, dvs = unknowns(sys), ps = parameters(sys); kwargs...) lhss = generate_canonical_form_lhss(sys) pre, sol_states = get_substitutions_and_solved_states(sys) @@ -194,12 +194,12 @@ end function jacobian_sparsity(sys::ConstraintsSystem) lhss = generate_canonical_form_lhss(sys) - jacobian_sparsity(lhss, states(sys)) + jacobian_sparsity(lhss, unknowns(sys)) end function hessian_sparsity(sys::ConstraintsSystem) lhss = generate_canonical_form_lhss(sys) - [hessian_sparsity(eq, states(sys)) for eq in lhss] + [hessian_sparsity(eq, unknowns(sys)) for eq in lhss] end """ diff --git a/src/systems/optimization/optimizationsystem.jl b/src/systems/optimization/optimizationsystem.jl index ce385f975f..7228c76726 100644 --- a/src/systems/optimization/optimizationsystem.jl +++ b/src/systems/optimization/optimizationsystem.jl @@ -26,7 +26,7 @@ struct OptimizationSystem <: AbstractOptimizationSystem """Objective function of the system.""" op::Any """Unknown variables.""" - states::Vector + unknowns::Vector """Parameters.""" ps::Vector """Array variables.""" @@ -61,17 +61,17 @@ struct OptimizationSystem <: AbstractOptimizationSystem """ parent::Any - function OptimizationSystem(tag, op, states, ps, var_to_name, observed, + function OptimizationSystem(tag, op, unknowns, ps, var_to_name, observed, constraints, name, systems, defaults, metadata = nothing, gui_metadata = nothing, complete = false, parent = nothing; checks::Union{Bool, Int} = true) if checks == true || (checks & CheckUnits) > 0 - u = __get_unit_type(states, ps) + u = __get_unit_type(unknowns, ps) unwrap(op) isa Symbolic && check_units(u, op) check_units(u, observed) check_units(u, constraints) end - new(tag, op, states, ps, var_to_name, observed, + new(tag, op, unknowns, ps, var_to_name, observed, constraints, name, systems, defaults, metadata, gui_metadata, complete, parent) end @@ -79,7 +79,7 @@ end equations(sys::AbstractOptimizationSystem) = objective(sys) # needed for Base.show -function OptimizationSystem(op, states, ps; +function OptimizationSystem(op, unknowns, ps; observed = [], constraints = [], default_u0 = Dict(), @@ -93,7 +93,7 @@ function OptimizationSystem(op, states, ps; name === nothing && throw(ArgumentError("The `name` keyword must be provided. Please consider using the `@named` macro")) constraints = value.(scalarize(constraints)) - states′ = value.(scalarize(states)) + states′ = value.(scalarize(unknowns)) ps′ = value.(scalarize(ps)) op′ = value(scalarize(op)) @@ -122,10 +122,10 @@ function OptimizationSystem(op, states, ps; end function calculate_gradient(sys::OptimizationSystem) - expand_derivatives.(gradient(objective(sys), states(sys))) + expand_derivatives.(gradient(objective(sys), unknowns(sys))) end -function generate_gradient(sys::OptimizationSystem, vs = states(sys), ps = parameters(sys); +function generate_gradient(sys::OptimizationSystem, vs = unknowns(sys), ps = parameters(sys); kwargs...) grad = calculate_gradient(sys) pre = get_preprocess_constants(grad) @@ -134,13 +134,13 @@ function generate_gradient(sys::OptimizationSystem, vs = states(sys), ps = param end function calculate_hessian(sys::OptimizationSystem) - expand_derivatives.(hessian(objective(sys), states(sys))) + expand_derivatives.(hessian(objective(sys), unknowns(sys))) end -function generate_hessian(sys::OptimizationSystem, vs = states(sys), ps = parameters(sys); +function generate_hessian(sys::OptimizationSystem, vs = unknowns(sys), ps = parameters(sys); sparse = false, kwargs...) if sparse - hess = sparsehessian(objective(sys), states(sys)) + hess = sparsehessian(objective(sys), unknowns(sys)) else hess = calculate_hessian(sys) end @@ -149,7 +149,7 @@ function generate_hessian(sys::OptimizationSystem, vs = states(sys), ps = parame kwargs...) end -function generate_function(sys::OptimizationSystem, vs = states(sys), ps = parameters(sys); +function generate_function(sys::OptimizationSystem, vs = unknowns(sys), ps = parameters(sys); kwargs...) eqs = subs_constants(objective(sys)) return build_function(eqs, vs, ps; @@ -195,7 +195,7 @@ function constraints(sys) isempty(systems) ? cs : [cs; reduce(vcat, namespace_constraints.(systems))] end -hessian_sparsity(sys::OptimizationSystem) = hessian_sparsity(get_op(sys), states(sys)) +hessian_sparsity(sys::OptimizationSystem) = hessian_sparsity(get_op(sys), unknowns(sys)) """ ```julia @@ -232,7 +232,7 @@ function DiffEqBase.OptimizationProblem{iip}(sys::OptimizationSystem, u0map, :OptimizationProblem, force = true) end - dvs = states(sys) + dvs = unknowns(sys) ps = parameters(sys) cstr = constraints(sys) @@ -359,7 +359,7 @@ function DiffEqBase.OptimizationProblem{iip}(sys::OptimizationSystem, u0map, grad = _grad, hess = _hess, hess_prototype = hess_prototype, - syms = Symbol.(states(sys)), + syms = Symbol.(unknowns(sys)), paramsyms = Symbol.(parameters(sys)), cons = cons[2], cons_j = _cons_j, @@ -377,7 +377,7 @@ function DiffEqBase.OptimizationProblem{iip}(sys::OptimizationSystem, u0map, SciMLBase.NoAD(); grad = _grad, hess = _hess, - syms = Symbol.(states(sys)), + syms = Symbol.(unknowns(sys)), paramsyms = Symbol.(parameters(sys)), hess_prototype = hess_prototype, expr = obj_expr, @@ -424,7 +424,7 @@ function OptimizationProblemExpr{iip}(sys::OptimizationSystem, u0map, :OptimizationProblem, force = true) end - dvs = states(sys) + dvs = unknowns(sys) ps = parameters(sys) cstr = constraints(sys) @@ -546,7 +546,7 @@ function OptimizationProblemExpr{iip}(sys::OptimizationSystem, u0map, ucons = $ucons cons_j = $_cons_j cons_h = $_cons_h - syms = $(Symbol.(states(sys))) + syms = $(Symbol.(unknowns(sys))) paramsyms = $(Symbol.(parameters(sys))) _f = OptimizationFunction{iip}(f, SciMLBase.NoAD(); grad = grad, @@ -574,7 +574,7 @@ function OptimizationProblemExpr{iip}(sys::OptimizationSystem, u0map, lb = $lb ub = $ub int = $int - syms = $(Symbol.(states(sys))) + syms = $(Symbol.(unknowns(sys))) paramsyms = $(Symbol.(parameters(sys))) _f = OptimizationFunction{iip}(f, SciMLBase.NoAD(); grad = grad, @@ -600,7 +600,7 @@ function structural_simplify(sys::OptimizationSystem; kwargs...) push!(icons, e) end end - nlsys = NonlinearSystem(econs, states(sys), parameters(sys); name = :___tmp_nlsystem) + nlsys = NonlinearSystem(econs, unknowns(sys), parameters(sys); name = :___tmp_nlsystem) snlsys = structural_simplify(nlsys; fully_determined = false, kwargs...) obs = observed(snlsys) subs = Dict(eq.lhs => eq.rhs for eq in observed(snlsys)) @@ -609,11 +609,11 @@ function structural_simplify(sys::OptimizationSystem; kwargs...) for (i, eq) in enumerate(Iterators.flatten((seqs, icons))) cons_simplified[i] = fixpoint_sub(eq, subs) end - newsts = setdiff(states(sys), keys(subs)) + newsts = setdiff(unknowns(sys), keys(subs)) @set! sys.constraints = cons_simplified @set! sys.observed = [observed(sys); obs] neweqs = fixpoint_sub.(equations(sys), (subs,)) @set! sys.op = length(neweqs) == 1 ? first(neweqs) : neweqs - @set! sys.states = newsts + @set! sys.unknowns = newsts return sys end diff --git a/src/systems/systems.jl b/src/systems/systems.jl index 39a527003a..5b93e07fc8 100644 --- a/src/systems/systems.jl +++ b/src/systems/systems.jl @@ -81,7 +81,7 @@ function __structural_simplify(sys::AbstractSystem, io = nothing; simplify = fal g = Matrix(sparse(Is, Js, vals)) sys = state.sys @set! sys.eqs = new_eqs - @set! sys.states = [v + @set! sys.unknowns = [v for (i, v) in enumerate(fullvars) if !iszero(new_idxs[i]) && invview(var_to_diff)[i] === nothing] @@ -100,7 +100,7 @@ function __structural_simplify(sys::AbstractSystem, io = nothing; simplify = fal end return SDESystem(full_equations(ode_sys), sorted_g_rows, - get_iv(ode_sys), states(ode_sys), parameters(ode_sys); + get_iv(ode_sys), unknowns(ode_sys), parameters(ode_sys); name = nameof(ode_sys)) end end diff --git a/src/systems/systemstructure.jl b/src/systems/systemstructure.jl index 69077b452f..1548c0cc50 100644 --- a/src/systems/systemstructure.jl +++ b/src/systems/systemstructure.jl @@ -577,7 +577,7 @@ function structural_simplify!(state::TearingState, io = nothing; simplify = fals dist_io = merge_io(io, inputs[i]) ss, = _structural_simplify!(state, dist_io; simplify, check_consistency, fully_determined, kwargs...) - append!(appended_parameters, inputs[i], states(ss)) + append!(appended_parameters, inputs[i], unknowns(ss)) discrete_subsystems[i] = ss end @set! sys.discrete_subsystems = discrete_subsystems, inputs, continuous_id, @@ -613,7 +613,7 @@ function _structural_simplify!(state::TearingState, io; simplify = false, else sys = ModelingToolkit.tearing(sys, state; simplify, mm, check_consistency) end - fullstates = [map(eq -> eq.lhs, observed(sys)); states(sys)] + fullstates = [map(eq -> eq.lhs, observed(sys)); unknowns(sys)] @set! sys.observed = ModelingToolkit.topsort_equations(observed(sys), fullstates) ModelingToolkit.invalidate_cache!(sys), input_idxs end diff --git a/src/systems/unit_check.jl b/src/systems/unit_check.jl index 9b474fcc1d..1fcde9f12f 100644 --- a/src/systems/unit_check.jl +++ b/src/systems/unit_check.jl @@ -211,10 +211,10 @@ function _validate(conn::Connection; info::String = "") valid = true syss = get_systems(conn) sys = first(syss) - st = states(sys) + st = unknowns(sys) for i in 2:length(syss) s = syss[i] - sst = states(s) + sst = unknowns(s) if length(st) != length(sst) valid = false @warn("$info: connected systems $(nameof(sys)) and $(nameof(s)) have $(length(st)) and $(length(sst)) states, cannor connect.") diff --git a/src/systems/validation.jl b/src/systems/validation.jl index 90b0745cd2..773a037d2b 100644 --- a/src/systems/validation.jl +++ b/src/systems/validation.jl @@ -185,10 +185,10 @@ function _validate(conn::Connection; info::String = "") valid = true syss = get_systems(conn) sys = first(syss) - st = states(sys) + st = unknowns(sys) for i in 2:length(syss) s = syss[i] - sst = states(s) + sst = unknowns(s) if length(st) != length(sst) valid = false @warn("$info: connected systems $(nameof(sys)) and $(nameof(s)) have $(length(st)) and $(length(sst)) states, cannor connect.") diff --git a/src/variables.jl b/src/variables.jl index 964eaa7859..9d1e767970 100644 --- a/src/variables.jl +++ b/src/variables.jl @@ -144,7 +144,7 @@ function SciMLBase.process_p_u0_symbolic(prob::Union{SciMLBase.AbstractDEProblem " Please use `remake` with the `p` keyword argument as a vector of values, paying attention to parameter order.")) end if eltype(u0) <: Pair - hasproperty(prob.f, :sys) && hasfield(typeof(prob.f.sys), :states) || + hasproperty(prob.f, :sys) && hasfield(typeof(prob.f.sys), :unknowns) || throw(ArgumentError("This problem does not support symbolic maps with `remake`, i.e. it does not have a symbolic origin." * " Please use `remake` with the `u0` keyword argument as a vector of values, paying attention to state order.")) end @@ -162,7 +162,7 @@ function SciMLBase.process_p_u0_symbolic(prob::Union{SciMLBase.AbstractDEProblem defs = mergedefaults(defs, prob.p, ps) end defs = mergedefaults(defs, p, ps) - sts = states(sys) + sts = unknowns(sys) defs = mergedefaults(defs, prob.u0, sts) defs = mergedefaults(defs, u0, sts) u0, p, defs = get_u0_p(sys, defs) @@ -229,7 +229,7 @@ function isdisturbance(x) end function disturbances(sys) - [filter(isdisturbance, states(sys)); filter(isdisturbance, parameters(sys))] + [filter(isdisturbance, unknowns(sys)); filter(isdisturbance, parameters(sys))] end ## Tunable ===================================================================== @@ -326,7 +326,7 @@ Create parameters with bounds like this @parameters p [bounds=(-1, 1)] ``` -To obtain state bounds, call `getbounds(sys, states(sys))` +To obtain state bounds, call `getbounds(sys, unknowns(sys))` """ function getbounds(sys::ModelingToolkit.AbstractSystem, p = parameters(sys)) Dict(p .=> getbounds.(p)) diff --git a/test/components.jl b/test/components.jl index 74950126a4..7d19817e68 100644 --- a/test/components.jl +++ b/test/components.jl @@ -153,16 +153,16 @@ sol = solve(prob, Tsit5()) include("../examples/serial_inductor.jl") sys = structural_simplify(ll_model) @test length(equations(sys)) == 2 -u0 = states(sys) .=> 0 +u0 = unknowns(sys) .=> 0 @test_nowarn ODEProblem(sys, u0, (0, 10.0)) @test_nowarn ODAEProblem(sys, u0, (0, 10.0)) -prob = DAEProblem(sys, Differential(t).(states(sys)) .=> 0, u0, (0, 0.5)) +prob = DAEProblem(sys, Differential(t).(unknowns(sys)) .=> 0, u0, (0, 0.5)) sol = solve(prob, DFBDF()) @test sol.retcode == SciMLBase.ReturnCode.Success sys2 = structural_simplify(ll2_model) @test length(equations(sys2)) == 3 -u0 = states(sys) .=> 0 +u0 = unknowns(sys) .=> 0 prob = ODEProblem(sys, u0, (0, 10.0)) @test_nowarn sol = solve(prob, FBDF()) diff --git a/test/dde.jl b/test/dde.jl index 479a1a59a7..9fdd15c35b 100644 --- a/test/dde.jl +++ b/test/dde.jl @@ -108,5 +108,5 @@ eqs = [osc1.jcn ~ osc2.delx, for coupledOsc in [coupledOsc, coupledOsc2] local sys = structural_simplify(coupledOsc) @test length(equations(sys)) == 4 - @test length(states(sys)) == 4 + @test length(unknowns(sys)) == 4 end diff --git a/test/domain_connectors.jl b/test/domain_connectors.jl index 3f42808664..d742ba9d5b 100644 --- a/test/domain_connectors.jl +++ b/test/domain_connectors.jl @@ -147,12 +147,12 @@ end @named odesys = System() esys = ModelingToolkit.expand_connections(odesys) -@test length(equations(esys)) == length(states(esys)) +@test length(equations(esys)) == length(unknowns(esys)) csys = complete(odesys) sys = structural_simplify(odesys) -@test length(equations(sys)) == length(states(sys)) +@test length(equations(sys)) == length(unknowns(sys)) sys_defs = ModelingToolkit.defaults(sys) @test Symbol(sys_defs[csys.vol.port.ρ]) == Symbol(csys.fluid.ρ) diff --git a/test/extensions/Project.toml b/test/extensions/Project.toml index 6720209cf2..6b3cfb57c2 100644 --- a/test/extensions/Project.toml +++ b/test/extensions/Project.toml @@ -1,4 +1,3 @@ [deps] BifurcationKit = "0f109fa4-8a5d-4b75-95aa-f515264e7665" - -[compat] +ModelingToolkit = "961ee093-0014-501f-94e3-6117800e7a78" diff --git a/test/input_output_handling.jl b/test/input_output_handling.jl index 249a94e9d0..1ce6ac159c 100644 --- a/test/input_output_handling.jl +++ b/test/input_output_handling.jl @@ -229,7 +229,7 @@ f, dvs, ps = ModelingToolkit.generate_control_function(model, simplify = true) @test length(ps) == length(parameters(model)) p = ModelingToolkit.varmap_to_vars(ModelingToolkit.defaults(model), ps) x = ModelingToolkit.varmap_to_vars(merge(ModelingToolkit.defaults(model), - Dict(D.(states(model)) .=> 0.0)), dvs) + Dict(D.(unknowns(model)) .=> 0.0)), dvs) u = [rand()] out = f[1](x, u, p, 1) i = findfirst(isequal(u[1]), out) @@ -328,7 +328,7 @@ eqs = [D(y₁) ~ -k₁ * y₁ + k₃ * y₂ * y₃ + u1 m_inputs = [u[1], u[2]] m_outputs = [y₂] sys_simp, input_idxs = structural_simplify(sys, (; inputs = m_inputs, outputs = m_outputs)) -@test isequal(states(sys_simp), collect(x[1:2])) +@test isequal(unknowns(sys_simp), collect(x[1:2])) @test length(input_idxs) == 2 # https://github.com/SciML/ModelingToolkit.jl/issues/1577 @@ -346,7 +346,7 @@ sys_simp, input_idxs = structural_simplify(sys, (; inputs = m_inputs, outputs = t, systems = [int, gain, c, fb]) sys = structural_simplify(model) -@test length(states(sys)) == length(equations(sys)) == 1 +@test length(unknowns(sys)) == length(equations(sys)) == 1 ## Disturbance models when plant has multiple inputs using ModelingToolkit, LinearAlgebra diff --git a/test/jacobiansparsity.jl b/test/jacobiansparsity.jl index e5738db218..f427c953c0 100644 --- a/test/jacobiansparsity.jl +++ b/test/jacobiansparsity.jl @@ -45,7 +45,7 @@ sys = modelingtoolkitize(prob_ode_brusselator_2d) # test sparse jacobian pattern only. prob = ODEProblem(sys, u0, (0, 11.5), sparse = true, jac = false) JP = prob.f.jac_prototype -@test findnz(Symbolics.jacobian_sparsity(map(x -> x.rhs, equations(sys)), states(sys)))[1:2] == +@test findnz(Symbolics.jacobian_sparsity(map(x -> x.rhs, equations(sys)), unknowns(sys)))[1:2] == findnz(JP)[1:2] # test sparse jacobian diff --git a/test/jumpsystem.jl b/test/jumpsystem.jl index 69ac24f9af..1640110bc0 100644 --- a/test/jumpsystem.jl +++ b/test/jumpsystem.jl @@ -14,7 +14,7 @@ affect₂ = [I ~ I - 1, R ~ R + 1] j₁ = ConstantRateJump(rate₁, affect₁) j₂ = VariableRateJump(rate₂, affect₂) @named js = JumpSystem([j₁, j₂], t, [S, I, R], [β, γ]) -statetoid = Dict(MT.value(state) => i for (i, state) in enumerate(states(js))) +statetoid = Dict(MT.value(state) => i for (i, state) in enumerate(unknowns(js))) mtjump1 = MT.assemble_crj(js, j₁, statetoid) mtjump2 = MT.assemble_vrj(js, j₂, statetoid) diff --git a/test/linearize.jl b/test/linearize.jl index d77793275c..6eaae99671 100644 --- a/test/linearize.jl +++ b/test/linearize.jl @@ -84,7 +84,7 @@ connections = [f.y ~ c.r # filtered reference to controller reference lsys0, ssys = linearize(cl, [f.u], [p.x]) desired_order = [f.x, p.x] -lsys = ModelingToolkit.reorder_states(lsys0, states(ssys), desired_order) +lsys = ModelingToolkit.reorder_states(lsys0, unknowns(ssys), desired_order) @test lsys.A == [-2 0; 1 -2] @test lsys.B == reshape([1, 0], 2, 1) @@ -110,7 +110,7 @@ Nd = 10 lsys0, ssys = linearize(pid, [reference.u, measurement.u], [ctr_output.u]) @unpack int, der = pid desired_order = [int.x, der.x] -lsys = ModelingToolkit.reorder_states(lsys0, states(ssys), desired_order) +lsys = ModelingToolkit.reorder_states(lsys0, unknowns(ssys), desired_order) @test lsys.A == [0 0; 0 -10] @test lsys.B == [2 -2; 10 -10] @@ -126,7 +126,7 @@ lsyss, _ = ModelingToolkit.linearize_symbolic(pid, [reference.u, measurement.u], @test substitute(lsyss.D, ModelingToolkit.defaults(pid)) == lsys.D # Test with the reverse desired state order as well to verify that similarity transform and reoreder_states really works -lsys = ModelingToolkit.reorder_states(lsys, states(ssys), reverse(desired_order)) +lsys = ModelingToolkit.reorder_states(lsys, unknowns(ssys), reverse(desired_order)) @test lsys.A == [-10 0; 0 0] @test lsys.B == [10 -10; 2 -2] @@ -245,7 +245,7 @@ if VERSION >= v"1.8" lsyss, sysss = ModelingToolkit.linearize_symbolic(model, lin_inputs, lin_outputs; allow_input_derivatives = true) - dummyder = setdiff(states(sysss), states(model)) + dummyder = setdiff(unknowns(sysss), unknowns(model)) def = merge(def, Dict(x => 0.0 for x in dummyder)) def[link1.fy1] = -def[link1.g] * def[link1.m] diff --git a/test/log.txt b/test/log.txt new file mode 100644 index 0000000000..1b40d3fa68 --- /dev/null +++ b/test/log.txt @@ -0,0 +1,2 @@ +integrator.t: 1.0 +integrator.u: [0.9999999999999998] diff --git a/test/modelingtoolkitize.jl b/test/modelingtoolkitize.jl index 517977f99f..3a88d3c126 100644 --- a/test/modelingtoolkitize.jl +++ b/test/modelingtoolkitize.jl @@ -180,7 +180,7 @@ p = [9.8, 1] tspan = (0, 10.0) pendulum_prob = ODEProblem(pendulum_fun!, u0, tspan, p) pendulum_sys_org = modelingtoolkitize(pendulum_prob) -sts = states(pendulum_sys_org) +sts = unknowns(pendulum_sys_org) pendulum_sys = dae_index_lowering(pendulum_sys_org) prob = ODEProblem(pendulum_sys, Pair[], tspan) sol = solve(prob, Rodas4()) @@ -254,7 +254,7 @@ sys = modelingtoolkitize(problem) @parameters t @test all(isequal.(parameters(sys), getproperty.(@variables(β, η, ω, φ, σ, μ), :val))) -@test all(isequal.(Symbol.(states(sys)), Symbol.(@variables(S(t), I(t), R(t), C(t))))) +@test all(isequal.(Symbol.(unknowns(sys)), Symbol.(@variables(S(t), I(t), R(t), C(t))))) # https://github.com/SciML/ModelingToolkit.jl/issues/1158 @@ -287,7 +287,7 @@ params = OrderedDict(:a => 10, :b => 20) u0 = [1, 2.0] prob = ODEProblem(ode_prob_dict, u0, (0.0, 1.0), params) sys = modelingtoolkitize(prob) -@test [ModelingToolkit.defaults(sys)[s] for s in states(sys)] == u0 +@test [ModelingToolkit.defaults(sys)[s] for s in unknowns(sys)] == u0 @test [ModelingToolkit.defaults(sys)[s] for s in parameters(sys)] == [10, 20] @test ModelingToolkit.has_tspan(sys) diff --git a/test/nonlinearsystem.jl b/test/nonlinearsystem.jl index 0d1fcf90da..ae2988d501 100644 --- a/test/nonlinearsystem.jl +++ b/test/nonlinearsystem.jl @@ -15,7 +15,7 @@ canonequal(a, b) = isequal(simplify(a), simplify(b)) function test_nlsys_inference(name, sys, vs, ps) @testset "NonlinearSystem construction: $name" begin - @test Set(states(sys)) == Set(value.(vs)) + @test Set(unknowns(sys)) == Set(value.(vs)) @test Set(parameters(sys)) == Set(value.(ps)) end end @@ -166,7 +166,7 @@ end @test isequal(union(Set(parameters(sys1)), Set(parameters(sys2))), Set(parameters(sys3))) - @test isequal(union(Set(states(sys1)), Set(states(sys2))), Set(states(sys3))) + @test isequal(union(Set(unknowns(sys1)), Set(unknowns(sys2))), Set(unknowns(sys3))) @test isequal(union(Set(equations(sys1)), Set(equations(sys2))), Set(equations(sys3))) end @@ -199,7 +199,7 @@ eq = [v1 ~ sin(2pi * t * h) u[4] ~ h] sys = NonlinearSystem(eqs, collect(u[1:4]), Num[], defaults = Dict([]), name = :test) - prob = NonlinearProblem(sys, ones(length(states(sys)))) + prob = NonlinearProblem(sys, ones(length(unknowns(sys)))) sol = NonlinearSolve.solve(prob, NewtonRaphson()) @@ -223,7 +223,7 @@ testdict = Dict([:test => 1]) 0 ~ x * (b - z) - y, 0 ~ x * y - c * z] @named sys = NonlinearSystem(eqs, [x, y, z], [a, b, c], defaults = Dict(x => 2.0)) - prob = NonlinearProblem(sys, ones(length(states(sys)))) + prob = NonlinearProblem(sys, ones(length(unknowns(sys)))) prob_ = remake(prob, u0 = [1.0, 2.0, 3.0], p = [1.1, 1.2, 1.3]) @test prob_.u0 == [1.0, 2.0, 3.0] @@ -262,7 +262,7 @@ end sys_init_simple = structural_simplify(sys_init) - prob = NonlinearProblem(sys_init_simple, get_default_or_guess.(states(sys_init_simple))) + prob = NonlinearProblem(sys_init_simple, get_default_or_guess.(unknowns(sys_init_simple))) @test prob.u0 == [0.5, -0.5] @@ -270,8 +270,8 @@ end @test sol.retcode == SciMLBase.ReturnCode.Success # Confirm for all the states of the non-simplified system - @test all(.≈(sol[states(sys)], [1e-5, 0, 1e-5 / 1.5, 0]; atol = 1e-8)) + @test all(.≈(sol[unknowns(sys)], [1e-5, 0, 1e-5 / 1.5, 0]; atol = 1e-8)) # Confirm for all the states of the simplified system - @test all(.≈(sol[states(sys_simple)], [1e-5 / 1.5, 0]; atol = 1e-8)) + @test all(.≈(sol[unknowns(sys_simple)], [1e-5 / 1.5, 0]; atol = 1e-8)) end diff --git a/test/odesystem.jl b/test/odesystem.jl index 9bcbbfc130..1232750c65 100644 --- a/test/odesystem.jl +++ b/test/odesystem.jl @@ -40,7 +40,7 @@ function test_diffeq_inference(name, sys, iv, dvs, ps) @testset "ODESystem construction: $name" begin @test isequal(independent_variables(sys)[1], value(iv)) @test length(independent_variables(sys)) == 1 - @test isempty(setdiff(Set(states(sys)), Set(value.(dvs)))) + @test isempty(setdiff(Set(unknowns(sys)), Set(value.(dvs)))) @test isempty(setdiff(Set(parameters(sys)), Set(value.(ps)))) end end @@ -163,7 +163,7 @@ lowered_eqs = [D(uˍtt) ~ 2uˍtt + uˍt + xˍt + 1 # issue #219 @test all(isequal.([ModelingToolkit.var_from_nested_derivative(eq.lhs)[1] for eq in equations(de1)], - states(@named lowered = ODESystem(lowered_eqs)))) + unknowns(@named lowered = ODESystem(lowered_eqs)))) test_diffeq_inference("first-order transform", de1, t, [uˍtt, xˍt, uˍt, u, x], []) du = zeros(5) @@ -248,7 +248,7 @@ prob13 = ODEProblem(sys, u0, tspan, (0.04, 3e7, 1e4)) prob14 = ODEProblem(sys, u0, tspan, p2) for p in [prob1, prob14] @test Set(Num.(parameters(sys)) .=> p.p) == Set([k₁ => 0.04, k₂ => 3e7, k₃ => 1e4]) - @test Set(Num.(states(sys)) .=> p.u0) == Set([y₁ => 1, y₂ => 0, y₃ => 0]) + @test Set(Num.(unknowns(sys)) .=> p.u0) == Set([y₁ => 1, y₂ => 0, y₃ => 0]) end # test remake with symbols p3 = [k₁ => 0.05, @@ -259,7 +259,7 @@ prob_pmap = remake(prob14; p = p3, u0 = u01) prob_dpmap = remake(prob14; p = Dict(p3), u0 = Dict(u01)) for p in [prob_pmap, prob_dpmap] @test Set(Num.(parameters(sys)) .=> p.p) == Set([k₁ => 0.05, k₂ => 2e7, k₃ => 1.1e4]) - @test Set(Num.(states(sys)) .=> p.u0) == Set([y₁ => 1, y₂ => 1, y₃ => 1]) + @test Set(Num.(unknowns(sys)) .=> p.u0) == Set([y₁ => 1, y₂ => 1, y₃ => 1]) end sol_pmap = solve(prob_pmap, Rodas5()) sol_dpmap = solve(prob_dpmap, Rodas5()) @@ -323,7 +323,7 @@ eqs = [D(x) ~ σ * (y - x), D(y) ~ x - β * y, x + z ~ y] @named sys = ODESystem(eqs) -@test all(isequal.(states(sys), [x, y, z])) +@test all(isequal.(unknowns(sys), [x, y, z])) @test all(isequal.(parameters(sys), [σ, β])) @test equations(sys) == eqs @test ModelingToolkit.isautonomous(sys) @@ -372,7 +372,7 @@ eqs = [ ] @named sys = ODESystem(eqs, t) @test isequal(ModelingToolkit.get_iv(sys), t) -@test isequal(states(sys), [x1, x2]) +@test isequal(unknowns(sys), [x1, x2]) @test isempty(parameters(sys)) # one equation ODESystem test @@ -870,11 +870,11 @@ let sys = structural_simplify(sys) u0 = ModelingToolkit.missing_variable_defaults(sys) - u0_expected = Pair[s => 0.0 for s in states(sys)] + u0_expected = Pair[s => 0.0 for s in unknowns(sys)] @test string(u0) == string(u0_expected) u0 = ModelingToolkit.missing_variable_defaults(sys, [1, 2]) - u0_expected = Pair[s => i for (i, s) in enumerate(states(sys))] + u0_expected = Pair[s => i for (i, s) in enumerate(unknowns(sys))] @test string(u0) == string(u0_expected) @test_nowarn ODEProblem(sys, u0, (0, 1)) @@ -970,7 +970,7 @@ let @named sys4 = ODESystem([der(x) ~ -y; der(y) ~ 1 + pp * y + x], t) sys4s = structural_simplify(sys4) prob = ODAEProblem(sys4s, [x => 1.0, D(x) => 1.0], (0, 1.0)) - @test string.(states(prob.f.sys)) == ["x(t)", "y(t)"] + @test string.(unknowns(prob.f.sys)) == ["x(t)", "y(t)"] @test string.(parameters(prob.f.sys)) == ["pp"] @test string.(independent_variables(prob.f.sys)) == ["t"] end @@ -1041,7 +1041,7 @@ vars_sub2 = @variables s2(t) @named sub = extend(partial_sub, sub) new_sys2 = complete(substitute(sys2, Dict(:sub => sub))) -Set(states(new_sys2)) == Set([new_sys2.x1, new_sys2.sys1.x1, +Set(unknowns(new_sys2)) == Set([new_sys2.x1, new_sys2.sys1.x1, new_sys2.sys1.sub.s1, new_sys2.sys1.sub.s2, new_sys2.sub.s1, new_sys2.sub.s2]) diff --git a/test/optimizationsystem.jl b/test/optimizationsystem.jl index 2dbf9f08ed..4e57e633a6 100644 --- a/test/optimizationsystem.jl +++ b/test/optimizationsystem.jl @@ -18,7 +18,7 @@ using ModelingToolkit: get_metadata name = :combinedsys) equations(combinedsys) - states(combinedsys) + unknowns(combinedsys) parameters(combinedsys) calculate_gradient(combinedsys) @@ -154,7 +154,7 @@ end prob = OptimizationProblem(sys, [0.0, 0.0]) @test isequal(constraints(sys), vcat(sys1.x + sys2.y ~ 2, sys1.x ~ 1, sys2.y ~ 1)) @test isequal(equations(sys), (sys1.x - sys1.a)^2 + (sys2.y - 1 / 2)^2) - @test isequal(states(sys), [sys1.x, sys2.y]) + @test isequal(unknowns(sys), [sys1.x, sys2.y]) prob_ = remake(prob, u0 = [1.0, 0.0], p = [2.0]) @test isequal(prob_.u0, [1.0, 0.0]) diff --git a/test/reduction.jl b/test/reduction.jl index 0b58c2de43..382a3f88de 100644 --- a/test/reduction.jl +++ b/test/reduction.jl @@ -39,7 +39,7 @@ str = String(take!(io)); reduced_eqs = [D(x) ~ σ * (y - x) D(y) ~ β + (ρ - z) * x - y] #test_equal.(equations(lorenz1_aliased), reduced_eqs) -@test isempty(setdiff(states(lorenz1_aliased), [x, y, z])) +@test isempty(setdiff(unknowns(lorenz1_aliased), [x, y, z])) #test_equal.(observed(lorenz1_aliased), [u ~ 0 # z ~ x - y # a ~ -z]) @@ -76,10 +76,10 @@ __x = x reduced_system = structural_simplify(connected) reduced_system2 = structural_simplify(tearing_substitution(structural_simplify(tearing_substitution(structural_simplify(connected))))) -@test isempty(setdiff(states(reduced_system), states(reduced_system2))) +@test isempty(setdiff(unknowns(reduced_system), unknowns(reduced_system2))) @test isequal(equations(tearing_substitution(reduced_system)), equations(reduced_system2)) @test isequal(observed(reduced_system), observed(reduced_system2)) -@test setdiff(states(reduced_system), +@test setdiff(unknowns(reduced_system), [s a lorenz1.x @@ -168,7 +168,7 @@ u0 = [u1 => 1 pp = [2] nlprob = NonlinearProblem(reducedsys, u0, pp) reducedsol = solve(nlprob, NewtonRaphson()) -residual = fill(100.0, length(states(reducedsys))) +residual = fill(100.0, length(unknowns(reducedsys))) nlprob.f(residual, reducedsol.u, pp) @test hypot(nlprob.f.observed(u2, reducedsol.u, pp), nlprob.f.observed(u1, reducedsol.u, pp)) * @@ -228,7 +228,7 @@ eq = [v47 ~ v1 sys = structural_simplify(sys0) @test length(equations(sys)) == 1 eq = equations(tearing_substitution(sys))[1] -vv = only(states(sys)) +vv = only(unknowns(sys)) @test isequal(eq.lhs, D(vv)) dvv = ModelingToolkit.value(ModelingToolkit.derivative(eq.rhs, vv)) @test dvv ≈ -60 @@ -299,6 +299,6 @@ ss = structural_simplify(sys) eqs = [D(D(x)) ~ -x] @named sys = ODESystem(eqs, t, [x], []) ss = alias_elimination(sys) -@test length(equations(ss)) == length(states(ss)) == 1 +@test length(equations(ss)) == length(unknowns(ss)) == 1 ss = structural_simplify(sys) -@test length(equations(ss)) == length(states(ss)) == 2 +@test length(equations(ss)) == length(unknowns(ss)) == 2 diff --git a/test/runtests.jl b/test/runtests.jl index e9b392dd4a..7fd6fe4baf 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -10,30 +10,30 @@ end @time begin if GROUP == "All" || GROUP == "InterfaceI" - @safetestset "Linear Algebra Test" include("linalg.jl") - @safetestset "AbstractSystem Test" include("abstractsystem.jl") - @safetestset "Variable Scope Tests" include("variable_scope.jl") - @safetestset "Symbolic Parameters Test" include("symbolic_parameters.jl") - @safetestset "Parsing Test" include("variable_parsing.jl") - @safetestset "Simplify Test" include("simplify.jl") - @safetestset "Direct Usage Test" include("direct.jl") - @safetestset "System Linearity Test" include("linearity.jl") - @safetestset "Linearization Tests" include("linearize.jl") - @safetestset "Input Output Test" include("input_output_handling.jl") - @safetestset "Clock Test" include("clock.jl") - @safetestset "DiscreteSystem Test" include("discretesystem.jl") - @safetestset "ODESystem Test" include("odesystem.jl") - @safetestset "Dynamic Quantities Test" include("dq_units.jl") - @safetestset "Unitful Quantities Test" include("units.jl") - @safetestset "LabelledArrays Test" include("labelledarrays.jl") - @safetestset "Mass Matrix Test" include("mass_matrix.jl") - @safetestset "SteadyStateSystem Test" include("steadystatesystems.jl") - @safetestset "SDESystem Test" include("sdesystem.jl") - @safetestset "NonlinearSystem Test" include("nonlinearsystem.jl") - @safetestset "PDE Construction Test" include("pde.jl") - @safetestset "JumpSystem Test" include("jumpsystem.jl") - @safetestset "Constraints Test" include("constraints.jl") - @safetestset "Reduction Test" include("reduction.jl") + # @safetestset "Linear Algebra Test" include("linalg.jl") + # @safetestset "AbstractSystem Test" include("abstractsystem.jl") + # @safetestset "Variable Scope Tests" include("variable_scope.jl") + # @safetestset "Symbolic Parameters Test" include("symbolic_parameters.jl") + # @safetestset "Parsing Test" include("variable_parsing.jl") + # @safetestset "Simplify Test" include("simplify.jl") + # @safetestset "Direct Usage Test" include("direct.jl") + # @safetestset "System Linearity Test" include("linearity.jl") + # @safetestset "Linearization Tests" include("linearize.jl") + # @safetestset "Input Output Test" include("input_output_handling.jl") + # @safetestset "Clock Test" include("clock.jl") + # @safetestset "DiscreteSystem Test" include("discretesystem.jl") + # @safetestset "ODESystem Test" include("odesystem.jl") + # @safetestset "Dynamic Quantities Test" include("dq_units.jl") + # @safetestset "Unitful Quantities Test" include("units.jl") + # @safetestset "LabelledArrays Test" include("labelledarrays.jl") + # @safetestset "Mass Matrix Test" include("mass_matrix.jl") + # @safetestset "SteadyStateSystem Test" include("steadystatesystems.jl") + # @safetestset "SDESystem Test" include("sdesystem.jl") + # @safetestset "NonlinearSystem Test" include("nonlinearsystem.jl") + # @safetestset "PDE Construction Test" include("pde.jl") + # @safetestset "JumpSystem Test" include("jumpsystem.jl") + # @safetestset "Constraints Test" include("constraints.jl") + # @safetestset "Reduction Test" include("reduction.jl") @safetestset "Split Parameters Test" include("split_parameters.jl") @safetestset "ODAEProblem Test" include("odaeproblem.jl") @safetestset "StaticArrays Test" include("static_arrays.jl") diff --git a/test/sdesystem.jl b/test/sdesystem.jl index a520a9d58e..a630deac99 100644 --- a/test/sdesystem.jl +++ b/test/sdesystem.jl @@ -555,7 +555,7 @@ end seeds = rand(UInt, numtraj) ensemble_prob = EnsembleProblem(prob; - output_func = (sol, i) -> (g(sol[end]), false), + output_func = (sol, i) -> (g(sol.u[end]), false), prob_func = prob_func) sim = solve(ensemble_prob, EM(), dt = dt, trajectories = numtraj) diff --git a/test/state_selection.jl b/test/state_selection.jl index 4b6121338d..f4fbbb3c0b 100644 --- a/test/state_selection.jl +++ b/test/state_selection.jl @@ -18,12 +18,12 @@ let dd = dummy_derivative(sys) has_dx2 |= D(x2) in vars || D(D(x2)) in vars end @test has_dx1 ⊻ has_dx2 # only one of x1 and x2 can be a dummy derivative - @test length(states(dd)) == length(equations(dd)) < 9 + @test length(unknowns(dd)) == length(equations(dd)) < 9 end @test_skip let pss = partial_state_selection(sys) @test length(equations(pss)) == 1 - @test length(states(pss)) == 2 + @test length(unknowns(pss)) == 2 @test length(equations(ode_order_lowering(pss))) == 2 end @@ -128,7 +128,7 @@ let D(supply_pipe.fluid_port_a.m) => 0.0] prob1 = ODEProblem(sys, u0, (0.0, 10.0), []) prob2 = ODAEProblem(sys, u0, (0.0, 10.0), []) - prob3 = DAEProblem(sys, D.(states(sys)) .=> 0.0, u0, (0.0, 10.0), []) + prob3 = DAEProblem(sys, D.(unknowns(sys)) .=> 0.0, u0, (0.0, 10.0), []) @test solve(prob1, FBDF()).retcode == ReturnCode.Success #@test solve(prob2, FBDF()).retcode == ReturnCode.Success @test solve(prob3, DFBDF()).retcode == ReturnCode.Success diff --git a/test/structural_transformation/index_reduction.jl b/test/structural_transformation/index_reduction.jl index e6f7534e58..a56a04f4c4 100644 --- a/test/structural_transformation/index_reduction.jl +++ b/test/structural_transformation/index_reduction.jl @@ -135,7 +135,7 @@ end let sys = structural_simplify(pendulum2) @test length(equations(sys)) == 5 - @test length(states(sys)) == 5 + @test length(unknowns(sys)) == 5 u0 = [ D(x) => 0.0, diff --git a/test/structural_transformation/tearing.jl b/test/structural_transformation/tearing.jl index b2e4b846d6..818daf6c95 100644 --- a/test/structural_transformation/tearing.jl +++ b/test/structural_transformation/tearing.jl @@ -154,7 +154,7 @@ eqs = [D(x) ~ z * h newdaesys = structural_simplify(daesys) @test equations(newdaesys) == [D(x) ~ z; 0 ~ y + sin(z) - p * t] @test equations(tearing_substitution(newdaesys)) == [D(x) ~ z; 0 ~ x + sin(z) - p * t] -@test isequal(states(newdaesys), [x, z]) +@test isequal(unknowns(newdaesys), [x, z]) prob = ODAEProblem(newdaesys, [x => 1.0], (0, 1.0), [p => 0.2]) du = [0.0]; u = [1.0]; diff --git a/test/symbolic_parameters.jl b/test/symbolic_parameters.jl index 1df6782faf..d779676b49 100644 --- a/test/symbolic_parameters.jl +++ b/test/symbolic_parameters.jl @@ -39,12 +39,12 @@ res = ModelingToolkit.varmap_to_vars(Dict(), parameters(top), defaults = ModelingToolkit.defaults(top)) @test res == [0.5, 1, 0.1 + 1, (0.1 + 1) * 1.1] -prob = NonlinearProblem(top, [states(ns, u) => 1.0, a => 1.0], []) +prob = NonlinearProblem(top, [unknowns(ns, u) => 1.0, a => 1.0], []) @test prob.u0 == [1.0, 0.5, 1.1, 0.9] @show sol = solve(prob, NewtonRaphson()) # test NullParameters+defaults -prob = NonlinearProblem(top, [states(ns, u) => 1.0, a => 1.0]) +prob = NonlinearProblem(top, [unknowns(ns, u) => 1.0, a => 1.0]) @test prob.u0 == [1.0, 0.5, 1.1, 0.9] @show sol = solve(prob, NewtonRaphson()) diff --git a/test/test_variable_metadata.jl b/test/test_variable_metadata.jl index 4e75f1f56c..a07713825c 100644 --- a/test/test_variable_metadata.jl +++ b/test/test_variable_metadata.jl @@ -65,7 +65,7 @@ lb, ub = getbounds(p) b = getbounds(sys) @test b[T] == (0, Inf) -b = getbounds(sys, states(sys)) +b = getbounds(sys, unknowns(sys)) @test b[x] == (-10, 10) p = tunable_parameters(sys, default = true) diff --git a/test/variable_scope.jl b/test/variable_scope.jl index 2049f0fd69..ce467ff20b 100644 --- a/test/variable_scope.jl +++ b/test/variable_scope.jl @@ -29,7 +29,7 @@ eqs = [0 ~ a @named sub1 = NonlinearSystem([], [], [], systems = [sub2]) @named sys = NonlinearSystem([], [], [], systems = [sub1]) -names = ModelingToolkit.getname.(states(sys)) +names = ModelingToolkit.getname.(unknowns(sys)) @test :d in names @test Symbol("sub1₊c") in names @test Symbol("sub1₊sub2₊b") in names From 3150dab9f263de552f1a8f390123d9e0a08af050 Mon Sep 17 00:00:00 2001 From: Aayush Sabharwal Date: Mon, 29 Jan 2024 12:46:35 +0530 Subject: [PATCH 2/3] refactor: rename semantic occurences of "state variables" to "unknown (variables)" --- docs/src/basics/AbstractSystem.md | 8 +-- docs/src/basics/Composition.md | 18 +++--- docs/src/basics/ContextualVariables.md | 4 +- docs/src/basics/Events.md | 12 ++-- docs/src/basics/FAQ.md | 2 +- docs/src/basics/Linearization.md | 4 +- docs/src/basics/MTKModel_Connector.md | 10 +-- .../modelingtoolkitize_index_reduction.md | 4 +- docs/src/examples/perturbation.md | 2 +- docs/src/examples/spring_mass.md | 10 +-- docs/src/internals.md | 2 +- docs/src/tutorials/acausal_components.md | 16 ++--- docs/src/tutorials/domain_connections.md | 6 +- docs/src/tutorials/ode_modeling.md | 14 ++--- .../tutorials/parameter_identifiability.md | 4 +- src/discretedomain.jl | 2 +- src/inputoutput.jl | 4 +- src/parameters.jl | 2 +- src/structural_transformation/codegen.jl | 40 ++++++------ src/structural_transformation/pantelides.jl | 2 +- .../partial_state_selection.jl | 4 +- .../symbolics_tearing.jl | 6 +- src/structural_transformation/utils.jl | 4 +- src/systems/abstractsystem.jl | 62 +++++++++---------- src/systems/alias_elimination.jl | 13 ++-- src/systems/callbacks.jl | 8 +-- src/systems/clock_inference.jl | 8 +-- src/systems/connectors.jl | 36 +++++------ src/systems/dependency_graphs.jl | 10 +-- src/systems/diffeqs/abstractodesystem.jl | 8 +-- src/systems/diffeqs/first_order_transform.jl | 8 +-- src/systems/diffeqs/odesystem.jl | 22 +++---- src/systems/diffeqs/sdesystem.jl | 20 +++--- .../discrete_system/discrete_system.jl | 30 ++++----- src/systems/jumps/jumpsystem.jl | 58 ++++++++--------- src/systems/nonlinear/nonlinearsystem.jl | 2 +- .../optimization/constraints_system.jl | 6 +- .../optimization/optimizationsystem.jl | 6 +- src/systems/systems.jl | 2 +- src/systems/systemstructure.jl | 14 ++--- src/systems/unit_check.jl | 6 +- src/systems/validation.jl | 18 +++--- src/utils.jl | 28 ++++----- src/variables.jl | 6 +- test/jumpsystem.jl | 6 +- test/linearize.jl | 8 +-- test/modelingtoolkitize.jl | 6 +- test/nonlinearsystem.jl | 4 +- test/odesystem.jl | 2 +- test/reduction.jl | 2 +- test/symbolic_events.jl | 2 +- 51 files changed, 290 insertions(+), 291 deletions(-) diff --git a/docs/src/basics/AbstractSystem.md b/docs/src/basics/AbstractSystem.md index feebf8ffdc..2161613353 100644 --- a/docs/src/basics/AbstractSystem.md +++ b/docs/src/basics/AbstractSystem.md @@ -22,7 +22,7 @@ Generally, it follows the order of: 1. Equations 2. Independent Variables - 3. Dependent Variables (or States) + 3. Dependent Variables (or Unknowns) 4. Parameters All other pieces are handled via keyword arguments. `AbstractSystem`s share the @@ -37,7 +37,7 @@ same keyword arguments, which are: ## Composition and Accessor Functions Each `AbstractSystem` has lists of variables in context, such as distinguishing -parameters vs states. In addition, an `AbstractSystem` can also hold other +parameters vs unknowns. In addition, an `AbstractSystem` can also hold other `AbstractSystem` types. Direct accessing of the values, such as `sys.unknowns`, gives the immediate list, while the accessor functions `unknowns(sys)` gives the total set, which includes that of all systems held inside. @@ -49,7 +49,7 @@ The values which are common to all `AbstractSystem`s are: - `parameters(sys)`: All parameters of the system and its subsystems. - `nameof(sys)`: The name of the current-level system. - `get_eqs(sys)`: Equations that define the current-level system. - - `get_unknowns(sys)`: States that are in the current-level system. + - `get_unknowns(sys)`: Unknowns that are in the current-level system. - `get_ps(sys)`: Parameters that are in the current-level system. - `get_systems(sys)`: Subsystems of the current-level system. @@ -129,7 +129,7 @@ pairs `var=>value`, which allows the user to designate the values without having to know the order that ModelingToolkit is internally using. For the value maps, the parameters are allowed to be functions of each other, -and value maps of states can be functions of the parameters, i.e. you can do: +and value maps of unknowns can be functions of the parameters, i.e. you can do: ``` u0 = [ diff --git a/docs/src/basics/Composition.md b/docs/src/basics/Composition.md index 6171b545a5..dc7dce4225 100644 --- a/docs/src/basics/Composition.md +++ b/docs/src/basics/Composition.md @@ -12,7 +12,7 @@ an optional forcing function, and allowing the user to specify the forcing later. Here, the library author defines a component named `decay`. The user then builds two `decay` components and connects them, saying the forcing term of `decay1` is a constant while the forcing term -of `decay2` is the value of the state variable `x`. +of `decay2` is the value of the unknown variable `x`. ```@example composition using ModelingToolkit @@ -70,18 +70,18 @@ subsystems. A model is the composition of itself and its subsystems. For example, if we have: ```julia -@named sys = compose(ODESystem(eqs, indepvar, states, ps), subsys) +@named sys = compose(ODESystem(eqs, indepvar, unknowns, ps), subsys) ``` the `equations` of `sys` is the concatenation of `get_eqs(sys)` and -`equations(subsys)`, the states are the concatenation of their states, +`equations(subsys)`, the unknowns are the concatenation of their unknowns, etc. When the `ODEProblem` or `ODEFunction` is generated from this system, it will build and compile the functions associated with this composition. The new equations within the higher level system can access the variables in the lower level system by namespacing via the `nameof(subsys)`. For -example, let's say there is a variable `x` in `states` and a variable +example, let's say there is a variable `x` in `unknowns` and a variable `x` in `subsys`. We can declare that these two variables are the same by specifying their equality: `x ~ subsys.x` in the `eqs` for `sys`. This algebraic relationship can then be simplified by transformations @@ -133,7 +133,7 @@ sys = ODESystem( sys.y = u * 1.1 ``` -In a hierarchical system, variables of the subsystem get namespaced by the name of the system they are in. This prevents naming clashes, but also enforces that every state and parameter is local to the subsystem it is used in. In some cases it might be desirable to have variables and parameters that are shared between subsystems, or even global. This can be accomplished as follows. +In a hierarchical system, variables of the subsystem get namespaced by the name of the system they are in. This prevents naming clashes, but also enforces that every unknown and parameter is local to the subsystem it is used in. In some cases it might be desirable to have variables and parameters that are shared between subsystems, or even global. This can be accomplished as follows. ```julia @parameters t a b c d e f @@ -186,12 +186,12 @@ i.e. equations which result in `0~0` expressions, in over-specified systems. Model inheritance can be done in two ways: implicitly or explicitly. First, one can use the `extend` function to extend a base model with another set of -equations, states, and parameters. An example can be found in the +equations, unknowns, and parameters. An example can be found in the [acausal components tutorial](@ref acausal). The explicit way is to shadow variables with equality expressions. For example, let's assume we have three separate systems which we want to compose to a single -one. This is how one could explicitly forward all states and parameters to the +one. This is how one could explicitly forward all unknowns and parameters to the higher level system: ```@example compose @@ -225,7 +225,7 @@ sir = compose(ODESystem([ reqn.γ => γ], name = :sir), seqn, ieqn, reqn) ``` -Note that the states are forwarded by an equality relationship, while +Note that the unknowns are forwarded by an equality relationship, while the parameters are forwarded through a relationship in their default values. The user of this model can then solve this model simply by specifying the values at the highest level: @@ -266,7 +266,7 @@ more efficient and more stable. ## Components with discontinuous dynamics When modeling, e.g., impacts, saturations or Coulomb friction, the dynamic -equations are discontinuous in either the state or one of its derivatives. This +equations are discontinuous in either the unknown or one of its derivatives. This causes the solver to take very small steps around the discontinuity, and sometimes leads to early stopping due to `dt <= dt_min`. The correct way to handle such dynamics is to tell the solver about the discontinuity by a diff --git a/docs/src/basics/ContextualVariables.md b/docs/src/basics/ContextualVariables.md index de2802ce40..110dbf3f40 100644 --- a/docs/src/basics/ContextualVariables.md +++ b/docs/src/basics/ContextualVariables.md @@ -10,7 +10,7 @@ the `@variable` which is defined by @variables x y(x) ``` -This is used for the “normal” variable of a given system, like the states of a +This is used for the “normal” variable of a given system, like the unknowns of a differential equation or objective function. All the macros below support the same syntax as `@variables`. @@ -18,7 +18,7 @@ the same syntax as `@variables`. All modeling projects have some form of parameters. `@parameters` marks a variable as being the parameter of some system, which allows automatic detection algorithms -to ignore such variables when attempting to find the states of a system. +to ignore such variables when attempting to find the unknowns of a system. ## Constants diff --git a/docs/src/basics/Events.md b/docs/src/basics/Events.md index bed148f4ef..e23b1a6381 100644 --- a/docs/src/basics/Events.md +++ b/docs/src/basics/Events.md @@ -43,7 +43,7 @@ event conditions, and the second vector of equations describes the effect on the state. Each affect equation must be of the form ```julia -single_state_variable ~ expression_involving_any_variables_or_parameters +single_unknown_variable ~ expression_involving_any_variables_or_parameters ``` or @@ -151,13 +151,13 @@ of one or more equations, an affect is defined as a `tuple`: [x ~ 0] => (affect!, [v, x], [p, q], ctx) ``` -where, `affect!` is a Julia function with the signature: `affect!(integ, u, p, ctx)`; `[u,v]` and `[p,q]` are the symbolic states (variables) and parameters +where, `affect!` is a Julia function with the signature: `affect!(integ, u, p, ctx)`; `[u,v]` and `[p,q]` are the symbolic unknowns (variables) and parameters that are accessed by `affect!`, respectively; and `ctx` is any context that is passed to `affect!` as the `ctx` argument. `affect!` receives a [DifferentialEquations.jl integrator](https://docs.sciml.ai/DiffEqDocs/stable/basics/integrator/) -as its first argument, which can then be used to access states and parameters +as its first argument, which can then be used to access unknowns and parameters that are provided in the `u` and `p` arguments (implemented as `NamedTuple`s). The integrator can also be manipulated more generally to control solution behavior, see the [integrator @@ -167,7 +167,7 @@ documentation. In affect functions, we have that ```julia function affect!(integ, u, p, ctx) # integ.t is the current time - # integ.u[u.v] is the value of the state `v` above + # integ.u[u.v] is the value of the unknown `v` above # integ.p[p.q] is the value of the parameter `q` above end ``` @@ -222,8 +222,8 @@ where conditions are symbolic expressions that should evaluate to `true` when an individual affect should be executed. Here `affect1` and `affect2` are each either a vector of one or more symbolic equations, or a functional affect, just as for continuous events. As before, for any *one* event the symbolic affect -equations can either all change states (i.e. variables) or all change -parameters, but one cannot currently mix state and parameter changes within one +equations can either all change unknowns (i.e. variables) or all change +parameters, but one cannot currently mix unknown variable and parameter changes within one individual event. ### Example: Injecting cells into a population diff --git a/docs/src/basics/FAQ.md b/docs/src/basics/FAQ.md index 7b6846354f..4902c5b471 100644 --- a/docs/src/basics/FAQ.md +++ b/docs/src/basics/FAQ.md @@ -130,7 +130,7 @@ julia> ModelingToolkit.missing_variable_defaults(sys, [1,2,3]) x3ˍtt(t) => 3 ``` -## Change the state vector type +## Change the unknown variable vector type Use the `u0_constructor` keyword argument to map an array to the desired container type. For example: diff --git a/docs/src/basics/Linearization.md b/docs/src/basics/Linearization.md index bf5c48f1bf..0782b87249 100644 --- a/docs/src/basics/Linearization.md +++ b/docs/src/basics/Linearization.md @@ -34,7 +34,7 @@ matrices, simplified_sys = linearize(sys, [r], [y]) # Linearize from r to y matrices ``` -The named tuple `matrices` contains the matrices of the linear statespace representation, while `simplified_sys` is an `ODESystem` that, among other things, indicates the state order in the linear system through +The named tuple `matrices` contains the matrices of the linear statespace representation, while `simplified_sys` is an `ODESystem` that, among other things, indicates the unknown variable order in the linear system through ```@example LINEARIZE using ModelingToolkit: inputs, outputs @@ -43,7 +43,7 @@ using ModelingToolkit: inputs, outputs ## Operating point -The operating point to linearize around can be specified with the keyword argument `op` like this: `op = Dict(x => 1, r => 2)`. The operating point may include specification of state variables, input variables and parameters. For variables that are not specified in `op`, the default value specified in the model will be used if available, if no value is specified, an error is thrown. +The operating point to linearize around can be specified with the keyword argument `op` like this: `op = Dict(x => 1, r => 2)`. The operating point may include specification of unknown variables, input variables and parameters. For variables that are not specified in `op`, the default value specified in the model will be used if available, if no value is specified, an error is thrown. ## Batch linearization and algebraic variables diff --git a/docs/src/basics/MTKModel_Connector.md b/docs/src/basics/MTKModel_Connector.md index b562c5323c..4472755c85 100644 --- a/docs/src/basics/MTKModel_Connector.md +++ b/docs/src/basics/MTKModel_Connector.md @@ -10,7 +10,7 @@ ModelingToolkit.Model ## Components -Components are models from various domains. These models contain states and their +Components are models from various domains. These models contain unknowns and their equations. ### [Defining components with `@mtkmodel`](@id mtkmodel) @@ -25,11 +25,11 @@ equations. - `@components`: for listing sub-components of the system - `@equations`: for the list of equations - - `@extend`: for extending a base system and unpacking its states + - `@extend`: for extending a base system and unpacking its unknowns - `@icon` : for embedding the model icon - `@parameters`: for specifying the symbolic parameters - `@structural_parameters`: for specifying non-symbolic parameters - - `@variables`: for specifying the states + - `@variables`: for specifying the unknowns Let's explore these in more detail with the following example: @@ -171,7 +171,7 @@ getdefault(model_c4.model_a.k_array[2]) Connectors are special models that can be used to connect different components together. MTK provides 3 distinct connectors: - - `DomainConnector`: A connector which has only one state which is of `Flow` type, + - `DomainConnector`: A connector which has only one unknown which is of `Flow` type, specified by `[connect = Flow]`. - `StreamConnector`: A connector which has atleast one stream variable, specified by `[connect = Stream]`. A `StreamConnector` must have exactly one flow variable. @@ -228,7 +228,7 @@ end `structure` stores metadata that describes composition of a model. It includes: - `:components`: List of sub-components in the form of [[name, sub_component_name],...]. - - `:extend`: The list of extended states, name given to the base system, and name of the base system. + - `:extend`: The list of extended unknowns, name given to the base system, and name of the base system. - `:structural_parameters`: Dictionary of structural parameters mapped to their default values. - `:parameters`: Dictionary of symbolic parameters mapped to their metadata. For parameter arrays, length is added to the metadata as `:size`. diff --git a/docs/src/examples/modelingtoolkitize_index_reduction.md b/docs/src/examples/modelingtoolkitize_index_reduction.md index fc6876d942..fea6cf19f3 100644 --- a/docs/src/examples/modelingtoolkitize_index_reduction.md +++ b/docs/src/examples/modelingtoolkitize_index_reduction.md @@ -81,7 +81,7 @@ However, one will quickly be greeted with the unfortunate message: └ @ OrdinaryDiffEq C:\Users\accou\.julia\packages\OrdinaryDiffEq\yCczp\src\initdt.jl:76 ┌ Warning: Automatic dt set the starting dt as NaN, causing instability. └ @ OrdinaryDiffEq C:\Users\accou\.julia\packages\OrdinaryDiffEq\yCczp\src\solve.jl:485 -┌ Warning: NaN dt detected. Likely a NaN value in the state, parameters, or derivative value caused this outcome. +┌ Warning: NaN dt detected. Likely a NaN value in the unknowns, parameters, or derivative value caused this outcome. └ @ SciMLBase C:\Users\accou\.julia\packages\SciMLBase\DrPil\src\integrator_interface.jl:325 ``` @@ -164,7 +164,7 @@ plot and the plot is shown in the same order as the original numerical code. Note that we can even go a bit further. If we use the `ODAEProblem` -constructor, we can remove the algebraic equations from the states of the +constructor, we can remove the algebraic equations from the unknowns of the system and fully transform the index-3 DAE into an index-0 ODE which can be solved via an explicit Runge-Kutta method: diff --git a/docs/src/examples/perturbation.md b/docs/src/examples/perturbation.md index 8416a013ac..95c4d5491d 100644 --- a/docs/src/examples/perturbation.md +++ b/docs/src/examples/perturbation.md @@ -94,7 +94,7 @@ using ModelingToolkit, DifferentialEquations @named sys = ODESystem(eqs, t) sys = structural_simplify(sys) -states(sys) +unknowns(sys) ``` ```julia diff --git a/docs/src/examples/spring_mass.md b/docs/src/examples/spring_mass.md index eafd8269ea..cabeebb680 100644 --- a/docs/src/examples/spring_mass.md +++ b/docs/src/examples/spring_mass.md @@ -141,10 +141,10 @@ We can take a look at the equations in the model using the `equations` function. equations(model) ``` -The states of this model are: +The unknowns of this model are: ```@example component -states(model) +unknowns(model) ``` And the parameters of this model are: @@ -162,7 +162,7 @@ sys = structural_simplify(model) equations(sys) ``` -We are left with only 4 equations involving 4 state variables (`mass.pos[1]`, +We are left with only 4 equations involving 4 unknown variables (`mass.pos[1]`, `mass.pos[2]`, `mass.v[1]`, `mass.v[2]`). We can solve the system by converting it to an `ODEProblem`. Some observed variables are not expanded by default. To view the complete equations, one can do @@ -179,13 +179,13 @@ sol = solve(prob, Rosenbrock23()) plot(sol) ``` -What if we want the timeseries of a different variable? That information is not lost! Instead, `structural_simplify` simply changes state variables into `observed` variables. +What if we want the timeseries of a different variable? That information is not lost! Instead, `structural_simplify` simply changes unknown variables into `observed` variables. ```@example component observed(sys) ``` -These are explicit algebraic equations which can be used to reconstruct the required variables on the fly. This leads to dramatic computational savings since implicitly solving an ODE scales as O(n^3), so fewer states are significantly better! +These are explicit algebraic equations which can be used to reconstruct the required variables on the fly. This leads to dramatic computational savings since implicitly solving an ODE scales as O(n^3), so fewer unknowns are significantly better! We can access these variables using the solution object. For example, let's retrieve the x-position of the mass over time: diff --git a/docs/src/internals.md b/docs/src/internals.md index 1e00461155..79ded5c57f 100644 --- a/docs/src/internals.md +++ b/docs/src/internals.md @@ -6,7 +6,7 @@ contributors to the library. ## Observables and Variable Elimination In the variable “elimination” algorithms, what is actually done is that variables -are removed from being states and equations are moved into the `observed` category +are removed from being unknowns and equations are moved into the `observed` category of the system. The `observed` equations are explicit algebraic equations which are then substituted out to completely eliminate these variables from the other equations, allowing the system to act as though these variables no longer exist. diff --git a/docs/src/tutorials/acausal_components.md b/docs/src/tutorials/acausal_components.md index 508912c860..0879317ab9 100644 --- a/docs/src/tutorials/acausal_components.md +++ b/docs/src/tutorials/acausal_components.md @@ -208,7 +208,7 @@ resistor's resistance. By doing so, if the resistance of this resistor is not overridden by a higher level default or overridden at `ODEProblem` construction time, this will be the value of the resistance. Also, note the use of `@extend`. For the `Resistor`, we want to simply inherit `OnePort`'s -equations and states and extend them with a new equation. Note that `v`, `i` are not namespaced as `oneport.v` or `oneport.i`. +equations and unknowns and extend them with a new equation. Note that `v`, `i` are not namespaced as `oneport.v` or `oneport.i`. Using our knowledge of circuits, we similarly construct the `Capacitor`: @@ -280,16 +280,16 @@ the parameters or defaults values of variables of subcomponents. This model is acausal because we have not specified anything about the causality of the model. We have simply specified what is true about each of the variables. This forms a system of differential-algebraic equations (DAEs) which define the evolution of each -state of the system. The equations are: +unknown of the system. The equations are: ```@example acausal equations(expand_connections(rc_model)) ``` -the states are: +the unknowns are: ```@example acausal -states(rc_model) +unknowns(rc_model) ``` and the parameters are: @@ -307,9 +307,9 @@ observed(rc_model) ## Solving this System We are left with a system of only two equations -with two state variables. One of the equations is a differential equation, +with two unknown variables. One of the equations is a differential equation, while the other is an algebraic equation. We can then give the values for the -initial conditions of our states, and solve the system by converting it to +initial conditions of our unknowns, and solve the system by converting it to an ODEProblem in mass matrix form and solving it with an [ODEProblem mass matrix DAE solver](https://docs.sciml.ai/DiffEqDocs/stable/solvers/dae_solve/#OrdinaryDiffEq.jl-(Mass-Matrix)). This is done as follows: @@ -325,7 +325,7 @@ plot(sol) However, what if we wanted to plot the timeseries of a different variable? Do not worry, that information was not thrown away! Instead, transformations -like `structural_simplify` simply change state variables into observables which are +like `structural_simplify` simply change unknown variables into observables which are defined by `observed` equations. ```@example acausal @@ -335,7 +335,7 @@ observed(rc_model) These are explicit algebraic equations which can then be used to reconstruct the required variables on the fly. This leads to dramatic computational savings because implicitly solving an ODE scales like O(n^3), so making there be as -few states as possible is good! +few unknowns as possible is good! The solution object can be accessed via its symbols. For example, let's retrieve the voltage of the resistor over time: diff --git a/docs/src/tutorials/domain_connections.md b/docs/src/tutorials/domain_connections.md index 1912d60048..f433021998 100644 --- a/docs/src/tutorials/domain_connections.md +++ b/docs/src/tutorials/domain_connections.md @@ -96,7 +96,7 @@ end nothing #hide ``` -When the system is defined we can generate a fluid component and connect it to the system. Here `fluid` is connected to the `src.port`, but it could also be connected to `vol.port`, any connection in the network is fine. Note: we can visualize the system using `ModelingToolkitDesigner.jl`, where a dashed line is used to show the `fluid` connection to represent a domain connection that is only transporting parameters and not states. +When the system is defined we can generate a fluid component and connect it to the system. Here `fluid` is connected to the `src.port`, but it could also be connected to `vol.port`, any connection in the network is fine. Note: we can visualize the system using `ModelingToolkitDesigner.jl`, where a dashed line is used to show the `fluid` connection to represent a domain connection that is only transporting parameters and not unknown variables. ```@example domain @component function System(; name) @@ -205,7 +205,7 @@ nothing #hide ![actsys2](https://github.com/SciML/ModelingToolkit.jl/assets/40798837/8ed50035-f6ac-48cb-a585-1ef415154a02) -After running `structural_simplify()` on `actsys2`, the defaults will show that `act.port_a.ρ` points to `fluid_a₊ρ` and `act.port_b.ρ` points to `fluid_b₊ρ`. This is a special case, in most cases a hydraulic system will have only 1 fluid, however this simple system has 2 separate domain networks. Therefore, we can connect a single fluid to both networks. This does not interfere with the mathematical equations of the system, since no states are connected. +After running `structural_simplify()` on `actsys2`, the defaults will show that `act.port_a.ρ` points to `fluid_a₊ρ` and `act.port_b.ρ` points to `fluid_b₊ρ`. This is a special case, in most cases a hydraulic system will have only 1 fluid, however this simple system has 2 separate domain networks. Therefore, we can connect a single fluid to both networks. This does not interfere with the mathematical equations of the system, since no unknown variables are connected. ```@example domain @component function ActuatorSystem1(; name) @@ -301,7 +301,7 @@ ModelingToolkit.defaults(sys)[complete(ressys).res.port_b.ρ] ModelingToolkit.defaults(sys)[complete(ressys).vol.port.ρ] ``` -To ensure that the `Restrictor` component does not disrupt the domain network, the [`domain_connect()`](@ref) function can be used, which explicitly only connects the domain network and not the states. +To ensure that the `Restrictor` component does not disrupt the domain network, the [`domain_connect()`](@ref) function can be used, which explicitly only connects the domain network and not the unknown variables. ```@example domain @component function Restrictor(; name, p_int) diff --git a/docs/src/tutorials/ode_modeling.md b/docs/src/tutorials/ode_modeling.md index c352959a07..9241eb230b 100644 --- a/docs/src/tutorials/ode_modeling.md +++ b/docs/src/tutorials/ode_modeling.md @@ -56,7 +56,7 @@ first-order lag element: \dot{x} = \frac{f(t) - x(t)}{\tau} ``` -Here, ``t`` is the independent variable (time), ``x(t)`` is the (scalar) state +Here, ``t`` is the independent variable (time), ``x(t)`` is the (scalar) unknown variable, ``f(t)`` is an external forcing function, and ``\tau`` is a parameter. In MTK, this system can be modelled as follows. For simplicity, we @@ -98,7 +98,7 @@ prob = ODEProblem(fol, [fol.x => 0.0], (0.0, 10.0), [fol.τ => 3.0]) plot(solve(prob)) ``` -The initial state and the parameter values are specified using a mapping +The initial unknown and the parameter values are specified using a mapping from the actual symbolic elements to their values, represented as an array of `Pair`s, which are constructed using the `=>` operator. @@ -150,7 +150,7 @@ For more information on this process, see [Observables and Variable Elimination] MTK still knows how to calculate them out of the information available in a simulation result. The intermediate variable `RHS` therefore can be plotted -along with the state variable. Note that this has to be requested explicitly +along with the unknown variable. Note that this has to be requested explicitly like as follows: ```@example ode2 @@ -307,11 +307,11 @@ connected_simp = structural_simplify(connected) full_equations(connected_simp) ``` -As expected, only the two state-derivative equations remain, +As expected, only the two equations with the derivatives of unknowns remain, as if you had manually eliminated as many variables as possible from the equations. Some observed variables are not expanded unless `full_equations` is used. As mentioned above, the hierarchical structure is preserved. So, the -initial state and the parameter values can be specified accordingly when +initial unknown and the parameter values can be specified accordingly when building the `ODEProblem`: ```@example ode2 @@ -329,7 +329,7 @@ More on this topic may be found in [Composing Models and Building Reusable Compo ## Initial Guess -It is often a good idea to specify reasonable values for the initial state and the +It is often a good idea to specify reasonable values for the initial unknown and the parameters of a model component. Then, these do not have to be explicitly specified when constructing the `ODEProblem`. ```@example ode2 @@ -369,7 +369,7 @@ end Note that the defaults can be functions of the other variables, which is then resolved at the time of the problem construction. Of course, the factory function could accept additional arguments to optionally specify the initial -state or parameter values, etc. +unknown or parameter values, etc. ## Symbolic and sparse derivatives diff --git a/docs/src/tutorials/parameter_identifiability.md b/docs/src/tutorials/parameter_identifiability.md index eb0837360b..19f43240f5 100644 --- a/docs/src/tutorials/parameter_identifiability.md +++ b/docs/src/tutorials/parameter_identifiability.md @@ -75,7 +75,7 @@ After that, we are ready to check the system for local identifiability: local_id_all = assess_local_identifiability(de, p = 0.99) ``` -We can see that all states (except $x_7$) and all parameters are locally identifiable with probability 0.99. +We can see that all unknowns (except $x_7$) and all parameters are locally identifiable with probability 0.99. Let's try to check specific parameters and their combinations @@ -84,7 +84,7 @@ to_check = [de.k5, de.k7, de.k10 / de.k9, de.k5 + de.k6] local_id_some = assess_local_identifiability(de, funcs_to_check = to_check, p = 0.99) ``` -Notice that in this case, everything (except the state variable $x_7$) is locally identifiable, including combinations such as $k_{10}/k_9, k_5+k_6$ +Notice that in this case, everything (except the unknown variable $x_7$) is locally identifiable, including combinations such as $k_{10}/k_9, k_5+k_6$ ## Global Identifiability diff --git a/src/discretedomain.jl b/src/discretedomain.jl index f9428b7eb4..575424ad91 100644 --- a/src/discretedomain.jl +++ b/src/discretedomain.jl @@ -177,7 +177,7 @@ function (xn::Num)(k::ShiftIndex) # Verify that the independent variables of k and x match and that the expression doesn't have multiple variables vars = Symbolics.get_variables(x) length(vars) == 1 || - error("Cannot shift a multivariate expression $x. Either create a new state and shift this, or shift the individual variables in the expression.") + error("Cannot shift a multivariate expression $x. Either create a new unknown and shift this, or shift the individual variables in the expression.") args = Symbolics.arguments(vars[]) # args should be one element vector with the t in x(t) length(args) == 1 || error("Cannot shift an expression with multiple independent variables $x.") diff --git a/src/inputoutput.jl b/src/inputoutput.jl index 45330aaea9..2b92dd706a 100644 --- a/src/inputoutput.jl +++ b/src/inputoutput.jl @@ -175,9 +175,9 @@ f_oop : (x,u,p,t) -> rhs f_ip : (xout,x,u,p,t) -> nothing ``` -The return values also include the remaining states and parameters, in the order they appear as arguments to `f`. +The return values also include the remaining unknowns and parameters, in the order they appear as arguments to `f`. -If `disturbance_inputs` is an array of variables, the generated dynamics function will preserve any state and dynamics associated with disturbance inputs, but the disturbance inputs themselves will not be included as inputs to the generated function. The use case for this is to generate dynamics for state observers that estimate the influence of unmeasured disturbances, and thus require state variables for the disturbance model, but without disturbance inputs since the disturbances are not available for measurement. +If `disturbance_inputs` is an array of variables, the generated dynamics function will preserve any state and dynamics associated with disturbance inputs, but the disturbance inputs themselves will not be included as inputs to the generated function. The use case for this is to generate dynamics for state observers that estimate the influence of unmeasured disturbances, and thus require unknown variables for the disturbance model, but without disturbance inputs since the disturbances are not available for measurement. See [`add_input_disturbance`](@ref) for a higher-level interface to this functionality. # Example diff --git a/src/parameters.jl b/src/parameters.jl index 19c225b877..dfaca86d95 100644 --- a/src/parameters.jl +++ b/src/parameters.jl @@ -45,7 +45,7 @@ toparam(s::Num) = wrap(toparam(value(s))) """ tovar(s) -Maps the variable to a state. +Maps the variable to an unknown. """ tovar(s::Symbolic) = setmetadata(s, MTKVariableTypeCtx, VARIABLE) tovar(s::Num) = Num(tovar(value(s))) diff --git a/src/structural_transformation/codegen.jl b/src/structural_transformation/codegen.jl index 3f11ed049f..a007e824f1 100644 --- a/src/structural_transformation/codegen.jl +++ b/src/structural_transformation/codegen.jl @@ -27,7 +27,7 @@ function torn_system_with_nlsolve_jacobian_sparsity(state, var_eq_matching, var_ # 0 # ``` # - # Let 𝑇 be the set of tearing variables and 𝑉 be the set of all *states* in + # Let 𝑇 be the set of tearing variables and 𝑉 be the set of all *unknowns* in # the residual equations. In the following code, we are going to assume the # connection between 𝑇 (the `u` in from above) and 𝑉 ∖ 𝑇 (the `p` in from # above) has full incidence. @@ -37,7 +37,7 @@ function torn_system_with_nlsolve_jacobian_sparsity(state, var_eq_matching, var_ # from other partitions. # # We know that partitions are BLT ordered. Hence, the tearing variables in - # each partition is unique, and all states in a partition must be + # each partition is unique, and all unknowns in a partition must be # either differential variables or algebraic tearing variables that are # from previous partitions. Hence, we can build the dependency chain as we # traverse the partitions. @@ -250,8 +250,8 @@ function build_torn_function(sys; toporder = topological_sort_by_dfs(condensed_graph) var_sccs = var_sccs[toporder] - states_idxs = collect(diffvars_range(state.structure)) - mass_matrix_diag = ones(length(states_idxs)) + unknowns_idxs = collect(diffvars_range(state.structure)) + mass_matrix_diag = ones(length(unknowns_idxs)) assignments, deps, sol_states = tearing_assignments(sys) invdeps = map(_ -> BitSet(), deps) @@ -284,11 +284,11 @@ function build_torn_function(sys; needs_extending = true append!(eqs_idxs, torn_eqs_idxs) append!(rhss, map(x -> x.rhs, eqs[torn_eqs_idxs])) - append!(states_idxs, torn_vars_idxs) + append!(unknowns_idxs, torn_vars_idxs) append!(mass_matrix_diag, zeros(length(torn_eqs_idxs))) end end - sort!(states_idxs) + sort!(unknowns_idxs) mass_matrix = needs_extending ? Diagonal(mass_matrix_diag) : I @@ -297,16 +297,16 @@ function build_torn_function(sys; out, rhss) - states = Any[fullvars[i] for i in states_idxs] - @set! sys.solved_unknowns = states - syms = map(Symbol, states) + unknown_vars = Any[fullvars[i] for i in unknowns_idxs] + @set! sys.solved_unknowns = unknown_vars + syms = map(Symbol, unknown_vars) pre = get_postprocess_fbody(sys) cpre = get_preprocess_constants(rhss) pre2 = x -> pre(cpre(x)) expr = SymbolicUtils.Code.toexpr(Func([out - DestructuredArgs(states, + DestructuredArgs(unknown_vars, inbounds = !checkbounds) DestructuredArgs(parameters(sys), inbounds = !checkbounds) @@ -318,11 +318,11 @@ function build_torn_function(sys; false))), sol_states) if expression - expr, states + expr, unknown_vars else observedfun = let state = state, dict = Dict(), - is_solver_state_idxs = insorted.(1:length(fullvars), (states_idxs,)), + is_solver_unknown_idxs = insorted.(1:length(fullvars), (unknowns_idxs,)), assignments = assignments, deps = (deps, invdeps), sol_states = sol_states, @@ -331,7 +331,7 @@ function build_torn_function(sys; function generated_observed(obsvar, args...) obs = get!(dict, value(obsvar)) do build_observed_function(state, obsvar, var_eq_matching, var_sccs, - is_solver_state_idxs, assignments, deps, + is_solver_unknown_idxs, assignments, deps, sol_states, var2assignment, checkbounds = checkbounds) end @@ -352,7 +352,7 @@ function build_torn_function(sys; var_sccs, nlsolve_scc_idxs, eqs_idxs, - states_idxs) : + unknowns_idxs) : nothing, syms = syms, paramsyms = Symbol.(parameters(sys)), @@ -360,7 +360,7 @@ function build_torn_function(sys; observed = observedfun, mass_matrix = mass_matrix, sys = sys), - states + unknown_vars end end @@ -382,7 +382,7 @@ function find_solve_sequence(sccs, vars) end function build_observed_function(state, ts, var_eq_matching, var_sccs, - is_solver_state_idxs, + is_solver_unknown_idxs, assignments, deps, sol_states, @@ -404,8 +404,8 @@ function build_observed_function(state, ts, var_eq_matching, var_sccs, fullvars = state.fullvars s = state.structure - unknown_states = fullvars[is_solver_state_idxs] - algvars = fullvars[.!is_solver_state_idxs] + unknown_vars = fullvars[is_solver_unknown_idxs] + algvars = fullvars[.!is_solver_unknown_idxs] required_algvars = Set(intersect(algvars, vars)) obs = observed(sys) @@ -437,7 +437,7 @@ function build_observed_function(state, ts, var_eq_matching, var_sccs, subs[s] = s′ continue end - throw(ArgumentError("$s is either an observed nor a state variable.")) + throw(ArgumentError("$s is either an observed nor an unknown variable.")) end continue end @@ -491,7 +491,7 @@ function build_observed_function(state, ts, var_eq_matching, var_sccs, cpre = get_preprocess_constants([obs[1:maxidx]; isscalar ? ts[1] : MakeArray(ts, output_type)]) pre2 = x -> pre(cpre(x)) - ex = Code.toexpr(Func([DestructuredArgs(unknown_states, inbounds = !checkbounds) + ex = Code.toexpr(Func([DestructuredArgs(unknown_vars, inbounds = !checkbounds) DestructuredArgs(parameters(sys), inbounds = !checkbounds) independent_variables(sys)], [], diff --git a/src/structural_transformation/pantelides.jl b/src/structural_transformation/pantelides.jl index a2693671ce..3fd80db5e7 100644 --- a/src/structural_transformation/pantelides.jl +++ b/src/structural_transformation/pantelides.jl @@ -21,7 +21,7 @@ function pantelides_reassemble(state::TearingState, var_eq_matching) for (varidx, diff) in edges(var_to_diff) # fullvars[diff] = D(fullvars[var]) vi = out_vars[varidx] - @assert vi!==nothing "Something went wrong on reconstructing states from variable association list" + @assert vi!==nothing "Something went wrong on reconstructing unknowns from variable association list" # `fullvars[i]` needs to be not a `D(...)`, because we want the DAE to be # first-order. if isdifferential(vi) diff --git a/src/structural_transformation/partial_state_selection.jl b/src/structural_transformation/partial_state_selection.jl index 8ba4892fd9..44edf71c08 100644 --- a/src/structural_transformation/partial_state_selection.jl +++ b/src/structural_transformation/partial_state_selection.jl @@ -334,8 +334,8 @@ end function tearing_with_dummy_derivatives(structure, dummy_derivatives) @unpack var_to_diff = structure - # We can eliminate variables that are not a selected state (differential - # variables). Selected states are differentiated variables that are not + # We can eliminate variables that are not selected (differential + # variables). Selected unknowns are differentiated variables that are not # dummy derivatives. can_eliminate = falses(length(var_to_diff)) for (v, dv) in enumerate(var_to_diff) diff --git a/src/structural_transformation/symbolics_tearing.jl b/src/structural_transformation/symbolics_tearing.jl index 4c7bcb68ab..5864161a6e 100644 --- a/src/structural_transformation/symbolics_tearing.jl +++ b/src/structural_transformation/symbolics_tearing.jl @@ -170,7 +170,7 @@ function to_mass_matrix_form(neweqs, ieq, graph, fullvars, isdervar::F, end rhs = eq.rhs if rhs isa Symbolic - # Check if the RHS is solvable in all state derivatives and if those + # Check if the RHS is solvable in all unknown variable derivatives and if those # the linear terms for them are all zero. If so, move them to the # LHS. dervar::Union{Nothing, Int} = nothing @@ -238,7 +238,7 @@ function tearing_reassemble(state::TearingState, var_eq_matching; # called dummy derivatives. # Step 1: - # Replace derivatives of non-selected states by dummy derivatives + # Replace derivatives of non-selected unknown variables by dummy derivatives if ModelingToolkit.has_iv(state.sys) iv = get_iv(state.sys) @@ -410,7 +410,7 @@ function tearing_reassemble(state::TearingState, var_eq_matching; eq_var_matching[dummy_eq] = dv end - # Will reorder equations and states to be: + # Will reorder equations and unknowns to be: # [diffeqs; ...] # [diffvars; ...] # such that the mass matrix is: diff --git a/src/structural_transformation/utils.jl b/src/structural_transformation/utils.jl index ff9ef2f82a..e6ede7f376 100644 --- a/src/structural_transformation/utils.jl +++ b/src/structural_transformation/utils.jl @@ -263,12 +263,12 @@ function linear_subsys_adjmat!(state::TransformationState; kwargs...) for i in eachindex(eqs) all_int_vars, rhs = find_eq_solvables!(state, i, to_rm, coeffs; kwargs...) - # Check if all states in the equation is both linear and homogeneous, + # Check if all unknowns in the equation is both linear and homogeneous, # i.e. it is in the form of # # ``∑ c_i * v_i = 0``, # - # where ``c_i`` ∈ ℤ and ``v_i`` denotes states. + # where ``c_i`` ∈ ℤ and ``v_i`` denotes unknowns. if all_int_vars && Symbolics._iszero(rhs) push!(linear_equations, i) push!(eadj, copy(𝑠neighbors(graph, i))) diff --git a/src/systems/abstractsystem.jl b/src/systems/abstractsystem.jl index 82f7226b02..b5496a1ef4 100644 --- a/src/systems/abstractsystem.jl +++ b/src/systems/abstractsystem.jl @@ -223,7 +223,7 @@ end SymbolicIndexingInterface.variable_symbols(sys::AbstractMultivariateSystem) = sys.dvs function SymbolicIndexingInterface.variable_symbols(sys::AbstractSystem) - return unknown_states(sys) + return solved_unknowns(sys) end function SymbolicIndexingInterface.is_parameter(sys::AbstractSystem, sym) @@ -487,7 +487,7 @@ function getvar(sys::AbstractSystem, name::Symbol; namespace = !iscomplete(sys)) end function Base.setproperty!(sys::AbstractSystem, prop::Symbol, val) - # We use this weird syntax because `parameters` and `states` calls are + # We use this weird syntax because `parameters` and `unknowns` calls are # potentially expensive. if (params = parameters(sys); idx = findfirst(s -> getname(s) == prop, params); @@ -652,21 +652,21 @@ _nonum(@nospecialize x) = x isa Num ? x.val : x function unknowns(sys::AbstractSystem) sts = get_unknowns(sys) systems = get_systems(sys) - nonunique_states = if isempty(systems) + nonunique_unknowns = if isempty(systems) sts else - system_states = reduce(vcat, namespace_variables.(systems)) - isempty(sts) ? system_states : [sts; system_states] + system_unknowns = reduce(vcat, namespace_variables.(systems)) + isempty(sts) ? system_unknowns : [sts; system_unknowns] end - isempty(nonunique_states) && return nonunique_states + isempty(nonunique_unknowns) && return nonunique_unknowns # `Vector{Any}` is incompatible with the `SymbolicIndexingInterface`, which uses # `elsymtype = symbolic_type(eltype(_arg))` # which inappropriately returns `NotSymbolic()` - if nonunique_states isa Vector{Any} - nonunique_states = _nonum.(nonunique_states) + if nonunique_unknowns isa Vector{Any} + nonunique_unknowns = _nonum.(nonunique_unknowns) end - @assert typeof(nonunique_states) !== Vector{Any} - unique(nonunique_states) + @assert typeof(nonunique_unknowns) !== Vector{Any} + unique(nonunique_unknowns) end function parameters(sys::AbstractSystem) @@ -769,7 +769,7 @@ function isaffine(sys::AbstractSystem) end function time_varying_as_func(x, sys::AbstractTimeDependentSystem) - # if something is not x(t) (the current state) + # if something is not x(t) (the current unknown) # but is `x(t-1)` or something like that, pass in `x` as a callable function rather # than pass in a value in place of x(t). # @@ -785,9 +785,9 @@ end """ $(SIGNATURES) -Return a list of actual states needed to be solved by solvers. +Return a list of actual unknowns needed to be solved by solvers. """ -function unknown_states(sys::AbstractSystem) +function solved_unknowns(sys::AbstractSystem) sts = unknowns(sys) if has_solved_unknowns(sys) sts = something(get_solved_unknowns(sys), sts) @@ -991,7 +991,7 @@ function Base.show(io::IO, mime::MIME"text/plain", sys::AbstractSystem) rows = first(displaysize(io)) ÷ 5 limit = get(io, :limit, false) - Base.printstyled(io, "States ($nvars):"; bold = true) + Base.printstyled(io, "Unknowns ($nvars):"; bold = true) nrows = min(nvars, limit ? rows : nvars) limited = nrows < length(vars) defs = has_defaults(sys) ? defaults(sys) : nothing @@ -1264,7 +1264,7 @@ $(SIGNATURES) Rewrite `@nonamespace a.b.c` to `getvar(getvar(a, :b; namespace = false), :c; namespace = false)`. -This is the default behavior of `getvar`. This should be used when inheriting states from a model. +This is the default behavior of `getvar`. This should be used when inheriting unknowns from a model. """ macro nonamespace(expr) esc(_config(expr, false)) @@ -1397,9 +1397,9 @@ y &= h(x, z, u) \\end{aligned} ``` -where `x` are differential state variables, `z` algebraic variables, `u` inputs and `y` outputs. To obtain a linear statespace representation, see [`linearize`](@ref). The input argument `variables` is a vector defining the operating point, corresponding to `unknowns(simplified_sys)` and `p` is a vector corresponding to the parameters of `simplified_sys`. Note: all variables in `inputs` have been converted to parameters in `simplified_sys`. +where `x` are differential unknown variables, `z` algebraic variables, `u` inputs and `y` outputs. To obtain a linear statespace representation, see [`linearize`](@ref). The input argument `variables` is a vector defining the operating point, corresponding to `unknowns(simplified_sys)` and `p` is a vector corresponding to the parameters of `simplified_sys`. Note: all variables in `inputs` have been converted to parameters in `simplified_sys`. -The `simplified_sys` has undergone [`structural_simplify`](@ref) and had any occurring input or output variables replaced with the variables provided in arguments `inputs` and `outputs`. The states of this system also indicate the order of the states that holds for the linearized matrices. +The `simplified_sys` has undergone [`structural_simplify`](@ref) and had any occurring input or output variables replaced with the variables provided in arguments `inputs` and `outputs`. The unknowns of this system also indicate the order of the unknowns that holds for the linearized matrices. # Arguments: @@ -1449,9 +1449,9 @@ function linearization_function(sys::AbstractSystem, inputs, chunk = ForwardDiff.Chunk(input_idxs) function (u, p, t) - if u !== nothing # Handle systems without states + if u !== nothing # Handle systems without unknowns length(sts) == length(u) || - error("Number of state variables ($(length(sts))) does not match the number of input states ($(length(u)))") + error("Number of unknown variables ($(length(sts))) does not match the number of input unknowns ($(length(u)))") if initialize && !isempty(alge_idxs) # This is expensive and can be omitted if the user knows that the system is already initialized residual = fun(u, p, t) if norm(residual[alge_idxs]) > √(eps(eltype(residual))) @@ -1469,7 +1469,7 @@ function linearization_function(sys::AbstractSystem, inputs, fg_u = jacobian_wrt_vars(pf, p, input_idxs, chunk) else length(sts) == 0 || - error("Number of state variables (0) does not match the number of input states ($(length(u)))") + error("Number of unknown variables (0) does not match the number of input unknowns ($(length(u)))") fg_xz = zeros(0, 0) h_xz = fg_u = zeros(0, length(inputs)) end @@ -1507,7 +1507,7 @@ ẋ &= f(x, z, u) \\\\ y &= h(x, z, u) \\end{aligned} ``` -where `x` are differential state variables, `z` algebraic variables, `u` inputs and `y` outputs. +where `x` are differential unknown variables, `z` algebraic variables, `u` inputs and `y` outputs. """ function linearize_symbolic(sys::AbstractSystem, inputs, outputs; simplify = false, allow_input_derivatives = false, @@ -1636,7 +1636,7 @@ If `allow_input_derivatives = false`, an error will be thrown if input derivativ `zero_dummy_der` can be set to automatically set the operating point to zero for all dummy derivatives. -See also [`linearization_function`](@ref) which provides a lower-level interface, [`linearize_symbolic`](@ref) and [`ModelingToolkit.reorder_states`](@ref). +See also [`linearization_function`](@ref) which provides a lower-level interface, [`linearize_symbolic`](@ref) and [`ModelingToolkit.reorder_unknowns`](@ref). See extended help for an example. @@ -1700,7 +1700,7 @@ connections = [f.y ~ c.r # filtered reference to controller reference lsys0, ssys = linearize(cl, [f.u], [p.x]) desired_order = [f.x, p.x] -lsys = ModelingToolkit.reorder_states(lsys0, unknowns(ssys), desired_order) +lsys = ModelingToolkit.reorder_unknowns(lsys0, unknowns(ssys), desired_order) @assert lsys.A == [-2 0; 1 -2] @assert lsys.B == [1; 0;;] @@ -1801,20 +1801,20 @@ function similarity_transform(sys::NamedTuple, T; unitary = false) end """ - reorder_states(sys::NamedTuple, old, new) + reorder_unknowns(sys::NamedTuple, old, new) -Permute the state representation of `sys` obtained from [`linearize`](@ref) so that the state order is changed from `old` to `new` +Permute the state representation of `sys` obtained from [`linearize`](@ref) so that the state unknown is changed from `old` to `new` Example: ``` lsys, ssys = linearize(pid, [reference.u, measurement.u], [ctr_output.u]) -desired_order = [int.x, der.x] # States that are present in unknowns(ssys) -lsys = ModelingToolkit.reorder_states(lsys, unknowns(ssys), desired_order) +desired_order = [int.x, der.x] # Unknowns that are present in unknowns(ssys) +lsys = ModelingToolkit.reorder_unknowns(lsys, unknowns(ssys), desired_order) ``` See also [`ModelingToolkit.similarity_transform`](@ref) """ -function reorder_states(sys::NamedTuple, old, new) +function reorder_unknowns(sys::NamedTuple, old, new) nx = length(old) length(new) == nx || error("old and new must have the same length") perm = [findfirst(isequal(n), old) for n in new] @@ -1872,13 +1872,13 @@ function check_eqs_u0(eqs, dvs, u0; check_length = true, kwargs...) if u0 !== nothing if check_length if !(length(eqs) == length(dvs) == length(u0)) - throw(ArgumentError("Equations ($(length(eqs))), states ($(length(dvs))), and initial conditions ($(length(u0))) are of different lengths. To allow a different number of equations than states use kwarg check_length=false.")) + throw(ArgumentError("Equations ($(length(eqs))), unknowns ($(length(dvs))), and initial conditions ($(length(u0))) are of different lengths. To allow a different number of equations than unknowns use kwarg check_length=false.")) end elseif length(dvs) != length(u0) - throw(ArgumentError("States ($(length(dvs))) and initial conditions ($(length(u0))) are of different lengths.")) + throw(ArgumentError("Unknowns ($(length(dvs))) and initial conditions ($(length(u0))) are of different lengths.")) end elseif check_length && (length(eqs) != length(dvs)) - throw(ArgumentError("Equations ($(length(eqs))) and states ($(length(dvs))) are of different lengths. To allow these to differ use kwarg check_length=false.")) + throw(ArgumentError("Equations ($(length(eqs))) and Unknowns ($(length(dvs))) are of different lengths. To allow these to differ use kwarg check_length=false.")) end return nothing end diff --git a/src/systems/alias_elimination.jl b/src/systems/alias_elimination.jl index efb79aae50..68c49a604d 100644 --- a/src/systems/alias_elimination.jl +++ b/src/systems/alias_elimination.jl @@ -113,7 +113,6 @@ function alias_elimination!(state::TearingState; kwargs...) eqs[ieq] = expand_derivatives(eqs[ieq]) end - newstates = [] diff_to_var = invview(var_to_diff) new_graph = BipartiteGraph(n_new_eqs, ndsts(graph)) new_solvable_graph = BipartiteGraph(n_new_eqs, ndsts(graph)) @@ -405,8 +404,8 @@ julia> ModelingToolkit.topsort_equations(eqs, [x, y, z, k]) Equation(x(t), y(t) + z(t)) ``` """ -function topsort_equations(eqs, states; check = true) - graph, assigns = observed2graph(eqs, states) +function topsort_equations(eqs, unknowns; check = true) + graph, assigns = observed2graph(eqs, unknowns) neqs = length(eqs) degrees = zeros(Int, neqs) @@ -442,9 +441,9 @@ function topsort_equations(eqs, states; check = true) return ordered_eqs end -function observed2graph(eqs, states) - graph = BipartiteGraph(length(eqs), length(states)) - v2j = Dict(states .=> 1:length(states)) +function observed2graph(eqs, unknowns) + graph = BipartiteGraph(length(eqs), length(unknowns)) + v2j = Dict(unknowns .=> 1:length(unknowns)) # `assigns: eq -> var`, `eq` defines `var` assigns = similar(eqs, Int) @@ -452,7 +451,7 @@ function observed2graph(eqs, states) for (i, eq) in enumerate(eqs) lhs_j = get(v2j, eq.lhs, nothing) lhs_j === nothing && - throw(ArgumentError("The lhs $(eq.lhs) of $eq, doesn't appear in states.")) + throw(ArgumentError("The lhs $(eq.lhs) of $eq, doesn't appear in unknowns.")) assigns[i] = lhs_j vs = vars(eq.rhs) for v in vs diff --git a/src/systems/callbacks.jl b/src/systems/callbacks.jl index 9a93606d20..9193e3a7d9 100644 --- a/src/systems/callbacks.jl +++ b/src/systems/callbacks.jl @@ -318,18 +318,18 @@ function compile_affect(eqs::Vector{Equation}, sys, dvs, ps; outputidxs = nothin error("Non-variable symbolic expression found on the left hand side of an affect equation. Such equations must be of the form variable ~ symbolic expression for the new value of the variable.") update_vars = collect(Iterators.flatten(map(ModelingToolkit.vars, lhss))) # these are the ones we're changing length(update_vars) == length(unique(update_vars)) == length(eqs) || - error("affected variables not unique, each state can only be affected by one equation for a single `root_eqs => affects` pair.") + error("affected variables not unique, each unknown can only be affected by one equation for a single `root_eqs => affects` pair.") alleq = all(isequal(isparameter(first(update_vars))), Iterators.map(isparameter, update_vars)) if !isparameter(first(lhss)) && alleq - stateind = Dict(reverse(en) for en in enumerate(dvs)) - update_inds = map(sym -> stateind[sym], update_vars) + unknownind = Dict(reverse(en) for en in enumerate(dvs)) + update_inds = map(sym -> unknownind[sym], update_vars) elseif isparameter(first(lhss)) && alleq psind = Dict(reverse(en) for en in enumerate(ps)) update_inds = map(sym -> psind[sym], update_vars) outvar = :p else - error("Error, building an affect function for a callback that wants to modify both parameters and states. This is not currently allowed in one individual callback.") + error("Error, building an affect function for a callback that wants to modify both parameters and unknowns. This is not currently allowed in one individual callback.") end else update_inds = outputidxs diff --git a/src/systems/clock_inference.jl b/src/systems/clock_inference.jl index 167304f0b0..5b54b9c28f 100644 --- a/src/systems/clock_inference.jl +++ b/src/systems/clock_inference.jl @@ -223,7 +223,7 @@ function generate_discrete_affect(syss, inputs, continuous_id, id_to_clock; c2d_view = view(p, $cont_to_disc_idxs) # Like Hold d2c_view = view(p, $disc_to_cont_idxs) - disc_state = view(p, $disc_range) + disc_unknowns = view(p, $disc_range) disc = $disc push!(saved_values.t, t) @@ -231,7 +231,7 @@ function generate_discrete_affect(syss, inputs, continuous_id, id_to_clock; # Write continuous into to discrete: handles `Sample` # Write discrete into to continuous - # Update discrete states + # Update discrete unknowns # At a tick, c2d must come first # state update comes in the middle @@ -240,9 +240,9 @@ function generate_discrete_affect(syss, inputs, continuous_id, id_to_clock; # @show "incoming", p copyto!(c2d_view, c2d_obs(integrator.u, p, t)) # @show "after c2d", p - $empty_disc || disc(disc_state, disc_state, p, t) + $empty_disc || disc(disc_unknowns, disc_unknowns, p, t) # @show "after state update", p - copyto!(d2c_view, d2c_obs(disc_state, p, t)) + copyto!(d2c_view, d2c_obs(disc_unknowns, p, t)) # @show "after d2c", p end) sv = SavedValues(Float64, Vector{Float64}) diff --git a/src/systems/connectors.jl b/src/systems/connectors.jl index 81cd516cba..0391484ee9 100644 --- a/src/systems/connectors.jl +++ b/src/systems/connectors.jl @@ -27,11 +27,11 @@ struct RegularConnector <: AbstractConnectorType end struct DomainConnector <: AbstractConnectorType end function connector_type(sys::AbstractSystem) - sts = get_unknowns(sys) + unkvars = get_unknowns(sys) n_stream = 0 n_flow = 0 - n_regular = 0 # state that is not input, output, stream, or flow. - for s in sts + n_regular = 0 # unknown that is not input, output, stream, or flow. + for s in unkvars vtype = get_connection_type(s) if vtype === Stream isarray(s) && error("Array stream variables are not supported. Got $s.") @@ -44,7 +44,7 @@ function connector_type(sys::AbstractSystem) end (n_stream > 0 && n_flow > 1) && error("There are multiple flow variables in the stream connector $(nameof(sys))!") - if n_flow == 1 && length(sts) == 1 + if n_flow == 1 && length(unkvars) == 1 return DomainConnector() end if n_flow != n_regular && !isframe(sys) @@ -261,19 +261,19 @@ function connection2set!(connectionsets, namespace, ss, isouter) sts1v = [sts1v; orientation_vars] end sts1 = Set(sts1v) - num_statevars = length(sts1) - csets = [T[] for _ in 1:num_statevars] # Add 9 orientation variables if connection is between multibody frames + num_unknowns = length(sts1) + csets = [T[] for _ in 1:num_unknowns] # Add 9 orientation variables if connection is between multibody frames for (i, s) in enumerate(ss) - sts = unknowns(s) + unknown_vars = unknowns(s) if isframe(s) # Multibody O = ori(s) orientation_vars = Symbolics.unwrap.(vec(O.R)) - sts = [sts; orientation_vars] + unknown_vars = [unknown_vars; orientation_vars] end - i != 1 && ((num_statevars == length(sts) && all(Base.Fix2(in, sts1), sts)) || + i != 1 && ((num_unknowns == length(unknown_vars) && all(Base.Fix2(in, sts1), unknown_vars)) || connection_error(ss)) io = isouter(s) - for (j, v) in enumerate(sts) + for (j, v) in enumerate(unknown_vars) push!(csets[j], T(LazyNamespace(namespace, s), v, io)) end end @@ -311,16 +311,16 @@ function generate_connection_set!(connectionsets, domain_csets, cts = [] # connections domain_cts = [] # connections - extra_states = [] + extra_unknowns = [] for eq in eqs′ lhs = eq.lhs rhs = eq.rhs if find !== nothing && find(rhs, _getname(namespace)) - neweq, extra_state = replace(rhs, _getname(namespace)) - if extra_state isa AbstractArray - append!(extra_states, unwrap.(extra_state)) - elseif extra_state !== nothing - push!(extra_states, extra_state) + neweq, extra_unknown = replace(rhs, _getname(namespace)) + if extra_unknown isa AbstractArray + append!(extra_unknowns, unwrap.(extra_unknown)) + elseif extra_unknown !== nothing + push!(extra_unknowns, extra_unknown) end neweq isa AbstractArray ? append!(eqs, neweq) : push!(eqs, neweq) else @@ -350,8 +350,8 @@ function generate_connection_set!(connectionsets, domain_csets, end # pre order traversal - if !isempty(extra_states) - @set! sys.unknowns = [get_unknowns(sys); extra_states] + if !isempty(extra_unknowns) + @set! sys.unknowns = [get_unknowns(sys); extra_unknowns] end @set! sys.systems = map(s -> generate_connection_set!(connectionsets, domain_csets, s, find, replace, diff --git a/src/systems/dependency_graphs.jl b/src/systems/dependency_graphs.jl index cb88021e95..08755a57cb 100644 --- a/src/systems/dependency_graphs.jl +++ b/src/systems/dependency_graphs.jl @@ -28,7 +28,7 @@ j₂ = ModelingToolkit.VariableRateJump(rate₂, affect₂) # create a JumpSystem using these jumps @named jumpsys = JumpSystem([j₁, j₂], t, [S, I, R], [β, γ]) -# dependency of each jump rate function on state variables +# dependency of each jump rate function on unknown variables equation_dependencies(jumpsys) # dependency of each jump rate function on parameters @@ -148,7 +148,7 @@ function variable_dependencies(sys::AbstractSystem; variables = unknowns(sys), deps = Set() badjlist = Vector{Vector{Int}}(undef, length(eqs)) for (eidx, eq) in enumerate(eqs) - modified_states!(deps, eq, variables) + modified_unknowns!(deps, eq, variables) badjlist[eidx] = sort!([vtois[var] for var in deps]) empty!(deps) end @@ -174,11 +174,11 @@ Convert a [`BipartiteGraph`](@ref) to a `LightGraph.SimpleDiGraph`. Notes: - The resulting `SimpleDiGraph` unifies the two sets of vertices (equations - and then states in the case it comes from [`asgraph`](@ref)), producing one + and then unknowns in the case it comes from [`asgraph`](@ref)), producing one ordered set of integer vertices (`SimpleDiGraph` does not support two distinct collections of vertices, so they must be merged). - `variables` gives the variables that `g` are associated with (usually the - `states` of a system). + `unknowns` of a system). - `equationsfirst` (default is `true`) gives whether the [`BipartiteGraph`](@ref) gives a mapping from equations to variables they depend on (`true`), as calculated by [`asgraph`](@ref), or whether it gives a mapping from variables to the equations @@ -238,7 +238,7 @@ function eqeq_dependencies(eqdeps::BipartiteGraph{T}, g = SimpleDiGraph{T}(length(eqdeps.fadjlist)) for (eqidx, sidxs) in enumerate(vardeps.badjlist) - # states modified by eqidx + # unknowns modified by eqidx for sidx in sidxs # equations depending on sidx foreach(v -> add_edge!(g, eqidx, v), eqdeps.badjlist[sidx]) diff --git a/src/systems/diffeqs/abstractodesystem.jl b/src/systems/diffeqs/abstractodesystem.jl index 5e2121dd59..d6cd0ce909 100644 --- a/src/systems/diffeqs/abstractodesystem.jl +++ b/src/systems/diffeqs/abstractodesystem.jl @@ -17,7 +17,7 @@ function calculate_tgrad(sys::AbstractODESystem; simplify = false) isempty(get_tgrad(sys)[]) || return get_tgrad(sys)[] # use cached tgrad, if possible - # We need to remove explicit time dependence on the state because when we + # We need to remove explicit time dependence on the unknown because when we # have `u(t) * t` we want to have the tgrad to be `u(t)` instead of `u'(t) * # t + u(t)`. rhs = [detime_dvs(eq.rhs) for eq in full_equations(sys)] @@ -167,7 +167,7 @@ function generate_function(sys::AbstractODESystem, dvs = unknowns(sys), ps = par if isdde build_function(rhss, u, DDE_HISTORY_FUN, p, t; kwargs...) else - pre, sol_states = get_substitutions_and_solved_states(sys, + pre, sol_states = get_substitutions_and_solved_unknowns(sys, no_postprocess = has_difference) if implicit_dae @@ -276,11 +276,11 @@ function calculate_massmatrix(sys::AbstractODESystem; simplify = false) eqs = [eq for eq in equations(sys) if !isdifferenceeq(eq)] dvs = unknowns(sys) M = zeros(length(eqs), length(eqs)) - state2idx = Dict(s => i for (i, s) in enumerate(dvs)) + unknown2idx = Dict(s => i for (i, s) in enumerate(dvs)) for (i, eq) in enumerate(eqs) if istree(eq.lhs) && operation(eq.lhs) isa Differential st = var_from_nested_derivative(eq.lhs)[1] - j = state2idx[st] + j = unknown2idx[st] M[i, j] = 1 else _iszero(eq.lhs) || diff --git a/src/systems/diffeqs/first_order_transform.jl b/src/systems/diffeqs/first_order_transform.jl index 517cdb8786..b1a51f3346 100644 --- a/src/systems/diffeqs/first_order_transform.jl +++ b/src/systems/diffeqs/first_order_transform.jl @@ -20,7 +20,7 @@ function dae_order_lowering(sys::ODESystem) return sys end -function ode_order_lowering(eqs, iv, states) +function ode_order_lowering(eqs, iv, unknown_vars) var_order = OrderedDict{Any, Int}() D = Differential(iv) diff_eqs = Equation[] @@ -53,10 +53,10 @@ function ode_order_lowering(eqs, iv, states) end # we want to order the equations and variables to be `(diff, alge)` - return (vcat(diff_eqs, alge_eqs), vcat(diff_vars, setdiff(states, diff_vars))) + return (vcat(diff_eqs, alge_eqs), vcat(diff_vars, setdiff(unknown_vars, diff_vars))) end -function dae_order_lowering(eqs, iv, states) +function dae_order_lowering(eqs, iv, unknown_vars) var_order = OrderedDict{Any, Int}() D = Differential(iv) diff_eqs = Equation[] @@ -102,5 +102,5 @@ function dae_order_lowering(eqs, iv, states) end return ([diff_eqs; substitute.(eqs, (subs,))], - vcat(collect(diff_vars), setdiff(states, diff_vars))) + vcat(collect(diff_vars), setdiff(unknown_vars, diff_vars))) end diff --git a/src/systems/diffeqs/odesystem.jl b/src/systems/diffeqs/odesystem.jl index 93d02b6074..fb9184871b 100644 --- a/src/systems/diffeqs/odesystem.jl +++ b/src/systems/diffeqs/odesystem.jl @@ -33,10 +33,10 @@ struct ODESystem <: AbstractODESystem """Independent variable.""" iv::BasicSymbolic{Real} """ - Dependent (state) variables. Must not contain the independent variable. + Dependent (unknown) variables. Must not contain the independent variable. N.B.: If `torn_matching !== nothing`, this includes all variables. Actual - ODE states are determined by the `SelectedState()` entries in `torn_matching`. + ODE unknowns are determined by the `SelectedState()` entries in `torn_matching`. """ unknowns::Vector """Parameter variables. Must not contain the independent variable.""" @@ -135,7 +135,7 @@ struct ODESystem <: AbstractODESystem """ discrete_subsystems::Any """ - A list of actual states needed to be solved by solvers. Only + A list of actual unknowns needed to be solved by solvers. Only used for ODAEProblem. """ solved_unknowns::Union{Nothing, Vector{Any}} @@ -235,7 +235,7 @@ function ODESystem(eqs, iv = nothing; kwargs...) eqs = scalarize(eqs) # NOTE: this assumes that the order of algebraic equations doesn't matter diffvars = OrderedSet() - allstates = OrderedSet() + allunknowns = OrderedSet() ps = OrderedSet() # reorder equations such that it is in the form of `diffeq, algeeq` diffeq = Equation[] @@ -254,8 +254,8 @@ function ODESystem(eqs, iv = nothing; kwargs...) compressed_eqs = Equation[] # equations that need to be expanded later, like `connect(a, b)` for eq in eqs eq.lhs isa Union{Symbolic, Number} || (push!(compressed_eqs, eq); continue) - collect_vars!(allstates, ps, eq.lhs, iv) - collect_vars!(allstates, ps, eq.rhs, iv) + collect_vars!(allunknowns, ps, eq.lhs, iv) + collect_vars!(allunknowns, ps, eq.rhs, iv) if isdiffeq(eq) diffvar, _ = var_from_nested_derivative(eq.lhs) isequal(iv, iv_from_nested_derivative(eq.lhs)) || @@ -268,11 +268,11 @@ function ODESystem(eqs, iv = nothing; kwargs...) push!(algeeq, eq) end end - for v in allstates + for v in allunknowns isdelay(v, iv) || continue - collect_vars!(allstates, ps, arguments(v)[1], iv) + collect_vars!(allunknowns, ps, arguments(v)[1], iv) end - algevars = setdiff(allstates, diffvars) + algevars = setdiff(allunknowns, diffvars) # the orders here are very important! return ODESystem(Equation[diffeq; algeeq; compressed_eqs], iv, collect(Iterators.flatten((diffvars, algevars))), ps; kwargs...) @@ -377,7 +377,7 @@ function build_explicit_observed_function(sys, ts; continue end if throw - Base.throw(ArgumentError("$s is neither an observed nor a state variable.")) + Base.throw(ArgumentError("$s is neither an observed nor an unknown variable.")) else # TODO: return variables that don't exist in the system. return nothing @@ -452,7 +452,7 @@ function convert_system(::Type{<:ODESystem}, sys, t; name = nameof(sys)) if istree(s) args = arguments(s) length(args) == 1 || - throw(InvalidSystemException("Illegal state: $s. The state can have at most one argument like `x(t)`.")) + throw(InvalidSystemException("Illegal unknown: $s. The unknown can have at most one argument like `x(t)`.")) arg = args[1] if isequal(arg, t) newsts[i] = s diff --git a/src/systems/diffeqs/sdesystem.jl b/src/systems/diffeqs/sdesystem.jl index 66cc92026d..edfca7cec8 100644 --- a/src/systems/diffeqs/sdesystem.jl +++ b/src/systems/diffeqs/sdesystem.jl @@ -38,7 +38,7 @@ struct SDESystem <: AbstractODESystem noiseeqs::AbstractArray """Independent variable.""" iv::BasicSymbolic{Real} - """Dependent (state) variables. Must not contain the independent variable.""" + """Dependent variables. Must not contain the independent variable.""" unknowns::Vector """Parameter variables. Must not contain the independent variable.""" ps::Vector @@ -250,7 +250,7 @@ function stochastic_integral_transform(sys::SDESystem, correction_factor) correction_factor * ∇σσ′[i] for i in eachindex(unknowns(sys))]...) else - dimstate, m = size(get_noiseeqs(sys)) + dimunknowns, m = size(get_noiseeqs(sys)) eqs = vcat([equations(sys)[i].lhs ~ get_noiseeqs(sys)[i] for i in eachindex(unknowns(sys))]...) de = ODESystem(eqs, get_iv(sys), unknowns(sys), parameters(sys), name = name, @@ -260,7 +260,7 @@ function stochastic_integral_transform(sys::SDESystem, correction_factor) ∇σσ′ = simplify.(jac * get_noiseeqs(sys)[:, 1]) for k in 2:m eqs = vcat([equations(sys)[i].lhs ~ get_noiseeqs(sys)[Int(i + - (k - 1) * dimstate)] + (k - 1) * dimunknowns)] for i in eachindex(unknowns(sys))]...) de = ODESystem(eqs, get_iv(sys), unknowns(sys), parameters(sys), name = name, checks = false) @@ -340,7 +340,7 @@ function Girsanov_transform(sys::SDESystem, u; θ0 = 1.0) @variables θ(t), weight(t) # determine the adjustable parameters `d` given `u` - # gradient of u with respect to states + # gradient of u with respect to unknowns grad = Symbolics.gradient(u, unknowns(sys)) noiseeqs = get_noiseeqs(sys) @@ -352,16 +352,16 @@ function Girsanov_transform(sys::SDESystem, u; θ0 = 1.0) drift_correction = noiseeqs * d end - # transformation adds additional state θ: newX = (X,θ) - # drift function for state is modified + # transformation adds additional unknowns θ: newX = (X,θ) + # drift function for unknowns is modified # θ has zero drift deqs = vcat([equations(sys)[i].lhs ~ equations(sys)[i].rhs - drift_correction[i] for i in eachindex(unknowns(sys))]...) deqsθ = D(θ) ~ 0 push!(deqs, deqsθ) - # diffusion matrix is of size d x m (d states, m noise), with diagonal noise represented as a d-dimensional vector - # for diagonal noise processes with m>1, the noise process will become non-diagonal; extra state component but no new noise process. + # diffusion matrix is of size d x m (d unknowns, m noise), with diagonal noise represented as a d-dimensional vector + # for diagonal noise processes with m>1, the noise process will become non-diagonal; extra unknown component but no new noise process. # new diffusion matrix is of size d+1 x M # diffusion for state is unchanged @@ -378,10 +378,10 @@ function Girsanov_transform(sys::SDESystem, u; θ0 = 1.0) noiseeqs = [Array(noiseeqs); noiseqsθ'] end - state = [unknowns(sys); θ] + unknown_vars = [unknowns(sys); θ] # return modified SDE System - SDESystem(deqs, noiseeqs, get_iv(sys), state, parameters(sys); + SDESystem(deqs, noiseeqs, get_iv(sys), unknown_vars, parameters(sys); defaults = Dict(θ => θ0), observed = [weight ~ θ / θ0], name = name, checks = false) end diff --git a/src/systems/discrete_system/discrete_system.jl b/src/systems/discrete_system/discrete_system.jl index 08875b8da9..fc595ddcab 100644 --- a/src/systems/discrete_system/discrete_system.jl +++ b/src/systems/discrete_system/discrete_system.jl @@ -33,7 +33,7 @@ struct DiscreteSystem <: AbstractTimeDependentSystem eqs::Vector{Equation} """Independent variable.""" iv::BasicSymbolic{Real} - """Dependent (state) variables. Must not contain the independent variable.""" + """Dependent (unknown) variables. Must not contain the independent variable.""" unknowns::Vector """Parameter variables. Must not contain the independent variable.""" ps::Vector @@ -166,7 +166,7 @@ function DiscreteSystem(eqs, iv = nothing; kwargs...) eqs = scalarize(eqs) # NOTE: this assumes that the order of algebraic equations doesn't matter diffvars = OrderedSet() - allstates = OrderedSet() + allunknowns = OrderedSet() ps = OrderedSet() # reorder equations such that it is in the form of `diffeq, algeeq` diffeq = Equation[] @@ -183,8 +183,8 @@ function DiscreteSystem(eqs, iv = nothing; kwargs...) iv = value(iv) iv === nothing && throw(ArgumentError("Please pass in independent variables.")) for eq in eqs - collect_vars_difference!(allstates, ps, eq.lhs, iv) - collect_vars_difference!(allstates, ps, eq.rhs, iv) + collect_vars_difference!(allunknowns, ps, eq.lhs, iv) + collect_vars_difference!(allunknowns, ps, eq.rhs, iv) if isdifferenceeq(eq) diffvar, _ = var_from_nested_difference(eq.lhs) isequal(iv, iv_from_nested_difference(eq.lhs)) || @@ -197,7 +197,7 @@ function DiscreteSystem(eqs, iv = nothing; kwargs...) push!(algeeq, eq) end end - algevars = setdiff(allstates, diffvars) + algevars = setdiff(allunknowns, diffvars) # the orders here are very important! return DiscreteSystem(append!(diffeq, algeeq), iv, collect(Iterators.flatten((diffvars, algevars))), ps; kwargs...) @@ -240,8 +240,8 @@ function SciMLBase.DiscreteProblem(sys::DiscreteSystem, u0map = [], tspan = get_ end function linearize_eqs(sys, eqs = get_eqs(sys); return_max_delay = false) - unique_states = unique(operation.(unknowns(sys))) - max_delay = Dict(v => 0.0 for v in unique_states) + unique_unknowns = unique(operation.(unknowns(sys))) + max_delay = Dict(v => 0.0 for v in unique_unknowns) r = @rule ~t::(t -> istree(t) && any(isequal(operation(t)), operation.(unknowns(sys))) && is_delay_var(get_iv(sys), t)) => begin delay = get_delay_val(get_iv(sys), first(arguments(~t))) @@ -253,20 +253,20 @@ function linearize_eqs(sys, eqs = get_eqs(sys); return_max_delay = false) SymbolicUtils.Postwalk(r).(rhss(eqs)) if any(values(max_delay) .> 0) - dts = Dict(v => Any[] for v in unique_states) - state_ops = Dict(v => Any[] for v in unique_states) - for v in unique_states + dts = Dict(v => Any[] for v in unique_unknowns) + unknown_ops = Dict(v => Any[] for v in unique_unknowns) + for v in unique_unknowns for eq in eqs if isdifferenceeq(eq) && istree(arguments(eq.lhs)[1]) && isequal(v, operation(arguments(eq.lhs)[1])) append!(dts[v], [operation(eq.lhs).dt]) - append!(state_ops[v], [operation(eq.lhs)]) + append!(unknown_ops[v], [operation(eq.lhs)]) end end end - all(length.(unique.(values(state_ops))) .<= 1) || - error("Each state should be used with single difference operator.") + all(length.(unique.(values(unknown_ops))) .<= 1) || + error("Each unknown should be used with single difference operator.") dts_gcd = Dict() for v in keys(dts) @@ -274,7 +274,7 @@ function linearize_eqs(sys, eqs = get_eqs(sys); return_max_delay = false) end lin_eqs = [v(get_iv(sys) - (t)) ~ v(get_iv(sys) - (t - dts_gcd[v])) - for v in unique_states if max_delay[v] > 0 && dts_gcd[v] !== nothing + for v in unique_unknowns if max_delay[v] > 0 && dts_gcd[v] !== nothing for t in collect(max_delay[v]:(-dts_gcd[v]):0)[1:(end - 1)]] eqs = vcat(eqs, lin_eqs) end @@ -301,7 +301,7 @@ function generate_function(sys::DiscreteSystem, dvs = unknowns(sys), ps = parame t = get_iv(sys) build_function(rhss, u, p, t; kwargs...) - pre, sol_states = get_substitutions_and_solved_states(sys) + pre, sol_states = get_substitutions_and_solved_unknowns(sys) build_function(rhss, u, p, t; postprocess_fbody = pre, states = sol_states, kwargs...) end diff --git a/src/systems/jumps/jumpsystem.jl b/src/systems/jumps/jumpsystem.jl index 2fcb131422..b5e842ca03 100644 --- a/src/systems/jumps/jumpsystem.jl +++ b/src/systems/jumps/jumpsystem.jl @@ -86,7 +86,7 @@ struct JumpSystem{U <: ArrayPartition} <: AbstractTimeDependentSystem analog to `SciMLBase.DiscreteCallback` that executes an affect when a given condition is true at the end of an integration step. Note, one must make sure to call `reset_aggregated_jumps!(integrator)` if using a custom affect function that changes any - state value or parameter. + unknown value or parameter. """ discrete_events::Vector{SymbolicDiscreteCallback} """ @@ -196,19 +196,19 @@ function generate_affect_function(js::JumpSystem, affect, outputidxs) expression = Val{true}, checkvars = false) end -function assemble_vrj(js, vrj, statetoid) +function assemble_vrj(js, vrj, unknowntoid) rate = drop_expr(@RuntimeGeneratedFunction(generate_rate_function(js, vrj.rate))) outputvars = (value(affect.lhs) for affect in vrj.affect!) - outputidxs = [statetoid[var] for var in outputvars] + outputidxs = [unknowntoid[var] for var in outputvars] affect = drop_expr(@RuntimeGeneratedFunction(generate_affect_function(js, vrj.affect!, outputidxs))) VariableRateJump(rate, affect) end -function assemble_vrj_expr(js, vrj, statetoid) +function assemble_vrj_expr(js, vrj, unknowntoid) rate = generate_rate_function(js, vrj.rate) outputvars = (value(affect.lhs) for affect in vrj.affect!) - outputidxs = ((statetoid[var] for var in outputvars)...,) + outputidxs = ((unknowntoid[var] for var in outputvars)...,) affect = generate_affect_function(js, vrj.affect!, outputidxs) quote rate = $rate @@ -217,19 +217,19 @@ function assemble_vrj_expr(js, vrj, statetoid) end end -function assemble_crj(js, crj, statetoid) +function assemble_crj(js, crj, unknowntoid) rate = drop_expr(@RuntimeGeneratedFunction(generate_rate_function(js, crj.rate))) outputvars = (value(affect.lhs) for affect in crj.affect!) - outputidxs = [statetoid[var] for var in outputvars] + outputidxs = [unknowntoid[var] for var in outputvars] affect = drop_expr(@RuntimeGeneratedFunction(generate_affect_function(js, crj.affect!, outputidxs))) ConstantRateJump(rate, affect) end -function assemble_crj_expr(js, crj, statetoid) +function assemble_crj_expr(js, crj, unknowntoid) rate = generate_rate_function(js, crj.rate) outputvars = (value(affect.lhs) for affect in crj.affect!) - outputidxs = ((statetoid[var] for var in outputvars)...,) + outputidxs = ((unknowntoid[var] for var in outputvars)...,) affect = generate_affect_function(js, crj.affect!, outputidxs) quote rate = $rate @@ -238,35 +238,35 @@ function assemble_crj_expr(js, crj, statetoid) end end -function numericrstoich(mtrs::Vector{Pair{V, W}}, statetoid) where {V, W} +function numericrstoich(mtrs::Vector{Pair{V, W}}, unknowntoid) where {V, W} rs = Vector{Pair{Int, W}}() for (wspec, stoich) in mtrs spec = value(wspec) if !istree(spec) && _iszero(spec) push!(rs, 0 => stoich) else - push!(rs, statetoid[spec] => stoich) + push!(rs, unknowntoid[spec] => stoich) end end sort!(rs) rs end -function numericnstoich(mtrs::Vector{Pair{V, W}}, statetoid) where {V, W} +function numericnstoich(mtrs::Vector{Pair{V, W}}, unknowntoid) where {V, W} ns = Vector{Pair{Int, W}}() for (wspec, stoich) in mtrs spec = value(wspec) !istree(spec) && _iszero(spec) && error("Net stoichiometry can not have a species labelled 0.") - push!(ns, statetoid[spec] => stoich) + push!(ns, unknowntoid[spec] => stoich) end sort!(ns) end # assemble a numeric MassActionJump from a MT symbolics MassActionJumps -function assemble_maj(majv::Vector{U}, statetoid, pmapper) where {U <: MassActionJump} - rs = [numericrstoich(maj.reactant_stoch, statetoid) for maj in majv] - ns = [numericnstoich(maj.net_stoch, statetoid) for maj in majv] +function assemble_maj(majv::Vector{U}, unknowntoid, pmapper) where {U <: MassActionJump} + rs = [numericrstoich(maj.reactant_stoch, unknowntoid) for maj in majv] + ns = [numericnstoich(maj.net_stoch, unknowntoid) for maj in majv] MassActionJump(rs, ns; param_mapper = pmapper, nocopy = true) end @@ -388,7 +388,7 @@ sol = solve(jprob, SSAStepper()) """ function JumpProcesses.JumpProblem(js::JumpSystem, prob, aggregator; callback = nothing, kwargs...) - statetoid = Dict(value(state) => i for (i, state) in enumerate(unknowns(js))) + unknowntoid = Dict(value(unknown) => i for (i, unknown) in enumerate(unknowns(js))) eqs = equations(js) invttype = prob.tspan[1] === nothing ? Float64 : typeof(1 / prob.tspan[2]) @@ -396,9 +396,9 @@ function JumpProcesses.JumpProblem(js::JumpSystem, prob, aggregator; callback = p = (prob.p isa DiffEqBase.NullParameters || prob.p === nothing) ? Num[] : prob.p majpmapper = JumpSysMajParamMapper(js, p; jseqs = eqs, rateconsttype = invttype) - majs = isempty(eqs.x[1]) ? nothing : assemble_maj(eqs.x[1], statetoid, majpmapper) - crjs = ConstantRateJump[assemble_crj(js, j, statetoid) for j in eqs.x[2]] - vrjs = VariableRateJump[assemble_vrj(js, j, statetoid) for j in eqs.x[3]] + majs = isempty(eqs.x[1]) ? nothing : assemble_maj(eqs.x[1], unknowntoid, majpmapper) + crjs = ConstantRateJump[assemble_crj(js, j, unknowntoid) for j in eqs.x[2]] + vrjs = VariableRateJump[assemble_vrj(js, j, unknowntoid) for j in eqs.x[3]] ((prob isa DiscreteProblem) && !isempty(vrjs)) && error("Use continuous problems such as an ODEProblem or a SDEProblem with VariableRateJumps") jset = JumpSet(Tuple(vrjs), Tuple(crjs), nothing, majs) @@ -424,7 +424,7 @@ function JumpProcesses.JumpProblem(js::JumpSystem, prob, aggregator; callback = callback = cbs, kwargs...) end -### Functions to determine which states a jump depends on +### Functions to determine which unknowns a jump depends on function get_variables!(dep, jump::Union{ConstantRateJump, VariableRateJump}, variables) jr = value(jump.rate) (jr isa Symbolic) && get_variables!(dep, jr, variables) @@ -440,20 +440,20 @@ function get_variables!(dep, jump::MassActionJump, variables) dep end -### Functions to determine which states are modified by a given jump -function modified_states!(mstates, jump::Union{ConstantRateJump, VariableRateJump}, sts) +### Functions to determine which unknowns are modified by a given jump +function modified_unknowns!(munknowns, jump::Union{ConstantRateJump, VariableRateJump}, sts) for eq in jump.affect! st = eq.lhs - any(isequal(st), sts) && push!(mstates, st) + any(isequal(st), sts) && push!(munknowns, st) end - mstates + munknowns end -function modified_states!(mstates, jump::MassActionJump, sts) - for (state, stoich) in jump.net_stoch - any(isequal(state), sts) && push!(mstates, state) +function modified_unknowns!(munknowns, jump::MassActionJump, sts) + for (unknown, stoich) in jump.net_stoch + any(isequal(unknown), sts) && push!(munknowns, unknown) end - mstates + munknowns end ###################### parameter mapper ########################### diff --git a/src/systems/nonlinear/nonlinearsystem.jl b/src/systems/nonlinear/nonlinearsystem.jl index 743000fdc3..aa3c14732d 100644 --- a/src/systems/nonlinear/nonlinearsystem.jl +++ b/src/systems/nonlinear/nonlinearsystem.jl @@ -193,7 +193,7 @@ end function generate_function(sys::NonlinearSystem, dvs = unknowns(sys), ps = parameters(sys); kwargs...) rhss = [deq.rhs for deq in equations(sys)] - pre, sol_states = get_substitutions_and_solved_states(sys) + pre, sol_states = get_substitutions_and_solved_unknowns(sys) return build_function(rhss, value.(dvs), value.(ps); postprocess_fbody = pre, states = sol_states, kwargs...) diff --git a/src/systems/optimization/constraints_system.jl b/src/systems/optimization/constraints_system.jl index bb0e93790b..e07bef22b4 100644 --- a/src/systems/optimization/constraints_system.jl +++ b/src/systems/optimization/constraints_system.jl @@ -109,7 +109,7 @@ function ConstraintsSystem(constraints, unknowns, ps; throw(ArgumentError("The `name` keyword must be provided. Please consider using the `@named` macro")) cstr = value.(Symbolics.canonical_form.(scalarize(constraints))) - states′ = value.(scalarize(unknowns)) + unknowns′ = value.(scalarize(unknowns)) ps′ = value.(scalarize(ps)) if !(isempty(default_u0) && isempty(default_p)) @@ -126,7 +126,7 @@ function ConstraintsSystem(constraints, unknowns, ps; defaults = Dict(value(k) => value(v) for (k, v) in pairs(defaults)) var_to_name = Dict() - process_variables!(var_to_name, defaults, states′) + process_variables!(var_to_name, defaults, unknowns′) process_variables!(var_to_name, defaults, ps′) isempty(observed) || collect_var_to_name!(var_to_name, (eq.lhs for eq in observed)) @@ -179,7 +179,7 @@ end function generate_function(sys::ConstraintsSystem, dvs = unknowns(sys), ps = parameters(sys); kwargs...) lhss = generate_canonical_form_lhss(sys) - pre, sol_states = get_substitutions_and_solved_states(sys) + pre, sol_states = get_substitutions_and_solved_unknowns(sys) func = build_function(lhss, value.(dvs), value.(ps); postprocess_fbody = pre, states = sol_states, kwargs...) diff --git a/src/systems/optimization/optimizationsystem.jl b/src/systems/optimization/optimizationsystem.jl index 7228c76726..e520c7490f 100644 --- a/src/systems/optimization/optimizationsystem.jl +++ b/src/systems/optimization/optimizationsystem.jl @@ -93,7 +93,7 @@ function OptimizationSystem(op, unknowns, ps; name === nothing && throw(ArgumentError("The `name` keyword must be provided. Please consider using the `@named` macro")) constraints = value.(scalarize(constraints)) - states′ = value.(scalarize(unknowns)) + unknowns′ = value.(scalarize(unknowns)) ps′ = value.(scalarize(ps)) op′ = value(scalarize(op)) @@ -109,12 +109,12 @@ function OptimizationSystem(op, unknowns, ps; defaults = Dict(value(k) => value(v) for (k, v) in pairs(defaults)) var_to_name = Dict() - process_variables!(var_to_name, defaults, states′) + process_variables!(var_to_name, defaults, unknowns′) process_variables!(var_to_name, defaults, ps′) isempty(observed) || collect_var_to_name!(var_to_name, (eq.lhs for eq in observed)) OptimizationSystem(Threads.atomic_add!(SYSTEM_COUNT, UInt(1)), - op′, states′, ps′, var_to_name, + op′, unknowns′, ps′, var_to_name, observed, constraints, name, systems, defaults, metadata, gui_metadata; diff --git a/src/systems/systems.jl b/src/systems/systems.jl index 5b93e07fc8..a2c037c1c8 100644 --- a/src/systems/systems.jl +++ b/src/systems/systems.jl @@ -14,7 +14,7 @@ types during tearing. The optional argument `io` may take a tuple `(inputs, outputs)`. This will convert all `inputs` to parameters and allow them to be unconnected, i.e., -simplification will allow models where `n_states = n_equations - n_inputs`. +simplification will allow models where `n_unknowns = n_equations - n_inputs`. """ function structural_simplify(sys::AbstractSystem, io = nothing; simplify = false, kwargs...) diff --git a/src/systems/systemstructure.jl b/src/systems/systemstructure.jl index 1548c0cc50..1c7c19443c 100644 --- a/src/systems/systemstructure.jl +++ b/src/systems/systemstructure.jl @@ -283,7 +283,7 @@ function TearingState(sys; quick_cancel = false, check = true) end vars!(vars, eq.rhs, op = Symbolics.Operator) isalgeq = true - statevars = [] + unknownvars = [] for var in vars ModelingToolkit.isdelay(var, iv) && continue set_incidence = true @@ -295,7 +295,7 @@ function TearingState(sys; quick_cancel = false, check = true) continue end varidx = addvar!(var) - set_incidence && push!(statevars, var) + set_incidence && push!(unknownvars, var) dvar = var idx = varidx @@ -337,8 +337,8 @@ function TearingState(sys; quick_cancel = false, check = true) @goto ANOTHER_VAR end end - push!(symbolic_incidence, copy(statevars)) - empty!(statevars) + push!(symbolic_incidence, copy(unknownvars)) + empty!(unknownvars) empty!(vars) if isalgeq eqs[i] = eq @@ -472,7 +472,7 @@ function Base.getindex(bgpm::SystemStructurePrintMatrix, i::Integer, j::Integer) match = unassigned if bgpm.var_eq_matching !== nothing && i - 1 <= length(bgpm.var_eq_matching) match = bgpm.var_eq_matching[i - 1] - isa(match, Union{Int, Unassigned}) || (match = true) # Selected State + isa(match, Union{Int, Unassigned}) || (match = true) # Selected Unknown end return BipartiteAdjacencyList(i - 1 <= ndsts(bgpm.bpg) ? 𝑑neighbors(bgpm.bpg, i - 1) : nothing, @@ -613,7 +613,7 @@ function _structural_simplify!(state::TearingState, io; simplify = false, else sys = ModelingToolkit.tearing(sys, state; simplify, mm, check_consistency) end - fullstates = [map(eq -> eq.lhs, observed(sys)); unknowns(sys)] - @set! sys.observed = ModelingToolkit.topsort_equations(observed(sys), fullstates) + fullunknowns = [map(eq -> eq.lhs, observed(sys)); unknowns(sys)] + @set! sys.observed = ModelingToolkit.topsort_equations(observed(sys), fullunknowns) ModelingToolkit.invalidate_cache!(sys), input_idxs end diff --git a/src/systems/unit_check.jl b/src/systems/unit_check.jl index 1fcde9f12f..2ae5957002 100644 --- a/src/systems/unit_check.jl +++ b/src/systems/unit_check.jl @@ -217,20 +217,20 @@ function _validate(conn::Connection; info::String = "") sst = unknowns(s) if length(st) != length(sst) valid = false - @warn("$info: connected systems $(nameof(sys)) and $(nameof(s)) have $(length(st)) and $(length(sst)) states, cannor connect.") + @warn("$info: connected systems $(nameof(sys)) and $(nameof(s)) have $(length(st)) and $(length(sst)) unknowns, cannot connect.") continue end for (i, x) in enumerate(st) j = findfirst(isequal(x), sst) if j == nothing valid = false - @warn("$info: connected systems $(nameof(sys)) and $(nameof(s)) do not have the same states.") + @warn("$info: connected systems $(nameof(sys)) and $(nameof(s)) do not have the same unknowns.") else aunit = safe_get_unit(x, info * string(nameof(sys)) * "#$i") bunit = safe_get_unit(sst[j], info * string(nameof(s)) * "#$j") if !equivalent(aunit, bunit) valid = false - @warn("$info: connected system states $x and $(sst[j]) have mismatched units.") + @warn("$info: connected system unknowns $x and $(sst[j]) have mismatched units.") end end end diff --git a/src/systems/validation.jl b/src/systems/validation.jl index 773a037d2b..25bdf4707b 100644 --- a/src/systems/validation.jl +++ b/src/systems/validation.jl @@ -185,26 +185,26 @@ function _validate(conn::Connection; info::String = "") valid = true syss = get_systems(conn) sys = first(syss) - st = unknowns(sys) + unks = unknowns(sys) for i in 2:length(syss) s = syss[i] - sst = unknowns(s) - if length(st) != length(sst) + _unks = unknowns(s) + if length(unks) != length(_unks) valid = false - @warn("$info: connected systems $(nameof(sys)) and $(nameof(s)) have $(length(st)) and $(length(sst)) states, cannor connect.") + @warn("$info: connected systems $(nameof(sys)) and $(nameof(s)) have $(length(unks)) and $(length(_unks)) unknowns, cannot connect.") continue end - for (i, x) in enumerate(st) - j = findfirst(isequal(x), sst) + for (i, x) in enumerate(unks) + j = findfirst(isequal(x), _unks) if j == nothing valid = false - @warn("$info: connected systems $(nameof(sys)) and $(nameof(s)) do not have the same states.") + @warn("$info: connected systems $(nameof(sys)) and $(nameof(s)) do not have the same unknowns.") else aunit = safe_get_unit(x, info * string(nameof(sys)) * "#$i") - bunit = safe_get_unit(sst[j], info * string(nameof(s)) * "#$j") + bunit = safe_get_unit(_unks[j], info * string(nameof(s)) * "#$j") if !equivalent(aunit, bunit) valid = false - @warn("$info: connected system states $x and $(sst[j]) have mismatched units.") + @warn("$info: connected system unknowns $x and $(_unks[j]) have mismatched units.") end end end diff --git a/src/utils.jl b/src/utils.jl index 19668689a1..f5e809be22 100644 --- a/src/utils.jl +++ b/src/utils.jl @@ -33,8 +33,8 @@ function retime_dvs(op, dvs, iv) op end -function modified_states!(mstates, e::Equation, statelist = nothing) - get_variables!(mstates, e.lhs, statelist) +function modified_unknowns!(munknowns, e::Equation, unknownlist = nothing) + get_variables!(munknowns, e.lhs, unknownlist) end macro showarr(x) @@ -132,7 +132,7 @@ function check_variables(dvs, iv) (is_delay_var(iv, dv) || occursin(iv, dv)) || throw(ArgumentError("Variable $dv is not a function of independent variable $iv.")) isparameter(dv) && - throw(ArgumentError("$dv is not a state. It is a parameter.")) + throw(ArgumentError("$dv is not an unknown. It is a parameter.")) end end @@ -457,44 +457,44 @@ function find_derivatives!(vars, expr, f) return vars end -function collect_vars!(states, parameters, expr, iv) +function collect_vars!(unknowns, parameters, expr, iv) if issym(expr) - collect_var!(states, parameters, expr, iv) + collect_var!(unknowns, parameters, expr, iv) else for var in vars(expr) if istree(var) && operation(var) isa Differential var, _ = var_from_nested_derivative(var) end - collect_var!(states, parameters, var, iv) + collect_var!(unknowns, parameters, var, iv) end end return nothing end -function collect_vars_difference!(states, parameters, expr, iv) +function collect_vars_difference!(unknowns, parameters, expr, iv) if issym(expr) - collect_var!(states, parameters, expr, iv) + collect_var!(unknowns, parameters, expr, iv) else for var in vars(expr) if istree(var) && operation(var) isa Difference var, _ = var_from_nested_difference(var) end - collect_var!(states, parameters, var, iv) + collect_var!(unknowns, parameters, var, iv) end end return nothing end -function collect_var!(states, parameters, var, iv) +function collect_var!(unknowns, parameters, var, iv) isequal(var, iv) && return nothing if isparameter(var) || (istree(var) && isparameter(operation(var))) push!(parameters, var) elseif !isconstant(var) - push!(states, var) + push!(unknowns, var) end # Add also any parameters that appear only as defaults in the var if hasdefault(var) - collect_vars!(states, parameters, getdefault(var), iv) + collect_vars!(unknowns, parameters, getdefault(var), iv) end return nothing end @@ -609,7 +609,7 @@ function get_cmap(sys) return cmap, cs end -function get_substitutions_and_solved_states(sys; no_postprocess = false) +function get_substitutions_and_solved_unknowns(sys; no_postprocess = false) cmap, cs = get_cmap(sys) if empty_substitutions(sys) && isempty(cs) sol_states = Code.LazyState() @@ -647,7 +647,7 @@ function mergedefaults(defaults, varmap, vars) end @noinline function throw_missingvars_in_sys(vars) - throw(ArgumentError("$vars are either missing from the variable map or missing from the system's states/parameters list.")) + throw(ArgumentError("$vars are either missing from the variable map or missing from the system's unknowns/parameters list.")) end function promote_to_concrete(vs; tofloat = true, use_union = true) diff --git a/src/variables.jl b/src/variables.jl index 9d1e767970..6eecf61e1f 100644 --- a/src/variables.jl +++ b/src/variables.jl @@ -146,7 +146,7 @@ function SciMLBase.process_p_u0_symbolic(prob::Union{SciMLBase.AbstractDEProblem if eltype(u0) <: Pair hasproperty(prob.f, :sys) && hasfield(typeof(prob.f.sys), :unknowns) || throw(ArgumentError("This problem does not support symbolic maps with `remake`, i.e. it does not have a symbolic origin." * - " Please use `remake` with the `u0` keyword argument as a vector of values, paying attention to state order.")) + " Please use `remake` with the `u0` keyword argument as a vector of values, paying attention to unknown variable order.")) end sys = prob.f.sys @@ -326,7 +326,7 @@ Create parameters with bounds like this @parameters p [bounds=(-1, 1)] ``` -To obtain state bounds, call `getbounds(sys, unknowns(sys))` +To obtain unknown variable bounds, call `getbounds(sys, unknowns(sys))` """ function getbounds(sys::ModelingToolkit.AbstractSystem, p = parameters(sys)) Dict(p .=> getbounds.(p)) @@ -410,7 +410,7 @@ end """ tobrownian(s::Sym) -Maps the brownianiable to a state. +Maps the brownianiable to an unknown. """ tobrownian(s::Symbolic) = setmetadata(s, MTKVariableTypeCtx, BROWNIAN) tobrownian(s::Num) = Num(tobrownian(value(s))) diff --git a/test/jumpsystem.jl b/test/jumpsystem.jl index 1640110bc0..fdb6356426 100644 --- a/test/jumpsystem.jl +++ b/test/jumpsystem.jl @@ -14,9 +14,9 @@ affect₂ = [I ~ I - 1, R ~ R + 1] j₁ = ConstantRateJump(rate₁, affect₁) j₂ = VariableRateJump(rate₂, affect₂) @named js = JumpSystem([j₁, j₂], t, [S, I, R], [β, γ]) -statetoid = Dict(MT.value(state) => i for (i, state) in enumerate(unknowns(js))) -mtjump1 = MT.assemble_crj(js, j₁, statetoid) -mtjump2 = MT.assemble_vrj(js, j₂, statetoid) +unknowntoid = Dict(MT.value(unknown) => i for (i, unknown) in enumerate(unknowns(js))) +mtjump1 = MT.assemble_crj(js, j₁, unknowntoid) +mtjump2 = MT.assemble_vrj(js, j₂, unknowntoid) # doc version rate1(u, p, t) = (0.1 / 1000.0) * u[1] * u[2] diff --git a/test/linearize.jl b/test/linearize.jl index 6eaae99671..f892d8cdf7 100644 --- a/test/linearize.jl +++ b/test/linearize.jl @@ -84,7 +84,7 @@ connections = [f.y ~ c.r # filtered reference to controller reference lsys0, ssys = linearize(cl, [f.u], [p.x]) desired_order = [f.x, p.x] -lsys = ModelingToolkit.reorder_states(lsys0, unknowns(ssys), desired_order) +lsys = ModelingToolkit.reorder_unknowns(lsys0, unknowns(ssys), desired_order) @test lsys.A == [-2 0; 1 -2] @test lsys.B == reshape([1, 0], 2, 1) @@ -110,7 +110,7 @@ Nd = 10 lsys0, ssys = linearize(pid, [reference.u, measurement.u], [ctr_output.u]) @unpack int, der = pid desired_order = [int.x, der.x] -lsys = ModelingToolkit.reorder_states(lsys0, unknowns(ssys), desired_order) +lsys = ModelingToolkit.reorder_unknowns(lsys0, unknowns(ssys), desired_order) @test lsys.A == [0 0; 0 -10] @test lsys.B == [2 -2; 10 -10] @@ -125,8 +125,8 @@ lsyss, _ = ModelingToolkit.linearize_symbolic(pid, [reference.u, measurement.u], @test substitute(lsyss.C, ModelingToolkit.defaults(pid)) == lsys.C @test substitute(lsyss.D, ModelingToolkit.defaults(pid)) == lsys.D -# Test with the reverse desired state order as well to verify that similarity transform and reoreder_states really works -lsys = ModelingToolkit.reorder_states(lsys, unknowns(ssys), reverse(desired_order)) +# Test with the reverse desired unknown order as well to verify that similarity transform and reoreder_unknowns really works +lsys = ModelingToolkit.reorder_unknowns(lsys, unknowns(ssys), reverse(desired_order)) @test lsys.A == [-10 0; 0 0] @test lsys.B == [10 -10; 2 -2] diff --git a/test/modelingtoolkitize.jl b/test/modelingtoolkitize.jl index 3a88d3c126..fea90491a3 100644 --- a/test/modelingtoolkitize.jl +++ b/test/modelingtoolkitize.jl @@ -111,7 +111,7 @@ function SIRD_ac!(du, u, p, t) C = regional_all_contact_matrix - # State variables + # Unknown variables S = @view u[(4 * 0 + 1):(4 * 1)] I = @view u[(4 * 1 + 1):(4 * 2)] R = @view u[(4 * 2 + 1):(4 * 3)] @@ -214,7 +214,7 @@ using ModelingToolkit # ODE model: simple SIR model with seasonally forced contact rate function SIR!(du, u, p, t) - # states + # Unknowns (S, I, R) = u[1:3] N = S + I + R @@ -230,7 +230,7 @@ function SIR!(du, u, p, t) βeff = β * (1.0 + η * cos(2.0 * π * (t - φ) / 365.0)) λ = βeff * I / N - # change in states + # change in unknowns du[1] = (μ * N - λ * S - μ * S + ω * R) du[2] = (λ * S - σ * I - μ * I) du[3] = (σ * I - μ * R - ω * R) diff --git a/test/nonlinearsystem.jl b/test/nonlinearsystem.jl index ae2988d501..aa1cd97973 100644 --- a/test/nonlinearsystem.jl +++ b/test/nonlinearsystem.jl @@ -269,9 +269,9 @@ end sol = solve(prob) @test sol.retcode == SciMLBase.ReturnCode.Success - # Confirm for all the states of the non-simplified system + # Confirm for all the unknowns of the non-simplified system @test all(.≈(sol[unknowns(sys)], [1e-5, 0, 1e-5 / 1.5, 0]; atol = 1e-8)) - # Confirm for all the states of the simplified system + # Confirm for all the unknowns of the simplified system @test all(.≈(sol[unknowns(sys_simple)], [1e-5 / 1.5, 0]; atol = 1e-8)) end diff --git a/test/odesystem.jl b/test/odesystem.jl index 1232750c65..493e186d38 100644 --- a/test/odesystem.jl +++ b/test/odesystem.jl @@ -223,7 +223,7 @@ prob = ODEProblem(lotka, [1.0, 1.0], (0.0, 1.0), [1.5, 1.0, 3.0, 1.0]) de = modelingtoolkitize(prob) ODEFunction(de)(similar(prob.u0), prob.u0, prob.p, 0.1) -# automatic state detection for DAEs +# automatic unknown detection for DAEs @parameters t k₁ k₂ k₃ @variables y₁(t) y₂(t) y₃(t) D = Differential(t) diff --git a/test/reduction.jl b/test/reduction.jl index 382a3f88de..b8b617baa5 100644 --- a/test/reduction.jl +++ b/test/reduction.jl @@ -35,7 +35,7 @@ lorenz1_aliased = structural_simplify(lorenz1) io = IOBuffer(); show(io, MIME("text/plain"), lorenz1_aliased); str = String(take!(io)); -@test all(s -> occursin(s, str), ["lorenz1", "States (2)", "Parameters (3)"]) +@test all(s -> occursin(s, str), ["lorenz1", "Unknowns (2)", "Parameters (3)"]) reduced_eqs = [D(x) ~ σ * (y - x) D(y) ~ β + (ρ - z) * x - y] #test_equal.(equations(lorenz1_aliased), reduced_eqs) diff --git a/test/symbolic_events.jl b/test/symbolic_events.jl index 4620fbaddb..d85f2118fd 100644 --- a/test/symbolic_events.jl +++ b/test/symbolic_events.jl @@ -189,7 +189,7 @@ sol = solve(prob, Tsit5()) @test minimum(t -> abs(t - 1), sol.t) < 1e-10 # test that the solver stepped at the first root @test minimum(t -> abs(t - 2), sol.t) < 1e-10 # test that the solver stepped at the second root -@named sys = ODESystem(eqs, continuous_events = [x ~ 1, x ~ 2]) # two root eqs using the same state +@named sys = ODESystem(eqs, continuous_events = [x ~ 1, x ~ 2]) # two root eqs using the same unknown prob = ODEProblem(sys, Pair[], (0.0, 3.0)) @test get_callback(prob) isa ModelingToolkit.DiffEqCallbacks.VectorContinuousCallback sol = solve(prob, Tsit5()) From ff1382aa681c4d3ef25b11b440267ab35332517c Mon Sep 17 00:00:00 2001 From: Aayush Sabharwal Date: Mon, 29 Jan 2024 13:11:42 +0530 Subject: [PATCH 3/3] refactor: rename `SelectedState` to `SelectedUnknown` --- .../partial_state_selection.jl | 12 ++++++------ src/structural_transformation/symbolics_tearing.jl | 12 ++++++------ src/systems/diffeqs/odesystem.jl | 2 +- src/systems/systemstructure.jl | 2 +- 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/structural_transformation/partial_state_selection.jl b/src/structural_transformation/partial_state_selection.jl index 44edf71c08..afabc581a6 100644 --- a/src/structural_transformation/partial_state_selection.jl +++ b/src/structural_transformation/partial_state_selection.jl @@ -35,7 +35,7 @@ function pss_graph_modia!(structure::SystemStructure, maximal_top_matching, varl # Find Strongly connected components. Note that after pantelides, we expect # a balanced system, so a maximal matching should be possible. var_sccs::Vector{Union{Vector{Int}, Int}} = find_var_sccs(graph, maximal_top_matching) - var_eq_matching = Matching{Union{Unassigned, SelectedState}}(ndsts(graph)) + var_eq_matching = Matching{Union{Unassigned, SelectedUnknown}}(ndsts(graph)) for vars in var_sccs # TODO: We should have a way to not have the scc code look at unassigned vars. if length(vars) == 1 && maximal_top_matching[vars[1]] === unassigned @@ -71,7 +71,7 @@ function pss_graph_modia!(structure::SystemStructure, maximal_top_matching, varl removed_vars = Int[] for var in old_level_vars old_assign = var_eq_matching[var] - if isa(old_assign, SelectedState) + if isa(old_assign, SelectedUnknown) push!(removed_vars, var) continue elseif !isa(old_assign, Int) || @@ -112,7 +112,7 @@ function pss_graph_modia!(structure::SystemStructure, maximal_top_matching, varl for var in remaining_vars if nlsolve_matching[var] === unassigned && var_eq_matching[var] === unassigned - var_eq_matching[var] = SelectedState() + var_eq_matching[var] = SelectedUnknown() end end end @@ -125,7 +125,7 @@ function pss_graph_modia!(structure::SystemStructure, maximal_top_matching, varl return complete(var_eq_matching) end -struct SelectedState end +struct SelectedUnknown end function partial_state_selection_graph!(structure::SystemStructure, var_eq_matching) @unpack eq_to_diff, var_to_diff, graph, solvable_graph = structure eq_to_diff = complete(eq_to_diff) @@ -346,13 +346,13 @@ function tearing_with_dummy_derivatives(structure, dummy_derivatives) end var_eq_matching, full_var_eq_matching, var_sccs = tear_graph_modia(structure, Base.Fix1(isdiffed, (structure, dummy_derivatives)), - Union{Unassigned, SelectedState}; + Union{Unassigned, SelectedUnknown}; varfilter = Base.Fix1(getindex, can_eliminate)) for v in eachindex(var_eq_matching) is_present(structure, v) || continue dv = var_to_diff[v] (dv === nothing || !is_some_diff(structure, dummy_derivatives, dv)) && continue - var_eq_matching[v] = SelectedState() + var_eq_matching[v] = SelectedUnknown() end return var_eq_matching, full_var_eq_matching, var_sccs, can_eliminate end diff --git a/src/structural_transformation/symbolics_tearing.jl b/src/structural_transformation/symbolics_tearing.jl index 5864161a6e..71b18e4fe8 100644 --- a/src/structural_transformation/symbolics_tearing.jl +++ b/src/structural_transformation/symbolics_tearing.jl @@ -18,7 +18,7 @@ function substitution_graph(graph, slist, dlist, var_eq_matching) newmatching = Matching(ns) for (v, e) in enumerate(var_eq_matching) - (e === unassigned || e === SelectedState()) && continue + (e === unassigned || e === SelectedUnknown()) && continue iv = vrename[v] ie = erename[e] iv == 0 && continue @@ -228,7 +228,7 @@ function tearing_reassemble(state::TearingState, var_eq_matching; # A general DAE is in the form of `F(u'(t), u(t), p, t) == 0`. We can # characterize variables in `u(t)` into two classes: differential variables # (denoted `v(t)`) and algebraic variables (denoted `z(t)`). Differential - # variables are marked as `SelectedState` and they are differentiated in the + # variables are marked as `SelectedUnknown` and they are differentiated in the # DAE system, i.e. `v'(t)` are all the variables in `u'(t)` that actually # appear in the system. Algebraic variables are variables that are not # differential variables. @@ -255,7 +255,7 @@ function tearing_reassemble(state::TearingState, var_eq_matching; for var in 1:length(fullvars) dv = var_to_diff[var] dv === nothing && continue - if var_eq_matching[var] !== SelectedState() + if var_eq_matching[var] !== SelectedUnknown() dd = fullvars[dv] v_t = setio(diff2term(unwrap(dd)), false, false) for eq in 𝑑neighbors(graph, dv) @@ -283,7 +283,7 @@ function tearing_reassemble(state::TearingState, var_eq_matching; end end - # `SelectedState` information is no longer needed past here. State selection + # `SelectedUnknown` information is no longer needed past here. State selection # is done. All non-differentiated variables are algebraic variables, and all # variables that appear differentiated are differential variables. @@ -567,10 +567,10 @@ function tearing(state::TearingState; kwargs...) var_eq_matching′, = tear_graph_modia(state.structure; varfilter = var -> var in algvars, eqfilter = eq -> eq in aeqs) - var_eq_matching = Matching{Union{Unassigned, SelectedState}}(var_eq_matching′) + var_eq_matching = Matching{Union{Unassigned, SelectedUnknown}}(var_eq_matching′) for var in 1:ndsts(graph) if isdiffvar(state.structure, var) - var_eq_matching[var] = SelectedState() + var_eq_matching[var] = SelectedUnknown() end end var_eq_matching diff --git a/src/systems/diffeqs/odesystem.jl b/src/systems/diffeqs/odesystem.jl index fb9184871b..b308c56895 100644 --- a/src/systems/diffeqs/odesystem.jl +++ b/src/systems/diffeqs/odesystem.jl @@ -36,7 +36,7 @@ struct ODESystem <: AbstractODESystem Dependent (unknown) variables. Must not contain the independent variable. N.B.: If `torn_matching !== nothing`, this includes all variables. Actual - ODE unknowns are determined by the `SelectedState()` entries in `torn_matching`. + ODE unknowns are determined by the `SelectedUnknown()` entries in `torn_matching`. """ unknowns::Vector """Parameter variables. Must not contain the independent variable.""" diff --git a/src/systems/systemstructure.jl b/src/systems/systemstructure.jl index 1c7c19443c..e56f6b9f41 100644 --- a/src/systems/systemstructure.jl +++ b/src/systems/systemstructure.jl @@ -538,7 +538,7 @@ function Base.show(io::IO, mime::MIME"text/plain", ms::MatchedSystemStructure) printstyled(io, "(Unsolvable + Matched)", color = :magenta) print(io, " | ") printstyled(io, " ∫", color = :cyan) - printstyled(io, " SelectedState") + printstyled(io, " SelectedUnknown") end # TODO: clean up