Interoperability – C and Python

Below is information and examples about the OpenModelica external C interfaces, as well as examples of Python interoperability.

Calling External C functions

The following is a small example ( to show the use of external C functions:

model ExternalLibraries

  function ExternalFunc1
    input Real x;
    output Real y;
  external y=ExternalFunc1_ext(x) annotation(Library="ExternalFunc1.o", LibraryDirectory="modelica://ExternalLibraries", Include="#include \"ExternalFunc1.h\"");
  end ExternalFunc1;

  function ExternalFunc2
    input Real x;
    output Real y;
  external "C" annotation(Library="ExternalFunc2", LibraryDirectory="modelica://ExternalLibraries");
  end ExternalFunc2;

  Real x(start=1.0, fixed=true), y(start=2.0, fixed=true);
end ExternalLibraries;

These C (.c) files and header files (.h) are needed (note that the headers are not needed since OpenModelica will generate the correct definition if it is not present; using the headers it is possible to write C-code directly in the Modelica source code or declare non-standard calling conventions):

Listing 8 ExternalFunc1.c
double ExternalFunc1_ext(double x)
  double res;
  res = x+2.0*x*x;
  return res;
Listing 9 ExternalFunc1.h
double ExternalFunc1_ext(double);
Listing 10 ExternalFunc2.c
double ExternalFunc2(double x)
  double res;
  res = (x-1.0)*(x+2.0);
  return res;

The following script file ExternalLibraries.mos will perform everything that is needed, provided you have gcc installed in your path:

>>> system(getCompiler() + " -c -o ExternalFunc1.o ExternalFunc1.c")
>>> system(getCompiler() + " -c -o ExternalFunc2.o ExternalFunc2.c")
>>> system("ar rcs libExternalFunc2.a ExternalFunc2.o")
>>> simulate(ExternalLibraries)
record SimulationResult
    resultFile = "«DOCHOME»/ExternalLibraries_res.mat",
    simulationOptions = "startTime = 0.0, stopTime = 1.0, numberOfIntervals = 500, tolerance = 1e-06, method = 'dassl', fileNamePrefix = 'ExternalLibraries', options = '', outputFormat = 'mat', variableFilter = '.*', cflags = '', simflags = ''",
    messages = "LOG_SUCCESS       | info    | The initialization finished successfully without homotopy method.
LOG_SUCCESS       | info    | The simulation finished successfully.
    timeFrontend = 0.006996472,
    timeBackend = 0.003135553,
    timeSimCode = 0.043587842,
    timeTemplates = 0.0249698,
    timeCompile = 0.5688452970000001,
    timeSimulation = 0.012719897,
    timeTotal = 0.6604026590000001
end SimulationResult;

And plot the results:


Figure 99 Plot generated by OpenModelica+gnuplot

Calling external Python Code from a Modelica model

The following calls external Python code through a very simplistic external function (no data is retrieved from the Python code). By making it a dynamically linked library, you might get the code to work without changing the linker settings.

function pyRunString
  input String s;
external "C" annotation(Include="
#include <Python.h>

void pyRunString(const char *str)
  Py_SetProgramName(\"pyRunString\");  /* optional but recommended */
end pyRunString;

model CallExternalPython
print 'Python says: simulation time',"+String(time)+"
end CallExternalPython;
>>> system("python-config --cflags > pycflags")
>>> system("python-config --ldflags > pyldflags")
>>> pycflags := stringReplace(readFile("pycflags"),"\n","");
>>> pyldflags := stringReplace(readFile("pyldflags"),"\n","");
>>> setCFlags(getCFlags()+pycflags)
>>> setLinkerFlags(getLinkerFlags()+pyldflags)
>>> simulate(CallExternalPython, stopTime=2)
record SimulationResult
    resultFile = "«DOCHOME»/CallExternalPython_res.mat",
    simulationOptions = "startTime = 0.0, stopTime = 2.0, numberOfIntervals = 500, tolerance = 1e-06, method = 'dassl', fileNamePrefix = 'CallExternalPython', options = '', outputFormat = 'mat', variableFilter = '.*', cflags = '', simflags = ''",
    messages = "Python says: simulation time 0
Python says: simulation time 0
LOG_SUCCESS       | info    | The initialization finished successfully without homotopy method.
Python says: simulation time 2
LOG_SUCCESS       | info    | The simulation finished successfully.
    timeFrontend = 0.00327731,
    timeBackend = 0.005025064,
    timeSimCode = 0.043988795,
    timeTemplates = 0.02633167,
    timeCompile = 0.666112764,
    timeSimulation = 0.042998065,
    timeTotal = 0.7878471970000001
end SimulationResult;

Calling OpenModelica from Python Code

This section describes a simple-minded approach to calling Python code from OpenModelica. For a description of Python scripting with OpenModelica, see OMPython – OpenModelica Python Interface.

The interaction with Python can be perfomed in four different ways whereas one is illustrated below. Assume that we have the following Modelica code:

Listing 11
model CalledbyPython
  Real x(start=1.0), y(start=2.0);
  parameter Real b = 2.0;
  der(x) = -b*y;
  der(y) = x;
end CalledbyPython;

In the following Python (.py) files the above Modelica model is simulated via the OpenModelica scripting interface:

Listing 12
import sys,os
global newb = 0.5
os.popen(r"omc CalledbyPython.mos").read()
Listing 13
mos_file = open('CalledbyPython.mos','w', 1)
Listing 14
def zeros(n): #
  vec = [0.0]
  for i in range(int(n)-1): vec = vec + [0.0]
  return vec
res_file = open("CalledbyPython_res.plt",'r',1)
line = res_file.readline()
size = int(res_file.readline().split('=')[1])
time = zeros(size)
y = zeros(size)
while line != ['DataSet: time\\n']:
  line = res_file.readline().split(',')[0:1]
for j in range(int(size)):
while line != ['DataSet: y\\n']:
for j in range(int(size)):

A second option of simulating the above Modelica model is to use the command buildModel instead of the simulate command and setting the parameter value in the initial parameter file, CalledbyPython_init.txt instead of using the command setComponentModifierValue. Then the file CalledbyPython.exe is just executed.

The third option is to use the Corba interface for invoking the compiler and then just use the scripting interface to send commands to the compiler via this interface.

The fourth variant is to use external function calls to directly communicate with the executing simulation process.