Skip to content

[ModelicaSystem] Cleanup & mypy #292

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 4, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 13 additions & 13 deletions OMPython/ModelicaSystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,8 +322,8 @@ def __init__(
customBuildDirectory: Optional[str | os.PathLike | pathlib.Path] = None,
omhome: Optional[str] = None,
session: Optional[OMCSessionZMQ] = None,
build: Optional[bool] = True
):
build: Optional[bool] = True,
) -> None:
"""Initialize, load and build a model.

The constructor loads the model file and builds it, generating exe and
Expand Down Expand Up @@ -401,8 +401,8 @@ def __init__(
self.inputFlag = False # for model with input quantity
self.simulationFlag = False # if the model is simulated?
self.outputFlag = False
self.csvFile = '' # for storing inputs condition
self.resultfile = None # for storing result file
self.csvFile: Optional[pathlib.Path] = None # for storing inputs condition
self.resultfile: Optional[pathlib.Path] = None # for storing result file
self.variableFilter = variableFilter

if self.fileName is not None and not self.fileName.is_file(): # if file does not exist
Expand All @@ -427,7 +427,7 @@ def __init__(
if build:
self.buildModel(variableFilter)

def setCommandLineOptions(self, commandLineOptions: str):
def setCommandLineOptions(self, commandLineOptions: Optional[str] = None):
# set commandLineOptions if provided by users
if commandLineOptions is None:
return
Expand Down Expand Up @@ -462,7 +462,7 @@ def loadLibrary(self, lmodel: list):
'1)["Modelica"]\n'
'2)[("Modelica","3.2.3"), "PowerSystems"]\n')

def setTempDirectory(self, customBuildDirectory) -> pathlib.Path:
def setTempDirectory(self, customBuildDirectory: Optional[str | os.PathLike | pathlib.Path] = None) -> pathlib.Path:
# create a unique temp directory for each session and build the model in that directory
if customBuildDirectory is not None:
if not os.path.exists(customBuildDirectory):
Expand All @@ -482,22 +482,22 @@ def setTempDirectory(self, customBuildDirectory) -> pathlib.Path:
def getWorkDirectory(self) -> pathlib.Path:
return self.tempdir

def buildModel(self, variableFilter=None):
def buildModel(self, variableFilter: Optional[str] = None):
if variableFilter is not None:
self.variableFilter = variableFilter

if self.variableFilter is not None:
varFilter = f'variableFilter="{self.variableFilter}"'
else:
varFilter = 'variableFilter=".*"'
logger.debug("varFilter=%s", varFilter)

buildModelResult = self.requestApi("buildModel", self.modelName, properties=varFilter)
logger.debug("OM model build result: %s", buildModelResult)

self.xmlFile = pathlib.Path(buildModelResult[0]).parent / buildModelResult[1]
self.xmlparse()

def sendExpression(self, expr, parsed=True):
def sendExpression(self, expr: str, parsed: bool = True):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be parsed: Optional[bool] = True, right?

Copy link
Contributor Author

@syntron syntron Jun 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not in this case as True is a valid bool value; it would be needed in case of parsed: Optional[bool] = None

Optional[abc] resolves to abc | None - both values are used as type hints

try:
retval = self.getconn.sendExpression(expr, parsed)
except OMCSessionException as ex:
Expand All @@ -522,7 +522,7 @@ def requestApi(self, apiName, entity=None, properties=None): # 2
return self.sendExpression(exp)

def xmlparse(self):
if not self.xmlFile.exists():
if not self.xmlFile.is_file():
raise ModelicaSystemError(f"XML file not generated: {self.xmlFile}")

tree = ET.parse(self.xmlFile)
Expand Down Expand Up @@ -597,7 +597,7 @@ def getContinuous(self, names=None): # 4
try:
value = self.getSolutions(i)
self.continuouslist[i] = value[0][-1]
except OMCSessionException as ex:
except (OMCSessionException, ModelicaSystemError) as ex:
raise ModelicaSystemError(f"{i} could not be computed") from ex
return self.continuouslist

Expand Down Expand Up @@ -999,8 +999,8 @@ def isParameterChangeable(self, name, value):
if q[0]["changeable"] == "false":
logger.verbose(f"setParameters() failed : It is not possible to set the following signal {repr(name)}. "
"It seems to be structural, final, protected or evaluated or has a non-constant binding, "
f"use sendExpression(\"setParameterValue({self.modelName}, {name}, {value})\", "
"parsed=False) and rebuild the model using buildModel() API")
f"use sendExpression(\"setParameterValue({self.modelName}, {name}, {value})\") "
"and rebuild the model using buildModel() API")
return False
return True

Expand Down
Loading