Skip to content

Commit 4b57911

Browse files
committed
[ModelicaSystemABC] define setInputCSV() - function to define input based on the content of a CSV file
1 parent efd6775 commit 4b57911

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

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
@@ -998,6 +999,44 @@ def setInputs(
998999

9991000
return True
10001001

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

0 commit comments

Comments
 (0)