Converting parameters to variables

This can be useful to replace a parameter that does not change in time in a model component with one specified by another system that does change in time (or space). For example, the code below specifies a first-order loss equation, and then changes the temperature (which determines the loss rate) with a temperature value that varies in time.

As an example, we will create a loss equation that depends on the temperature, starting with a constant temperature. We will then create a temperature equation that varies in time, and use the param_to_var function to replace the constant temperature in the loss equation with the time-varying temperature.

So first, let's specify the original system with constant temperature.

using ModelingToolkit, EarthSciMLBase, Unitful

@variables t [unit=u"s", description="time"]

function Loss(t)
    @variables A(t)=1 [unit=u"kg"]
    @parameters k=1 [unit=u"s^-1"]
    @parameters T=300 [unit=u"K"]
    @constants T₀=300 [unit=u"K"]
    eq = Differential(t)(A) ~ -k*exp(T/T₀) * A
    ODESystem([eq]; name=:Docs₊Loss)
end

Loss(t)

\[ \begin{align} \frac{\mathrm{d} A\left( t \right)}{\mathrm{d}t} =& - k e^{\frac{T}{T_0}} A\left( t \right) \end{align} \]

Next, we specify the temperature that varies in time.

function Temperature(t)
    @variables T(t)=300 [unit=u"K"]
    @constants Tc=1.0 [unit=u"K/s"]
    @constants tc=1.0 [unit=u"s"]
    eq = Differential(t)(T) ~ sin(t/tc)*Tc
    ODESystem([eq]; name=:Docs₊Temperature)
end

Temperature(t)

\[ \begin{align} \frac{\mathrm{d} T\left( t \right)}{\mathrm{d}t} =& Tc \sin\left( \frac{t}{tc} \right) \end{align} \]

Now, we specify how to compose the two systems using param_to_var.

register_coupling(Loss(t), Temperature(t)) do loss, temp
    loss = param_to_var(loss, :T)
    ConnectorSystem([loss.T ~ temp.T], loss, temp)
end
#1 (generic function with 1 method)

Finally, we create the system components and the composed system.

l = Loss(t)
t = Temperature(t)
variable_loss = couple(l, t)

get_mtk(variable_loss)

\[ \begin{align} Docs_{+}Loss_{+}T\left( t \right) =& Docs_{+}Temperature_{+}T\left( t \right) \\ \frac{\mathrm{d} Docs_{+}Loss_{+}A\left( t \right)}{\mathrm{d}t} =& - Docs_{+}Loss_{+}k Docs_{+}Loss_{+}A\left( t \right) e^{\frac{Docs_{+}Loss_{+}T\left( t \right)}{Docs_{+}Loss_{+}T_0}} \\ \frac{\mathrm{d} Docs_{+}Temperature_{+}T\left( t \right)}{\mathrm{d}t} =& Docs_{+}Temperature_{+}Tc \sin\left( \frac{t}{Docs_{+}Temperature_{+}tc} \right) \end{align} \]

If we wanted to, we could then run a simulation with the composed system.