This page shows how to compile and run a Modelica model in Python, using the FMI standard.
The PyFMI package is required, which is only compatible with Python 2.7. The easiest way for a functional PyFMI framework is to install the JModelica platform and to run Python scripts from its IPython or pylab console. The JModelica installer includes a Python 2.7 distribution, which you can use in addition to an eventual other one.
This exercise requires the Annex60 Modelica library. Before running the code, the ppath
variable below should point to the location of this library on your drive.
#==============================================================================
# Compile the FMU from the .mo file
#==============================================================================
from pymodelica import compile_fmu
ppath = 'C:\\path_to_the_annex60_library_on_your_drive'
model_name = 'Annex60.Controls.Continuous.Examples.PIDHysteresis'
fmu1 = compile_fmu(model_name, ppath)
#==============================================================================
# Loading the FMU
#==============================================================================
# Without JModelica, you can skip the part above and load a .fmu file that
# has been generated by another simulator
from pyfmi import load_fmu
PID = load_fmu('Buildings_Controls_Continuous_Examples_PIDHysteresis.fmu')
# Choice of the time discretisation
tStart = 0
tStop = 3600*24
# Simulation
Tset_init = PID.get('TSet.k')
PID.set('TSet.k', 273.15 + 40)
PID_res = PID.simulate(tStart, tStop)
# Extract output values from the dictionary PID_res
t = PID_res['time']
T = PID_res['temSen.T']
y = PID_res['con.y']
#==============================================================================
# Plotting results
#==============================================================================
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(211)
ax.plot(t/3600, T-273.15, '-k', linewidth = 1.5, label = 'T')
ax.set_xlabel('Time (h)')
ax.set_ylabel('Temperature (C)')
ax.legend()
ax = fig.add_subplot(212)
ax.plot(t/3600, y, '-b', linewidth = 1.5, label = 'y')
ax.set_xlabel('Time (h)')
ax.set_ylabel('y')
ax.legend(loc = 'lower right')
plt.savefig('JModelica_Ex1_plot.png')