Skip to content

Commit 6cfe458

Browse files
committed
Merge branch 'parser' of https://github.com/syntron/OMPython into parser
2 parents fbd5c50 + a906365 commit 6cfe458

File tree

3 files changed

+52
-63
lines changed

3 files changed

+52
-63
lines changed

OMPython/ModelicaSystem.py

Lines changed: 48 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -320,8 +320,9 @@ def _run_cmd(self, cmd: list):
320320
raise ModelicaSystemError(f"Error running command {cmd}: {stderr}")
321321
if self._verbose and stdout:
322322
logger.info("OM output for command %s:\n%s", cmd, stdout)
323-
p.wait()
324-
p.terminate()
323+
# check process returncode, some errors don't print to stderr
324+
if p.wait():
325+
raise ModelicaSystemError(f"Error running command {cmd}: nonzero returncode")
325326
except Exception as e:
326327
raise ModelicaSystemError(f"Exception {type(e)} running command {cmd}: {e}")
327328

@@ -395,19 +396,11 @@ def xmlparse(self):
395396
scalar["changeable"] = sv.get('isValueChangeable')
396397
scalar["aliasvariable"] = sv.get('aliasVariable')
397398
ch = list(sv)
398-
start = None
399-
min = None
400-
max = None
401-
unit = None
402399
for att in ch:
403-
start = att.get('start')
404-
min = att.get('min')
405-
max = att.get('max')
406-
unit = att.get('unit')
407-
scalar["start"] = start
408-
scalar["min"] = min
409-
scalar["max"] = max
410-
scalar["unit"] = unit
400+
scalar["start"] = att.get('start')
401+
scalar["min"] = att.get('min')
402+
scalar["max"] = att.get('max')
403+
scalar["unit"] = att.get('unit')
411404

412405
if scalar["variability"] == "parameter":
413406
if scalar["name"] in self.overridevariables:
@@ -438,6 +431,8 @@ def getQuantities(self, names=None): # 3
438431
elif isinstance(names, list):
439432
return [x for y in names for x in self.quantitiesList if x["name"] == y]
440433

434+
raise ModelicaSystemError("Unhandled input for getQuantities()")
435+
441436
def getContinuous(self, names=None): # 4
442437
"""
443438
This method returns dict. The key is continuous names and value is corresponding continuous value.
@@ -482,6 +477,8 @@ def getContinuous(self, names=None): # 4
482477
raise ModelicaSystemError(f"OM error: {i} is not continuous")
483478
return valuelist
484479

480+
raise ModelicaSystemError("Unhandled input for getContinous()")
481+
485482
def getParameters(self, names: Optional[str | list[str]] = None) -> dict[str, str] | list[str]: # 5
486483
"""Get parameter values.
487484
@@ -509,7 +506,9 @@ def getParameters(self, names: Optional[str | list[str]] = None) -> dict[str, st
509506
elif isinstance(names, str):
510507
return [self.paramlist.get(names, "NotExist")]
511508
elif isinstance(names, list):
512-
return ([self.paramlist.get(x, "NotExist") for x in names])
509+
return [self.paramlist.get(x, "NotExist") for x in names]
510+
511+
raise ModelicaSystemError("Unhandled input for getParameters()")
513512

514513
def getInputs(self, names: Optional[str | list[str]] = None) -> dict | list: # 6
515514
"""Get input values.
@@ -543,7 +542,9 @@ def getInputs(self, names: Optional[str | list[str]] = None) -> dict | list: #
543542
elif isinstance(names, str):
544543
return [self.inputlist.get(names, "NotExist")]
545544
elif isinstance(names, list):
546-
return ([self.inputlist.get(x, "NotExist") for x in names])
545+
return [self.inputlist.get(x, "NotExist") for x in names]
546+
547+
raise ModelicaSystemError("Unhandled input for getInputs()")
547548

548549
def getOutputs(self, names: Optional[str | list[str]] = None): # 7
549550
"""Get output values.
@@ -588,7 +589,7 @@ def getOutputs(self, names: Optional[str | list[str]] = None): # 7
588589
elif isinstance(names, str):
589590
return [self.outputlist.get(names, "NotExist")]
590591
else:
591-
return ([self.outputlist.get(x, "NotExist") for x in names])
592+
return [self.outputlist.get(x, "NotExist") for x in names]
592593
else:
593594
if names is None:
594595
for i in self.outputlist:
@@ -601,7 +602,7 @@ def getOutputs(self, names: Optional[str | list[str]] = None): # 7
601602
self.outputlist[names] = value[0][-1]
602603
return [self.outputlist.get(names)]
603604
else:
604-
return (names, " is not Output")
605+
return names, " is not Output"
605606
elif isinstance(names, list):
606607
valuelist = []
607608
for i in names:
@@ -610,9 +611,11 @@ def getOutputs(self, names: Optional[str | list[str]] = None): # 7
610611
self.outputlist[i] = value[0][-1]
611612
valuelist.append(value[0][-1])
612613
else:
613-
return (i, "is not Output")
614+
return i, "is not Output"
614615
return valuelist
615616

617+
raise ModelicaSystemError("Unhandled input for getOutputs()")
618+
616619
def getSimulationOptions(self, names=None): # 8
617620
"""
618621
This method returns dict. The key is simulation option names and value is corresponding simulation option value.
@@ -627,7 +630,9 @@ def getSimulationOptions(self, names=None): # 8
627630
elif isinstance(names, str):
628631
return [self.simulateOptions.get(names, "NotExist")]
629632
elif isinstance(names, list):
630-
return ([self.simulateOptions.get(x, "NotExist") for x in names])
633+
return [self.simulateOptions.get(x, "NotExist") for x in names]
634+
635+
raise ModelicaSystemError("Unhandled input for getSimulationOptions()")
631636

632637
def getLinearizationOptions(self, names=None): # 9
633638
"""
@@ -643,7 +648,9 @@ def getLinearizationOptions(self, names=None): # 9
643648
elif isinstance(names, str):
644649
return [self.linearOptions.get(names, "NotExist")]
645650
elif isinstance(names, list):
646-
return ([self.linearOptions.get(x, "NotExist") for x in names])
651+
return [self.linearOptions.get(x, "NotExist") for x in names]
652+
653+
raise ModelicaSystemError("Unhandled input for getLinearizationOptions()")
647654

648655
def getOptimizationOptions(self, names=None): # 10
649656
"""
@@ -657,7 +664,9 @@ def getOptimizationOptions(self, names=None): # 10
657664
elif isinstance(names, str):
658665
return [self.optimizeOptions.get(names, "NotExist")]
659666
elif isinstance(names, list):
660-
return ([self.optimizeOptions.get(x, "NotExist") for x in names])
667+
return [self.optimizeOptions.get(x, "NotExist") for x in names]
668+
669+
raise ModelicaSystemError("Unhandled input for getOptimizationOptions()")
661670

662671
def get_exe_file(self) -> pathlib.Path:
663672
"""Get path to model executable."""
@@ -728,7 +737,7 @@ def simulate(self, resultfile=None, simflags=None): # 11
728737
raise Exception(f"Error: Application file path not found: {exe_file}")
729738

730739
cmd = exe_file.as_posix() + override + csvinput + r + simflags
731-
cmd = cmd.split(" ")
740+
cmd = [s for s in cmd.split(' ') if s]
732741
self._run_cmd(cmd=cmd)
733742
self.simulationFlag = True
734743

@@ -752,41 +761,40 @@ def getSolutions(self, varList=None, resultfile=None): # 12
752761

753762
# check for result file exits
754763
if not os.path.exists(resFile):
755-
errstr = f"Error: Result file does not exist {resFile}"
756-
self._raise_error(errstr=errstr)
757-
return
764+
raise ModelicaSystemError(f"Result file does not exist {resFile}")
758765
resultVars = self.sendExpression(f'readSimulationResultVars("{resFile}")')
759766
self.sendExpression("closeSimulationResultFile()")
760767
if varList is None:
761768
return resultVars
762769
elif isinstance(varList, str):
763770
if varList not in resultVars and varList != "time":
764-
self._raise_error(errstr=f'!!! {varList} does not exist')
765-
return
771+
raise ModelicaSystemError(f"Requested data {repr(varList)} does not exist")
766772
res = self.sendExpression(f'readSimulationResult("{resFile}", {{{varList}}})')
767773
npRes = np.array(res)
768774
self.sendExpression("closeSimulationResultFile()")
769775
return npRes
770776
elif isinstance(varList, list):
771-
# varList, = varList
772-
for v in varList:
773-
if v == "time":
777+
for var in varList:
778+
if var == "time":
774779
continue
775-
if v not in resultVars:
776-
self._raise_error(errstr=f'!!! {v} does not exist')
777-
return
780+
if var not in resultVars:
781+
raise ModelicaSystemError(f"Requested data {repr(var)} does not exist")
778782
variables = ",".join(varList)
779783
res = self.sendExpression(f'readSimulationResult("{resFile}",{{{variables}}})')
780784
npRes = np.array(res)
781785
self.sendExpression("closeSimulationResultFile()")
782786
return npRes
783787

788+
raise ModelicaSystemError("Unhandled input for getSolutions()")
789+
784790
def strip_space(self, name):
785791
if isinstance(name, str):
786792
return name.replace(" ", "")
787793
elif isinstance(name, list):
788794
return [x.replace(" ", "") for x in name]
789795

796+
raise ModelicaSystemError("Unhandled input for strip_space()")
797+
790798
def setMethodHelper(self, args1, args2, args3, args4=None):
791799
"""
792800
Helper function for setParameter(),setContinuous(),setSimulationOptions(),setLinearizationOption(),setOptimizationOption()
@@ -811,7 +819,8 @@ def apply_single(args1):
811819
return True
812820

813821
else:
814-
self._raise_error(errstr=f'"{value[0]}" is not a {args3} variable')
822+
raise ModelicaSystemError("Unhandled case in setMethodHelper.apply_single() - "
823+
f"{repr(value[0])} is not a {repr(args3)} variable")
815824

816825
result = []
817826
if isinstance(args1, str):
@@ -847,7 +856,7 @@ def setParameters(self, pvals): # 14
847856

848857
def isParameterChangeable(self, name, value):
849858
q = self.getQuantities(name)
850-
if (q[0]["changeable"] == "false"):
859+
if q[0]["changeable"] == "false":
851860
if self._verbose:
852861
logger.info("setParameters() failed : It is not possible to set "
853862
f'the following signal "{name}", It seems to be structural, final, '
@@ -916,10 +925,10 @@ def setInputs(self, name): # 15
916925
value = var.split("=")
917926
if value[0] in self.inputlist:
918927
tmpvalue = eval(value[1])
919-
if (isinstance(tmpvalue, int) or isinstance(tmpvalue, float)):
928+
if isinstance(tmpvalue, int) or isinstance(tmpvalue, float):
920929
self.inputlist[value[0]] = [(float(self.simulateOptions["startTime"]), float(value[1])),
921930
(float(self.simulateOptions["stopTime"]), float(value[1]))]
922-
elif (isinstance(tmpvalue, list)):
931+
elif isinstance(tmpvalue, list):
923932
self.checkValidInputs(tmpvalue)
924933
self.inputlist[value[0]] = tmpvalue
925934
self.inputFlag = True
@@ -1106,7 +1115,7 @@ def linearize(self, lintime: Optional[float] = None, simflags: Optional[str] = N
11061115
raise Exception(f"Error: Application file path not found: {exe_file}")
11071116
else:
11081117
cmd = exe_file.as_posix() + linruntime + override + csvinput + simflags
1109-
cmd = cmd.split(' ')
1118+
cmd = [s for s in cmd.split(' ') if s]
11101119
self._run_cmd(cmd=cmd)
11111120

11121121
# code to get the matrix and linear inputs, outputs and states

OMPython/OMCSession.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -253,17 +253,15 @@ def getComponentModifierNames(self, className, componentName):
253253
return self.ask('getComponentModifierNames', f'{className}, {componentName}')
254254

255255
def getComponentModifierValue(self, className, componentName):
256-
result = self._ask_with_fallback(question='getComponentModifierValue',
257-
opt=f'{className}, {componentName}')
258-
return result[2:]
256+
return self._ask_with_fallback(question='getComponentModifierValue',
257+
opt=f'{className}, {componentName}')
259258

260259
def getExtendsModifierNames(self, className, componentName):
261260
return self.ask('getExtendsModifierNames', f'{className}, {componentName}')
262261

263262
def getExtendsModifierValue(self, className, extendsName, modifierName):
264-
result = self._ask_with_fallback(question='getExtendsModifierValue',
265-
opt=f'{className}, {extendsName}, {modifierName}')
266-
return result[2:]
263+
return self._ask_with_fallback(question='getExtendsModifierValue',
264+
opt=f'{className}, {extendsName}, {modifierName}')
267265

268266
def getNthComponentModification(self, className, comp_id):
269267
# FIXME: OMPython exception Results KeyError exception

OMPython/__init__.py

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -36,27 +36,9 @@
3636
CONDITIONS OF OSMC-PL.
3737
"""
3838

39-
import logging
40-
4139
from OMPython.OMCSession import OMCSessionBase, OMCSessionZMQ
4240
from OMPython.ModelicaSystem import ModelicaSystem, ModelicaSystemError, LinearizationResult
4341

44-
# Logger Defined
45-
logger = logging.getLogger('OMPython')
46-
logger.setLevel(logging.DEBUG)
47-
# create console handler with a higher log level
48-
logger_console_handler = logging.StreamHandler()
49-
logger_console_handler.setLevel(logging.INFO)
50-
51-
# create formatter and add it to the handlers
52-
logger_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
53-
logger_console_handler.setFormatter(logger_formatter)
54-
55-
# add the handlers to the logger
56-
logger.addHandler(logger_console_handler)
57-
logger.setLevel(logging.WARNING)
58-
59-
6042
# global names imported if import 'from OMPython import *' is used
6143
__all__ = [
6244
'ModelicaSystem',

0 commit comments

Comments
 (0)