Skip to content

Add accumulation #2055

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/ModelingToolkit.jl
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,8 @@ end

export AbstractTimeDependentSystem, AbstractTimeIndependentSystem,
AbstractMultivariateSystem
export ODESystem, ODEFunction, ODEFunctionExpr, ODEProblemExpr, convert_system
export ODESystem, ODEFunction, ODEFunctionExpr, ODEProblemExpr, convert_system,
add_accumulations
export DAEFunctionExpr, DAEProblemExpr
export SDESystem, SDEFunction, SDEFunctionExpr, SDEProblemExpr
export SystemStructure
Expand Down
18 changes: 18 additions & 0 deletions src/systems/diffeqs/odesystem.jl
Original file line number Diff line number Diff line change
Expand Up @@ -436,3 +436,21 @@ function convert_system(::Type{<:ODESystem}, sys, t; name = nameof(sys))
return ODESystem(neweqs, t, newsts, parameters(sys); defaults = defs, name = name,
checks = false)
end

"""
$(SIGNATURES)

Add accumulation variables for `vars`.
"""
function add_accumulations(sys::ODESystem, vars = states(sys))
eqs = get_eqs(sys)
accs = filter(x -> startswith(string(x), "accumulation_"), states(sys))
if !isempty(accs)
error("$accs variable names start with \"accumulation_\"")
end
avars = [rename(v, Symbol(:accumulation_, getname(v))) for v in vars]
D = Differential(get_iv(sys))
@set! sys.eqs = [eqs; Equation[D(a) ~ v for (a, v) in zip(avars, vars)]]
@set! sys.states = [get_states(sys); avars]
@set! sys.defaults = merge(get_defaults(sys), Dict(a => 0.0 for a in avars))
end
9 changes: 9 additions & 0 deletions test/odesystem.jl
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,15 @@ D = Differential(t)
@variables x(t) y(t) z(t)
D = Differential(t)
@named sys = ODESystem([D(x) ~ y, 0 ~ x + z, 0 ~ x - y], t, [z, y, x], [])
asys = add_accumulations(sys)
@variables accumulation_x(t) accumulation_y(t) accumulation_z(t)
eqs = [0 ~ x + z
0 ~ x - y
D(accumulation_x) ~ x
D(accumulation_y) ~ y
D(accumulation_z) ~ z
D(x) ~ y]
@test sort(equations(asys), by = string) == eqs
sys2 = ode_order_lowering(sys)
M = ModelingToolkit.calculate_massmatrix(sys2)
@test M == Diagonal([1, 0, 0])
Expand Down