Skip to content

Commit 88e2dbe

Browse files
committed
Merge branch 'ModelicaSystem_workdir' into MERGE@all
2 parents 82ade31 + a64a330 commit 88e2dbe

1 file changed

Lines changed: 41 additions & 25 deletions

File tree

OMPython/ModelicaSystem.py

Lines changed: 41 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -317,7 +317,7 @@ def __init__(
317317
lmodel: Optional[list[str | tuple[str, str]]] = None,
318318
commandLineOptions: Optional[str] = None,
319319
variableFilter: Optional[str] = None,
320-
customBuildDirectory: Optional[str | os.PathLike | pathlib.Path] = None,
320+
customBuildDirectory: Optional[str | os.PathLike] = None,
321321
omhome: Optional[str] = None,
322322
omc_process: Optional[OMCProcessLocal] = None,
323323
build: bool = True,
@@ -414,7 +414,7 @@ def __init__(
414414
self.setCommandLineOptions("--linearizationDumpLanguage=python")
415415
self.setCommandLineOptions("--generateSymbolicLinearization")
416416

417-
self._tempdir = self.setTempDirectory(customBuildDirectory)
417+
self._work_dir: pathlib.Path = self.setWorkDirectory(customBuildDirectory)
418418

419419
if self._file_name is not None:
420420
self._loadLibrary(lmodel=self._lmodel)
@@ -462,25 +462,34 @@ def _loadLibrary(self, lmodel: list):
462462
'1)["Modelica"]\n'
463463
'2)[("Modelica","3.2.3"), "PowerSystems"]\n')
464464

465-
def setTempDirectory(self, customBuildDirectory: Optional[str | os.PathLike | pathlib.Path] = None) -> pathlib.Path:
466-
# create a unique temp directory for each session and build the model in that directory
465+
def setWorkDirectory(self, customBuildDirectory: Optional[str | os.PathLike] = None) -> pathlib.Path:
466+
"""
467+
Define the work directory for the ModelicaSystem / OpenModelica session. The model is build within this
468+
directory. If no directory is defined a unique temporary directory is created.
469+
"""
467470
if customBuildDirectory is not None:
468-
if not os.path.exists(customBuildDirectory):
469-
raise IOError(f"{customBuildDirectory} does not exist")
470-
tempdir = pathlib.Path(customBuildDirectory).absolute()
471+
workdir = pathlib.Path(customBuildDirectory).absolute()
472+
if not workdir.is_dir():
473+
raise IOError(f"Provided work directory does not exists: {customBuildDirectory}!")
471474
else:
472-
tempdir = pathlib.Path(tempfile.mkdtemp()).absolute()
473-
if not tempdir.is_dir():
474-
raise IOError(f"{tempdir} could not be created")
475+
workdir = pathlib.Path(tempfile.mkdtemp()).absolute()
476+
if not workdir.is_dir():
477+
raise IOError(f"{workdir} could not be created")
475478

476-
logger.info("Define tempdir as %s", tempdir)
477-
exp = f'cd("{tempdir.as_posix()}")'
479+
logger.info("Define work dir as %s", workdir)
480+
exp = f'cd("{workdir.as_posix()}")'
478481
self.sendExpression(exp)
479482

480-
return tempdir
483+
# set the class variable _tempdir ...
484+
self._work_dir = workdir
485+
# ... and also return the defined path
486+
return workdir
481487

482488
def getWorkDirectory(self) -> pathlib.Path:
483-
return self._tempdir
489+
"""
490+
Return the defined working directory for this ModelicaSystem / OpenModelica session.
491+
"""
492+
return self._work_dir
484493

485494
def buildModel(self, variableFilter: Optional[str] = None):
486495
if variableFilter is not None:
@@ -973,7 +982,11 @@ def simulate_cmd(
973982
An instance if ModelicaSystemCmd to run the requested simulation.
974983
"""
975984

976-
om_cmd = ModelicaSystemCmd(runpath=self._tempdir, modelname=self._model_name, timeout=timeout)
985+
om_cmd = ModelicaSystemCmd(
986+
runpath=self.getWorkDirectory(),
987+
modelname=self._model_name,
988+
timeout=timeout,
989+
)
977990

978991
# always define the result file to use
979992
om_cmd.arg_set(key="r", val=result_file.as_posix())
@@ -985,7 +998,7 @@ def simulate_cmd(
985998
if simargs:
986999
om_cmd.args_set(args=simargs)
9871000

988-
overrideFile = self._tempdir / f"{self._model_name}_override.txt"
1001+
overrideFile = self.getWorkDirectory() / f"{self._model_name}_override.txt"
9891002
if self._override_variables or self._simulate_options_override:
9901003
tmpdict = self._override_variables.copy()
9911004
tmpdict.update(self._simulate_options_override)
@@ -1044,11 +1057,11 @@ def simulate(
10441057

10451058
if resultfile is None:
10461059
# default result file generated by OM
1047-
self._result_file = self._tempdir / f"{self._model_name}_res.mat"
1060+
self._result_file = self.getWorkDirectory() / f"{self._model_name}_res.mat"
10481061
elif os.path.exists(resultfile):
10491062
self._result_file = pathlib.Path(resultfile)
10501063
else:
1051-
self._result_file = self._tempdir / resultfile
1064+
self._result_file = self.getWorkDirectory() / resultfile
10521065

10531066
om_cmd = self.simulate_cmd(
10541067
result_file=self._result_file,
@@ -1454,7 +1467,7 @@ def _createCSVData(self, csvfile: Optional[pathlib.Path] = None) -> pathlib.Path
14541467
csv_rows.append(row)
14551468

14561469
if csvfile is None:
1457-
csvfile = self._tempdir / f'{self._model_name}.csv'
1470+
csvfile = self.getWorkDirectory() / f'{self._model_name}.csv'
14581471

14591472
with open(file=csvfile, mode="w", encoding="utf-8", newline="") as fh:
14601473
writer = csv.writer(fh)
@@ -1578,9 +1591,13 @@ def linearize(self, lintime: Optional[float] = None, simflags: Optional[str] = N
15781591
"use ModelicaSystem() to build the model first"
15791592
)
15801593

1581-
om_cmd = ModelicaSystemCmd(runpath=self._tempdir, modelname=self._model_name, timeout=timeout)
1594+
om_cmd = ModelicaSystemCmd(
1595+
runpath=self.getWorkDirectory(),
1596+
modelname=self._model_name,
1597+
timeout=timeout,
1598+
)
15821599

1583-
overrideLinearFile = self._tempdir / f'{self._model_name}_override_linear.txt'
1600+
overrideLinearFile = self.getWorkDirectory() / f'{self._model_name}_override_linear.txt'
15841601

15851602
with open(file=overrideLinearFile, mode="w", encoding="utf-8") as fh:
15861603
for key1, value1 in self._override_variables.items():
@@ -1610,19 +1627,18 @@ def linearize(self, lintime: Optional[float] = None, simflags: Optional[str] = N
16101627
om_cmd.args_set(args=simargs)
16111628

16121629
# the file create by the model executable which contains the matrix and linear inputs, outputs and states
1613-
linear_file = self._tempdir / "linearized_model.py"
1630+
linear_file = self.getWorkDirectory() / "linearized_model.py"
16141631

16151632
linear_file.unlink(missing_ok=True)
16161633

16171634
returncode = om_cmd.run()
16181635
if returncode != 0:
16191636
raise ModelicaSystemError(f"Linearize failed with return code: {returncode}")
1620-
1621-
self._simulated = True
1622-
16231637
if not linear_file.exists():
16241638
raise ModelicaSystemError(f"Linearization failed: {linear_file} not found!")
16251639

1640+
self._simulated = True
1641+
16261642
# extract data from the python file with the linearized model using the ast module - this allows to get the
16271643
# needed information without executing the created code
16281644
linear_data = {}

0 commit comments

Comments
 (0)