Skip to content

Commit bf405db

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

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
@@ -983,6 +984,44 @@ def setInputs(
983984

984985
return True
985986

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

0 commit comments

Comments
 (0)