Skip to content

Commit 9d83dd4

Browse files
committed
[ModelicaSystem] use pathlib.Path() / simplify
1 parent c2f2c28 commit 9d83dd4

2 files changed

Lines changed: 21 additions & 20 deletions

File tree

OMPython/ModelicaSystem.py

Lines changed: 20 additions & 19 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] = None,
320+
customBuildDirectory: Optional[str | os.PathLike | pathlib.Path] = None,
321321
omhome: Optional[str] = None,
322322
session: Optional[OMCSessionZMQ] = None,
323323
build: Optional[bool] = True
@@ -375,7 +375,6 @@ def __init__(
375375
self.linearinputs = [] # linearization input list
376376
self.linearoutputs = [] # linearization output list
377377
self.linearstates = [] # linearization states list
378-
self.tempdir = ""
379378

380379
if session is not None:
381380
if not isinstance(session, OMCSessionZMQ):
@@ -413,7 +412,7 @@ def __init__(
413412
self.setCommandLineOptions("--linearizationDumpLanguage=python")
414413
self.setCommandLineOptions("--generateSymbolicLinearization")
415414

416-
self.setTempDirectory(customBuildDirectory)
415+
self.tempdir = self.setTempDirectory(customBuildDirectory)
417416

418417
if self.fileName is not None:
419418
self.loadLibrary(lmodel=self.lmodel)
@@ -461,22 +460,24 @@ def loadLibrary(self, lmodel: list):
461460
'1)["Modelica"]\n'
462461
'2)[("Modelica","3.2.3"), "PowerSystems"]\n')
463462

464-
def setTempDirectory(self, customBuildDirectory):
463+
def setTempDirectory(self, customBuildDirectory) -> pathlib.Path:
465464
# create a unique temp directory for each session and build the model in that directory
466465
if customBuildDirectory is not None:
467466
if not os.path.exists(customBuildDirectory):
468467
raise IOError(customBuildDirectory, " does not exist")
469-
self.tempdir = customBuildDirectory
468+
tempdir = pathlib.Path(customBuildDirectory)
470469
else:
471-
self.tempdir = tempfile.mkdtemp()
472-
if not os.path.exists(self.tempdir):
473-
raise IOError(self.tempdir, " cannot be created")
470+
tempdir = pathlib.Path(tempfile.mkdtemp())
471+
if not tempdir.is_dir():
472+
raise IOError(tempdir, " cannot be created")
474473

475-
logger.info("Define tempdir as %s", self.tempdir)
476-
exp = f'cd("{pathlib.Path(self.tempdir).absolute().as_posix()}")'
474+
logger.info("Define tempdir as %s", tempdir)
475+
exp = f'cd("{tempdir.absolute().as_posix()}")'
477476
self.sendExpression(exp)
478477

479-
def getWorkDirectory(self):
478+
return tempdir
479+
480+
def getWorkDirectory(self) -> pathlib.Path:
480481
return self.tempdir
481482

482483
def buildModel(self, variableFilter=None):
@@ -814,15 +815,15 @@ def simulate(self, resultfile: Optional[str] = None, simflags: Optional[str] = N
814815
>>> simulate(simargs={"noEventEmit": None, "noRestart": None, "override": "e=0.3,g=10"}) # using simargs
815816
"""
816817

817-
om_cmd = ModelicaSystemCmd(runpath=pathlib.Path(self.tempdir), modelname=self.modelName, timeout=timeout)
818+
om_cmd = ModelicaSystemCmd(runpath=self.tempdir, modelname=self.modelName, timeout=timeout)
818819

819820
if resultfile is None:
820821
# default result file generated by OM
821-
self.resultfile = (pathlib.Path(self.tempdir) / f"{self.modelName}_res.mat").as_posix()
822+
self.resultfile = (self.tempdir / f"{self.modelName}_res.mat").as_posix()
822823
elif os.path.exists(resultfile):
823824
self.resultfile = resultfile
824825
else:
825-
self.resultfile = (pathlib.Path(self.tempdir) / resultfile).as_posix()
826+
self.resultfile = (self.tempdir / resultfile).as_posix()
826827
# always define the resultfile to use
827828
om_cmd.arg_set(key="r", val=self.resultfile)
828829

@@ -833,7 +834,7 @@ def simulate(self, resultfile: Optional[str] = None, simflags: Optional[str] = N
833834
if simargs:
834835
om_cmd.args_set(args=simargs)
835836

836-
overrideFile = pathlib.Path(self.tempdir) / f"{self.modelName}_override.txt"
837+
overrideFile = self.tempdir / f"{self.modelName}_override.txt"
837838
if self.overridevariables or self.simoptionsoverride:
838839
tmpdict = self.overridevariables.copy()
839840
tmpdict.update(self.simoptionsoverride)
@@ -1108,7 +1109,7 @@ def createCSVData(self) -> pathlib.Path:
11081109
]
11091110
csv_rows.append(row)
11101111

1111-
csvFile = pathlib.Path(self.tempdir) / f'{self.modelName}.csv'
1112+
csvFile = self.tempdir / f'{self.modelName}.csv'
11121113

11131114
with open(csvFile, "w", newline="") as f:
11141115
writer = csv.writer(f)
@@ -1200,9 +1201,9 @@ def linearize(self, lintime: Optional[float] = None, simflags: Optional[str] = N
12001201
raise IOError("Linearization cannot be performed as the model is not build, "
12011202
"use ModelicaSystem() to build the model first")
12021203

1203-
om_cmd = ModelicaSystemCmd(runpath=pathlib.Path(self.tempdir), modelname=self.modelName, timeout=timeout)
1204+
om_cmd = ModelicaSystemCmd(runpath=self.tempdir, modelname=self.modelName, timeout=timeout)
12041205

1205-
overrideLinearFile = pathlib.Path(self.tempdir) / f'{self.modelName}_override_linear.txt'
1206+
overrideLinearFile = self.tempdir / f'{self.modelName}_override_linear.txt'
12061207

12071208
with open(overrideLinearFile, "w") as file:
12081209
for key, value in self.overridevariables.items():
@@ -1235,7 +1236,7 @@ def linearize(self, lintime: Optional[float] = None, simflags: Optional[str] = N
12351236
self.simulationFlag = om_cmd.run()
12361237

12371238
# code to get the matrix and linear inputs, outputs and states
1238-
linearFile = pathlib.Path(self.tempdir) / "linearized_model.py"
1239+
linearFile = self.tempdir / "linearized_model.py"
12391240

12401241
# support older openmodelica versions before OpenModelica v1.16.2 where linearize() generates "linear_modelname.mo" file
12411242
if not linearFile.exists():

tests/test_ModelicaSystem.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ def test_customBuildDirectory(self):
100100
tmpdir = self.tmp / "tmpdir1"
101101
tmpdir.mkdir()
102102
m = OMPython.ModelicaSystem(filePath, "M", customBuildDirectory=tmpdir)
103-
assert pathlib.Path(m.getWorkDirectory()).resolve() == tmpdir.resolve()
103+
assert m.getWorkDirectory().resolve() == tmpdir.resolve()
104104
result_file = tmpdir / "a.mat"
105105
assert not result_file.exists()
106106
m.simulate(resultfile="a.mat")

0 commit comments

Comments
 (0)