Skip to content

Commit 56a787c

Browse files
committed
[ModelicaSystemABC] define setInputCSV() - function to define input based on the content of a CSV file
1 parent 6d8ecd9 commit 56a787c

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

OMPython/modelica_system_abc.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
import abc
77
import ast
8+
import csv
89
from dataclasses import dataclass
910
import logging
1011
import numbers
@@ -992,6 +993,44 @@ def setInputs(
992993

993994
return True
994995

996+
def setInputsCSV(
997+
self,
998+
csvfile: os.PathLike,
999+
) -> None:
1000+
"""
1001+
Read content from a CSV file and use it to define the time based input data.
1002+
"""
1003+
1004+
# real type is 'dict[str, list[tuple[float, float]]]' - 'dict[str, Any]' is used to make setInputs() happy
1005+
inputs: dict[str, Any] = {}
1006+
try:
1007+
with open(csvfile, newline='') as csvfh:
1008+
dialect = csv.Sniffer().sniff(csvfh.read(1024))
1009+
csvfh.seek(0)
1010+
reader = csv.DictReader(csvfh, dialect=dialect)
1011+
1012+
keys: list[str] = []
1013+
for idx, line in enumerate(reader):
1014+
if not keys:
1015+
keys = list(line.keys())
1016+
for var in keys[1:]:
1017+
if var in inputs:
1018+
raise ModelicaSystemError(f"Error reading {csvfile}: duplicated column {var}!")
1019+
inputs[var] = []
1020+
try:
1021+
# use key[0] as time; all other columns use the header as name
1022+
for var in keys[1:]:
1023+
inputs[var].append((float(line[keys[0]]), float(line[var])))
1024+
except (ValueError, TypeError) as exc2:
1025+
raise ModelicaSystemError(f"Invalid value reading {csvfile} line {idx}/{var}: "
1026+
f"{line}!") from exc2
1027+
1028+
except IOError as exc1:
1029+
raise ModelicaSystemError(f"Error reading {csvfile}: {exc1}") from exc1
1030+
1031+
if inputs:
1032+
self.setInputs(**inputs)
1033+
9951034
def _createCSVData(self, csvfile: Optional[OMPathABC] = None) -> OMPathABC:
9961035
"""
9971036
Create a csv file with inputs for the simulation/optimization of the model. If csvfile is provided as argument,

0 commit comments

Comments
 (0)