Example
This section shows a simple Python scripting example for simulating a
Dymola Behavior Modeling
model called
CoupledClutches.
Note:
Before executing the following example, you need to start the HTTP
server from a
Dymola Behavior Modeling
session. For more information, see
Launching HTTP Server.
from dymola.dymola_interface import DymolaInterface
from dymola.dymola_exception import DymolaException
dymola = None
try:
# Instantiate the DBM interface and start Dymola
dymola = DymolaInterface(startDymola=False, port=44000)
# Call a function in DBM and check its return value
result = dymola.simulateModel("Modelica.Mechanics.Rotational.Examples.CoupledClutches")
if not result:
print("Simulation failed. Below is the translation log.")
log = dymola.getLastError()
print(log)
exit(1)
dymola.plot(["J1.w", "J2.w", "J3.w", "J4.w"])
dymola.ExportPlotAsImage("C:/temp/plot.png")
print("OK")
except DymolaException as ex:
print("Error: " + str(ex))
finally:
if dymola is not None:
dymola.close()
dymola = None
Correspondence:
Dymola Behavior Modeling
and Python Interface
There is one-to-one correspondence between the parameters of a
Dymola Behavior Modeling
command and the parameters of a Python method. If default value for a parameter
exits, it can be found in the documentation for that parameter. The list of
available commands can be found in the directory
.\win_b64\resources\Dymola\python_interface\doc.
You can start by opening the home page
index.html.
Note:
In the Python interface documentation, default values and array
dimensions are formatted as in Modelica.
The following table illustrates the correspondence using a
function
simulateModel . An example call can be written as:
result = dymola.simulateModel("MotorDriveTest", 0, 1.2,
resultFile="MotorDriveTest")
- Dymola Behavior Modeling
Implementation
-
Function simulateModel "simulate a Modelica model"
input String problem := "" "Name of model, e.g. Modelica.Mechanics
.Rotational.Components.Clutch";
input Real startTime := 0.0 "Start of simulation";
input Real stopTime := 1.0 "End of simulation";
input Integer numberOfIntervals := 0 "Number of output points";
input Real outputInterval := 0.0 "Distance between output points";
input String method := "Dassl" "Integration method";
input Real tolerance := 0.0001 "Tolerance of integration";
input Real fixedstepsize := 0.0 "Fixed step size for Euler";
input String resultFile := "dsres" "Where to store result";
output Boolean result "true if successful";
external "builtin";
annotation(Documentation(info="If not done: translate a model from
Modelica into simulation code (see translateModel).
Then simulate with the given parameters"));
end simulateModel;
- Python Interface Implementation
-
simulateModel(problem="", startTime=0.0, stopTime=1.0, numberOfIntervals=0, outputInterval=0.0, method='Dassl', tolerance=0.0001, fixedstepsize=0.0, resultFile='dsres')
Dymola Interface Commands
Following table illustrates some of the commonly used functions in
Dymola interface.
How To?
|
Solution
|
Details
|
Execute a command which is not part of the
Python interface
|
Function:
dymola.ExecuteCommand("a=1")
|
The function takes a string parameter which
may contain a command or an expression.
Note:
You have to ensure that the command is valid as it is not
type checked.
|
Get the translation and simulation log
|
Function:
getLastError
result =
dymola.translateModel(
"Modelica.Mechanics.Rotational.Examples.CoupledClutches")
if not result:
print("Translation failed.")
log = dymola.getLastError()
print(log)
|
The fucntion returns the last error in text
format.
Note:
Issuing a new command will erase the contents of
getLastError .
|
Exit Dymola/Dymola Behavior Modeling
session
|
Function:
DymolaInterface.close()
dymola = None
try:
dymola = DymolaInterface()
...
except DymolaException as ex:
print("Error: " + str(ex))
finally:
if dymola is not None:
dymola.close()
dymola = None
|
It is a good practice to enclose the
interface calls in a
try/except block and close Dymola in the
finally block.
|
Simulate a model with set parameters and
start values
|
Function:
simulateExtendedModel()
Function call:
simulateExtendedModel(
"Modelica.Mechanics.Rotational.Examples.CoupledClutches",
initialNames={"J1.J","J2.J"},
initialValues={2,3},
finalNames={"J1.w","J4.w"})
Response:
= true, {6.213412958654296, 1.000000000000004}
|
The function returns two values, a Boolean status flag and a
vector of values. The output parameters are available as elements in a list.
The corresponding call in the Python interface is shown below:
output = dymola.simulateExtendedModel(
"Modelica.Mechanics.Rotational.Examples.CoupledClutches",
0.0, 1.0, 0, 0.0, "Dassl", 0.0001, 0.0,"test3",
["J1.J", "J2.J"], [2, 3], ["J1.w", "J4.w" ], True)
status = output[0]
values = output[1]
J1_w = values[0]
J4_w = values[1]
|
Simulate multiple models with set
parameters and start values
|
Function:
simulateMultiExtendedModel()
Function call:
simulateMultiExtendedModel(
"Modelica.Mechanics.Rotational.Examples.CoupledClutches",
initialNames={"J1.J","J2.J"},
initialValues=[2,3;3,4;4,5],
finalNames={"J1.w","J4.w"});
Response:
= true,[6.213412958654296, 1.000000000000004;
7.483558191010655, 1.000000000000003;
8.107446379737779, 0.9999999999999931]
|
The function returns two values, a Boolean status flag and a
two-dimensional array of values. The corresponding call in the Python interface
is shown below:
initialValues = [[2, 3], [3, 4], [4, 5]]
output = dymola.simulateMultiExtendedModel(
"Modelica.Mechanics.Rotational.Examples.CoupledClutches",
0.0, 1.0, 0, 0.0, "Dassl", 0.0001, 0.0, "dsres",
["J1.J", "J2.J"], initialValues, ["J1.w","J4.w"])
status = output[0]
values = output[1]
result1 = values[0]
J1_w = result1[0]
J4_w = result1[1]
result2 = values[1]
J1_w = result2[0]
J4_w = result2[1]
result3 = values[2]
J1_w = result3[0]
J4_w = result3[1]
|
Virtual Execution Interface Commands
Following table illustrates some of the commonly used functions in
virtual execution interface. Some examples can be found in
.\win_b64\code\python2.7\lib\catsysekpythonnodetst.
How To?
|
Solution
|
Details
|
Start a new
Dymola Behavior Modeling
session with a opened HTTP server
|
Service:
CATSysEKPythonHttpNode()
Example:
from catsysekpythonnode.catsysekpythonhttpnode import CATSysEKPythonHttpNode
from catsysekpythonnode.catsysekpythonfmunode import CATSysEKPythonNodeFMU
from catsysekpythonnode.catsysekpythonfmunode import CATSysEKPythonNodeCore
from dymola.dymola_interface import DymolaInterface
from dymola.dymola_exception import DymolaException
nodehttp=CATSysEKPythonHttpNode()
port=nodehttp.startHttpServer()
dbm = DymolaInterface(port=port, startDymola=False)
dbm.openModelFile("Modelica","","3.2.2")
# retrieve current directory of the node
corenode=CATSysEKPythonNodeCore(nodehttp)
dir=corenode.pwd()
#export to FMU
file = dbm.translateModelFMU(
"Modelica.Mechanics.Rotational.Examples.CoupledClutches",
fmiType="csSolver")
fmupath=dir+file+".fmu"
# run the FMU
fmu=CATSysEKPythonNodeFMU()
rc=fmu.load(fmupath)
rc=fmu.setStartValueByName("J1.J",2.5)
rc=fmu.start()
rc=fmu.runTo(1.5)
val=fmu.getValueByName(name="J1.w")
vals=fmu.getNumericalValueHistory( "J1.w")
rc=fmu.stop()
nodehttp.stopHttpServer()
nodehttp=None
corenode=None
fmu=None
fmucorenode=None
dbm=None
|
CATSysEKPythonHttpNode is
a service contained in
catsysekpythonhttpnode.pyc which allows you to
start a new
Dymola Behavior Modeling
session, with a opened HTTP server. This session can be used by DymolaInterface
for python to execute commands. Also using this API you can create and work on
several
Dymola Behavior Modeling
sessions in parallel.
For more information on available methods of the service,
use the following help function:
help(CATSysEKPythonHttpNode)
|
Simulate a FMU
|
Service:
CATSysEKPythonNodeFMU()
Example:
import catsysekpythonnode
from catsysekpythonnode.catsysekpythonfmunode import *
fmudir="e:\temp\python\CoupledClutches.fmu"
fmu=CATSysEKPythonNodeFMU()
fmu.load(fmuPath=fmudir)
fmu.setStartValueByName("J1.J",2.5)
fmu.start()
fmu.runTo(time=1.5)
fmu.getValueByName(name="J1.w")
fmu.getNumericalValueHistory(name="J1.w")
fmu.stop()
fmu=None
|
CATSysEKPythonNodeFMU is a
service contained in
catsysekpythonfmunode.pyc which allows you to
simulate a FMU.
For more information on available methods of the service,
use the following help function:
help(CATSysEKPythonFmu)
|
Simulate multiple FMUs in parallel
|
Service:
CATSimulateMultiFMU()
Example:
import catsysekpythonnode
from catsysekpythonnode.catsysekpythonfmunode import CATSimulateMultiFMU
fmudir="e:\temp\python\CoupledClutches.fmu"
values=[[i,i+1] for i in range(2,8)]
fmu_MP=CATSimulateMultiFMU(
fmupath=fmudir,startTime=0,stopTime=1.5,names=["J1.J","J2.J"],
values=values,finalNames=["J1.w","J4.w"],
resultNames=["J1.w","J2.w"],nbThreadsMax=6)
resfinal=fmu_MP.getFinalResults()
res_history=fmu_MP.getResults()
print(resfinal,res_history)
|
CATSimulateMultiFMU a
service contained in
catsysekpythonfmunode.pyc which allows you to
simulate multiple FMUs in parallel.
For more information on available methods of the service,
use the following help function:
help(CATSimulateMultiFMU)
|
|