49
49
import warnings
50
50
import xml .etree .ElementTree as ET
51
51
52
- from OMPython .OMCSession import OMCSessionZMQ , OMCSessionException
52
+ from OMPython .OMCSession import OMCSessionException , OMCSessionZMQ
53
53
54
54
# define logger using the current module name as ID
55
55
logger = logging .getLogger (__name__ )
56
56
57
57
58
58
class ModelicaSystemError (Exception ):
59
- pass
59
+ """
60
+ Exception used in ModelicaSystem and ModelicaSystemCmd classes.
61
+ """
60
62
61
63
62
64
@dataclass
@@ -235,8 +237,8 @@ def run(self) -> int:
235
237
if not path_bat .exists ():
236
238
raise ModelicaSystemError ("Batch file (*.bat) does not exist " + str (path_bat ))
237
239
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 :
240
242
match = re .match (r"^SET PATH=([^%]*)" , line , re .IGNORECASE )
241
243
if match :
242
244
path_dll = match .group (1 ).strip (';' ) # Remove any trailing semicolons
@@ -248,7 +250,7 @@ def run(self) -> int:
248
250
249
251
try :
250
252
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 )
252
254
stdout = cmdres .stdout .strip ()
253
255
stderr = cmdres .stderr .strip ()
254
256
returncode = cmdres .returncode
@@ -257,8 +259,8 @@ def run(self) -> int:
257
259
258
260
if stderr :
259
261
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
262
264
except subprocess .CalledProcessError as ex :
263
265
raise ModelicaSystemError (f"Error running command { repr (cmdl )} " ) from ex
264
266
@@ -298,7 +300,7 @@ def parse_simflags(simflags: str) -> dict[str, Optional[str | dict[str, str]]]:
298
300
override_dict = {}
299
301
for item in override .split (',' ):
300
302
kv = item .split ('=' )
301
- if not ( 0 < len (kv ) < 3 ) :
303
+ if not 0 < len (kv ) < 3 :
302
304
raise ModelicaSystemError (f"Invalid value for '-override': { override } " )
303
305
if kv [0 ]:
304
306
try :
@@ -322,7 +324,7 @@ def __init__(
322
324
customBuildDirectory : Optional [str | os .PathLike | pathlib .Path ] = None ,
323
325
omhome : Optional [str ] = None ,
324
326
session : Optional [OMCSessionZMQ ] = None ,
325
- build : Optional [ bool ] = True ,
327
+ build : bool = True ,
326
328
) -> None :
327
329
"""Initialize, load and build a model.
328
330
@@ -573,9 +575,11 @@ def getQuantities(self, names=None): # 3
573
575
"""
574
576
if names is None :
575
577
return self .quantitiesList
576
- elif isinstance (names , str ):
578
+
579
+ if isinstance (names , str ):
577
580
return [x for x in self .quantitiesList if x ["name" ] == names ]
578
- elif isinstance (names , list ):
581
+
582
+ if isinstance (names , list ):
579
583
return [x for y in names for x in self .quantitiesList if x ["name" ] == y ]
580
584
581
585
raise ModelicaSystemError ("Unhandled input for getQuantities()" )
@@ -591,9 +595,11 @@ def getContinuous(self, names=None): # 4
591
595
if not self .simulationFlag :
592
596
if names is None :
593
597
return self .continuouslist
594
- elif isinstance (names , str ):
598
+
599
+ if isinstance (names , str ):
595
600
return [self .continuouslist .get (names , "NotExist" )]
596
- elif isinstance (names , list ):
601
+
602
+ if isinstance (names , list ):
597
603
return [self .continuouslist .get (x , "NotExist" ) for x in names ]
598
604
else :
599
605
if names is None :
@@ -605,15 +611,15 @@ def getContinuous(self, names=None): # 4
605
611
raise ModelicaSystemError (f"{ i } could not be computed" ) from ex
606
612
return self .continuouslist
607
613
608
- elif isinstance (names , str ):
614
+ if isinstance (names , str ):
609
615
if names in self .continuouslist :
610
616
value = self .getSolutions (names )
611
617
self .continuouslist [names ] = value [0 ][- 1 ]
612
618
return [self .continuouslist .get (names )]
613
619
else :
614
620
raise ModelicaSystemError (f"{ names } is not continuous" )
615
621
616
- elif isinstance (names , list ):
622
+ if isinstance (names , list ):
617
623
valuelist = []
618
624
for i in names :
619
625
if i in self .continuouslist :
@@ -851,9 +857,9 @@ def simulate(self, resultfile: Optional[str] = None, simflags: Optional[str] = N
851
857
tmpdict = self .overridevariables .copy ()
852
858
tmpdict .update (self .simoptionsoverride )
853
859
# write to override file
854
- with open (overrideFile , "w" ) as file :
860
+ with open (file = overrideFile , mode = "w" , encoding = "utf-8" ) as fh :
855
861
for key , value in tmpdict .items ():
856
- file .write (f"{ key } ={ value } \n " )
862
+ fh .write (f"{ key } ={ value } \n " )
857
863
858
864
om_cmd .arg_set (key = "overrideFile" , val = overrideFile .as_posix ())
859
865
@@ -909,14 +915,16 @@ def getSolutions(self, varList=None, resultfile=None): # 12
909
915
self .sendExpression ("closeSimulationResultFile()" )
910
916
if varList is None :
911
917
return resultVars
912
- elif isinstance (varList , str ):
918
+
919
+ if isinstance (varList , str ):
913
920
if varList not in resultVars and varList != "time" :
914
921
raise ModelicaSystemError (f"Requested data { repr (varList )} does not exist" )
915
922
res = self .sendExpression (f'readSimulationResult("{ resFile } ", {{{ varList } }})' )
916
923
npRes = np .array (res )
917
924
self .sendExpression ("closeSimulationResultFile()" )
918
925
return npRes
919
- elif isinstance (varList , list ):
926
+
927
+ if isinstance (varList , list ):
920
928
for var in varList :
921
929
if var == "time" :
922
930
continue
@@ -934,7 +942,8 @@ def getSolutions(self, varList=None, resultfile=None): # 12
934
942
def _strip_space (name ):
935
943
if isinstance (name , str ):
936
944
return name .replace (" " , "" )
937
- elif isinstance (name , list ):
945
+
946
+ if isinstance (name , list ):
938
947
return [x .replace (" " , "" ) for x in name ]
939
948
940
949
raise ModelicaSystemError ("Unhandled input for strip_space()" )
@@ -1051,7 +1060,7 @@ def setInputs(self, name): # 15
1051
1060
value = name .split ("=" )
1052
1061
if value [0 ] in self .inputlist :
1053
1062
tmpvalue = eval (value [1 ])
1054
- if isinstance (tmpvalue , int ) or isinstance ( tmpvalue , float ):
1063
+ if isinstance (tmpvalue , ( int , float ) ):
1055
1064
self .inputlist [value [0 ]] = [(float (self .simulateOptions ["startTime" ]), float (value [1 ])),
1056
1065
(float (self .simulateOptions ["stopTime" ]), float (value [1 ]))]
1057
1066
elif isinstance (tmpvalue , list ):
@@ -1066,7 +1075,7 @@ def setInputs(self, name): # 15
1066
1075
value = var .split ("=" )
1067
1076
if value [0 ] in self .inputlist :
1068
1077
tmpvalue = eval (value [1 ])
1069
- if isinstance (tmpvalue , int ) or isinstance ( tmpvalue , float ):
1078
+ if isinstance (tmpvalue , ( int , float ) ):
1070
1079
self .inputlist [value [0 ]] = [(float (self .simulateOptions ["startTime" ]), float (value [1 ])),
1071
1080
(float (self .simulateOptions ["stopTime" ]), float (value [1 ]))]
1072
1081
elif isinstance (tmpvalue , list ):
@@ -1132,8 +1141,8 @@ def createCSVData(self) -> pathlib.Path:
1132
1141
1133
1142
csvFile = self .tempdir / f'{ self .modelName } .csv'
1134
1143
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 )
1137
1146
writer .writerows (csv_rows )
1138
1147
1139
1148
return csvFile
@@ -1234,11 +1243,11 @@ def load_module_from_path(module_name, file_path):
1234
1243
1235
1244
overrideLinearFile = self .tempdir / f'{ self .modelName } _override_linear.txt'
1236
1245
1237
- with open (overrideLinearFile , "w" ) as file :
1246
+ with open (file = overrideLinearFile , mode = "w" , encoding = "utf-8" ) as fh :
1238
1247
for key , value in self .overridevariables .items ():
1239
- file .write (f"{ key } ={ value } \n " )
1248
+ fh .write (f"{ key } ={ value } \n " )
1240
1249
for key , value in self .linearOptions .items ():
1241
- file .write (f"{ key } ={ value } \n " )
1250
+ fh .write (f"{ key } ={ value } \n " )
1242
1251
1243
1252
om_cmd .arg_set (key = "overrideFile" , val = overrideLinearFile .as_posix ())
1244
1253
0 commit comments