2. A first example

This example focuses on how to use JModelica.org's simulation functionality in the most basic way. The model which is to be simulated is the Van der Pol problem described in the code below. The model is also available from the examples in JModelica.org in the file VDP.mop.

model VDP
    // State start values
    parameter Real x1_0 = 0;
    parameter Real x2_0 = 1;

    // The states
    Real x1(start = x1_0);
    Real x2(start = x2_0);

    // The control signal
    input Real u;

  equation
    der(x1) = (1 - x2^2) * x1 - x2 + u;
    der(x2) = x1;
end VDP;

Create a new file in your working directory called VDP.mo and save the model.

Next, create a Python script file and write (or copy paste) the commands for compiling and loading a model:

# Import the function for compilation of models and the load_fmu method
from pymodelica import compile_fmu
from pyfmi import load_fmu

# Import the plotting library
import matplotlib.pyplot as plt

Next, we compile and load the model:

# Compile model
fmu_name = compile_fmu("VDP","VDP.mo")

# Load model
vdp = load_fmu(fmu_name)

The function compile_fmu compiles the model into a binary, which is then loaded when the vdp object is created. This object represents the compiled model, an FMU, and is used to invoke the simulation algorithm (for more information about model creations and options, see Chapter 4, Working with Models):

res = vdp.simulate(final_time=10)

In this case we use the default simulation algorithm together with default options, except for the final time which we set to 10. The result object can now be used to access in a dictionary-like way the simulation result:

x1 = res['x1']
x2 = res['x2']
t  = res['time']

The variable trajectories are returned as NumPy arrays and can be used for further analysis of the simulation result or for visualization:

plt.figure(1)
plt.plot(t, x1, t, x2)
plt.legend(('x1','x2'))
plt.title('Van der Pol oscillator.')
plt.ylabel('Angle (rad)')
plt.xlabel('Time (s)')
plt.show()

In Figure 5.1, “Simulation result of the Van der Pol oscillator.” the simulation result is shown.

Figure 5.1. Simulation result of the Van der Pol oscillator.

Simulation result of the Van der Pol oscillator.