Skip to content

Commit 2e69f3c

Browse files
authored
ModelicaSystem - remove xml_file as class variable (#321)
* [ModelicaSystem] update handling of xml_file * [ModelicaSystem] replace ET.parse() with ET.ElementTree(ET.fromstring()) read the file content and work on this string see: https://stackoverflow.com/questions/647071/python-xml-elementtree-from-a-string-source * [ModelicaSystem._xmlparse] mypy fixes & cleanup * [ModelicaSystem] remove class variable _xml_file * [ModelicaSystem] fix mypy warning - value can have different types in this code (int or str)
1 parent abcae09 commit 2e69f3c

File tree

1 file changed

+30
-18
lines changed

1 file changed

+30
-18
lines changed

OMPython/ModelicaSystem.py

Lines changed: 30 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -383,7 +383,6 @@ def __init__(
383383
if not isinstance(lmodel, list):
384384
raise ModelicaSystemError(f"Invalid input type for lmodel: {type(lmodel)} - list expected!")
385385

386-
self._xml_file = None
387386
self._lmodel = lmodel # may be needed if model is derived from other model
388387
self._model_name = modelName # Model class name
389388
self._file_name = pathlib.Path(fileName).resolve() if fileName is not None else None # Model file/package name
@@ -480,8 +479,8 @@ def buildModel(self, variableFilter: Optional[str] = None):
480479
buildModelResult = self._requestApi("buildModel", self._model_name, properties=varFilter)
481480
logger.debug("OM model build result: %s", buildModelResult)
482481

483-
self._xml_file = pathlib.Path(buildModelResult[0]).parent / buildModelResult[1]
484-
self._xmlparse()
482+
xml_file = pathlib.Path(buildModelResult[0]).parent / buildModelResult[1]
483+
self._xmlparse(xml_file=xml_file)
485484

486485
def sendExpression(self, expr: str, parsed: bool = True):
487486
try:
@@ -507,30 +506,42 @@ def _requestApi(self, apiName, entity=None, properties=None): # 2
507506

508507
return self.sendExpression(exp)
509508

510-
def _xmlparse(self):
511-
if not self._xml_file.is_file():
512-
raise ModelicaSystemError(f"XML file not generated: {self._xml_file}")
509+
def _xmlparse(self, xml_file: pathlib.Path):
510+
if not xml_file.is_file():
511+
raise ModelicaSystemError(f"XML file not generated: {xml_file}")
513512

514-
tree = ET.parse(self._xml_file)
513+
xml_content = xml_file.read_text()
514+
tree = ET.ElementTree(ET.fromstring(xml_content))
515515
rootCQ = tree.getroot()
516516
for attr in rootCQ.iter('DefaultExperiment'):
517517
for key in ("startTime", "stopTime", "stepSize", "tolerance",
518518
"solver", "outputFormat"):
519-
self._simulate_options[key] = attr.get(key)
519+
self._simulate_options[key] = str(attr.get(key))
520520

521521
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')
522+
translations = {
523+
"alias": "alias",
524+
"aliasvariable": "aliasVariable",
525+
"causality": "causality",
526+
"changeable": "isValueChangeable",
527+
"description": "description",
528+
"name": "name",
529+
"variability": "variability",
530+
}
531+
532+
scalar: dict[str, Any] = {}
533+
for key_dst, key_src in translations.items():
534+
val = sv.get(key_src)
535+
scalar[key_dst] = None if val is None else str(val)
536+
527537
ch = list(sv)
528538
for att in ch:
529539
scalar["start"] = att.get('start')
530540
scalar["min"] = att.get('min')
531541
scalar["max"] = att.get('max')
532542
scalar["unit"] = att.get('unit')
533543

544+
# save parameters in the corresponding class variables
534545
if scalar["variability"] == "parameter":
535546
if scalar["name"] in self._override_variables:
536547
self._params[scalar["name"]] = self._override_variables[scalar["name"]]
@@ -1535,7 +1546,8 @@ def linearize(self, lintime: Optional[float] = None, simflags: Optional[str] = N
15351546
compatibility, because linearize() used to return `[A, B, C, D]`.
15361547
"""
15371548

1538-
if self._xml_file is None:
1549+
if len(self._quantities) == 0:
1550+
# if self._quantities has no content, the xml file was not parsed; see self._xmlparse()
15391551
raise ModelicaSystemError(
15401552
"Linearization cannot be performed as the model is not build, "
15411553
"use ModelicaSystem() to build the model first"
@@ -1546,10 +1558,10 @@ def linearize(self, lintime: Optional[float] = None, simflags: Optional[str] = N
15461558
overrideLinearFile = self._tempdir / f'{self._model_name}_override_linear.txt'
15471559

15481560
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")
1561+
for key1, value1 in self._override_variables.items():
1562+
fh.write(f"{key1}={value1}\n")
1563+
for key2, value2 in self._linearization_options.items():
1564+
fh.write(f"{key2}={value2}\n")
15531565

15541566
om_cmd.arg_set(key="overrideFile", val=overrideLinearFile.as_posix())
15551567

0 commit comments

Comments
 (0)