Skip to content

Commit 23fbb95

Browse files
committed
Merge branch 'ModelicaSystem_xml' into ModelicaSystem_use_OMCPath
2 parents b86b8cf + 56de1e7 commit 23fbb95

1 file changed

Lines changed: 33 additions & 21 deletions

File tree

OMPython/ModelicaSystem.py

Lines changed: 33 additions & 21 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
@@ -490,8 +489,8 @@ def buildModel(self, variableFilter: Optional[str] = None):
490489
buildModelResult = self._requestApi("buildModel", self._model_name, properties=varFilter)
491490
logger.debug("OM model build result: %s", buildModelResult)
492491

493-
self._xml_file = pathlib.Path(buildModelResult[0]).parent / buildModelResult[1]
494-
self._xmlparse()
492+
xml_file = pathlib.Path(buildModelResult[0]).parent / buildModelResult[1]
493+
self._xmlparse(xml_file=xml_file)
495494

496495
def sendExpression(self, expr: str, parsed: bool = True):
497496
try:
@@ -517,30 +516,42 @@ def _requestApi(self, apiName, entity=None, properties=None): # 2
517516

518517
return self.sendExpression(exp)
519518

520-
def _xmlparse(self):
521-
if not self._xml_file.is_file():
522-
raise ModelicaSystemError(f"XML file not generated: {self._xml_file}")
519+
def _xmlparse(self, xml_file: pathlib.Path):
520+
if not xml_file.is_file():
521+
raise ModelicaSystemError(f"XML file not generated: {xml_file}")
523522

524-
tree = ET.parse(self._xml_file)
523+
xml_content = xml_file.read_text()
524+
tree = ET.ElementTree(ET.fromstring(xml_content))
525525
rootCQ = tree.getroot()
526526
for attr in rootCQ.iter('DefaultExperiment'):
527527
for key in ("startTime", "stopTime", "stepSize", "tolerance",
528528
"solver", "outputFormat"):
529-
self._simulate_options[key] = attr.get(key)
529+
self._simulate_options[key] = str(attr.get(key))
530530

531531
for sv in rootCQ.iter('ScalarVariable'):
532-
scalar = {}
533-
for key in ("name", "description", "variability", "causality", "alias"):
534-
scalar[key] = sv.get(key)
535-
scalar["changeable"] = sv.get('isValueChangeable')
536-
scalar["aliasvariable"] = sv.get('aliasVariable')
532+
translations = {
533+
"alias": "alias",
534+
"aliasvariable": "aliasVariable",
535+
"causality": "causality",
536+
"changeable": "isValueChangeable",
537+
"description": "description",
538+
"name": "name",
539+
"variability": "variability",
540+
}
541+
542+
scalar: dict[str, Any] = {}
543+
for key_dst, key_src in translations.items():
544+
val = sv.get(key_src)
545+
scalar[key_dst] = None if val is None else str(val)
546+
537547
ch = list(sv)
538548
for att in ch:
539549
scalar["start"] = att.get('start')
540550
scalar["min"] = att.get('min')
541551
scalar["max"] = att.get('max')
542552
scalar["unit"] = att.get('unit')
543553

554+
# save parameters in the corresponding class variables
544555
if scalar["variability"] == "parameter":
545556
if scalar["name"] in self._override_variables:
546557
self._params[scalar["name"]] = self._override_variables[scalar["name"]]
@@ -1451,7 +1462,8 @@ def linearize(self, lintime: Optional[float] = None, simflags: Optional[str] = N
14511462
compatibility, because linearize() used to return `[A, B, C, D]`.
14521463
"""
14531464

1454-
if self._xml_file is None:
1465+
if len(self._quantities) == 0:
1466+
# if self._quantities has no content, the xml file was not parsed; see self._xmlparse()
14551467
raise ModelicaSystemError(
14561468
"Linearization cannot be performed as the model is not build, "
14571469
"use ModelicaSystem() to build the model first"
@@ -1466,17 +1478,17 @@ def linearize(self, lintime: Optional[float] = None, simflags: Optional[str] = N
14661478
overrideLinearFile = self.getWorkDirectory() / f'{self._model_name}_override_linear.txt'
14671479

14681480
with open(file=overrideLinearFile, mode="w", encoding="utf-8") as fh:
1469-
for key, value in self._override_variables.items():
1470-
fh.write(f"{key}={value}\n")
1471-
for key, value in self._linearization_options.items():
1472-
fh.write(f"{key}={value}\n")
1481+
for key1, value1 in self._override_variables.items():
1482+
fh.write(f"{key1}={value1}\n")
1483+
for key2, value2 in self._linearization_options.items():
1484+
fh.write(f"{key2}={value2}\n")
14731485

14741486
om_cmd.arg_set(key="overrideFile", val=overrideLinearFile.as_posix())
14751487

14761488
if self._has_inputs:
1477-
nameVal = self.getInputs()
1478-
for n in nameVal:
1479-
tupleList = nameVal.get(n)
1489+
nameVal = self._inputs
1490+
for name in nameVal:
1491+
tupleList = nameVal.get(name)
14801492
if tupleList is not None:
14811493
for l in tupleList:
14821494
if l[0] < float(self._simulate_options["startTime"]):

0 commit comments

Comments
 (0)