From 4d235053ae2c4fce678fd13e1b156979293217f5 Mon Sep 17 00:00:00 2001 From: syntron Date: Wed, 4 Jun 2025 21:02:04 +0200 Subject: [PATCH 1/8] [ModelicaSystemError] add docstring --- OMPython/ModelicaSystem.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/OMPython/ModelicaSystem.py b/OMPython/ModelicaSystem.py index e362520a..ad2263fb 100644 --- a/OMPython/ModelicaSystem.py +++ b/OMPython/ModelicaSystem.py @@ -56,6 +56,9 @@ class ModelicaSystemError(Exception): + """ + Exception used in ModelicaSystem and ModelicaSystemCmd classes. + """ pass From 72f68f60bd1156ade876569f069fe1ef380323d0 Mon Sep 17 00:00:00 2001 From: syntron Date: Wed, 4 Jun 2025 21:02:27 +0200 Subject: [PATCH 2/8] [ModelicaSystem] simplify check for variable type --- OMPython/ModelicaSystem.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/OMPython/ModelicaSystem.py b/OMPython/ModelicaSystem.py index ad2263fb..df18f757 100644 --- a/OMPython/ModelicaSystem.py +++ b/OMPython/ModelicaSystem.py @@ -1050,7 +1050,7 @@ def setInputs(self, name): # 15 value = name.split("=") if value[0] in self.inputlist: tmpvalue = eval(value[1]) - if isinstance(tmpvalue, int) or isinstance(tmpvalue, float): + if isinstance(tmpvalue, (int, float)): self.inputlist[value[0]] = [(float(self.simulateOptions["startTime"]), float(value[1])), (float(self.simulateOptions["stopTime"]), float(value[1]))] elif isinstance(tmpvalue, list): @@ -1065,7 +1065,7 @@ def setInputs(self, name): # 15 value = var.split("=") if value[0] in self.inputlist: tmpvalue = eval(value[1]) - if isinstance(tmpvalue, int) or isinstance(tmpvalue, float): + if isinstance(tmpvalue, (int, float)): self.inputlist[value[0]] = [(float(self.simulateOptions["startTime"]), float(value[1])), (float(self.simulateOptions["stopTime"]), float(value[1]))] elif isinstance(tmpvalue, list): From 7ef4602dd4994cb4ccf6d690c71d062fb4657294 Mon Sep 17 00:00:00 2001 From: syntron Date: Wed, 4 Jun 2025 21:02:59 +0200 Subject: [PATCH 3/8] [ModelicaSystem] Optional[] is only needed if the value is set to None --- OMPython/ModelicaSystem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OMPython/ModelicaSystem.py b/OMPython/ModelicaSystem.py index df18f757..8407bb43 100644 --- a/OMPython/ModelicaSystem.py +++ b/OMPython/ModelicaSystem.py @@ -325,7 +325,7 @@ def __init__( customBuildDirectory: Optional[str | os.PathLike | pathlib.Path] = None, omhome: Optional[str] = None, session: Optional[OMCSessionZMQ] = None, - build: Optional[bool] = True, + build: bool = True, ) -> None: """Initialize, load and build a model. From a7f9fadb05348bfb312047be4c3b6dbecf17a252 Mon Sep 17 00:00:00 2001 From: syntron Date: Wed, 4 Jun 2025 21:03:39 +0200 Subject: [PATCH 4/8] [ModelicaSystemCmd] set check=True for subprocess.run() --- OMPython/ModelicaSystem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OMPython/ModelicaSystem.py b/OMPython/ModelicaSystem.py index 8407bb43..24a17f27 100644 --- a/OMPython/ModelicaSystem.py +++ b/OMPython/ModelicaSystem.py @@ -251,7 +251,7 @@ def run(self) -> int: try: cmdres = subprocess.run(cmdl, capture_output=True, text=True, env=my_env, cwd=self._runpath, - timeout=self._timeout) + timeout=self._timeout, check=True) stdout = cmdres.stdout.strip() stderr = cmdres.stderr.strip() returncode = cmdres.returncode From a114c7abee59eff770d80d491cbacfb020181eeb Mon Sep 17 00:00:00 2001 From: syntron Date: Wed, 4 Jun 2025 21:03:53 +0200 Subject: [PATCH 5/8] [ModelicaSystem] reorder imports --- OMPython/ModelicaSystem.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OMPython/ModelicaSystem.py b/OMPython/ModelicaSystem.py index 24a17f27..c426ab76 100644 --- a/OMPython/ModelicaSystem.py +++ b/OMPython/ModelicaSystem.py @@ -49,7 +49,7 @@ import warnings import xml.etree.ElementTree as ET -from OMPython.OMCSession import OMCSessionZMQ, OMCSessionException +from OMPython.OMCSession import OMCSessionException, OMCSessionZMQ # define logger using the current module name as ID logger = logging.getLogger(__name__) From 10f947bfd98059ebbb56ddb8faffe16ad1dbef1d Mon Sep 17 00:00:00 2001 From: syntron Date: Tue, 10 Jun 2025 17:24:49 +0200 Subject: [PATCH 6/8] [ModelicaSystem*] fix pylint error - open() * use open() with encoding & use fh for filehandle --- OMPython/ModelicaSystem.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/OMPython/ModelicaSystem.py b/OMPython/ModelicaSystem.py index c426ab76..875c4f9f 100644 --- a/OMPython/ModelicaSystem.py +++ b/OMPython/ModelicaSystem.py @@ -238,8 +238,8 @@ def run(self) -> int: if not path_bat.exists(): raise ModelicaSystemError("Batch file (*.bat) does not exist " + str(path_bat)) - with open(path_bat, 'r') as file: - for line in file: + with open(file=path_bat, mode='r', encoding='utf-8') as fh: + for line in fh: match = re.match(r"^SET PATH=([^%]*)", line, re.IGNORECASE) if match: path_dll = match.group(1).strip(';') # Remove any trailing semicolons @@ -850,9 +850,9 @@ def simulate(self, resultfile: Optional[str] = None, simflags: Optional[str] = N tmpdict = self.overridevariables.copy() tmpdict.update(self.simoptionsoverride) # write to override file - with open(overrideFile, "w") as file: + with open(file=overrideFile, mode="w", encoding="utf-8") as fh: for key, value in tmpdict.items(): - file.write(f"{key}={value}\n") + fh.write(f"{key}={value}\n") om_cmd.arg_set(key="overrideFile", val=overrideFile.as_posix()) @@ -1131,8 +1131,8 @@ def createCSVData(self) -> pathlib.Path: csvFile = self.tempdir / f'{self.modelName}.csv' - with open(csvFile, "w", newline="") as f: - writer = csv.writer(f) + with open(file=csvFile, mode="w", encoding="utf-8", newline="") as fh: + writer = csv.writer(fh) writer.writerows(csv_rows) return csvFile @@ -1233,11 +1233,11 @@ def load_module_from_path(module_name, file_path): overrideLinearFile = self.tempdir / f'{self.modelName}_override_linear.txt' - with open(overrideLinearFile, "w") as file: + with open(file=overrideLinearFile, mode="w", encoding="utf-8") as fh: for key, value in self.overridevariables.items(): - file.write(f"{key}={value}\n") + fh.write(f"{key}={value}\n") for key, value in self.linearOptions.items(): - file.write(f"{key}={value}\n") + fh.write(f"{key}={value}\n") om_cmd.arg_set(key="overrideFile", val=overrideLinearFile.as_posix()) From 19d5194960236e6732afba4463e3776e01a6cf5c Mon Sep 17 00:00:00 2001 From: syntron Date: Tue, 10 Jun 2025 17:36:11 +0200 Subject: [PATCH 7/8] [ModelicaSystem*] fix pylint error - small cleanups * exception handling - use from ex * remove not needed pass * remove brackets --- OMPython/ModelicaSystem.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/OMPython/ModelicaSystem.py b/OMPython/ModelicaSystem.py index 875c4f9f..a7b2e6d2 100644 --- a/OMPython/ModelicaSystem.py +++ b/OMPython/ModelicaSystem.py @@ -59,7 +59,6 @@ class ModelicaSystemError(Exception): """ Exception used in ModelicaSystem and ModelicaSystemCmd classes. """ - pass @dataclass @@ -260,8 +259,8 @@ def run(self) -> int: if stderr: raise ModelicaSystemError(f"Error running command {repr(cmdl)}: {stderr}") - except subprocess.TimeoutExpired: - raise ModelicaSystemError(f"Timeout running command {repr(cmdl)}") + except subprocess.TimeoutExpired as ex: + raise ModelicaSystemError(f"Timeout running command {repr(cmdl)}") from ex except subprocess.CalledProcessError as ex: raise ModelicaSystemError(f"Error running command {repr(cmdl)}") from ex @@ -301,7 +300,7 @@ def parse_simflags(simflags: str) -> dict[str, Optional[str | dict[str, str]]]: override_dict = {} for item in override.split(','): kv = item.split('=') - if not (0 < len(kv) < 3): + if not 0 < len(kv) < 3: raise ModelicaSystemError(f"Invalid value for '-override': {override}") if kv[0]: try: From ea0fb4f75bd852e3465775ffb835aef7b0fb0045 Mon Sep 17 00:00:00 2001 From: syntron Date: Tue, 10 Jun 2025 17:36:02 +0200 Subject: [PATCH 8/8] [ModelicaSystem*] fix pylint error - elif after return * do not use elif after return - only modified if it produces readable code --- OMPython/ModelicaSystem.py | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/OMPython/ModelicaSystem.py b/OMPython/ModelicaSystem.py index a7b2e6d2..898f4f30 100644 --- a/OMPython/ModelicaSystem.py +++ b/OMPython/ModelicaSystem.py @@ -571,9 +571,11 @@ def getQuantities(self, names=None): # 3 """ if names is None: return self.quantitiesList - elif isinstance(names, str): + + if isinstance(names, str): return [x for x in self.quantitiesList if x["name"] == names] - elif isinstance(names, list): + + if isinstance(names, list): return [x for y in names for x in self.quantitiesList if x["name"] == y] raise ModelicaSystemError("Unhandled input for getQuantities()") @@ -589,9 +591,11 @@ def getContinuous(self, names=None): # 4 if not self.simulationFlag: if names is None: return self.continuouslist - elif isinstance(names, str): + + if isinstance(names, str): return [self.continuouslist.get(names, "NotExist")] - elif isinstance(names, list): + + if isinstance(names, list): return [self.continuouslist.get(x, "NotExist") for x in names] else: if names is None: @@ -603,7 +607,7 @@ def getContinuous(self, names=None): # 4 raise ModelicaSystemError(f"{i} could not be computed") from ex return self.continuouslist - elif isinstance(names, str): + if isinstance(names, str): if names in self.continuouslist: value = self.getSolutions(names) self.continuouslist[names] = value[0][-1] @@ -611,7 +615,7 @@ def getContinuous(self, names=None): # 4 else: raise ModelicaSystemError(f"{names} is not continuous") - elif isinstance(names, list): + if isinstance(names, list): valuelist = [] for i in names: if i in self.continuouslist: @@ -907,14 +911,16 @@ def getSolutions(self, varList=None, resultfile=None): # 12 self.sendExpression("closeSimulationResultFile()") if varList is None: return resultVars - elif isinstance(varList, str): + + if isinstance(varList, str): if varList not in resultVars and varList != "time": raise ModelicaSystemError(f"Requested data {repr(varList)} does not exist") res = self.sendExpression(f'readSimulationResult("{resFile}", {{{varList}}})') npRes = np.array(res) self.sendExpression("closeSimulationResultFile()") return npRes - elif isinstance(varList, list): + + if isinstance(varList, list): for var in varList: if var == "time": continue @@ -932,7 +938,8 @@ def getSolutions(self, varList=None, resultfile=None): # 12 def _strip_space(name): if isinstance(name, str): return name.replace(" ", "") - elif isinstance(name, list): + + if isinstance(name, list): return [x.replace(" ", "") for x in name] raise ModelicaSystemError("Unhandled input for strip_space()")