3333"""
3434
3535import ast
36- import csv
3736from dataclasses import dataclass
3837import logging
3938import numbers
@@ -383,7 +382,6 @@ def __init__(
383382 if not isinstance (lmodel , list ):
384383 raise ModelicaSystemError (f"Invalid input type for lmodel: { type (lmodel )} - list expected!" )
385384
386- self ._xml_file = None
387385 self ._lmodel = lmodel # may be needed if model is derived from other model
388386 self ._model_name = modelName # Model class name
389387 self ._file_name = pathlib .Path (fileName ).resolve () if fileName is not None else None # Model file/package name
@@ -480,8 +478,8 @@ def buildModel(self, variableFilter: Optional[str] = None):
480478 buildModelResult = self ._requestApi ("buildModel" , self ._model_name , properties = varFilter )
481479 logger .debug ("OM model build result: %s" , buildModelResult )
482480
483- self . _xml_file = pathlib .Path (buildModelResult [0 ]).parent / buildModelResult [1 ]
484- self ._xmlparse ()
481+ xml_file = pathlib .Path (buildModelResult [0 ]).parent / buildModelResult [1 ]
482+ self ._xmlparse (xml_file = xml_file )
485483
486484 def sendExpression (self , expr : str , parsed : bool = True ):
487485 try :
@@ -507,30 +505,42 @@ def _requestApi(self, apiName, entity=None, properties=None): # 2
507505
508506 return self .sendExpression (exp )
509507
510- def _xmlparse (self ):
511- if not self . _xml_file .is_file ():
512- raise ModelicaSystemError (f"XML file not generated: { self . _xml_file } " )
508+ def _xmlparse (self , xml_file : pathlib . Path ):
509+ if not xml_file .is_file ():
510+ raise ModelicaSystemError (f"XML file not generated: { xml_file } " )
513511
514- tree = ET .parse (self ._xml_file )
512+ xml_content = xml_file .read_text ()
513+ tree = ET .ElementTree (ET .fromstring (xml_content ))
515514 rootCQ = tree .getroot ()
516515 for attr in rootCQ .iter ('DefaultExperiment' ):
517516 for key in ("startTime" , "stopTime" , "stepSize" , "tolerance" ,
518517 "solver" , "outputFormat" ):
519- self ._simulate_options [key ] = attr .get (key )
518+ self ._simulate_options [key ] = str ( attr .get (key ) )
520519
521520 for sv in rootCQ .iter ('ScalarVariable' ):
522- scalar = {}
523- for key in ("name" , "description" , "variability" , "causality" , "alias" ):
524- scalar [key ] = sv .get (key )
525- scalar ["changeable" ] = sv .get ('isValueChangeable' )
526- scalar ["aliasvariable" ] = sv .get ('aliasVariable' )
521+ translations = {
522+ "alias" : "alias" ,
523+ "aliasvariable" : "aliasVariable" ,
524+ "causality" : "causality" ,
525+ "changeable" : "isValueChangeable" ,
526+ "description" : "description" ,
527+ "name" : "name" ,
528+ "variability" : "variability" ,
529+ }
530+
531+ scalar : dict [str , Any ] = {}
532+ for key_dst , key_src in translations .items ():
533+ val = sv .get (key_src )
534+ scalar [key_dst ] = None if val is None else str (val )
535+
527536 ch = list (sv )
528537 for att in ch :
529538 scalar ["start" ] = att .get ('start' )
530539 scalar ["min" ] = att .get ('min' )
531540 scalar ["max" ] = att .get ('max' )
532541 scalar ["unit" ] = att .get ('unit' )
533542
543+ # save parameters in the corresponding class variables
534544 if scalar ["variability" ] == "parameter" :
535545 if scalar ["name" ] in self ._override_variables :
536546 self ._params [scalar ["name" ]] = self ._override_variables [scalar ["name" ]]
@@ -954,16 +964,17 @@ def simulate_cmd(
954964 if simargs :
955965 om_cmd .args_set (args = simargs )
956966
957- overrideFile = self ._tempdir / f"{ self ._model_name } _override.txt"
958967 if self ._override_variables or self ._simulate_options_override :
959- tmpdict = self ._override_variables .copy ()
960- tmpdict .update (self ._simulate_options_override )
961- # write to override file
962- with open (file = overrideFile , mode = "w" , encoding = "utf-8" ) as fh :
963- for key , value in tmpdict .items ():
964- fh .write (f"{ key } ={ value } \n " )
968+ override_file = result_file .parent / f"{ result_file .stem } _override.txt"
969+
970+ override_content = (
971+ "\n " .join ([f"{ key } ={ value } " for key , value in self ._override_variables .items ()])
972+ + "\n " .join ([f"{ key } ={ value } " for key , value in self ._simulate_options_override .items ()])
973+ + "\n "
974+ )
965975
966- om_cmd .arg_set (key = "overrideFile" , val = overrideFile .as_posix ())
976+ override_file .write_text (override_content )
977+ om_cmd .arg_set (key = "overrideFile" , val = override_file .as_posix ())
967978
968979 if self ._inputs : # if model has input quantities
969980 for key in self ._inputs :
@@ -1421,9 +1432,10 @@ def _createCSVData(self, csvfile: Optional[pathlib.Path] = None) -> pathlib.Path
14211432 if csvfile is None :
14221433 csvfile = self ._tempdir / f'{ self ._model_name } .csv'
14231434
1424- with open (file = csvfile , mode = "w" , encoding = "utf-8" , newline = "" ) as fh :
1425- writer = csv .writer (fh )
1426- writer .writerows (csv_rows )
1435+ # basic definition of a CSV file using csv_rows as input
1436+ csv_content = "\n " .join (["," .join (map (str , row )) for row in csv_rows ]) + "\n "
1437+
1438+ csvfile .write_text (csv_content )
14271439
14281440 return csvfile
14291441
@@ -1535,7 +1547,8 @@ def linearize(self, lintime: Optional[float] = None, simflags: Optional[str] = N
15351547 compatibility, because linearize() used to return `[A, B, C, D]`.
15361548 """
15371549
1538- if self ._xml_file is None :
1550+ if len (self ._quantities ) == 0 :
1551+ # if self._quantities has no content, the xml file was not parsed; see self._xmlparse()
15391552 raise ModelicaSystemError (
15401553 "Linearization cannot be performed as the model is not build, "
15411554 "use ModelicaSystem() to build the model first"
@@ -1546,10 +1559,10 @@ def linearize(self, lintime: Optional[float] = None, simflags: Optional[str] = N
15461559 overrideLinearFile = self ._tempdir / f'{ self ._model_name } _override_linear.txt'
15471560
15481561 with open (file = overrideLinearFile , mode = "w" , encoding = "utf-8" ) as fh :
1549- for key , value in self ._override_variables .items ():
1550- fh .write (f"{ key } ={ value } \n " )
1551- for key , value in self ._linearization_options .items ():
1552- fh .write (f"{ key } ={ value } \n " )
1562+ for key1 , value1 in self ._override_variables .items ():
1563+ fh .write (f"{ key1 } ={ value1 } \n " )
1564+ for key2 , value2 in self ._linearization_options .items ():
1565+ fh .write (f"{ key2 } ={ value2 } \n " )
15531566
15541567 om_cmd .arg_set (key = "overrideFile" , val = overrideLinearFile .as_posix ())
15551568
0 commit comments