Skip to content

ModelicaSystem - remove csvfile as class variable #313

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
27 changes: 18 additions & 9 deletions OMPython/ModelicaSystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,6 @@ def __init__(
self.inputFlag = False # for model with input quantity
self.simulationFlag = False # if the model is simulated?
self.outputFlag = False
self.csvFile: Optional[pathlib.Path] = None # for storing inputs condition
self.resultfile: Optional[pathlib.Path] = None # for storing result file
self.variableFilter = variableFilter

Expand Down Expand Up @@ -910,6 +909,9 @@ def simulate(self, resultfile: Optional[str] = None, simflags: Optional[str] = N
om_cmd.arg_set(key="overrideFile", val=overrideFile.as_posix())

if self.inputFlag: # if model has input quantities
# csvfile is based on name used for result file
csvfile = self.resultfile.parent / f"{self.resultfile.stem}.csv"

for i in self.inputlist:
val = self.inputlist[i]
if val is None:
Expand All @@ -921,9 +923,11 @@ def simulate(self, resultfile: Optional[str] = None, simflags: Optional[str] = N
raise ModelicaSystemError(f"startTime not matched for Input {i}!")
if float(self.simulateOptions["stopTime"]) != val[-1][0]:
raise ModelicaSystemError(f"stopTime not matched for Input {i}!")
self.csvFile = self.createCSVData() # create csv file

om_cmd.arg_set(key="csvInput", val=self.csvFile.as_posix())
# write csv file and store the name
csvfile = self.createCSVData(csvfile=csvfile)

om_cmd.arg_set(key="csvInput", val=csvfile.as_posix())

# delete resultfile ...
if self.resultfile.is_file():
Expand Down Expand Up @@ -1144,7 +1148,11 @@ def checkValidInputs(self, name):
else:
raise ModelicaSystemError('Error!!! Value must be in tuple format')

def createCSVData(self) -> pathlib.Path:
def createCSVData(self, csvfile: Optional[pathlib.Path] = None) -> pathlib.Path:
"""
Create a csv file with inputs for the simulation/optimization of the model. If csvfile is provided as argument,
this file is used; else a generic file name is created.
"""
start_time: float = float(self.simulateOptions["startTime"])
stop_time: float = float(self.simulateOptions["stopTime"])

Expand Down Expand Up @@ -1185,13 +1193,14 @@ def createCSVData(self) -> pathlib.Path:
]
csv_rows.append(row)

csvFile = self.tempdir / f'{self.modelName}.csv'
if csvfile is None:
csvfile = self.tempdir / f'{self.modelName}.csv'

with open(file=csvFile, mode="w", encoding="utf-8", newline="") as fh:
with open(file=csvfile, mode="w", encoding="utf-8", newline="") as fh:
writer = csv.writer(fh)
writer.writerows(csv_rows)

return csvFile
return csvfile

# to convert Modelica model to FMU
def convertMo2Fmu(self, version="2.0", fmuType="me_cs", fileNamePrefix="<default>", includeResources=True): # 19
Expand Down Expand Up @@ -1307,8 +1316,8 @@ def load_module_from_path(module_name, file_path):
for l in tupleList:
if l[0] < float(self.simulateOptions["startTime"]):
raise ModelicaSystemError('Input time value is less than simulation startTime')
self.csvFile = self.createCSVData()
om_cmd.arg_set(key="csvInput", val=self.csvFile.as_posix())
csvfile = self.createCSVData()
om_cmd.arg_set(key="csvInput", val=csvfile.as_posix())

om_cmd.arg_set(key="l", val=str(lintime or self.linearOptions["stopTime"]))

Expand Down
6 changes: 4 additions & 2 deletions tests/test_ModelicaSystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,12 +396,14 @@ def test_simulate_inputs(tmp_path):
"u1=[(0.0, 0), (1.0, 1)]",
"u2=[(0.0, 0), (0.25, 0.5), (0.5, 1.0), (1.0, 0)]",
])
mod.simulate()
assert pathlib.Path(mod.csvFile).read_text() == """time,u1,u2,end
csv_file = mod.createCSVData()
assert pathlib.Path(csv_file).read_text() == """time,u1,u2,end
0.0,0.0,0.0,0
0.25,0.25,0.5,0
0.5,0.5,1.0,0
1.0,1.0,0.0,0
"""

mod.simulate()
y = mod.getSolutions("y")[0]
assert np.isclose(y[-1], 1.0)
Loading