Skip to content
86 changes: 44 additions & 42 deletions OMPython/ModelicaSystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,18 +329,18 @@ class ModelicaSystem:

def __init__(
self,
commandLineOptions: Optional[list[str]] = None,
customBuildDirectory: Optional[str | os.PathLike] = None,
command_line_options: Optional[list[str]] = None,
work_directory: Optional[str | os.PathLike] = None,
omhome: Optional[str] = None,
omc_process: Optional[OMCProcess] = None,
) -> None:
"""Create a ModelicaSystem instance. To define the model use model() or convertFmu2Mo().

Args:
commandLineOptions: List with extra command line options as elements. The list elements are
command_line_options: List with extra command line options as elements. The list elements are
provided to omc via setCommandLineOptions(). If set, the default values will be overridden.
To disable any command line options, use an empty list.
customBuildDirectory: Path to a directory to be used for temporary
work_directory: Path to a directory to be used for temporary
files like the model executable. If left unspecified, a tmp
directory will be created.
omhome: path to OMC to be used when creating the OMC session (see OMCSessionZMQ).
Expand Down Expand Up @@ -378,20 +378,20 @@ def __init__(
self._session = OMCSessionZMQ(omhome=omhome)

# set commandLineOptions using default values or the user defined list
if commandLineOptions is None:
if command_line_options is None:
# set default command line options to improve the performance of linearization and to avoid recompilation if
# the simulation executable is reused in linearize() via the runtime flag '-l'
commandLineOptions = [
command_line_options = [
"--linearizationDumpLanguage=python",
"--generateSymbolicLinearization",
]
for opt in commandLineOptions:
self.setCommandLineOptions(commandLineOptions=opt)
for opt in command_line_options:
self.set_command_line_options(command_line_option=opt)

self._simulated = False # True if the model has already been simulated
self._result_file: Optional[OMCPath] = None # for storing result file

self._work_dir: OMCPath = self.setWorkDirectory(customBuildDirectory)
self._work_dir: OMCPath = self.setWorkDirectory(work_directory)

self._model_name: Optional[str] = None
self._libraries: Optional[list[str | tuple[str, str]]] = None
Expand All @@ -400,8 +400,8 @@ def __init__(

def model(
self,
name: Optional[str] = None,
file: Optional[str | os.PathLike] = None,
model_name: Optional[str] = None,
model_file: Optional[str | os.PathLike] = None,
libraries: Optional[list[str | tuple[str, str]]] = None,
variable_filter: Optional[str] = None,
build: bool = True,
Expand All @@ -411,9 +411,9 @@ def model(
This method loads the model file and builds it if requested (build == True).

Args:
file: Path to the model file. Either absolute or relative to
model_file: Path to the model file. Either absolute or relative to
the current working directory.
name: The name of the model class. If it is contained within
model_name: The name of the model class. If it is contained within
a package, "PackageName.ModelName" should be used.
libraries: List of libraries to be loaded before the model itself is
loaded. Two formats are supported for the list elements:
Expand All @@ -439,7 +439,7 @@ def model(
raise ModelicaSystemError("Can not reuse this instance of ModelicaSystem "
f"defined for {repr(self._model_name)}!")

if name is None or not isinstance(name, str):
if model_name is None or not isinstance(model_name, str):
raise ModelicaSystemError("A model name must be provided!")

if libraries is None:
Expand All @@ -449,16 +449,16 @@ def model(
raise ModelicaSystemError(f"Invalid input type for libraries: {type(libraries)} - list expected!")

# set variables
self._model_name = name # Model class name
self._model_name = model_name # Model class name
self._libraries = libraries # may be needed if model is derived from other model
self._variable_filter = variable_filter

if self._libraries:
self._loadLibrary(libraries=self._libraries)

self._file_name = None
if file is not None:
file_path = pathlib.Path(file)
if model_file is not None:
file_path = pathlib.Path(model_file)
# special handling for OMCProcessLocal - consider a relative path
if isinstance(self._session.omc_process, OMCProcessLocal) and not file_path.is_absolute():
file_path = pathlib.Path.cwd() / file_path
Expand Down Expand Up @@ -487,11 +487,11 @@ def session(self) -> OMCSessionZMQ:
"""
return self._session

def setCommandLineOptions(self, commandLineOptions: str):
def set_command_line_options(self, command_line_option: str):
"""
Set the provided command line option via OMC setCommandLineOptions().
"""
exp = f'setCommandLineOptions("{commandLineOptions}")'
exp = f'setCommandLineOptions("{command_line_option}")'
self.sendExpression(exp)

def _loadFile(self, fileName: OMCPath):
Expand Down Expand Up @@ -522,15 +522,15 @@ def _loadLibrary(self, libraries: list):
'1)["Modelica"]\n'
'2)[("Modelica","3.2.3"), "PowerSystems"]\n')

def setWorkDirectory(self, customBuildDirectory: Optional[str | os.PathLike] = None) -> OMCPath:
def setWorkDirectory(self, work_directory: Optional[str | os.PathLike] = None) -> OMCPath:
"""
Define the work directory for the ModelicaSystem / OpenModelica session. The model is build within this
directory. If no directory is defined a unique temporary directory is created.
"""
if customBuildDirectory is not None:
workdir = self._session.omcpath(customBuildDirectory).absolute()
if work_directory is not None:
workdir = self._session.omcpath(work_directory).absolute()
if not workdir.is_dir():
raise IOError(f"Provided work directory does not exists: {customBuildDirectory}!")
raise IOError(f"Provided work directory does not exists: {work_directory}!")
else:
workdir = self._session.omcpath_tempdir().absolute()
if not workdir.is_dir():
Expand Down Expand Up @@ -1709,8 +1709,8 @@ def convertFmu2Mo(
raise ModelicaSystemError(f"Missing file {filepath.as_posix()}")

self.model(
name=f"{fmu_path.stem}_me_FMU",
file=filepath,
model_name=f"{fmu_path.stem}_me_FMU",
model_file=filepath,
)

return filepath
Expand Down Expand Up @@ -1744,7 +1744,7 @@ def optimize(self) -> dict[str, Any]:
"""
cName = self._model_name
properties = ','.join(f"{key}={val}" for key, val in self._optimization_options.items())
self.setCommandLineOptions("-g=Optimica")
self.set_command_line_options("-g=Optimica")
optimizeResult = self._requestApi(apiName='optimize', entity=cName, properties=properties)

return optimizeResult
Expand Down Expand Up @@ -1926,8 +1926,8 @@ def run_doe():
resdir.mkdir(exist_ok=True)

doe_mod = OMPython.ModelicaSystemDoE(
fileName=model.as_posix(),
modelName="M",
model_name="M",
model_file=model.as_posix(),
parameters=param,
resultpath=resdir,
simargs={"override": {'stopTime': 1.0}},
Expand Down Expand Up @@ -1955,12 +1955,12 @@ def run_doe():
def __init__(
self,
# data to be used for ModelicaSystem
fileName: Optional[str | os.PathLike] = None,
modelName: Optional[str] = None,
lmodel: Optional[list[str | tuple[str, str]]] = None,
commandLineOptions: Optional[list[str]] = None,
variableFilter: Optional[str] = None,
customBuildDirectory: Optional[str | os.PathLike] = None,
model_file: Optional[str | os.PathLike] = None,
model_name: Optional[str] = None,
libraries: Optional[list[str | tuple[str, str]]] = None,
command_line_options: Optional[list[str]] = None,
variable_filter: Optional[str] = None,
work_directory: Optional[str | os.PathLike] = None,
omhome: Optional[str] = None,
omc_process: Optional[OMCProcess] = None,
# simulation specific input
Expand All @@ -1976,21 +1976,23 @@ def __init__(
ModelicaSystem.simulate(). Additionally, the path to store the result files is needed (= resultpath) as well as
a list of parameters to vary for the Doe (= parameters). All possible combinations are considered.
"""
if model_name is None:
raise ModelicaSystemError("No model name provided!")

self._mod = ModelicaSystem(
commandLineOptions=commandLineOptions,
customBuildDirectory=customBuildDirectory,
command_line_options=command_line_options,
work_directory=work_directory,
omhome=omhome,
omc_process=omc_process,
)
self._mod.model(
file=fileName,
name=modelName,
libraries=lmodel,
variable_filter=variableFilter,
model_file=model_file,
model_name=model_name,
libraries=libraries,
variable_filter=variable_filter,
)

self._model_name = modelName
self._model_name = model_name

self._simargs = simargs
self._timeout = timeout
Expand Down Expand Up @@ -2046,7 +2048,7 @@ def prepare(self) -> int:

build_dir = self._resultpath / f"DOE_{idx_pc_structure:09d}"
build_dir.mkdir()
self._mod.setWorkDirectory(customBuildDirectory=build_dir)
self._mod.setWorkDirectory(work_directory=build_dir)

sim_param_structure = {}
for idx_structure, pk_structure in enumerate(param_structure.keys()):
Expand Down
4 changes: 2 additions & 2 deletions tests/test_FMIExport.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
def test_CauerLowPassAnalog():
mod = OMPython.ModelicaSystem()
mod.model(
name="Modelica.Electrical.Analog.Examples.CauerLowPassAnalog",
model_name="Modelica.Electrical.Analog.Examples.CauerLowPassAnalog",
libraries=["Modelica"],
)
tmp = pathlib.Path(mod.getWorkDirectory())
Expand All @@ -21,7 +21,7 @@ def test_CauerLowPassAnalog():
def test_DrumBoiler():
mod = OMPython.ModelicaSystem()
mod.model(
name="Modelica.Fluid.Examples.DrumBoiler.DrumBoiler",
model_name="Modelica.Fluid.Examples.DrumBoiler.DrumBoiler",
libraries=["Modelica"],
)
tmp = pathlib.Path(mod.getWorkDirectory())
Expand Down
4 changes: 2 additions & 2 deletions tests/test_FMIImport.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def test_FMIImport(model_firstorder):

# create model & simulate it
mod1 = OMPython.ModelicaSystem()
mod1.model(file=filePath, name="M")
mod1.model(model_file=filePath, model_name="M")
mod1.simulate()

# create FMU & check
Expand All @@ -33,7 +33,7 @@ def test_FMIImport(model_firstorder):

# import FMU & check & simulate
# TODO: why is '--allowNonStandardModelica=reinitInAlgorithms' needed? any example without this possible?
mod2 = OMPython.ModelicaSystem(commandLineOptions=['--allowNonStandardModelica=reinitInAlgorithms'])
mod2 = OMPython.ModelicaSystem(command_line_options=['--allowNonStandardModelica=reinitInAlgorithms'])
mo = mod2.convertFmu2Mo(fmu=fmu)
assert os.path.exists(mo)

Expand Down
38 changes: 19 additions & 19 deletions tests/test_ModelicaSystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ def worker():
filePath = model_firstorder.as_posix()
mod = OMPython.ModelicaSystem()
mod.model(
file=filePath,
name="M",
model_file=filePath,
model_name="M",
)
mod.simulate()
mod.convertMo2Fmu(fmuType="me")
Expand All @@ -55,8 +55,8 @@ def test_setParameters():
model_path = omc.omcpath(model_path_str)
mod = OMPython.ModelicaSystem()
mod.model(
file=model_path / "BouncingBall.mo",
name="BouncingBall",
model_file=model_path / "BouncingBall.mo",
model_name="BouncingBall",
)

# method 1 (test depreciated variants)
Expand Down Expand Up @@ -90,8 +90,8 @@ def test_setSimulationOptions():
model_path = omc.omcpath(model_path_str)
mod = OMPython.ModelicaSystem()
mod.model(
file=model_path / "BouncingBall.mo",
name="BouncingBall",
model_file=model_path / "BouncingBall.mo",
model_name="BouncingBall",
)

# method 1
Expand Down Expand Up @@ -127,8 +127,8 @@ def test_relative_path(model_firstorder):

mod = OMPython.ModelicaSystem()
mod.model(
file=model_relative,
name="M",
model_file=model_relative,
model_name="M",
)
assert float(mod.getParameters("a")[0]) == -1
finally:
Expand All @@ -139,10 +139,10 @@ def test_customBuildDirectory(tmp_path, model_firstorder):
filePath = model_firstorder.as_posix()
tmpdir = tmp_path / "tmpdir1"
tmpdir.mkdir()
mod = OMPython.ModelicaSystem(customBuildDirectory=tmpdir)
mod = OMPython.ModelicaSystem(work_directory=tmpdir)
mod.model(
file=filePath,
name="M",
model_file=filePath,
model_name="M",
)
assert pathlib.Path(mod.getWorkDirectory()).resolve() == tmpdir.resolve()
result_file = tmpdir / "a.mat"
Expand All @@ -161,8 +161,8 @@ def test_getSolutions_docker(model_firstorder):
omc_process=omc.omc_process,
)
mod.model(
name="M",
file=model_firstorder.as_posix(),
model_file=model_firstorder,
model_name="M",
)

_run_getSolutions(mod)
Expand All @@ -171,8 +171,8 @@ def test_getSolutions_docker(model_firstorder):
def test_getSolutions(model_firstorder):
mod = OMPython.ModelicaSystem()
mod.model(
file=model_firstorder.as_posix(),
name="M",
model_file=model_firstorder,
model_name="M",
)

_run_getSolutions(mod)
Expand Down Expand Up @@ -219,8 +219,8 @@ def test_getters(tmp_path):
""")
mod = OMPython.ModelicaSystem()
mod.model(
file=model_file.as_posix(),
name="M_getters",
model_file=model_file.as_posix(),
model_name="M_getters",
)

q = mod.getQuantities()
Expand Down Expand Up @@ -415,8 +415,8 @@ def test_simulate_inputs(tmp_path):
""")
mod = OMPython.ModelicaSystem()
mod.model(
file=model_file.as_posix(),
name="M_input",
model_file=model_file.as_posix(),
model_name="M_input",
)

simOptions = {"stopTime": 1.0}
Expand Down
4 changes: 2 additions & 2 deletions tests/test_ModelicaSystemCmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ def model_firstorder(tmp_path):
def mscmd_firstorder(model_firstorder):
mod = OMPython.ModelicaSystem()
mod.model(
file=model_firstorder.as_posix(),
name="M",
model_file=model_firstorder.as_posix(),
model_name="M",
)
mscmd = OMPython.ModelicaSystemCmd(
session=mod.session(),
Expand Down
Loading