Skip to content

Commit 70cb446

Browse files
syntronadeas31
andauthored
update usage of flake8 (#357)
* define flake8 config in pyproject.toml / remove setup.py * fix flake8 E741 - ambiguous variable name * cleanup OMTypedParser * function names * PEP8 renames in pyparsing (setParseAction() => set_parse_action()) * long lines * fix flake8 E501 - line too long * flake8 - fix test_linearization.py --------- Co-authored-by: Adeel Asghar <[email protected]>
1 parent 35e8b4f commit 70cb446

File tree

8 files changed

+71
-38
lines changed

8 files changed

+71
-38
lines changed

.pre-commit-config.yaml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ repos:
2020
rev: '7.2.0'
2121
hooks:
2222
- id: flake8
23+
additional_dependencies:
24+
- Flake8-pyproject
2325

2426
- repo: https://github.com/codespell-project/codespell
2527
rev: v2.4.1

OMPython/ModelicaSystem.py

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -877,7 +877,8 @@ def getSimulationOptions(self, names: Optional[str | list[str]] = None) -> dict[
877877
878878
Examples:
879879
>>> mod.getSimulationOptions()
880-
{'startTime': '0', 'stopTime': '1.234', 'stepSize': '0.002', 'tolerance': '1.1e-08', 'solver': 'dassl', 'outputFormat': 'mat'}
880+
{'startTime': '0', 'stopTime': '1.234',
881+
'stepSize': '0.002', 'tolerance': '1.1e-08', 'solver': 'dassl', 'outputFormat': 'mat'}
881882
>>> mod.getSimulationOptions("stopTime")
882883
['1.234']
883884
>>> mod.getSimulationOptions(["tolerance", "stopTime"])
@@ -1061,8 +1062,10 @@ def simulate(
10611062
Examples:
10621063
mod.simulate()
10631064
mod.simulate(resultfile="a.mat")
1064-
mod.simulate(simflags="-noEventEmit -noRestart -override=e=0.3,g=10") # set runtime simulation flags, deprecated
1065-
mod.simulate(simargs={"noEventEmit": None, "noRestart": None, "override": "override": {"e": 0.3, "g": 10}}) # using simargs
1065+
# set runtime simulation flags, deprecated
1066+
mod.simulate(simflags="-noEventEmit -noRestart -override=e=0.3,g=10")
1067+
# using simargs
1068+
mod.simulate(simargs={"noEventEmit": None, "noRestart": None, "override": "override": {"e": 0.3, "g": 10}})
10661069
"""
10671070

10681071
if resultfile is None:
@@ -1376,7 +1379,8 @@ def setSimulationOptions(
13761379
) -> bool:
13771380
"""
13781381
This method is used to set simulation options. It can be called:
1379-
with a sequence of simulation options name and assigning corresponding values as arguments as show in the example below:
1382+
with a sequence of simulation options name and assigning corresponding values as arguments as show in the
1383+
example below:
13801384
usage
13811385
>>> setSimulationOptions("Name=value") # depreciated
13821386
>>> setSimulationOptions(["Name1=value1","Name2=value2"]) # depreciated
@@ -1400,7 +1404,8 @@ def setLinearizationOptions(
14001404
) -> bool:
14011405
"""
14021406
This method is used to set linearization options. It can be called:
1403-
with a sequence of linearization options name and assigning corresponding value as arguments as show in the example below
1407+
with a sequence of linearization options name and assigning corresponding value as arguments as show in the
1408+
example below
14041409
usage
14051410
>>> setLinearizationOptions("Name=value") # depreciated
14061411
>>> setLinearizationOptions(["Name1=value1","Name2=value2"]) # depreciated
@@ -1424,7 +1429,8 @@ def setOptimizationOptions(
14241429
) -> bool:
14251430
"""
14261431
This method is used to set optimization options. It can be called:
1427-
with a sequence of optimization options name and assigning corresponding values as arguments as show in the example below:
1432+
with a sequence of optimization options name and assigning corresponding values as arguments as show in the
1433+
example below:
14281434
usage
14291435
>>> setOptimizationOptions("Name=value") # depreciated
14301436
>>> setOptimizationOptions(["Name1=value1","Name2=value2"]) # depreciated
@@ -1564,7 +1570,8 @@ def convertMo2Fmu(self, version: str = "2.0", fmuType: str = "me_cs",
15641570
Examples:
15651571
>>> mod.convertMo2Fmu()
15661572
'/tmp/tmpmhfx9umo/CauerLowPassAnalog.fmu'
1567-
>>> mod.convertMo2Fmu(version="2.0", fmuType="me|cs|me_cs", fileNamePrefix="<default>", includeResources=True)
1573+
>>> mod.convertMo2Fmu(version="2.0", fmuType="me|cs|me_cs", fileNamePrefix="<default>",
1574+
includeResources=True)
15681575
'/tmp/tmpmhfx9umo/CauerLowPassAnalog.fmu'
15691576
"""
15701577

@@ -1587,7 +1594,8 @@ def convertMo2Fmu(self, version: str = "2.0", fmuType: str = "me_cs",
15871594
# to convert FMU to Modelica model
15881595
def convertFmu2Mo(self, fmuName): # 20
15891596
"""
1590-
In order to load FMU, at first it needs to be translated into Modelica model. This method is used to generate Modelica model from the given FMU. It generates "fmuName_me_FMU.mo".
1597+
In order to load FMU, at first it needs to be translated into Modelica model. This method is used to generate
1598+
Modelica model from the given FMU. It generates "fmuName_me_FMU.mo".
15911599
Currently, it only supports Model Exchange conversion.
15921600
usage
15931601
>>> convertFmu2Mo("c:/BouncingBall.Fmu")

OMPython/OMCSession.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@
5757
import zmq
5858

5959
# TODO: replace this with the new parser
60-
from OMPython.OMTypedParser import parseString as om_parser_typed
60+
from OMPython.OMTypedParser import om_parser_typed
6161
from OMPython.OMParser import om_parser_basic
6262

6363
# define logger using the current module name as ID

OMPython/OMTypedParser.py

Lines changed: 43 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@
3131
__status__ = "Prototype"
3232
__maintainer__ = "https://openmodelica.org"
3333

34+
from typing import Any
35+
3436
from pyparsing import (
3537
Combine,
3638
Dict,
@@ -52,45 +54,45 @@
5254
)
5355

5456

55-
def convertNumbers(s, l, toks):
57+
def convert_numbers(s, loc, toks):
5658
n = toks[0]
5759
try:
5860
return int(n)
5961
except ValueError:
6062
return float(n)
6163

6264

63-
def convertString2(s, s2):
65+
def convert_string2(s, s2):
6466
tmp = s2[0].replace("\\\"", "\"")
6567
tmp = tmp.replace("\"", "\\\"")
6668
tmp = tmp.replace("\'", "\\'")
6769
tmp = tmp.replace("\f", "\\f")
6870
tmp = tmp.replace("\n", "\\n")
6971
tmp = tmp.replace("\r", "\\r")
7072
tmp = tmp.replace("\t", "\\t")
71-
return "'"+tmp+"'"
73+
return "'" + tmp + "'"
7274

7375

74-
def convertString(s, s2):
76+
def convert_string(s, s2):
7577
return s2[0].replace("\\\"", '"')
7678

7779

78-
def convertDict(d):
80+
def convert_dict(d):
7981
return dict(d[0])
8082

8183

82-
def convertTuple(t):
84+
def convert_tuple(t):
8385
return tuple(t[0])
8486

8587

86-
def evaluateExpression(s, loc, toks):
88+
def evaluate_expression(s, loc, toks):
8789
# Convert the tokens (ParseResults) into a string expression
8890
flat_list = [item for sublist in toks[0] for item in sublist]
8991
expr = "".join(flat_list)
9092
try:
9193
# Evaluate the expression safely
9294
return eval(expr)
93-
except Exception:
95+
except (SyntaxError, NameError):
9496
return expr
9597

9698

@@ -102,42 +104,60 @@ def evaluateExpression(s, loc, toks):
102104
(Word("*/", exact=1), 2, opAssoc.LEFT),
103105
(Word("+-", exact=1), 2, opAssoc.LEFT),
104106
],
105-
).setParseAction(evaluateExpression)
107+
).set_parse_action(evaluate_expression)
106108

107109
omcRecord = Forward()
108110
omcValue = Forward()
109111

110112
# pyparsing's replace_with (and thus replaceWith) has incorrect type
111113
# annotation: https://github.com/pyparsing/pyparsing/issues/602
112-
TRUE = Keyword("true").setParseAction(replaceWith(True)) # type: ignore
113-
FALSE = Keyword("false").setParseAction(replaceWith(False)) # type: ignore
114-
NONE = (Keyword("NONE") + Suppress("(") + Suppress(")")).setParseAction(replaceWith(None)) # type: ignore
114+
TRUE = Keyword("true").set_parse_action(replaceWith(True)) # type: ignore
115+
FALSE = Keyword("false").set_parse_action(replaceWith(False)) # type: ignore
116+
NONE = (Keyword("NONE") + Suppress("(") + Suppress(")")).set_parse_action(replaceWith(None)) # type: ignore
115117
SOME = (Suppress(Keyword("SOME")) + Suppress("(") + omcValue + Suppress(")"))
116118

117-
omcString = QuotedString(quoteChar='"', escChar='\\', multiline=True).setParseAction(convertString)
119+
omcString = QuotedString(quoteChar='"', escChar='\\', multiline=True).set_parse_action(convert_string)
118120
omcNumber = Combine(Optional('-') + ('0' | Word('123456789', nums)) +
119121
Optional('.' + Word(nums)) +
120122
Optional(Word('eE', exact=1) + Word(nums + '+-', nums)))
121123

122124
# ident = Word(alphas + "_", alphanums + "_") | Combine("'" + Word(alphanums + "!#$%&()*+,-./:;<>=?@[]^{}|~ ") + "'")
123-
ident = Word(alphas + "_", alphanums + "_") | QuotedString(quoteChar='\'', escChar='\\').setParseAction(convertString2)
125+
ident = (Word(alphas + "_", alphanums + "_")
126+
| QuotedString(quoteChar='\'', escChar='\\').set_parse_action(convert_string2))
124127
fqident = Forward()
125128
fqident << ((ident + "." + fqident) | ident)
126129
omcValues = delimitedList(omcValue)
127-
omcTuple = Group(Suppress('(') + Optional(omcValues) + Suppress(')')).setParseAction(convertTuple)
128-
omcArray = Group(Suppress('{') + Optional(omcValues) + Suppress('}')).setParseAction(convertTuple)
129-
omcArraySpecialTypes = Group(Suppress('{') + delimitedList(arrayDimension) + Suppress('}')).setParseAction(convertTuple)
130-
omcValue << (omcString | omcNumber | omcRecord | omcArray | omcArraySpecialTypes | omcTuple | SOME | TRUE | FALSE | NONE | Combine(fqident))
130+
omcTuple = Group(Suppress('(') + Optional(omcValues) + Suppress(')')).set_parse_action(convert_tuple)
131+
omcArray = Group(Suppress('{') + Optional(omcValues) + Suppress('}')).set_parse_action(convert_tuple)
132+
omcArraySpecialTypes = Group(Suppress('{')
133+
+ delimitedList(arrayDimension)
134+
+ Suppress('}')).set_parse_action(convert_tuple)
135+
omcValue << (omcString
136+
| omcNumber
137+
| omcRecord
138+
| omcArray
139+
| omcArraySpecialTypes
140+
| omcTuple
141+
| SOME
142+
| TRUE
143+
| FALSE
144+
| NONE
145+
| Combine(fqident))
131146
recordMember = delimitedList(Group(ident + Suppress('=') + omcValue))
132-
omcRecord << Group(Suppress('record') + Suppress(fqident) + Dict(recordMember) + Suppress('end') + Suppress(fqident) + Suppress(';')).setParseAction(convertDict)
147+
omcRecord << Group(Suppress('record')
148+
+ Suppress(fqident)
149+
+ Dict(recordMember)
150+
+ Suppress('end')
151+
+ Suppress(fqident)
152+
+ Suppress(';')).set_parse_action(convert_dict)
133153

134154
omcGrammar = Optional(omcValue) + StringEnd()
135155

136-
omcNumber.setParseAction(convertNumbers)
156+
omcNumber.set_parse_action(convert_numbers)
137157

138158

139-
def parseString(string):
140-
res = omcGrammar.parseString(string)
159+
def om_parser_typed(string) -> Any:
160+
res = omcGrammar.parse_string(string)
141161
if len(res) == 0:
142-
return
162+
return None
143163
return res[0]

pyproject.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,8 @@ Documentation = "https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/ompy
3232
Issues = "https://github.com/OpenModelica/OMPython/issues"
3333
"Release Notes" = "https://github.com/OpenModelica/OMPython/releases"
3434
Download = "https://pypi.org/project/OMPython/#files"
35+
36+
[tool.flake8]
37+
max-line-length = 120
38+
extend-ignore = [
39+
]

setup.cfg

Lines changed: 0 additions & 2 deletions
This file was deleted.

tests/test_linearization.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,12 +67,12 @@ def test_getters(tmp_path):
6767

6868
mod.setInputs(u1=10, u2=0)
6969
[A, B, C, D] = mod.linearize()
70-
g = float(mod.getParameters("g")[0])
71-
l = float(mod.getParameters("l")[0])
70+
param_g = float(mod.getParameters("g")[0])
71+
param_l = float(mod.getParameters("l")[0])
7272
assert mod.getLinearInputs() == ["u1", "u2"]
7373
assert mod.getLinearStates() == ["omega", "phi"]
7474
assert mod.getLinearOutputs() == ["y1", "y2"]
75-
assert np.isclose(A, [[0, g/l], [1, 0]]).all()
75+
assert np.isclose(A, [[0, param_g / param_l], [1, 0]]).all()
7676
assert np.isclose(B, [[0, 0], [0, 1]]).all()
7777
assert np.isclose(C, [[0.5, 1], [0, 1]]).all()
7878
assert np.isclose(D, [[1, 0], [1, 0]]).all()

tests/test_typedParser.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from OMPython import OMTypedParser
22

3-
typeCheck = OMTypedParser.parseString
3+
typeCheck = OMTypedParser.om_parser_typed
44

55

66
def test_newline_behaviour():

0 commit comments

Comments
 (0)