[PYTHON] Solve the initial value problem of ordinary differential equations with JModelica

Purpose / aim

For the environment construction method, refer to the article Installing JModelica on Ubuntu.

Basic usage of JModelica

  1. Prepare a Model file (* .mo)
  2. Compile to Function Mockup Units (FMUs)
  3. Load FMUs
  4. Calculate the loaded FMUs
  5. View results

Of course, it is also possible to read compiled FMUs from step 3.


Solve ordinary differential equations

According to Google Sensei, when you say Hello World in Modelica, there are many initial value problems of linear ordinary differential equations of the first order.

\begin{eqnarray}
\frac{dx(t)}{dt} &=& -x(t) \\
  x(0) & = & 1
\end{eqnarray}

The method of solving with paper and pencil is left to the textbook, and the derivation of the analytical solution is done with SymPy. Execute the following under the environment where SymPy can be used.

python


import sympy
x = sympy.Function("x"); t,C1 = sympy.symbols("t C1")
#x(t)Solve about x(t) == C1*exp(-t)
ans = sympy.dsolve(x(t).diff(t)+x(t),x(t))
#Calculate the constant of integration C1(t=0,x(0)=1)And substitute for the expression of ans
C = {C1:ans.subs(x(t),1).subs(t,0).lhs}
ans.subs(C)
#--> x(t) == exp(-t)

From the above, the analytical solution is as follows.

\begin{eqnarray}
  x(t) & = & \exp(-t)
\end{eqnarray}

Solve ordinary differential equations with JModelica

1. Preparation of model file

Prepare the following model file

ode_test.mo


model HelloWorld 
	Real x(start=1);
equation
	der(x)= -x;
end HelloWorld;

Lines 1-5: Model (class) definition 2nd line: Definition of state variable x with initial value 1 3rd line: The relational expression of each variable is defined below. Signal 4th line: Define the equation of dx / dt = -x


2. Compile the model into FMUs

Start JModelica in the model file directory. (Change the installation location as appropriate)

bash


/home/ubuntu/JModelica/bin/jm_ipython.sh

ipython


from pymodelica import compile_fmu
hello_fmu = compile_fmu("HelloWorld","./ode_test.mo")

3. Load FMUs

ipython


from pyfmi import load_fmu
hello_model = load_fmu(hello_fmu)

4. Calculate the loaded FMUs

Calculate for 1 second

ipython


res = hello_model.simulate(final_time=1)

5. View results

The result of the state variable x can be accessed with res ["x "]. Graph the above analytical solutions together.

ipython


import numpy as np
from matplotlib import pyplot as plt
t = np.linspace(0,1,101)
x = np.exp(-t) 
plt.plot(t, x, label="$x=e^(-t)$")
plt.plot(res["time"],res["x"],"--",label="JModelica")
plt.legend()
plt.show()

first_liner_ode.png


Solve ordinary differential equations with Assimulo

What is Assimulo

ipython


from assimulo.solvers import CVode
from assimulo.problem import Explicit_Problem
#Define a function that represents a differential equation
def ode_func(t,x):
    dxdt = -x[0]
    return np.array([dxdt])
#Define and calculate a model that includes explicit problems and integrators
exp_mod = Explicit_Problem(ode_func, 1) #The initial value of x is 1
exp_sim = CVode(exp_mod)
t1, x1 = exp_sim.simulate(1)#Calculation time 1 second
#Result plot
plt.plot(t, x, label="$x=\exp(-t)$")#Analytical solution calculated earlier
plt.plot(res["time"],res["x"],'--',label="JModelica")#Numerical solution of JModelica
plt.plot(t1,x1,'-.',label="assimulo")#Numerical solution of Assimulo
plt.legend()
plt.show()

first_liner_ode_assimulo.png


Summary

Recommended Posts

Solve the initial value problem of ordinary differential equations with JModelica
[Science / technical calculation by Python] Numerical solution of first-order ordinary differential equations, initial value problem, numerical calculation
[Scientific / technical calculation by Python] Numerical solution of second-order ordinary differential equations, initial value problem, numerical calculation
Solve simultaneous ordinary differential equations with Python and SymPy.
Solve ordinary differential equations in Python
Numerical analysis of ordinary differential equations with Scipy's odeint and ode
Try to solve the N Queens problem with SA of PyQUBO
Find the numerical solution of the second-order ordinary differential equation with scipy
Numerical calculation of differential equations with TensorFlow 2.0
Solve the traveling salesman problem with OR-Tools
Try to solve the fizzbuzz problem with Keras
[AtCoder] Solve A problem of ABC101 ~ 169 with Python
Solving ordinary differential equations with Python ~ Universal gravitation
[At Coder] Solve the problem of binary search
Initial value problem of NMF (Nonnegative Matrix Factorization)
Take the value of SwitchBot thermo-hygrometer with Raspberry Pi
Log the value of SwitchBot thermo-hygrometer with Raspberry Pi
I tried to solve the problem with Python Vol.1
The 15th offline real-time I tried to solve the problem of how to write with python
Your URL didn't respond with the value of the challenge parameter.
The true value of Terraform automation starting with Oracle Cloud
Solve the Monty Hall problem
Solve the problem of missing libcudart in Ubuntu 16.04 + CUDA 8.0 + Tensorflow environment
Find the optimal value of a function with a genetic algorithm (Part 2)
I wanted to solve the ABC164 A ~ D problem with Python
Solve the Python knapsack problem with a branch and bound method
Tips: [Python] Calculate the average value of the specified area with bedgraph
Solve the subset sum problem with a full search in Python
Periodically log the value of Omron environment sensor with Raspberry Pi
I want to solve the problem of memory leak when outputting a large number of images with Matplotlib
Find the definition of the value of errno
Extract the maximum value with pandas.
About the return value of pthread_mutex_init ()
Solve the delay of interferometer observation
About the return value of the histogram.
Illustration of the results of the knapsack problem
Use Raspberry Pi to solve the problem of insufficient mobile Wi-Fi connection
The 16th offline real-time how to write reference problem to solve with Python
Try to solve the traveling salesman problem with a genetic algorithm (Theory)
The 19th offline real-time how to write reference problem to solve with Python
Logging the value of Omron environment sensor with Raspberry Pi (USB type)
Try to solve a set problem of high school math with Python
Get the return value of an external shell script (ls) with python3