|
5 | 5 |
|
6 | 6 | import abc |
7 | 7 | import ast |
| 8 | +import csv |
8 | 9 | from dataclasses import dataclass |
9 | 10 | import logging |
10 | 11 | import numbers |
@@ -983,6 +984,44 @@ def setInputs( |
983 | 984 |
|
984 | 985 | return True |
985 | 986 |
|
| 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 | + |
986 | 1025 | def _createCSVData(self, csvfile: Optional[OMPathABC] = None) -> OMPathABC: |
987 | 1026 | """ |
988 | 1027 | Create a csv file with inputs for the simulation/optimization of the model. If csvfile is provided as argument, |
|
0 commit comments