Search code examples
pythoninterfacesyntax-errordymola

How to locate models in the python interface for Dymola?


I want to run Dymola via python, so I am using the python interface that is delivered with Dymola and all is working well.

So Dymola gives an example for the python interface (within Dymola > Modelica > library > python_interface > examples > DymolaExample.py)

import platform

from dymola.dymola_interface import DymolaInterface
from dymola.dymola_exception import DymolaException

osString = platform.system()
isWindows = osString.startswith("Win")

dymola = None
try:
    # Instantiate the Dymola interface and start Dymola
    dymola = DymolaInterface()

    # Call a function in Dymola 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.getLastErrorLog()
        print(log)
        exit(1)

    dymola.plot(["J1.w", "J2.w", "J3.w", "J4.w"])
    if (isWindows):
        plotPath = "C:/temp/plot.png"
    else:
        plotPath = "/tmp/plot.png";
    dymola.ExportPlotAsImage(plotPath)
    print("OK")
except DymolaException as ex:
    print(("Error: " + str(ex)))
finally:
    if dymola is not None:
        dymola.close()
        dymola = None

Now, they give an example, namely: result = dymola.simulateModel("Modelica.Mechanics.Rotational.Examples.CoupledClutches") but I want to change the model of course, which is located in a totally different directory (just in in a random folder on my personal computer).

How do I do this?

I tried changing result = dymola.simulateModel("Modelica.Mechanics.Rotational.Examples.CoupledClutches")

to result = dymola.simulateModel("C:\Users\to the location where my model is located.name_of_package.name_of_model")

but this gave a syntex error: File <unknown>:21 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape


Solution

  • There are a number of possibilities:

    • Directly opening the file dymola.openModel("C:/Users/to the location where my model is located/MyModel.mo") - Read the documentation, it as default automatically changes directory.
    • Change Dymola's directory to where your model is located using dymola.cd("C:/Users/to the location where my model is located"). Assuming the model MyModel is stored in MyModel.mo or as a directory MyModel (with package.mo) that should then work.
    • Setting the environment variable MODELICAPATH to include "C:/Users/to the location where my model is located". (not sure exactly how.)