# How to write equations less redundant

How can this code be written less redundant?

``````    if lin
@parameters a=eq.a_bar b=eq.b_bar
eqs = [D(ω)    ~ (Pr - Pg) / (J * ω),
D(Uest) ~ Ku * e_p,
r_ω     ~ Uest * λnom / R,
e_ω     ~ r_ω - ω,
e_p     ~ Pg - Pr_est + J * D(ω) * ω,
λest    ~ ω * R / Uest,
Pr_est  ~ 0.5 *  ρ * A * Uest^3 * Γest * (a*λest + b),
λ       ~ ω * R/U,
Pr      ~ 0.5 * ρ * A * U^3 * Γ * (a*λ + b),
Pg      ~ Pgc + Pge]
else
eqs = [D(ω)    ~ (Pr - Pg) / (J * ω),
D(Uest) ~ Ku * e_p,
r_ω     ~ Uest * λnom / R,
e_ω     ~ r_ω - ω,
e_p     ~ Pg - Pr_est + J * D(ω) * ω,
λest    ~ ω * R / Uest,
Pr_est  ~ 0.5 *  ρ * A * Uest^3 * Γest * Cp(λest),
λ       ~ ω * R/U,
Pr      ~ 0.5 * ρ * A * U^3 * Γ * Cp(λ),
Pg      ~ Pgc + Pge]
end
``````
``````eqs = [D(ω)    ~ (Pr - Pg) / (J * ω),
D(Uest) ~ Ku * e_p,
r_ω     ~ Uest * λnom / R,
e_ω     ~ r_ω - ω,
e_p     ~ Pg - Pr_est + J * D(ω) * ω,
λest    ~ ω * R / Uest,
λ       ~ ω * R/U,
Pg      ~ Pgc + Pge]
if lin
@parameters a=eq.a_bar b=eq.b_bar
append!(eqs,
[Pr_est  ~ 0.5 *  ρ * A * Uest^3 * Γest * (a*λest + b),
Pr      ~ 0.5 * ρ * A * U^3 * Γ * (a*λ + b)])
else
append!(eqs,
[Pr_est ~ 0.5 *  ρ * A * Uest^3 * Γest * Cp(λest),
Pr     ~ 0.5 * ρ * A * U^3 * Γ * Cp(λ)]_
end
``````

Or

``````eqs = [D(ω)    ~ (Pr - Pg) / (J * ω),
D(Uest) ~ Ku * e_p,
r_ω     ~ Uest * λnom / R,
e_ω     ~ r_ω - ω,
e_p     ~ Pg - Pr_est + J * D(ω) * ω,
λest    ~ ω * R / Uest,
Pr_est  ~ 0.5 *  ρ * A * Uest^3 * Γest * ifelse(lin, (a*λest + b), Cp(λest)),
λ       ~ ω * R/U,
Pr      ~ 0.5 * ρ * A * U^3 * Γ * ifelse(lin, (a*λ + b), Cp(λ)),
Pg      ~ Pgc + Pge]

``````

Or even

``````eqs = [D(ω)    ~ (Pr - Pg) / (J * ω),
D(Uest) ~ Ku * e_p,
r_ω     ~ Uest * λnom / R,
e_ω     ~ r_ω - ω,
e_p     ~ Pg - Pr_est + J * D(ω) * ω,
λest    ~ ω * R / Uest,
Cp′     ~ ifelse(lin, (a*λest + b), Cp(λest))
Pr_est  ~ 0.5 *  ρ * A * Uest^3 * Γest *  Cp′,
λ       ~ ω * R/U,
Pr      ~ 0.5 * ρ * A * U^3 * Γ *  Cp′,
Pg      ~ Pgc + Pge]
``````

if `lin` is a `Bool`, `ifelse` will be evaluated when the equations are constructed, if `lin` is a symbolic expression then it will be evaluated when the equations are evaluated which may not be what you want.

3 Likes

lin is Bool

OK, your last version is a little bit wrong, because there is Cp(λ) and Cp(λest), but I get the idea…

It would make sense to have a `Cp()` function for both cases.
A simplified example:

``````using ModelingToolkit, OrdinaryDiffEq
using Plots

lin = true  # case distinction

function CpNew(λ::Float64, a::Float64, b::Float64)::Float64
if lin
a*λ + b
else
end
end

@register_symbolic CpNew(λ,a,b)

@variables t x(t)
@parameters a  b
D = Differential(t)
eqs = [ D(x) ~ CpNew(x, a, b)  ]
@named sys = ODESystem(eqs)
prob = ODEProblem(sys, [0.1], (0.0,5.0), [0.01, 0.5])
sol = solve(prob, Tsit5())

display(plot(sol))
display(sol)
``````
1 Like