Skip to content

Commit 8d5ca52

Browse files
syntronadeas31
andauthored
Modelica system cleanup2 (#297)
* [ModelicaSystemError] add docstring * [ModelicaSystem] simplify check for variable type * [ModelicaSystem] Optional[] is only needed if the value is set to None * [ModelicaSystemCmd] set check=True for subprocess.run() * [ModelicaSystem] reorder imports * [ModelicaSystem*] fix pylint error - open() * use open() with encoding & use fh for filehandle * [ModelicaSystem*] fix pylint error - small cleanups * exception handling - use from ex * remove not needed pass * remove brackets * [ModelicaSystem*] fix pylint error - elif after return * do not use elif after return - only modified if it produces readable code --------- Co-authored-by: Adeel Asghar <adeel.asghar@liu.se>
1 parent 1edd4e8 commit 8d5ca52

File tree

1 file changed

+36
-27
lines changed

1 file changed

+36
-27
lines changed

OMPython/ModelicaSystem.py

Lines changed: 36 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -49,14 +49,16 @@
4949
import warnings
5050
import xml.etree.ElementTree as ET
5151

52-
from OMPython.OMCSession import OMCSessionZMQ, OMCSessionException
52+
from OMPython.OMCSession import OMCSessionException, OMCSessionZMQ
5353

5454
# define logger using the current module name as ID
5555
logger = logging.getLogger(__name__)
5656

5757

5858
class ModelicaSystemError(Exception):
59-
pass
59+
"""
60+
Exception used in ModelicaSystem and ModelicaSystemCmd classes.
61+
"""
6062

6163

6264
@dataclass
@@ -235,8 +237,8 @@ def run(self) -> int:
235237
if not path_bat.exists():
236238
raise ModelicaSystemError("Batch file (*.bat) does not exist " + str(path_bat))
237239

238-
with open(path_bat, 'r') as file:
239-
for line in file:
240+
with open(file=path_bat, mode='r', encoding='utf-8') as fh:
241+
for line in fh:
240242
match = re.match(r"^SET PATH=([^%]*)", line, re.IGNORECASE)
241243
if match:
242244
path_dll = match.group(1).strip(';') # Remove any trailing semicolons
@@ -248,7 +250,7 @@ def run(self) -> int:
248250

249251
try:
250252
cmdres = subprocess.run(cmdl, capture_output=True, text=True, env=my_env, cwd=self._runpath,
251-
timeout=self._timeout)
253+
timeout=self._timeout, check=True)
252254
stdout = cmdres.stdout.strip()
253255
stderr = cmdres.stderr.strip()
254256
returncode = cmdres.returncode
@@ -257,8 +259,8 @@ def run(self) -> int:
257259

258260
if stderr:
259261
raise ModelicaSystemError(f"Error running command {repr(cmdl)}: {stderr}")
260-
except subprocess.TimeoutExpired:
261-
raise ModelicaSystemError(f"Timeout running command {repr(cmdl)}")
262+
except subprocess.TimeoutExpired as ex:
263+
raise ModelicaSystemError(f"Timeout running command {repr(cmdl)}") from ex
262264
except subprocess.CalledProcessError as ex:
263265
raise ModelicaSystemError(f"Error running command {repr(cmdl)}") from ex
264266

@@ -298,7 +300,7 @@ def parse_simflags(simflags: str) -> dict[str, Optional[str | dict[str, str]]]:
298300
override_dict = {}
299301
for item in override.split(','):
300302
kv = item.split('=')
301-
if not (0 < len(kv) < 3):
303+
if not 0 < len(kv) < 3:
302304
raise ModelicaSystemError(f"Invalid value for '-override': {override}")
303305
if kv[0]:
304306
try:
@@ -322,7 +324,7 @@ def __init__(
322324
customBuildDirectory: Optional[str | os.PathLike | pathlib.Path] = None,
323325
omhome: Optional[str] = None,
324326
session: Optional[OMCSessionZMQ] = None,
325-
build: Optional[bool] = True,
327+
build: bool = True,
326328
) -> None:
327329
"""Initialize, load and build a model.
328330
@@ -573,9 +575,11 @@ def getQuantities(self, names=None): # 3
573575
"""
574576
if names is None:
575577
return self.quantitiesList
576-
elif isinstance(names, str):
578+
579+
if isinstance(names, str):
577580
return [x for x in self.quantitiesList if x["name"] == names]
578-
elif isinstance(names, list):
581+
582+
if isinstance(names, list):
579583
return [x for y in names for x in self.quantitiesList if x["name"] == y]
580584

581585
raise ModelicaSystemError("Unhandled input for getQuantities()")
@@ -591,9 +595,11 @@ def getContinuous(self, names=None): # 4
591595
if not self.simulationFlag:
592596
if names is None:
593597
return self.continuouslist
594-
elif isinstance(names, str):
598+
599+
if isinstance(names, str):
595600
return [self.continuouslist.get(names, "NotExist")]
596-
elif isinstance(names, list):
601+
602+
if isinstance(names, list):
597603
return [self.continuouslist.get(x, "NotExist") for x in names]
598604
else:
599605
if names is None:
@@ -605,15 +611,15 @@ def getContinuous(self, names=None): # 4
605611
raise ModelicaSystemError(f"{i} could not be computed") from ex
606612
return self.continuouslist
607613

608-
elif isinstance(names, str):
614+
if isinstance(names, str):
609615
if names in self.continuouslist:
610616
value = self.getSolutions(names)
611617
self.continuouslist[names] = value[0][-1]
612618
return [self.continuouslist.get(names)]
613619
else:
614620
raise ModelicaSystemError(f"{names} is not continuous")
615621

616-
elif isinstance(names, list):
622+
if isinstance(names, list):
617623
valuelist = []
618624
for i in names:
619625
if i in self.continuouslist:
@@ -851,9 +857,9 @@ def simulate(self, resultfile: Optional[str] = None, simflags: Optional[str] = N
851857
tmpdict = self.overridevariables.copy()
852858
tmpdict.update(self.simoptionsoverride)
853859
# write to override file
854-
with open(overrideFile, "w") as file:
860+
with open(file=overrideFile, mode="w", encoding="utf-8") as fh:
855861
for key, value in tmpdict.items():
856-
file.write(f"{key}={value}\n")
862+
fh.write(f"{key}={value}\n")
857863

858864
om_cmd.arg_set(key="overrideFile", val=overrideFile.as_posix())
859865

@@ -909,14 +915,16 @@ def getSolutions(self, varList=None, resultfile=None): # 12
909915
self.sendExpression("closeSimulationResultFile()")
910916
if varList is None:
911917
return resultVars
912-
elif isinstance(varList, str):
918+
919+
if isinstance(varList, str):
913920
if varList not in resultVars and varList != "time":
914921
raise ModelicaSystemError(f"Requested data {repr(varList)} does not exist")
915922
res = self.sendExpression(f'readSimulationResult("{resFile}", {{{varList}}})')
916923
npRes = np.array(res)
917924
self.sendExpression("closeSimulationResultFile()")
918925
return npRes
919-
elif isinstance(varList, list):
926+
927+
if isinstance(varList, list):
920928
for var in varList:
921929
if var == "time":
922930
continue
@@ -934,7 +942,8 @@ def getSolutions(self, varList=None, resultfile=None): # 12
934942
def _strip_space(name):
935943
if isinstance(name, str):
936944
return name.replace(" ", "")
937-
elif isinstance(name, list):
945+
946+
if isinstance(name, list):
938947
return [x.replace(" ", "") for x in name]
939948

940949
raise ModelicaSystemError("Unhandled input for strip_space()")
@@ -1051,7 +1060,7 @@ def setInputs(self, name): # 15
10511060
value = name.split("=")
10521061
if value[0] in self.inputlist:
10531062
tmpvalue = eval(value[1])
1054-
if isinstance(tmpvalue, int) or isinstance(tmpvalue, float):
1063+
if isinstance(tmpvalue, (int, float)):
10551064
self.inputlist[value[0]] = [(float(self.simulateOptions["startTime"]), float(value[1])),
10561065
(float(self.simulateOptions["stopTime"]), float(value[1]))]
10571066
elif isinstance(tmpvalue, list):
@@ -1066,7 +1075,7 @@ def setInputs(self, name): # 15
10661075
value = var.split("=")
10671076
if value[0] in self.inputlist:
10681077
tmpvalue = eval(value[1])
1069-
if isinstance(tmpvalue, int) or isinstance(tmpvalue, float):
1078+
if isinstance(tmpvalue, (int, float)):
10701079
self.inputlist[value[0]] = [(float(self.simulateOptions["startTime"]), float(value[1])),
10711080
(float(self.simulateOptions["stopTime"]), float(value[1]))]
10721081
elif isinstance(tmpvalue, list):
@@ -1132,8 +1141,8 @@ def createCSVData(self) -> pathlib.Path:
11321141

11331142
csvFile = self.tempdir / f'{self.modelName}.csv'
11341143

1135-
with open(csvFile, "w", newline="") as f:
1136-
writer = csv.writer(f)
1144+
with open(file=csvFile, mode="w", encoding="utf-8", newline="") as fh:
1145+
writer = csv.writer(fh)
11371146
writer.writerows(csv_rows)
11381147

11391148
return csvFile
@@ -1234,11 +1243,11 @@ def load_module_from_path(module_name, file_path):
12341243

12351244
overrideLinearFile = self.tempdir / f'{self.modelName}_override_linear.txt'
12361245

1237-
with open(overrideLinearFile, "w") as file:
1246+
with open(file=overrideLinearFile, mode="w", encoding="utf-8") as fh:
12381247
for key, value in self.overridevariables.items():
1239-
file.write(f"{key}={value}\n")
1248+
fh.write(f"{key}={value}\n")
12401249
for key, value in self.linearOptions.items():
1241-
file.write(f"{key}={value}\n")
1250+
fh.write(f"{key}={value}\n")
12421251

12431252
om_cmd.arg_set(key="overrideFile", val=overrideLinearFile.as_posix())
12441253

0 commit comments

Comments
 (0)