|
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 |
@@ -992,6 +993,44 @@ def setInputs( |
992 | 993 |
|
993 | 994 | return True |
994 | 995 |
|
| 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 | + |
995 | 1034 | def _createCSVData(self, csvfile: Optional[OMPathABC] = None) -> OMPathABC: |
996 | 1035 | """ |
997 | 1036 | Create a csv file with inputs for the simulation/optimization of the model. If csvfile is provided as argument, |
|
0 commit comments