Skip to content

Commit 59be6a3

Browse files
committed
[ModelicaSystem.linearize] do not execute python file but use ast to get the data
1 parent 797eb84 commit 59be6a3

1 file changed

Lines changed: 47 additions & 31 deletions

File tree

OMPython/ModelicaSystem.py

Lines changed: 47 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,9 @@
3232
CONDITIONS OF OSMC-PL.
3333
"""
3434

35+
import ast
3536
import csv
3637
from dataclasses import dataclass
37-
import importlib
3838
import logging
3939
import numbers
4040
import numpy as np
@@ -1429,14 +1429,6 @@ def linearize(self, lintime: Optional[float] = None, simflags: Optional[str] = N
14291429
compatibility, because linearize() used to return `[A, B, C, D]`.
14301430
"""
14311431

1432-
# replacement for depreciated importlib.load_module()
1433-
def load_module_from_path(module_name, file_path):
1434-
spec = importlib.util.spec_from_file_location(module_name, file_path)
1435-
module_def = importlib.util.module_from_spec(spec)
1436-
spec.loader.exec_module(module_def)
1437-
1438-
return module_def
1439-
14401432
if self._xml_file is None:
14411433
raise ModelicaSystemError(
14421434
"Linearization cannot be performed as the model is not build, "
@@ -1475,38 +1467,62 @@ def load_module_from_path(module_name, file_path):
14751467
if simargs:
14761468
om_cmd.args_set(args=simargs)
14771469

1470+
# the file create by the model executable which contains the matrix and linear inputs, outputs and states
1471+
linear_file = self._tempdir / "linearized_model.py"
1472+
1473+
linear_file.unlink(missing_ok=True)
1474+
14781475
returncode = om_cmd.run()
14791476
if returncode != 0:
14801477
raise ModelicaSystemError(f"Linearize failed with return code: {returncode}")
14811478

14821479
self._simulated = True
14831480

1484-
# code to get the matrix and linear inputs, outputs and states
1485-
linearFile = self._tempdir / "linearized_model.py"
1481+
if not linear_file.exists():
1482+
raise ModelicaSystemError(f"Linearization failed: {linear_file} not found!")
14861483

14871484
# support older openmodelica versions before OpenModelica v1.16.2 where linearize() generates "linear_model_name.mo" file
1488-
if not linearFile.exists():
1489-
linearFile = pathlib.Path(f'linear_{self._model_name}.py')
1490-
1491-
if not linearFile.exists():
1492-
raise ModelicaSystemError(f"Linearization failed: {linearFile} not found!")
1485+
if not linear_file.exists():
1486+
linear_file = pathlib.Path(f'linear_{self._model_name}.py')
14931487

1494-
# this function is called from the generated python code linearized_model.py at runtime,
1495-
# to improve the performance by directly reading the matrices A, B, C and D from the julia code and avoid building the linearized modelica model
1488+
# extract data from the python file with the linearized model using the ast module - this allows to get the
1489+
# needed information without executing the created code
1490+
linear_data = {}
1491+
linear_file_content = linear_file.read_text()
14961492
try:
1497-
# do not add the linearfile directory to path, as multiple execution of linearization will always use the first added path, instead execute the file
1498-
# https://github.com/OpenModelica/OMPython/issues/196
1499-
module = load_module_from_path(module_name="linearized_model", file_path=linearFile.as_posix())
1500-
1501-
result = module.linearized_model()
1502-
(n, m, p, x0, u0, A, B, C, D, stateVars, inputVars, outputVars) = result
1503-
self._linearized_inputs = inputVars
1504-
self._linearized_outputs = outputVars
1505-
self._linearized_states = stateVars
1506-
return LinearizationResult(n, m, p, A, B, C, D, x0, u0, stateVars,
1507-
inputVars, outputVars)
1508-
except ModuleNotFoundError as ex:
1509-
raise ModelicaSystemError("No module named 'linearized_model'") from ex
1493+
linear_file_ast = ast.parse(linear_file_content)
1494+
for body_part in linear_file_ast.body[0].body:
1495+
if not isinstance(body_part, ast.Assign):
1496+
continue
1497+
1498+
target = body_part.targets[0].id
1499+
value = ast.literal_eval(body_part.value)
1500+
1501+
linear_data[target] = value
1502+
except (AttributeError, IndexError, ValueError, SyntaxError, TypeError) as ex:
1503+
raise ModelicaSystemError(f"Error parsing linearization file {linear_file}!") from ex
1504+
1505+
# remove the file
1506+
linear_file.unlink()
1507+
1508+
self._linearized_inputs = linear_data["inputVars"]
1509+
self._linearized_outputs = linear_data["outputVars"]
1510+
self._linearized_states = linear_data["stateVars"]
1511+
1512+
return LinearizationResult(
1513+
n=linear_data["n"],
1514+
m=linear_data["m"],
1515+
p=linear_data["p"],
1516+
x0=linear_data["x0"],
1517+
u0=linear_data["u0"],
1518+
A=linear_data["A"],
1519+
B=linear_data["B"],
1520+
C=linear_data["C"],
1521+
D=linear_data["D"],
1522+
stateVars=linear_data["stateVars"],
1523+
inputVars=linear_data["inputVars"],
1524+
outputVars=linear_data["outputVars"],
1525+
)
15101526

15111527
def getLinearInputs(self) -> list[str]:
15121528
"""Get names of input variables of the linearized model."""

0 commit comments

Comments
 (0)