r2x 1.0.0rc0__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.
- r2x/__init__.py +4 -0
- r2x/__main__.py +5 -0
- r2x/__version__.py +3 -0
- r2x/api.py +184 -0
- r2x/cli.py +61 -0
- r2x/cli_functions.py +152 -0
- r2x/config.py +376 -0
- r2x/core.py +5 -0
- r2x/defaults/__init__.py +0 -0
- r2x/defaults/config.json +323 -0
- r2x/defaults/example_defaults_override.yml +7 -0
- r2x/defaults/mapping_schema.json +34 -0
- r2x/defaults/plexos_horizons.json +454 -0
- r2x/defaults/plexos_input.json +49 -0
- r2x/defaults/plexos_mapping.json +7 -0
- r2x/defaults/plexos_models.json +468 -0
- r2x/defaults/plexos_output.json +213 -0
- r2x/defaults/plexos_reports.json +722 -0
- r2x/defaults/plexos_simulation_objects.json +402 -0
- r2x/defaults/plugins_config.json +10 -0
- r2x/defaults/sienna_config.json +236 -0
- r2x/defaults/sienna_mapping.json +6 -0
- r2x/enums.py +80 -0
- r2x/exceptions.py +30 -0
- r2x/exporter/__init__.py +4 -0
- r2x/exporter/handler.py +268 -0
- r2x/exporter/plexos.py +838 -0
- r2x/exporter/sienna.py +444 -0
- r2x/logger.py +76 -0
- r2x/models/__init__.py +24 -0
- r2x/models/branch.py +122 -0
- r2x/models/core.py +59 -0
- r2x/models/costs.py +50 -0
- r2x/models/generators.py +312 -0
- r2x/models/load.py +85 -0
- r2x/models/services.py +105 -0
- r2x/models/topology.py +97 -0
- r2x/models/utils.py +31 -0
- r2x/parser/__init__.py +5 -0
- r2x/parser/handler.py +238 -0
- r2x/parser/parser_helpers.py +187 -0
- r2x/parser/plexos.py +1503 -0
- r2x/plugins/__init__.py +0 -0
- r2x/plugins/break_gens.py +209 -0
- r2x/plugins/utils.py +71 -0
- r2x/runner.py +162 -0
- r2x/units.py +70 -0
- r2x/utils.py +714 -0
- r2x/validation.py +114 -0
- r2x-1.0.0rc0.dist-info/METADATA +60 -0
- r2x-1.0.0rc0.dist-info/RECORD +54 -0
- r2x-1.0.0rc0.dist-info/WHEEL +4 -0
- r2x-1.0.0rc0.dist-info/entry_points.txt +2 -0
- r2x-1.0.0rc0.dist-info/licenses/LICENCE.txt +13 -0
r2x/__init__.py
ADDED
r2x/__main__.py
ADDED
r2x/__version__.py
ADDED
r2x/api.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""R2X API for data model."""
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from os import PathLike
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from itertools import chain
|
|
8
|
+
from collections.abc import Iterable
|
|
9
|
+
from loguru import logger
|
|
10
|
+
|
|
11
|
+
from infrasys.component import Component
|
|
12
|
+
from infrasys.system import System as ISSystem
|
|
13
|
+
from .__version__ import __data_model_version__
|
|
14
|
+
import uuid
|
|
15
|
+
import infrasys.cost_curves
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class System(ISSystem):
|
|
19
|
+
"""API to interact with the SystemModel."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, *args, **kwargs):
|
|
22
|
+
super().__init__(*args, **kwargs)
|
|
23
|
+
self.data_format_version = __data_model_version__
|
|
24
|
+
|
|
25
|
+
def __str__(self) -> str:
|
|
26
|
+
return f"System(name={self.name}, DataModel Version={self.version})"
|
|
27
|
+
|
|
28
|
+
def __repr__(self) -> str:
|
|
29
|
+
return str(self)
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def version(self):
|
|
33
|
+
"""The version property."""
|
|
34
|
+
return __data_model_version__
|
|
35
|
+
|
|
36
|
+
def export_component_to_csv(
|
|
37
|
+
self,
|
|
38
|
+
component: type[Component],
|
|
39
|
+
fields: list | None = None,
|
|
40
|
+
filter_func: Callable | None = None,
|
|
41
|
+
fpath: PathLike | None = None,
|
|
42
|
+
key_mapping: dict | None = None,
|
|
43
|
+
unnest_key: str = "name",
|
|
44
|
+
**dict_writer_kwargs,
|
|
45
|
+
):
|
|
46
|
+
"""Export components into a csv.
|
|
47
|
+
|
|
48
|
+
component:
|
|
49
|
+
Component type to get from the system
|
|
50
|
+
"""
|
|
51
|
+
# Get desired components to offload to csv
|
|
52
|
+
components = map(
|
|
53
|
+
lambda component: component.model_dump(
|
|
54
|
+
exclude={"ext"}, exclude_none=True, mode="json", context={"magnitude_only": True}
|
|
55
|
+
),
|
|
56
|
+
self.get_components(component, filter_func=filter_func),
|
|
57
|
+
)
|
|
58
|
+
if fpath is None:
|
|
59
|
+
fpath = Path(f"{component.__name__}.csv")
|
|
60
|
+
|
|
61
|
+
self._export_dict_to_csv(
|
|
62
|
+
components,
|
|
63
|
+
fpath=fpath,
|
|
64
|
+
fields=fields,
|
|
65
|
+
key_mapping=key_mapping,
|
|
66
|
+
unnest_key=unnest_key,
|
|
67
|
+
**dict_writer_kwargs,
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
def _add_operation_cost_data( # noqa: C901
|
|
71
|
+
self,
|
|
72
|
+
data: Iterable[dict],
|
|
73
|
+
fields: list | None = None,
|
|
74
|
+
):
|
|
75
|
+
operation_cost_fields = set()
|
|
76
|
+
for sub_dict in data:
|
|
77
|
+
if "operation_cost" not in sub_dict.keys():
|
|
78
|
+
continue
|
|
79
|
+
|
|
80
|
+
operation_cost = sub_dict["operation_cost"]
|
|
81
|
+
for cost_field_key, cost_field_value in operation_cost.items():
|
|
82
|
+
if isinstance(cost_field_value, dict):
|
|
83
|
+
assert (
|
|
84
|
+
"uuid" in cost_field_value.keys()
|
|
85
|
+
), f"Operation cost field {cost_field_key} was assumed to be a component but is not."
|
|
86
|
+
variable_cost = self.get_component_by_uuid(uuid.UUID(cost_field_value["uuid"]))
|
|
87
|
+
sub_dict["variable_cost"] = variable_cost.vom_units.function_data.proportional_term
|
|
88
|
+
if "fuel_cost" in variable_cost.model_fields:
|
|
89
|
+
# Note: We multiply the fuel price by 1000 to offset the division
|
|
90
|
+
# done by Sienna when it parses .csv files
|
|
91
|
+
sub_dict["fuel_price"] = variable_cost.fuel_cost * 1000
|
|
92
|
+
operation_cost_fields.add("fuel_price")
|
|
93
|
+
|
|
94
|
+
function_data = variable_cost.value_curve.function_data
|
|
95
|
+
if "constant_term" in function_data.model_fields:
|
|
96
|
+
sub_dict["heat_rate_a0"] = function_data.constant_term
|
|
97
|
+
operation_cost_fields.add("heat_rate_a0")
|
|
98
|
+
if "proportional_term" in function_data.model_fields:
|
|
99
|
+
sub_dict["heat_rate_a1"] = function_data.proportional_term
|
|
100
|
+
operation_cost_fields.add("heat_rate_a1")
|
|
101
|
+
if "quadratic_term" in function_data.model_fields:
|
|
102
|
+
sub_dict["heat_rate_a2"] = function_data.quadratic_term
|
|
103
|
+
operation_cost_fields.add("heat_rate_a2")
|
|
104
|
+
if "x_coords" in function_data.model_fields:
|
|
105
|
+
x_y_coords = dict(zip(function_data.x_coords, function_data.y_coords))
|
|
106
|
+
match type(variable_cost):
|
|
107
|
+
case infrasys.cost_curves.CostCurve:
|
|
108
|
+
for i, (x_coord, y_coord) in enumerate(x_y_coords.items()):
|
|
109
|
+
output_point_col = f"output_point_{i}"
|
|
110
|
+
sub_dict[output_point_col] = x_coord
|
|
111
|
+
operation_cost_fields.add(output_point_col)
|
|
112
|
+
|
|
113
|
+
cost_point_col = f"cost_point_{i}"
|
|
114
|
+
sub_dict[cost_point_col] = y_coord
|
|
115
|
+
operation_cost_fields.add(cost_point_col)
|
|
116
|
+
|
|
117
|
+
case infrasys.cost_curves.FuelCurve:
|
|
118
|
+
for i, (x_coord, y_coord) in enumerate(x_y_coords.items()):
|
|
119
|
+
output_point_col = f"output_point_{i}"
|
|
120
|
+
sub_dict[output_point_col] = x_coord
|
|
121
|
+
operation_cost_fields.add(output_point_col)
|
|
122
|
+
|
|
123
|
+
heat_rate_col = "heat_rate_avg_0" if i == 0 else f"heat_rate_incr_{i}"
|
|
124
|
+
sub_dict[heat_rate_col] = y_coord
|
|
125
|
+
operation_cost_fields.add(heat_rate_col)
|
|
126
|
+
elif cost_field_key not in sub_dict.keys():
|
|
127
|
+
sub_dict[cost_field_key] = cost_field_value
|
|
128
|
+
operation_cost_fields.add(cost_field_key)
|
|
129
|
+
else:
|
|
130
|
+
pass
|
|
131
|
+
|
|
132
|
+
fields.remove("operation_cost") # type: ignore
|
|
133
|
+
fields.extend(list(operation_cost_fields)) # type: ignore
|
|
134
|
+
|
|
135
|
+
return data, fields
|
|
136
|
+
|
|
137
|
+
def _export_dict_to_csv(
|
|
138
|
+
self,
|
|
139
|
+
data: Iterable[dict],
|
|
140
|
+
fpath: PathLike,
|
|
141
|
+
fields: list | None = None,
|
|
142
|
+
key_mapping: dict | None = None,
|
|
143
|
+
unnest_key: str = "name",
|
|
144
|
+
**dict_writer_kwargs,
|
|
145
|
+
):
|
|
146
|
+
# Remaping keys
|
|
147
|
+
# NOTE: It does not work recursively for nested components
|
|
148
|
+
if key_mapping:
|
|
149
|
+
data = [
|
|
150
|
+
{key_mapping.get(key, key): value for key, value in sub_dict.items()} for sub_dict in data
|
|
151
|
+
]
|
|
152
|
+
if fields:
|
|
153
|
+
fields = list(map(lambda key: key_mapping.get(key, key), fields))
|
|
154
|
+
|
|
155
|
+
if fields is None:
|
|
156
|
+
fields = list(set(chain.from_iterable(data)))
|
|
157
|
+
|
|
158
|
+
if "operation_cost" in fields:
|
|
159
|
+
data, fields = self._add_operation_cost_data(data, fields)
|
|
160
|
+
|
|
161
|
+
with open(str(fpath), "w", newline="") as csvfile:
|
|
162
|
+
writer = csv.DictWriter(csvfile, fieldnames=fields, extrasaction="ignore", **dict_writer_kwargs) # type: ignore
|
|
163
|
+
writer.writeheader()
|
|
164
|
+
for row in data:
|
|
165
|
+
filter_row = {
|
|
166
|
+
key: value if not isinstance(value, dict) else value.get(unnest_key)
|
|
167
|
+
for key, value in row.items()
|
|
168
|
+
}
|
|
169
|
+
writer.writerow(filter_row)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
if __name__ == "__main__":
|
|
173
|
+
from .logger import setup_logging
|
|
174
|
+
from rich.console import Console
|
|
175
|
+
|
|
176
|
+
setup_logging(level="TRACE")
|
|
177
|
+
logger.enable("infra_sys")
|
|
178
|
+
|
|
179
|
+
console = Console()
|
|
180
|
+
|
|
181
|
+
# from tests.models.systems import ieee_5bus
|
|
182
|
+
#
|
|
183
|
+
# system = ieee_5bus()
|
|
184
|
+
# logger.info("From ARTEX")
|
r2x/cli.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""CLI for R2X."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import sys
|
|
5
|
+
import pathlib
|
|
6
|
+
from .cli_functions import base_cli
|
|
7
|
+
from .config import Configuration
|
|
8
|
+
from .runner import scenario_runner
|
|
9
|
+
from .utils import read_yaml
|
|
10
|
+
from .logger import setup_logging
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def cli():
|
|
14
|
+
"""Entry point for R2X."""
|
|
15
|
+
parser = base_cli()
|
|
16
|
+
if len(sys.argv) == 1:
|
|
17
|
+
parser.print_help(sys.stderr)
|
|
18
|
+
sys.exit(0)
|
|
19
|
+
|
|
20
|
+
args, remaining_args = parser.parse_known_args()
|
|
21
|
+
|
|
22
|
+
if "--help" in remaining_args:
|
|
23
|
+
parser.print_help(sys.stderr)
|
|
24
|
+
sys.exit(0)
|
|
25
|
+
|
|
26
|
+
args = parser.parse_args()
|
|
27
|
+
|
|
28
|
+
setup_logging(debug=args.debug)
|
|
29
|
+
|
|
30
|
+
cli_args = {k: v for k, v in vars(args).items() if v is not None}
|
|
31
|
+
user_dict = cli_args.pop("user_dict", None)
|
|
32
|
+
|
|
33
|
+
# Try to read file first
|
|
34
|
+
if user_dict is not None:
|
|
35
|
+
if pathlib.Path(user_dict).exists():
|
|
36
|
+
if o_dict := read_yaml(user_dict):
|
|
37
|
+
user_dict = o_dict
|
|
38
|
+
else:
|
|
39
|
+
user_dict = json.loads(user_dict)
|
|
40
|
+
|
|
41
|
+
if cli_args.get("cases_file") is None:
|
|
42
|
+
if solve_year := cli_args.get("solve_year"):
|
|
43
|
+
cli_args["solve_year"] = solve_year[0] if len(solve_year) == 1 else solve_year
|
|
44
|
+
config_mgr = Configuration.from_cli(cli_args, user_dict=user_dict)
|
|
45
|
+
else:
|
|
46
|
+
config_mgr = Configuration.from_cases(
|
|
47
|
+
cases_fpath=cli_args["cases_file"], cli_args=cli_args, user_dict=user_dict
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
if scenario_name := cli_args.get("scenario_name", None):
|
|
51
|
+
config_mgr = config_mgr.get(scenario_name)
|
|
52
|
+
|
|
53
|
+
scenario_runner(config_mgr)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
if __name__ == "__main__":
|
|
57
|
+
from rich.console import Console
|
|
58
|
+
|
|
59
|
+
console = Console()
|
|
60
|
+
setup_logging(level="TRACE")
|
|
61
|
+
args = cli()
|
r2x/cli_functions.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""CLI helper functions."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import importlib
|
|
5
|
+
from importlib.resources import files
|
|
6
|
+
from .__version__ import __version__
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Flags(argparse.Action):
|
|
10
|
+
"""Class to enable feature flags on the code and CLI.
|
|
11
|
+
|
|
12
|
+
This will save the feature flags in a `flags` argument in the NameSpace of
|
|
13
|
+
argparse
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def __call__( # type: ignore
|
|
17
|
+
self,
|
|
18
|
+
parser: argparse.ArgumentParser,
|
|
19
|
+
namespace: argparse.Namespace,
|
|
20
|
+
values: str,
|
|
21
|
+
optional_str: str,
|
|
22
|
+
) -> None:
|
|
23
|
+
"""Save flags as arguments in Namespace."""
|
|
24
|
+
setattr(namespace, self.dest, dict())
|
|
25
|
+
|
|
26
|
+
for value in values:
|
|
27
|
+
# split it into key and value
|
|
28
|
+
key, value = value.split("=")
|
|
29
|
+
# assign into dictionary
|
|
30
|
+
getattr(namespace, self.dest)[key] = value
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def get_additional_arguments(
|
|
34
|
+
parser: argparse.ArgumentParser,
|
|
35
|
+
folder: str = "r2x.plugins",
|
|
36
|
+
) -> argparse.ArgumentParser:
|
|
37
|
+
"""Add plugin arguments to CLI.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
parser: CLI parser object.
|
|
41
|
+
plugin_list: List of plugins.
|
|
42
|
+
folder: Folder that contains the plugin.
|
|
43
|
+
"""
|
|
44
|
+
plugin_files = [plugin for plugin in files(folder).rglob("*.py") if "__" not in plugin.name] # type: ignore
|
|
45
|
+
for plugin in plugin_files:
|
|
46
|
+
plugin_module = importlib.import_module(f".{plugin.stem}", folder)
|
|
47
|
+
if hasattr(plugin_module, "cli_arguments"):
|
|
48
|
+
plugin_cli_group = parser.add_argument_group(f"Plugin {plugin.stem}")
|
|
49
|
+
plugin_module.cli_arguments(plugin_cli_group)
|
|
50
|
+
|
|
51
|
+
parser_files = [parser for parser in files("r2x.parser").rglob("*.py")] # type: ignore
|
|
52
|
+
for parser_file in parser_files:
|
|
53
|
+
parser_module = importlib.import_module(f".{parser_file.stem}", "r2x.parser")
|
|
54
|
+
if hasattr(parser_module, "cli_arguments"):
|
|
55
|
+
parser_cli_group = parser.add_argument_group(f"Parser {parser_file.stem}")
|
|
56
|
+
parser_module.cli_arguments(parser_cli_group)
|
|
57
|
+
return parser
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def base_cli() -> argparse.ArgumentParser:
|
|
61
|
+
"""Create parser object for CLI."""
|
|
62
|
+
parser = argparse.ArgumentParser(
|
|
63
|
+
description="""Execute translation of ReEDS scenario results into X model""",
|
|
64
|
+
add_help=True,
|
|
65
|
+
prog="r2x",
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
group_run = parser.add_argument_group("Options for running the code")
|
|
69
|
+
group = group_run.add_mutually_exclusive_group()
|
|
70
|
+
group.add_argument(
|
|
71
|
+
"-i",
|
|
72
|
+
dest="run_folder",
|
|
73
|
+
help="Location of the folder with the input model data",
|
|
74
|
+
)
|
|
75
|
+
group.add_argument(
|
|
76
|
+
"--cases",
|
|
77
|
+
dest="cases_file",
|
|
78
|
+
help="Path to the cases file",
|
|
79
|
+
)
|
|
80
|
+
group_cli = parser.add_argument_group("Args used alongside run folder")
|
|
81
|
+
group_cli.add_argument(
|
|
82
|
+
"--name",
|
|
83
|
+
dest="name",
|
|
84
|
+
help="Scenario name",
|
|
85
|
+
)
|
|
86
|
+
group_cli.add_argument(
|
|
87
|
+
"--input-model",
|
|
88
|
+
dest="input_model",
|
|
89
|
+
choices=[
|
|
90
|
+
"plexos",
|
|
91
|
+
"reeds-US",
|
|
92
|
+
"plexos",
|
|
93
|
+
"infrasys",
|
|
94
|
+
],
|
|
95
|
+
help="Input model to convert from",
|
|
96
|
+
)
|
|
97
|
+
group_cli.add_argument(
|
|
98
|
+
"--output-model",
|
|
99
|
+
dest="output_model",
|
|
100
|
+
choices=["plexos", "sienna", "pras"],
|
|
101
|
+
help="Output model to convert to",
|
|
102
|
+
)
|
|
103
|
+
group_cli.add_argument(
|
|
104
|
+
"-o",
|
|
105
|
+
nargs="?",
|
|
106
|
+
dest="output_folder",
|
|
107
|
+
help="Path to save the result translation",
|
|
108
|
+
)
|
|
109
|
+
group_cli.add_argument(
|
|
110
|
+
"-y",
|
|
111
|
+
"--year",
|
|
112
|
+
type=int,
|
|
113
|
+
nargs="+",
|
|
114
|
+
dest="solve_year",
|
|
115
|
+
help="Year to translate",
|
|
116
|
+
)
|
|
117
|
+
group_cli.add_argument(
|
|
118
|
+
"--weather-year",
|
|
119
|
+
type=int,
|
|
120
|
+
dest="weather_year",
|
|
121
|
+
help="Year to translate",
|
|
122
|
+
)
|
|
123
|
+
group_cli.add_argument(
|
|
124
|
+
"--scenario",
|
|
125
|
+
dest="scenario_name",
|
|
126
|
+
help="Scenario to select from cases file",
|
|
127
|
+
)
|
|
128
|
+
group_cli.add_argument(
|
|
129
|
+
"-ud",
|
|
130
|
+
"--user-dict",
|
|
131
|
+
dest="user_dict",
|
|
132
|
+
help="User provided overrides to defaults",
|
|
133
|
+
)
|
|
134
|
+
group_cli.add_argument(
|
|
135
|
+
"-p",
|
|
136
|
+
"--plugins",
|
|
137
|
+
dest="plugins",
|
|
138
|
+
nargs="*",
|
|
139
|
+
help="Plugins to be included in the translation",
|
|
140
|
+
)
|
|
141
|
+
group_cli.add_argument(
|
|
142
|
+
"--save",
|
|
143
|
+
action="store_true",
|
|
144
|
+
help="Store system in the same output folder",
|
|
145
|
+
)
|
|
146
|
+
group_cli.add_argument("--inspect", action="store_true", help="Inspect infrasys system")
|
|
147
|
+
group_cli.add_argument("--upgrade", action="store_true", help="Run upgrader")
|
|
148
|
+
group_cli.add_argument("--flags", nargs="*", dest="feature_flags", action=Flags, help="Feature flags")
|
|
149
|
+
parser.add_argument("--debug", action="store_true", help="Enable debug logging")
|
|
150
|
+
parser.add_argument("--version", action="version", version=f"R2X version: {__version__}")
|
|
151
|
+
parser = get_additional_arguments(parser)
|
|
152
|
+
return parser
|