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 (ExternalLibraries.mo) 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);
equation
der(x)=-ExternalFunc1(x);
der(y)=-ExternalFunc2(y);
end ExternalLibraries;
Error
[<interactive>:1:1-1:0:writable] Error: Variable currentSimulationResult not found in scope <global scope>.
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):
double ExternalFunc1_ext(double x)
{
double res;
res = x+2.0*x*x;
return res;
}
double ExternalFunc1_ext(double);
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")
0
>>> system(getCompiler() + " -c -o ExternalFunc2.o ExternalFunc2.c")
0
>>> system("ar rcs libExternalFunc2.a ExternalFunc2.o")
0
>>> 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.001279499,
timeBackend = 0.003529286,
timeSimCode = 0.001328772,
timeTemplates = 0.003156724,
timeCompile = 0.6416156,
timeSimulation = 0.024275388,
timeTotal = 0.67530159
end SimulationResult;
And plot the results:
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 */
Py_Initialize();
PyRun_SimpleString(str);
Py_Finalize();
}
");
end pyRunString;
model CallExternalPython
algorithm
pyRunString("
print 'Python says: simulation time',"+String(time)+"
");
end CallExternalPython;
>>> system("python-config --cflags > pycflags")
0
>>> system("python-config --ldflags > pyldflags")
0
>>> pycflags := stringReplace(readFile("pycflags"),"\n","");
>>> pyldflags := stringReplace(readFile("pyldflags"),"\n","");
>>> setCFlags(getCFlags()+pycflags)
true
>>> setLinkerFlags(getLinkerFlags()+pyldflags)
true
>>> 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.005897747,
timeBackend = 0.003838503,
timeSimCode = 0.001020327,
timeTemplates = 0.002750858,
timeCompile = 0.699621563,
timeSimulation = 0.06480922700000001,
timeTotal = 0.778148761
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:
model CalledbyPython
Real x(start=1.0), y(start=2.0);
parameter Real b = 2.0;
equation
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:
#!/usr/bin/python
import sys,os
global newb = 0.5
execfile('CreateMosFile.py')
os.popen(r"omc CalledbyPython.mos").read()
execfile('RetrResult.py')
#!/usr/bin/python
mos_file = open('CalledbyPython.mos','w', 1)
mos_file.write('loadFile("CalledbyPython.mo");\n')
mos_file.write('setComponentModifierValue(CalledbyPython,b,$Code(="+str(newb)+"));\n')
mos_file.write('simulate(CalledbyPython,stopTime=10);\n')
mos_file.close()
#!/usr/bin/python
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)):
time[j]=float(res\_file.readline().split(',')[0])
while line != ['DataSet: y\\n']:
line=res_file.readline().split(',')[0:1]
for j in range(int(size)):
y[j]=float(res\_file.readline().split(',')[1])
res_file.close()
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.