Skip to content

Commit 7616030

Browse files
authored
[ModelicaSystem] update handling of work directory (#329)
* [ModelicaSystem] update handling of work directory * use as input str or os.PathLike; the later covers all pathlib objects * rename _tempdir to _work_dir * rename setTempDirectory() => setWorkDirectory() * setWorkDirectory() sets the work dir and also returns its path * use setWorkDirectory() within code; this allows to add special handling to the function if needed * [ModelicaSystem] fix comment
1 parent ea287fc commit 7616030

File tree

1 file changed

+40
-25
lines changed

1 file changed

+40
-25
lines changed

OMPython/ModelicaSystem.py

Lines changed: 40 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,7 @@ def __init__(
300300
lmodel: Optional[list[str | tuple[str, str]]] = None,
301301
commandLineOptions: Optional[str] = None,
302302
variableFilter: Optional[str] = None,
303-
customBuildDirectory: Optional[str | os.PathLike | pathlib.Path] = None,
303+
customBuildDirectory: Optional[str | os.PathLike] = None,
304304
omhome: Optional[str] = None,
305305
omc_process: Optional[OMCProcessLocal] = None,
306306
build: bool = True,
@@ -397,7 +397,7 @@ def __init__(
397397
self.setCommandLineOptions("--linearizationDumpLanguage=python")
398398
self.setCommandLineOptions("--generateSymbolicLinearization")
399399

400-
self._tempdir = self.setTempDirectory(customBuildDirectory)
400+
self._work_dir: pathlib.Path = self.setWorkDirectory(customBuildDirectory)
401401

402402
if self._file_name is not None:
403403
self._loadLibrary(lmodel=self._lmodel)
@@ -445,25 +445,34 @@ def _loadLibrary(self, lmodel: list):
445445
'1)["Modelica"]\n'
446446
'2)[("Modelica","3.2.3"), "PowerSystems"]\n')
447447

448-
def setTempDirectory(self, customBuildDirectory: Optional[str | os.PathLike | pathlib.Path] = None) -> pathlib.Path:
449-
# create a unique temp directory for each session and build the model in that directory
448+
def setWorkDirectory(self, customBuildDirectory: Optional[str | os.PathLike] = None) -> pathlib.Path:
449+
"""
450+
Define the work directory for the ModelicaSystem / OpenModelica session. The model is build within this
451+
directory. If no directory is defined a unique temporary directory is created.
452+
"""
450453
if customBuildDirectory is not None:
451-
if not os.path.exists(customBuildDirectory):
452-
raise IOError(f"{customBuildDirectory} does not exist")
453-
tempdir = pathlib.Path(customBuildDirectory).absolute()
454+
workdir = pathlib.Path(customBuildDirectory).absolute()
455+
if not workdir.is_dir():
456+
raise IOError(f"Provided work directory does not exists: {customBuildDirectory}!")
454457
else:
455-
tempdir = pathlib.Path(tempfile.mkdtemp()).absolute()
456-
if not tempdir.is_dir():
457-
raise IOError(f"{tempdir} could not be created")
458+
workdir = pathlib.Path(tempfile.mkdtemp()).absolute()
459+
if not workdir.is_dir():
460+
raise IOError(f"{workdir} could not be created")
458461

459-
logger.info("Define tempdir as %s", tempdir)
460-
exp = f'cd("{tempdir.as_posix()}")'
462+
logger.info("Define work dir as %s", workdir)
463+
exp = f'cd("{workdir.as_posix()}")'
461464
self.sendExpression(exp)
462465

463-
return tempdir
466+
# set the class variable _work_dir ...
467+
self._work_dir = workdir
468+
# ... and also return the defined path
469+
return workdir
464470

465471
def getWorkDirectory(self) -> pathlib.Path:
466-
return self._tempdir
472+
"""
473+
Return the defined working directory for this ModelicaSystem / OpenModelica session.
474+
"""
475+
return self._work_dir
467476

468477
def buildModel(self, variableFilter: Optional[str] = None):
469478
if variableFilter is not None:
@@ -951,7 +960,11 @@ def simulate_cmd(
951960
An instance if ModelicaSystemCmd to run the requested simulation.
952961
"""
953962

954-
om_cmd = ModelicaSystemCmd(runpath=self._tempdir, modelname=self._model_name, timeout=timeout)
963+
om_cmd = ModelicaSystemCmd(
964+
runpath=self.getWorkDirectory(),
965+
modelname=self._model_name,
966+
timeout=timeout,
967+
)
955968

956969
# always define the result file to use
957970
om_cmd.arg_set(key="r", val=result_file.as_posix())
@@ -1023,11 +1036,11 @@ def simulate(
10231036

10241037
if resultfile is None:
10251038
# default result file generated by OM
1026-
self._result_file = self._tempdir / f"{self._model_name}_res.mat"
1039+
self._result_file = self.getWorkDirectory() / f"{self._model_name}_res.mat"
10271040
elif os.path.exists(resultfile):
10281041
self._result_file = pathlib.Path(resultfile)
10291042
else:
1030-
self._result_file = self._tempdir / resultfile
1043+
self._result_file = self.getWorkDirectory() / resultfile
10311044

10321045
om_cmd = self.simulate_cmd(
10331046
result_file=self._result_file,
@@ -1429,7 +1442,7 @@ def _createCSVData(self, csvfile: Optional[pathlib.Path] = None) -> pathlib.Path
14291442
csv_rows.append(row)
14301443

14311444
if csvfile is None:
1432-
csvfile = self._tempdir / f'{self._model_name}.csv'
1445+
csvfile = self.getWorkDirectory() / f'{self._model_name}.csv'
14331446

14341447
# basic definition of a CSV file using csv_rows as input
14351448
csv_content = "\n".join([",".join(map(str, row)) for row in csv_rows]) + "\n"
@@ -1553,9 +1566,13 @@ def linearize(self, lintime: Optional[float] = None, simflags: Optional[str] = N
15531566
"use ModelicaSystem() to build the model first"
15541567
)
15551568

1556-
om_cmd = ModelicaSystemCmd(runpath=self._tempdir, modelname=self._model_name, timeout=timeout)
1569+
om_cmd = ModelicaSystemCmd(
1570+
runpath=self.getWorkDirectory(),
1571+
modelname=self._model_name,
1572+
timeout=timeout,
1573+
)
15571574

1558-
overrideLinearFile = self._tempdir / f'{self._model_name}_override_linear.txt'
1575+
overrideLinearFile = self.getWorkDirectory() / f'{self._model_name}_override_linear.txt'
15591576

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

15871604
# the file create by the model executable which contains the matrix and linear inputs, outputs and states
1588-
linear_file = self._tempdir / "linearized_model.py"
1589-
1605+
linear_file = self.getWorkDirectory() / "linearized_model.py"
15901606
linear_file.unlink(missing_ok=True)
15911607

15921608
returncode = om_cmd.run()
15931609
if returncode != 0:
15941610
raise ModelicaSystemError(f"Linearize failed with return code: {returncode}")
1595-
1596-
self._simulated = True
1597-
15981611
if not linear_file.exists():
15991612
raise ModelicaSystemError(f"Linearization failed: {linear_file} not found!")
16001613

1614+
self._simulated = True
1615+
16011616
# extract data from the python file with the linearized model using the ast module - this allows to get the
16021617
# needed information without executing the created code
16031618
linear_data = {}

0 commit comments

Comments
 (0)