Skip to content

Commit cb657cf

Browse files
authored
Fix modelica system (#271)
* [ModelicaSystem] simplify code in xmlparse() * [ModelicaSystem] add ModelicaSystemError() for unhandled final else cases there are a lot of functions which check the type of the input; this is done by if ... elif ... - however, invalid input is not catched, i.e. there is *NO* return value define (would be None) if the input is not matching any of the if branches * [ModelicaSystem.getSolution()] do not try to continue on error but fail Rule: fail early, fail hard - tell the user that something is wrong! In this case, the user ask for the solution but could get None (= plain 'return') - this would case hard to track errors later (if verbose==False and raiseerrors==False) * [ModelicaSystem] remove redundant parentheses (type hint by PyCharm)
1 parent f6ac6cb commit cb657cf

File tree

1 file changed

+43
-35
lines changed

1 file changed

+43
-35
lines changed

OMPython/ModelicaSystem.py

Lines changed: 43 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -395,19 +395,11 @@ def xmlparse(self):
395395
scalar["changeable"] = sv.get('isValueChangeable')
396396
scalar["aliasvariable"] = sv.get('aliasVariable')
397397
ch = list(sv)
398-
start = None
399-
min = None
400-
max = None
401-
unit = None
402398
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
399+
scalar["start"] = att.get('start')
400+
scalar["min"] = att.get('min')
401+
scalar["max"] = att.get('max')
402+
scalar["unit"] = att.get('unit')
411403

412404
if scalar["variability"] == "parameter":
413405
if scalar["name"] in self.overridevariables:
@@ -438,6 +430,8 @@ def getQuantities(self, names=None): # 3
438430
elif isinstance(names, list):
439431
return [x for y in names for x in self.quantitiesList if x["name"] == y]
440432

433+
raise ModelicaSystemError("Unhandled input for getQuantities()")
434+
441435
def getContinuous(self, names=None): # 4
442436
"""
443437
This method returns dict. The key is continuous names and value is corresponding continuous value.
@@ -482,6 +476,8 @@ def getContinuous(self, names=None): # 4
482476
raise ModelicaSystemError(f"OM error: {i} is not continuous")
483477
return valuelist
484478

479+
raise ModelicaSystemError("Unhandled input for getContinous()")
480+
485481
def getParameters(self, names: Optional[str | list[str]] = None) -> dict[str, str] | list[str]: # 5
486482
"""Get parameter values.
487483
@@ -509,7 +505,9 @@ def getParameters(self, names: Optional[str | list[str]] = None) -> dict[str, st
509505
elif isinstance(names, str):
510506
return [self.paramlist.get(names, "NotExist")]
511507
elif isinstance(names, list):
512-
return ([self.paramlist.get(x, "NotExist") for x in names])
508+
return [self.paramlist.get(x, "NotExist") for x in names]
509+
510+
raise ModelicaSystemError("Unhandled input for getParameters()")
513511

514512
def getInputs(self, names: Optional[str | list[str]] = None) -> dict | list: # 6
515513
"""Get input values.
@@ -543,7 +541,9 @@ def getInputs(self, names: Optional[str | list[str]] = None) -> dict | list: #
543541
elif isinstance(names, str):
544542
return [self.inputlist.get(names, "NotExist")]
545543
elif isinstance(names, list):
546-
return ([self.inputlist.get(x, "NotExist") for x in names])
544+
return [self.inputlist.get(x, "NotExist") for x in names]
545+
546+
raise ModelicaSystemError("Unhandled input for getInputs()")
547547

548548
def getOutputs(self, names: Optional[str | list[str]] = None): # 7
549549
"""Get output values.
@@ -588,7 +588,7 @@ def getOutputs(self, names: Optional[str | list[str]] = None): # 7
588588
elif isinstance(names, str):
589589
return [self.outputlist.get(names, "NotExist")]
590590
else:
591-
return ([self.outputlist.get(x, "NotExist") for x in names])
591+
return [self.outputlist.get(x, "NotExist") for x in names]
592592
else:
593593
if names is None:
594594
for i in self.outputlist:
@@ -601,7 +601,7 @@ def getOutputs(self, names: Optional[str | list[str]] = None): # 7
601601
self.outputlist[names] = value[0][-1]
602602
return [self.outputlist.get(names)]
603603
else:
604-
return (names, " is not Output")
604+
return names, " is not Output"
605605
elif isinstance(names, list):
606606
valuelist = []
607607
for i in names:
@@ -610,9 +610,11 @@ def getOutputs(self, names: Optional[str | list[str]] = None): # 7
610610
self.outputlist[i] = value[0][-1]
611611
valuelist.append(value[0][-1])
612612
else:
613-
return (i, "is not Output")
613+
return i, "is not Output"
614614
return valuelist
615615

616+
raise ModelicaSystemError("Unhandled input for getOutputs()")
617+
616618
def getSimulationOptions(self, names=None): # 8
617619
"""
618620
This method returns dict. The key is simulation option names and value is corresponding simulation option value.
@@ -627,7 +629,9 @@ def getSimulationOptions(self, names=None): # 8
627629
elif isinstance(names, str):
628630
return [self.simulateOptions.get(names, "NotExist")]
629631
elif isinstance(names, list):
630-
return ([self.simulateOptions.get(x, "NotExist") for x in names])
632+
return [self.simulateOptions.get(x, "NotExist") for x in names]
633+
634+
raise ModelicaSystemError("Unhandled input for getSimulationOptions()")
631635

632636
def getLinearizationOptions(self, names=None): # 9
633637
"""
@@ -643,7 +647,9 @@ def getLinearizationOptions(self, names=None): # 9
643647
elif isinstance(names, str):
644648
return [self.linearOptions.get(names, "NotExist")]
645649
elif isinstance(names, list):
646-
return ([self.linearOptions.get(x, "NotExist") for x in names])
650+
return [self.linearOptions.get(x, "NotExist") for x in names]
651+
652+
raise ModelicaSystemError("Unhandled input for getLinearizationOptions()")
647653

648654
def getOptimizationOptions(self, names=None): # 10
649655
"""
@@ -657,7 +663,9 @@ def getOptimizationOptions(self, names=None): # 10
657663
elif isinstance(names, str):
658664
return [self.optimizeOptions.get(names, "NotExist")]
659665
elif isinstance(names, list):
660-
return ([self.optimizeOptions.get(x, "NotExist") for x in names])
666+
return [self.optimizeOptions.get(x, "NotExist") for x in names]
667+
668+
raise ModelicaSystemError("Unhandled input for getOptimizationOptions()")
661669

662670
def get_exe_file(self) -> pathlib.Path:
663671
"""Get path to model executable."""
@@ -752,41 +760,40 @@ def getSolutions(self, varList=None, resultfile=None): # 12
752760

753761
# check for result file exits
754762
if not os.path.exists(resFile):
755-
errstr = f"Error: Result file does not exist {resFile}"
756-
self._raise_error(errstr=errstr)
757-
return
763+
raise ModelicaSystemError(f"Result file does not exist {resFile}")
758764
resultVars = self.sendExpression(f'readSimulationResultVars("{resFile}")')
759765
self.sendExpression("closeSimulationResultFile()")
760766
if varList is None:
761767
return resultVars
762768
elif isinstance(varList, str):
763769
if varList not in resultVars and varList != "time":
764-
self._raise_error(errstr=f'!!! {varList} does not exist')
765-
return
770+
raise ModelicaSystemError(f"Requested data {repr(varList)} does not exist")
766771
res = self.sendExpression(f'readSimulationResult("{resFile}", {{{varList}}})')
767772
npRes = np.array(res)
768773
self.sendExpression("closeSimulationResultFile()")
769774
return npRes
770775
elif isinstance(varList, list):
771-
# varList, = varList
772-
for v in varList:
773-
if v == "time":
776+
for var in varList:
777+
if var == "time":
774778
continue
775-
if v not in resultVars:
776-
self._raise_error(errstr=f'!!! {v} does not exist')
777-
return
779+
if var not in resultVars:
780+
raise ModelicaSystemError(f"Requested data {repr(var)} does not exist")
778781
variables = ",".join(varList)
779782
res = self.sendExpression(f'readSimulationResult("{resFile}",{{{variables}}})')
780783
npRes = np.array(res)
781784
self.sendExpression("closeSimulationResultFile()")
782785
return npRes
783786

787+
raise ModelicaSystemError("Unhandled input for getSolutions()")
788+
784789
def strip_space(self, name):
785790
if isinstance(name, str):
786791
return name.replace(" ", "")
787792
elif isinstance(name, list):
788793
return [x.replace(" ", "") for x in name]
789794

795+
raise ModelicaSystemError("Unhandled input for strip_space()")
796+
790797
def setMethodHelper(self, args1, args2, args3, args4=None):
791798
"""
792799
Helper function for setParameter(),setContinuous(),setSimulationOptions(),setLinearizationOption(),setOptimizationOption()
@@ -811,7 +818,8 @@ def apply_single(args1):
811818
return True
812819

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

816824
result = []
817825
if isinstance(args1, str):
@@ -847,7 +855,7 @@ def setParameters(self, pvals): # 14
847855

848856
def isParameterChangeable(self, name, value):
849857
q = self.getQuantities(name)
850-
if (q[0]["changeable"] == "false"):
858+
if q[0]["changeable"] == "false":
851859
if self._verbose:
852860
logger.info("setParameters() failed : It is not possible to set "
853861
f'the following signal "{name}", It seems to be structural, final, '
@@ -916,10 +924,10 @@ def setInputs(self, name): # 15
916924
value = var.split("=")
917925
if value[0] in self.inputlist:
918926
tmpvalue = eval(value[1])
919-
if (isinstance(tmpvalue, int) or isinstance(tmpvalue, float)):
927+
if isinstance(tmpvalue, int) or isinstance(tmpvalue, float):
920928
self.inputlist[value[0]] = [(float(self.simulateOptions["startTime"]), float(value[1])),
921929
(float(self.simulateOptions["stopTime"]), float(value[1]))]
922-
elif (isinstance(tmpvalue, list)):
930+
elif isinstance(tmpvalue, list):
923931
self.checkValidInputs(tmpvalue)
924932
self.inputlist[value[0]] = tmpvalue
925933
self.inputFlag = True

0 commit comments

Comments
 (0)