Skip to content

Instantly share code, notes, and snippets.

@baggepinnen
Last active February 23, 2024 07:24
Show Gist options
  • Save baggepinnen/7dda5a13dc898cb06f8fdd5c1dc101a2 to your computer and use it in GitHub Desktop.
Save baggepinnen/7dda5a13dc898cb06f8fdd5c1dc101a2 to your computer and use it in GitHub Desktop.
Describe an ODESystem using a table
using PrettyTables
using ModelingToolkit, Symbolics
using ModelingToolkit: has_defaults, defaults, getbounds, AbstractODESystem, n_extra_equations, get_iv
using Symbolics: unwrap, VariableSource
function describe(io::IO, sys::AbstractODESystem; backend = Val(:text), alignment = :l)
header = ["Variable name", "Variable type", "Default value", "Bounds", "Description"]
x = sort(states(sys), by=string)
p = sort(parameters(sys), by=string)
vars = [x; p]
defs = has_defaults(sys) ? defaults(sys) : nothing
rows = map(vars) do var
x = unwrap(var)
vartype, name = get(x.metadata, VariableSource, (:unknown, :unknown))
default = get(defs, var, "")
bounds = getbounds(var)
desc = getdescription(var)
[string(name), string(vartype), string(default), string(bounds), desc]
end
data = reduce(hcat, rows) |> permutedims
eqs = equations(sys)
nvars = length(x)
if eqs isa AbstractArray && eltype(eqs) <: Equation
neqs = count(eq -> !(eq.lhs isa Connection), eqs)
Base.printstyled(io, "Model $(nameof(sys)) with\n$neqs "; bold = true)
nextras = n_extra_equations(sys)
if nextras > 0
Base.printstyled(io, "("; bold = true)
Base.printstyled(io, neqs + nextras; bold = true, color = :magenta)
Base.printstyled(io, ") "; bold = true)
end
Base.printstyled(io, "equations\n"; bold = true)
else
Base.printstyled(io, "Model $(nameof(sys))\n"; bold = true)
end
Base.printstyled(io, "$nvars states\n"; bold = true)
Base.printstyled(io, "$(length(p)) parameters\n"; bold = true)
iv = get_iv(sys)
Base.printstyled(io, "Inependent variable $(iv): $(getdescription(iv))\n"; bold = true)
pretty_table(io, data; header, backend, alignment)
end
describe(sys::AbstractODESystem; kwargs...) = describe(stdout, sys; kwargs...)
## Exampel usage ===========================================
using ModelingToolkitStandardLibrary
@parameters t [description="Time"]
@parameters p [description = "A description of p"]
@variables u(t) [description = "A short description of u", bounds=(-1,1)]
@named PI = ModelingToolkitStandardLibrary.Blocks.LimPID()
@named sys = ODESystem([u ~ p + PI.ctr_output.u], t, systems=[PI])
describe(sys)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment