tz-oss-interop-testing 0.1.2rc1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- interop_testing/__init__.py +50 -0
- interop_testing/builders/__init__.py +7 -0
- interop_testing/builders/caiso_stack_models.py +154 -0
- interop_testing/builders/otoole_models.py +128 -0
- interop_testing/builders/plexos_csv_files.py +108 -0
- interop_testing/builders/plexos_generator_specs.py +130 -0
- interop_testing/builders/plexos_models.py +465 -0
- interop_testing/builders/plexos_resources.py +553 -0
- interop_testing/builders/plexos_tables.py +428 -0
- interop_testing/builders/plexos_vocabulary.py +133 -0
- interop_testing/builders/power_systems_investments_results.py +103 -0
- interop_testing/builders/pypsa_networks.py +534 -0
- interop_testing/builders/sienna_documents.py +532 -0
- interop_testing/builders/sienna_results.py +110 -0
- interop_testing/builders/sienna_systems.py +747 -0
- interop_testing/builders/tz_osemosys_models.py +75 -0
- interop_testing/builders/yearly_results_csv.py +30 -0
- interop_testing/files.py +44 -0
- interop_testing/pipeline_driver.py +39 -0
- interop_testing/projects.py +79 -0
- interop_testing/py.typed +0 -0
- interop_testing/steps/__init__.py +29 -0
- interop_testing/steps/caiso_stack_model.py +70 -0
- interop_testing/steps/files.py +103 -0
- interop_testing/steps/isolation.py +34 -0
- interop_testing/steps/osemosys_model.py +231 -0
- interop_testing/steps/pipeline.py +56 -0
- interop_testing/steps/plexos_model.py +496 -0
- interop_testing/steps/plexos_resources.py +850 -0
- interop_testing/steps/power_simulations.py +332 -0
- interop_testing/steps/power_systems_investments.py +242 -0
- interop_testing/steps/power_systems_investments_results.py +92 -0
- interop_testing/steps/pypsa_network/__init__.py +15 -0
- interop_testing/steps/pypsa_network/_written_network.py +163 -0
- interop_testing/steps/pypsa_network/assert_network.py +448 -0
- interop_testing/steps/pypsa_network/build_network.py +551 -0
- interop_testing/steps/reports.py +196 -0
- interop_testing/steps/sienna_portfolio.py +190 -0
- interop_testing/steps/sienna_results.py +107 -0
- interop_testing/steps/sienna_schema.py +225 -0
- interop_testing/steps/sienna_system.py +1279 -0
- interop_testing/steps/yearly_results_csv.py +54 -0
- tz_oss_interop_testing-0.1.2rc1.dist-info/METADATA +59 -0
- tz_oss_interop_testing-0.1.2rc1.dist-info/RECORD +47 -0
- tz_oss_interop_testing-0.1.2rc1.dist-info/WHEEL +4 -0
- tz_oss_interop_testing-0.1.2rc1.dist-info/licenses/LICENSE +201 -0
- tz_oss_interop_testing-0.1.2rc1.dist-info/licenses/NOTICE +12 -0
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Test harness for projects that build tz-oss-interop pipelines.
|
|
2
|
+
|
|
3
|
+
Installed as the distribution ``tz-oss-interop-testing``. It publishes the
|
|
4
|
+
fixture builders for every framework tz-oss-interop reads or writes, the
|
|
5
|
+
helpers that scaffold a project directory, and a driver that runs one pipeline
|
|
6
|
+
in-process. ``interop_testing.steps`` holds the matching pytest-bdd vocabulary,
|
|
7
|
+
so a project can write ``.feature`` files against its own pipelines without
|
|
8
|
+
copying any of this.
|
|
9
|
+
|
|
10
|
+
``interop_testing.builders`` holds one importable module per framework behind its
|
|
11
|
+
step module, so a project needing an assertion the vocabulary does not cover can
|
|
12
|
+
read the artefact with the same helpers rather than parsing it afresh.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from interop_testing.builders.caiso_stack_models import CaisoStackModelBuilder
|
|
16
|
+
from interop_testing.builders.plexos_models import PlexosModelBuilder
|
|
17
|
+
from interop_testing.builders.pypsa_networks import PyPSANetworkBuilder, read_network
|
|
18
|
+
from interop_testing.builders.sienna_results import SiennaResultsBuilder
|
|
19
|
+
from interop_testing.builders.sienna_systems import SiennaSystemBuilder
|
|
20
|
+
from interop_testing.builders.yearly_results_csv import YearlyResultsCsvBuilder
|
|
21
|
+
from interop_testing.pipeline_driver import run_pipeline
|
|
22
|
+
from interop_testing.projects import (
|
|
23
|
+
DEFAULT_ADAPTERS_YAML,
|
|
24
|
+
write_adapters_config,
|
|
25
|
+
write_noop_pipeline,
|
|
26
|
+
write_noop_validator_pipeline,
|
|
27
|
+
write_pipeline,
|
|
28
|
+
write_project_plugin,
|
|
29
|
+
write_project_plugin_in_subdir,
|
|
30
|
+
write_results_pipeline,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"DEFAULT_ADAPTERS_YAML",
|
|
35
|
+
"CaisoStackModelBuilder",
|
|
36
|
+
"PlexosModelBuilder",
|
|
37
|
+
"PyPSANetworkBuilder",
|
|
38
|
+
"SiennaResultsBuilder",
|
|
39
|
+
"SiennaSystemBuilder",
|
|
40
|
+
"YearlyResultsCsvBuilder",
|
|
41
|
+
"read_network",
|
|
42
|
+
"run_pipeline",
|
|
43
|
+
"write_adapters_config",
|
|
44
|
+
"write_noop_pipeline",
|
|
45
|
+
"write_noop_validator_pipeline",
|
|
46
|
+
"write_pipeline",
|
|
47
|
+
"write_project_plugin",
|
|
48
|
+
"write_project_plugin_in_subdir",
|
|
49
|
+
"write_results_pipeline",
|
|
50
|
+
]
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Fixture builders, one module per framework interop reads or writes.
|
|
2
|
+
|
|
3
|
+
Each module holds a builder that assembles a source document component by
|
|
4
|
+
component and serialises it once, plus the readers its assertions use to read
|
|
5
|
+
one back. The matching pytest-bdd vocabulary lives in ``interop_testing.steps``;
|
|
6
|
+
the builders themselves are plain Python and can be driven directly.
|
|
7
|
+
"""
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""``CaisoStackModelBuilder``: write the pair of CSVs the CAISO stack-model source reads.
|
|
2
|
+
|
|
3
|
+
The source takes two files a user writes from CAISO's published assessment: an hourly
|
|
4
|
+
stack model, and a monthly capacity-by-fuel appendix. This builder writes both in the
|
|
5
|
+
column shape the source expects, so a test states only the few values it cares about and
|
|
6
|
+
every other column lands at zero.
|
|
7
|
+
|
|
8
|
+
The builder is plain Python, so it can be driven directly. The matching pytest-bdd
|
|
9
|
+
vocabulary lives in ``interop_testing.steps.caiso_stack_model``.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from collections.abc import Mapping
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
import polars as pl
|
|
18
|
+
|
|
19
|
+
# Headers the source reads, spelled as the published assessment spells them.
|
|
20
|
+
_MONTH = "MONTH"
|
|
21
|
+
_DAY = "Day"
|
|
22
|
+
_HOUR_ENDING = "HOUR (PDT)"
|
|
23
|
+
_LOAD = "2025 IEPR Forecast"
|
|
24
|
+
_CHARGING_LOAD = "Charging Load (Y/N)"
|
|
25
|
+
_SURPLUS = "Surplus MW"
|
|
26
|
+
_FUEL_TYPE = "Fuel type"
|
|
27
|
+
|
|
28
|
+
# The eight columns the source reads as available capacity, and the two it reads as
|
|
29
|
+
# dispatch. Every one is written on every row, so a test names only what it asserts on.
|
|
30
|
+
CAPACITY_CATEGORIES = (
|
|
31
|
+
"Natural Gas",
|
|
32
|
+
"Nuclear",
|
|
33
|
+
"Hydro",
|
|
34
|
+
"Other",
|
|
35
|
+
"Other Renewables",
|
|
36
|
+
"Solar",
|
|
37
|
+
"Wind",
|
|
38
|
+
"Imports",
|
|
39
|
+
)
|
|
40
|
+
DISPATCH_CATEGORIES = ("Battery Storage", "Demand Response")
|
|
41
|
+
|
|
42
|
+
# The appendix states one column per month, under these headers.
|
|
43
|
+
MONTH_HEADERS = (
|
|
44
|
+
"Jan",
|
|
45
|
+
"Feb",
|
|
46
|
+
"Mar",
|
|
47
|
+
"Apr",
|
|
48
|
+
"May",
|
|
49
|
+
"Jun",
|
|
50
|
+
"Jul",
|
|
51
|
+
"Aug",
|
|
52
|
+
"Sep",
|
|
53
|
+
"Oct",
|
|
54
|
+
"Nov",
|
|
55
|
+
"Dec",
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
# The stack model states each hour twice, once with battery charging folded into demand
|
|
59
|
+
# and once without. The source reads the with-charging scenario.
|
|
60
|
+
CHARGING_LOAD_YES = "Y"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class CaisoStackModelBuilder:
|
|
64
|
+
"""Incrementally builds the stack-model and appendix tables, and writes them once."""
|
|
65
|
+
|
|
66
|
+
def __init__(self) -> None:
|
|
67
|
+
self._hours: list[dict[str, object]] = []
|
|
68
|
+
self._appendix: dict[str, dict[str, float]] = {}
|
|
69
|
+
self._saved = False
|
|
70
|
+
|
|
71
|
+
def _check_not_saved(self, what: str) -> None:
|
|
72
|
+
if self._saved:
|
|
73
|
+
raise RuntimeError(f"Cannot add {what}: stack model already saved.")
|
|
74
|
+
|
|
75
|
+
def add_hour(
|
|
76
|
+
self,
|
|
77
|
+
*,
|
|
78
|
+
month: int,
|
|
79
|
+
day: int,
|
|
80
|
+
hour_ending: int,
|
|
81
|
+
load: float,
|
|
82
|
+
surplus: float,
|
|
83
|
+
charging_load: str = CHARGING_LOAD_YES,
|
|
84
|
+
) -> None:
|
|
85
|
+
"""Add one hour of the stack model, with every capacity and dispatch column at zero."""
|
|
86
|
+
self._check_not_saved(f"hour ending {hour_ending}")
|
|
87
|
+
row: dict[str, object] = {
|
|
88
|
+
_MONTH: month,
|
|
89
|
+
_DAY: day,
|
|
90
|
+
_HOUR_ENDING: hour_ending,
|
|
91
|
+
_LOAD: load,
|
|
92
|
+
_CHARGING_LOAD: charging_load,
|
|
93
|
+
_SURPLUS: surplus,
|
|
94
|
+
}
|
|
95
|
+
for category in (*CAPACITY_CATEGORIES, *DISPATCH_CATEGORIES):
|
|
96
|
+
row[category] = 0.0
|
|
97
|
+
self._hours.append(row)
|
|
98
|
+
|
|
99
|
+
def set_capacity(self, category: str, value: float) -> None:
|
|
100
|
+
"""State one availability category on the hour added last."""
|
|
101
|
+
self._set_category(CAPACITY_CATEGORIES, "capacity", category, value)
|
|
102
|
+
|
|
103
|
+
def set_dispatch(self, category: str, value: float) -> None:
|
|
104
|
+
"""State one dispatch category on the hour added last."""
|
|
105
|
+
self._set_category(DISPATCH_CATEGORIES, "dispatch", category, value)
|
|
106
|
+
|
|
107
|
+
def _set_category(
|
|
108
|
+
self, allowed: tuple[str, ...], kind: str, category: str, value: float
|
|
109
|
+
) -> None:
|
|
110
|
+
self._check_not_saved(f"{kind} {category!r}")
|
|
111
|
+
if category not in allowed:
|
|
112
|
+
raise ValueError(f"{category!r} is not a stack-model {kind} category: {allowed}")
|
|
113
|
+
if not self._hours:
|
|
114
|
+
raise RuntimeError(f"Add an hour before stating its {kind}.")
|
|
115
|
+
self._hours[-1][category] = value
|
|
116
|
+
|
|
117
|
+
def add_appendix_fuel(self, fuel_type: str, values_by_month: Mapping[str, float]) -> None:
|
|
118
|
+
"""State one appendix fuel row's capacity in the named months; the rest stay at zero.
|
|
119
|
+
|
|
120
|
+
Calling this again for the same fuel adds to the months already stated rather than
|
|
121
|
+
replacing them, so a test can state one month at a time.
|
|
122
|
+
"""
|
|
123
|
+
self._check_not_saved(f"appendix fuel {fuel_type!r}")
|
|
124
|
+
unknown = sorted(set(values_by_month) - set(MONTH_HEADERS))
|
|
125
|
+
if unknown:
|
|
126
|
+
raise ValueError(f"Not appendix month headers: {unknown}")
|
|
127
|
+
self._appendix.setdefault(fuel_type, {}).update(values_by_month)
|
|
128
|
+
|
|
129
|
+
def save(self, stack_model_path: Path, appendix_path: Path) -> None:
|
|
130
|
+
if self._saved:
|
|
131
|
+
raise RuntimeError("Stack model already saved. Cannot call save() twice.")
|
|
132
|
+
# Both files always carry rows in practice, and an empty one has no column types
|
|
133
|
+
# for the source to read, so each is required rather than written empty.
|
|
134
|
+
if not self._hours:
|
|
135
|
+
raise RuntimeError("A stack model needs at least one hour before it is saved.")
|
|
136
|
+
if not self._appendix:
|
|
137
|
+
raise RuntimeError("An appendix needs at least one fuel row before it is saved.")
|
|
138
|
+
_write_csv(pl.DataFrame(self._hours), stack_model_path)
|
|
139
|
+
_write_csv(pl.DataFrame(self._appendix_rows()), appendix_path)
|
|
140
|
+
self._saved = True
|
|
141
|
+
|
|
142
|
+
def _appendix_rows(self) -> list[dict[str, object]]:
|
|
143
|
+
return [
|
|
144
|
+
{
|
|
145
|
+
_FUEL_TYPE: fuel_type,
|
|
146
|
+
**{header: float(by_month.get(header, 0.0)) for header in MONTH_HEADERS},
|
|
147
|
+
}
|
|
148
|
+
for fuel_type, by_month in self._appendix.items()
|
|
149
|
+
]
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _write_csv(frame: pl.DataFrame, path: Path) -> None:
|
|
153
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
154
|
+
frame.write_csv(path)
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field, replace
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import yaml
|
|
7
|
+
|
|
8
|
+
VALUE_COLUMN = "VALUE"
|
|
9
|
+
_CSV_SUFFIX = ".csv"
|
|
10
|
+
_RESULT_CELL = "1"
|
|
11
|
+
_PADDING = " "
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class OtooleSet:
|
|
16
|
+
"""One declared set; ``is_padded`` writes a space before and after each member."""
|
|
17
|
+
|
|
18
|
+
members: list[str]
|
|
19
|
+
has_file: bool = True
|
|
20
|
+
is_padded: bool = False
|
|
21
|
+
|
|
22
|
+
@property
|
|
23
|
+
def rows(self) -> list[list[str]]:
|
|
24
|
+
padding = _PADDING if self.is_padded else ""
|
|
25
|
+
return [[f"{padding}{member}{padding}"] for member in self.members]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class OtooleParameter:
|
|
30
|
+
"""One declared parameter; its CSV file takes the ``short_name`` when it has one."""
|
|
31
|
+
|
|
32
|
+
name: str
|
|
33
|
+
key: list[str]
|
|
34
|
+
default: float
|
|
35
|
+
rows: list[list[str]]
|
|
36
|
+
short_name: str | None = None
|
|
37
|
+
has_file: bool = True
|
|
38
|
+
header: list[str] | None = None
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def file_stem(self) -> str:
|
|
42
|
+
return self.short_name or self.name
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def columns(self) -> list[str]:
|
|
46
|
+
return self.header if self.header is not None else [*self.key, VALUE_COLUMN]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class OtooleModelBuilder:
|
|
51
|
+
sets: dict[str, OtooleSet] = field(default_factory=dict)
|
|
52
|
+
parameters: dict[str, OtooleParameter] = field(default_factory=dict)
|
|
53
|
+
results: dict[str, list[str]] = field(default_factory=dict)
|
|
54
|
+
|
|
55
|
+
def set_members(self, name: str, members: list[str], *, has_file: bool = True) -> None:
|
|
56
|
+
self.sets[name] = OtooleSet(members, has_file)
|
|
57
|
+
|
|
58
|
+
def set_member_padding(self, name: str) -> None:
|
|
59
|
+
self.sets[name] = replace(self.sets[name], is_padded=True)
|
|
60
|
+
|
|
61
|
+
def set_parameter(
|
|
62
|
+
self,
|
|
63
|
+
name: str,
|
|
64
|
+
key: list[str],
|
|
65
|
+
default: float,
|
|
66
|
+
rows: list[list[str]],
|
|
67
|
+
*,
|
|
68
|
+
has_file: bool = True,
|
|
69
|
+
) -> None:
|
|
70
|
+
self.parameters[name] = OtooleParameter(name, key, default, rows, has_file=has_file)
|
|
71
|
+
|
|
72
|
+
def drop_parameter(self, name: str) -> None:
|
|
73
|
+
"""Leave the parameter out of the config and the CSV files."""
|
|
74
|
+
self.parameters.pop(name, None)
|
|
75
|
+
|
|
76
|
+
def set_result(self, name: str, key: list[str]) -> None:
|
|
77
|
+
self.results[name] = key
|
|
78
|
+
|
|
79
|
+
def set_short_name(self, name: str, short_name: str) -> None:
|
|
80
|
+
self.parameters[name] = replace(self.parameters[name], short_name=short_name)
|
|
81
|
+
|
|
82
|
+
def set_header(self, name: str, header: list[str]) -> None:
|
|
83
|
+
self.parameters[name] = replace(self.parameters[name], header=header)
|
|
84
|
+
|
|
85
|
+
def write(self, config_path: Path, csv_dir: Path) -> None:
|
|
86
|
+
config_path.parent.mkdir(parents=True, exist_ok=True)
|
|
87
|
+
csv_dir.mkdir(parents=True, exist_ok=True)
|
|
88
|
+
config_path.write_text(yaml.safe_dump(self._build_config()), encoding="utf-8")
|
|
89
|
+
for name, otoole_set in self.sets.items():
|
|
90
|
+
if otoole_set.has_file:
|
|
91
|
+
_write_csv(csv_dir / f"{name}{_CSV_SUFFIX}", [VALUE_COLUMN], otoole_set.rows)
|
|
92
|
+
for parameter in self.parameters.values():
|
|
93
|
+
if parameter.has_file:
|
|
94
|
+
csv_path = csv_dir / f"{parameter.file_stem}{_CSV_SUFFIX}"
|
|
95
|
+
_write_csv(csv_path, parameter.columns, parameter.rows)
|
|
96
|
+
for name, key in self.results.items():
|
|
97
|
+
_write_csv(
|
|
98
|
+
csv_dir / f"{name}{_CSV_SUFFIX}",
|
|
99
|
+
[*key, VALUE_COLUMN],
|
|
100
|
+
[[_RESULT_CELL] * (len(key) + 1)],
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
def _build_config(self) -> dict[str, dict[str, object]]:
|
|
104
|
+
config: dict[str, dict[str, object]] = {
|
|
105
|
+
name: {"type": "set", "dtype": "str"} for name in self.sets
|
|
106
|
+
}
|
|
107
|
+
for parameter in self.parameters.values():
|
|
108
|
+
config[parameter.name] = _build_parameter_entry(parameter)
|
|
109
|
+
for name, key in self.results.items():
|
|
110
|
+
config[name] = {"type": "result", "indices": key, "dtype": "float", "default": 0}
|
|
111
|
+
return config
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _build_parameter_entry(parameter: OtooleParameter) -> dict[str, object]:
|
|
115
|
+
entry: dict[str, object] = {
|
|
116
|
+
"type": "param",
|
|
117
|
+
"indices": parameter.key,
|
|
118
|
+
"dtype": "float",
|
|
119
|
+
"default": parameter.default,
|
|
120
|
+
}
|
|
121
|
+
if parameter.short_name is not None:
|
|
122
|
+
entry["short_name"] = parameter.short_name
|
|
123
|
+
return entry
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _write_csv(path: Path, header: list[str], rows: list[list[str]]) -> None:
|
|
127
|
+
lines = [",".join(header), *(",".join(row) for row in rows)]
|
|
128
|
+
path.write_text("".join(f"{line}\n" for line in lines), encoding="utf-8")
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Writing one PLEXOS Data File CSV, in whichever layout a fixture asks for.
|
|
2
|
+
|
|
3
|
+
A published PLEXOS package writes its traces in several shapes, and a fixture has to be
|
|
4
|
+
able to produce each one so the source's reshaper is read against the real thing.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import csv
|
|
10
|
+
from datetime import date, timedelta
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
# Every written CSV dates its rows to this year; only Month/Day/Period within it vary.
|
|
14
|
+
_CSV_YEAR_DEFAULT = 2026
|
|
15
|
+
|
|
16
|
+
# A monthly-by-name Data File's calendar-month column headers.
|
|
17
|
+
_MONTH_COLUMNS = tuple(f"M{month:02d}" for month in range(1, 13))
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def normalise_path(text_path: str) -> Path:
|
|
21
|
+
"""PLEXOS stores Windows-style paths; write the CSV at the POSIX equivalent."""
|
|
22
|
+
return Path(text_path.replace("\\", "/"))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def write_csv(csv_path: Path, samples: list[list[float]]) -> None:
|
|
26
|
+
"""Write one Value column for a single sample, or one numbered column per replication."""
|
|
27
|
+
csv_path.parent.mkdir(parents=True, exist_ok=True)
|
|
28
|
+
headers = ["Value"] if len(samples) == 1 else [str(i + 1) for i in range(len(samples))]
|
|
29
|
+
lines = [",".join(["Year", "Month", "Day", "Period", *headers])]
|
|
30
|
+
for hour, values in enumerate(zip(*samples, strict=True)):
|
|
31
|
+
lines.append(
|
|
32
|
+
",".join([str(_CSV_YEAR_DEFAULT), "1", "1", str(hour + 1), *(str(v) for v in values)])
|
|
33
|
+
)
|
|
34
|
+
csv_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def write_csv_rows(csv_path: Path, rows: list[list[str]]) -> None:
|
|
38
|
+
"""Write rows as given, quoting a cell that holds a comma, as a PLEXOS pattern does."""
|
|
39
|
+
csv_path.parent.mkdir(parents=True, exist_ok=True)
|
|
40
|
+
with csv_path.open("w", newline="", encoding="utf-8") as handle:
|
|
41
|
+
csv.writer(handle).writerows(rows)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def write_csv_by_object(csv_path: Path, values_by_object: dict[str, list[float]]) -> None:
|
|
45
|
+
"""Write a Month/Day/Period trace with one column per object, headed by the object names."""
|
|
46
|
+
csv_path.parent.mkdir(parents=True, exist_ok=True)
|
|
47
|
+
objects = list(values_by_object.keys())
|
|
48
|
+
lines = [",".join(["Year", "Month", "Day", "Period", *objects])]
|
|
49
|
+
rows = zip(*values_by_object.values(), strict=True)
|
|
50
|
+
for period, values in enumerate(rows, start=1):
|
|
51
|
+
lines.append(
|
|
52
|
+
",".join([str(_CSV_YEAR_DEFAULT), "1", "1", str(period), *(str(v) for v in values)])
|
|
53
|
+
)
|
|
54
|
+
csv_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def write_csv_with_text_column(
|
|
58
|
+
csv_path: Path, hourly_values: list[float], text_column: str, text_values: list[str]
|
|
59
|
+
) -> None:
|
|
60
|
+
"""Write a Value column plus an unrelated text column PLEXOS carries alongside it."""
|
|
61
|
+
csv_path.parent.mkdir(parents=True, exist_ok=True)
|
|
62
|
+
lines = [",".join(["Year", "Month", "Day", "Period", "Value", text_column])]
|
|
63
|
+
for period, (value, text) in enumerate(zip(hourly_values, text_values, strict=True), start=1):
|
|
64
|
+
lines.append(f"{_CSV_YEAR_DEFAULT},1,1,{period},{value},{text}")
|
|
65
|
+
csv_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def write_csv_by_period_column(csv_path: Path, periods_per_day: int, values: list[float]) -> None:
|
|
69
|
+
"""Write one row per day with each intra-day period in its own zero-padded column."""
|
|
70
|
+
csv_path.parent.mkdir(parents=True, exist_ok=True)
|
|
71
|
+
headers = [f"{period:02d}" for period in range(1, periods_per_day + 1)]
|
|
72
|
+
lines = [",".join(["Year", "Month", "Day", *headers])]
|
|
73
|
+
for day, start in enumerate(range(0, len(values), periods_per_day)):
|
|
74
|
+
row = values[start : start + periods_per_day]
|
|
75
|
+
lines.append(",".join([_date_columns(day), *(_format_number(v) for v in row)]))
|
|
76
|
+
csv_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _format_number(value: float) -> str:
|
|
80
|
+
"""Write a whole number without a decimal point, as a real export does.
|
|
81
|
+
|
|
82
|
+
A reader that infers column types from a bounded window then sees an integer column
|
|
83
|
+
that only turns fractional later, which is the case worth reproducing here.
|
|
84
|
+
"""
|
|
85
|
+
return str(int(value)) if value.is_integer() else str(value)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def write_daily_csv(csv_path: Path, value_column: str, daily_values: list[float]) -> None:
|
|
89
|
+
"""Write one row per day, the value in a column the file names itself."""
|
|
90
|
+
csv_path.parent.mkdir(parents=True, exist_ok=True)
|
|
91
|
+
lines = [",".join(["Year", "Month", "Day", value_column])]
|
|
92
|
+
for day, value in enumerate(daily_values):
|
|
93
|
+
lines.append(f"{_date_columns(day)},{value}")
|
|
94
|
+
csv_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _date_columns(days_in: int) -> str:
|
|
98
|
+
"""Year,Month,Day for the nth day of the fixture year, rolling into later months."""
|
|
99
|
+
stamp = date(_CSV_YEAR_DEFAULT, 1, 1) + timedelta(days=days_in)
|
|
100
|
+
return f"{stamp.year},{stamp.month},{stamp.day}"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def write_monthly_csv(csv_path: Path, component: str, monthly_values: list[float]) -> None:
|
|
104
|
+
"""Write a single Name-keyed row of twelve calendar-month columns."""
|
|
105
|
+
csv_path.parent.mkdir(parents=True, exist_ok=True)
|
|
106
|
+
lines = [",".join(["Name", *_MONTH_COLUMNS])]
|
|
107
|
+
lines.append(",".join([component, *(str(v) for v in monthly_values)]))
|
|
108
|
+
csv_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""The comma-separated spec a fixture writes one PLEXOS Generator with.
|
|
2
|
+
|
|
3
|
+
``node=Bus1, fuel=Gas, Max Capacity=100`` names the memberships, the category and every
|
|
4
|
+
property in one string, so a scenario states a generator on one line and no step has to
|
|
5
|
+
know which properties that kind of generator carries.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from typing import NamedTuple
|
|
12
|
+
|
|
13
|
+
# Keys in a generator spec that name something other than a property value. Everything
|
|
14
|
+
# else in a spec is a PLEXOS property name, written verbatim.
|
|
15
|
+
_NODE_KEY = "node"
|
|
16
|
+
_CATEGORY_KEY = "category"
|
|
17
|
+
_FUEL_KEY = "fuel"
|
|
18
|
+
_MEMBERSHIP_KEYS = (_NODE_KEY, _CATEGORY_KEY, _FUEL_KEY)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# Marks a property whose values live in a Data File rather than in the XML.
|
|
22
|
+
_FILE_BACKED_PREFIX = "file:"
|
|
23
|
+
|
|
24
|
+
# Marks a property whose value scales a Variable's own profile: ``variable:<name>:<value>``,
|
|
25
|
+
# where an omitted value is zero (a Units Out trace states the shape, not a share of it).
|
|
26
|
+
_VARIABLE_BACKED_PREFIX = "variable:"
|
|
27
|
+
_VARIABLE_FIELD_SEPARATOR = ":"
|
|
28
|
+
_NO_VARIABLE_SHARE = 0.0
|
|
29
|
+
|
|
30
|
+
# A spec's entries are separated by commas, so no value may hold one.
|
|
31
|
+
_SPEC_SEPARATOR = ","
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class VariableShare(NamedTuple):
|
|
35
|
+
"""A property whose value is a share of the named Variable's profile."""
|
|
36
|
+
|
|
37
|
+
variable: str
|
|
38
|
+
value: float
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class GeneratorSpec:
|
|
43
|
+
"""One PLEXOS Generator: what it connects to, what category it is in, what it carries."""
|
|
44
|
+
|
|
45
|
+
node: str | None = None
|
|
46
|
+
fuels: tuple[str, ...] = ()
|
|
47
|
+
category: str | None = None
|
|
48
|
+
properties: dict[str, float] = field(default_factory=dict)
|
|
49
|
+
file_backed: dict[str, str] = field(default_factory=dict)
|
|
50
|
+
variable_backed: dict[str, VariableShare] = field(default_factory=dict)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def parse_generator_spec(spec: str) -> GeneratorSpec:
|
|
54
|
+
"""Read a comma-separated generator spec, e.g. ``node=Bus1, Max Capacity=100``.
|
|
55
|
+
|
|
56
|
+
``node``, ``category`` and ``fuel`` (repeatable, in priority order) name memberships
|
|
57
|
+
and the object's category. Every other key is a PLEXOS property name and takes a
|
|
58
|
+
number, ``file:<data file>`` where the property's values are file-backed, or
|
|
59
|
+
``variable:<variable>:<value>`` where the value scales that Variable's own profile.
|
|
60
|
+
"""
|
|
61
|
+
entries = _spec_entries(spec)
|
|
62
|
+
return GeneratorSpec(
|
|
63
|
+
node=_first_value(entries, _NODE_KEY),
|
|
64
|
+
fuels=tuple(value for key, value in entries if key == _FUEL_KEY),
|
|
65
|
+
category=_first_value(entries, _CATEGORY_KEY),
|
|
66
|
+
properties=_property_values(entries),
|
|
67
|
+
file_backed=_prefixed_values(entries, _FILE_BACKED_PREFIX),
|
|
68
|
+
variable_backed=_variable_backed_properties(entries),
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def build_generator_spec(fields: dict[str, str]) -> GeneratorSpec:
|
|
73
|
+
"""Read a generator spec given field by field, as a Gherkin table row gives it.
|
|
74
|
+
|
|
75
|
+
Rejects a value holding a comma rather than letting the spec split on it, since a
|
|
76
|
+
table cell reads as one value even where the comma-separated form could not hold it.
|
|
77
|
+
"""
|
|
78
|
+
for key, value in fields.items():
|
|
79
|
+
if _SPEC_SEPARATOR in value:
|
|
80
|
+
raise ValueError(f"generator field {key!r} may not hold a comma: {value!r}")
|
|
81
|
+
return parse_generator_spec(
|
|
82
|
+
f"{_SPEC_SEPARATOR} ".join(f"{key}={value}" for key, value in fields.items())
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
_SpecEntries = list[tuple[str, str]]
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _spec_entries(spec: str) -> _SpecEntries:
|
|
90
|
+
entries = []
|
|
91
|
+
for entry in spec.split(_SPEC_SEPARATOR):
|
|
92
|
+
key, _, value = entry.partition("=")
|
|
93
|
+
entries.append((key.strip(), value.strip()))
|
|
94
|
+
return entries
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _first_value(entries: _SpecEntries, wanted: str) -> str | None:
|
|
98
|
+
return next((value for key, value in entries if key == wanted), None)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _property_values(entries: _SpecEntries) -> dict[str, float]:
|
|
102
|
+
return {
|
|
103
|
+
key: float(value)
|
|
104
|
+
for key, value in _property_entries(entries)
|
|
105
|
+
if not value.startswith((_FILE_BACKED_PREFIX, _VARIABLE_BACKED_PREFIX))
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _prefixed_values(entries: _SpecEntries, prefix: str) -> dict[str, str]:
|
|
110
|
+
return {
|
|
111
|
+
key: value.removeprefix(prefix)
|
|
112
|
+
for key, value in _property_entries(entries)
|
|
113
|
+
if value.startswith(prefix)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _variable_backed_properties(entries: _SpecEntries) -> dict[str, VariableShare]:
|
|
118
|
+
return {
|
|
119
|
+
key: _read_variable_share(value)
|
|
120
|
+
for key, value in _prefixed_values(entries, _VARIABLE_BACKED_PREFIX).items()
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _read_variable_share(stated: str) -> VariableShare:
|
|
125
|
+
variable, _, share = stated.partition(_VARIABLE_FIELD_SEPARATOR)
|
|
126
|
+
return VariableShare(variable, float(share) if share else _NO_VARIABLE_SHARE)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _property_entries(entries: _SpecEntries) -> _SpecEntries:
|
|
130
|
+
return [(key, value) for key, value in entries if key not in _MEMBERSHIP_KEYS]
|