r2x 1.0.0__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.
Files changed (75) hide show
  1. r2x/__init__.py +4 -0
  2. r2x/__main__.py +5 -0
  3. r2x/__version__.py +3 -0
  4. r2x/api.py +108 -0
  5. r2x/cli.py +68 -0
  6. r2x/cli_functions.py +173 -0
  7. r2x/config_models.py +138 -0
  8. r2x/config_scenario.py +316 -0
  9. r2x/config_utils.py +96 -0
  10. r2x/core.py +5 -0
  11. r2x/defaults/__init__.py +0 -0
  12. r2x/defaults/config.json +310 -0
  13. r2x/defaults/example_defaults_override.yml +7 -0
  14. r2x/defaults/mapping_schema.json +34 -0
  15. r2x/defaults/master_9.2R6_btu.xml +186158 -0
  16. r2x/defaults/month_hrs.csv +13 -0
  17. r2x/defaults/pcm_defaults.json +1341 -0
  18. r2x/defaults/plexos_horizons.json +454 -0
  19. r2x/defaults/plexos_input.json +74 -0
  20. r2x/defaults/plexos_mapping.json +7 -0
  21. r2x/defaults/plexos_models.json +468 -0
  22. r2x/defaults/plexos_output.json +223 -0
  23. r2x/defaults/plexos_reports.json +842 -0
  24. r2x/defaults/plexos_simulation_objects.json +410 -0
  25. r2x/defaults/plugins_config.json +11 -0
  26. r2x/defaults/reeds_input.json +395 -0
  27. r2x/defaults/reeds_us_mapping.json +488 -0
  28. r2x/defaults/sienna_config.json +330 -0
  29. r2x/defaults/sienna_mapping.json +6 -0
  30. r2x/defaults/user_dict.yaml +16 -0
  31. r2x/enums.py +93 -0
  32. r2x/exceptions.py +34 -0
  33. r2x/exporter/__init__.py +4 -0
  34. r2x/exporter/handler.py +305 -0
  35. r2x/exporter/plexos.py +1060 -0
  36. r2x/exporter/sienna.py +642 -0
  37. r2x/exporter/utils.py +371 -0
  38. r2x/logger.py +87 -0
  39. r2x/models/__init__.py +24 -0
  40. r2x/models/branch.py +120 -0
  41. r2x/models/core.py +60 -0
  42. r2x/models/costs.py +88 -0
  43. r2x/models/generators.py +328 -0
  44. r2x/models/load.py +85 -0
  45. r2x/models/services.py +110 -0
  46. r2x/models/topology.py +97 -0
  47. r2x/models/utils.py +40 -0
  48. r2x/parser/__init__.py +7 -0
  49. r2x/parser/handler.py +305 -0
  50. r2x/parser/parser_helpers.py +346 -0
  51. r2x/parser/plexos.py +1740 -0
  52. r2x/parser/plexos_utils.py +508 -0
  53. r2x/parser/polars_helpers.py +209 -0
  54. r2x/parser/reeds.py +834 -0
  55. r2x/plugins/__init__.py +0 -0
  56. r2x/plugins/break_gens.py +210 -0
  57. r2x/plugins/ccs_credit.py +93 -0
  58. r2x/plugins/emission_cap.py +117 -0
  59. r2x/plugins/hurdle_rate.py +70 -0
  60. r2x/plugins/imports.py +91 -0
  61. r2x/plugins/pcm_defaults.py +168 -0
  62. r2x/plugins/utils.py +71 -0
  63. r2x/runner.py +186 -0
  64. r2x/units.py +78 -0
  65. r2x/upgrader/__init__.py +3 -0
  66. r2x/upgrader/file_tracker.csv +18 -0
  67. r2x/upgrader/functions.py +368 -0
  68. r2x/upgrader/helpers.py +49 -0
  69. r2x/utils.py +664 -0
  70. r2x/validation.py +114 -0
  71. r2x-1.0.0.dist-info/METADATA +24 -0
  72. r2x-1.0.0.dist-info/RECORD +75 -0
  73. r2x-1.0.0.dist-info/WHEEL +4 -0
  74. r2x-1.0.0.dist-info/entry_points.txt +2 -0
  75. r2x-1.0.0.dist-info/licenses/LICENCE.txt +13 -0
r2x/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .core import *
2
+ from .models import ACBus, Generator
3
+ from .__version__ import __version__
4
+ from .__version__ import __data_model_version__
r2x/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ # ruff: noqa
2
+ from .cli import cli
3
+
4
+ if __name__ == "__main__":
5
+ cli()
r2x/__version__.py ADDED
@@ -0,0 +1,3 @@
1
+ # This file containts the version # noqa: D100
2
+ __version__ = "v1.0.0"
3
+ __data_model_version__ = "0.0.1"
r2x/api.py ADDED
@@ -0,0 +1,108 @@
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 collections.abc import Iterable
8
+ from loguru import logger
9
+
10
+ import inspect
11
+ from infrasys.component import Component
12
+ from infrasys.system import System as ISSystem
13
+
14
+ from .__version__ import __data_model_version__
15
+
16
+
17
+ class System(ISSystem):
18
+ """API to interact with the SystemModel."""
19
+
20
+ def __init__(self, *args, **kwargs):
21
+ super().__init__(*args, **kwargs)
22
+ self.data_format_version = __data_model_version__
23
+
24
+ def __str__(self) -> str:
25
+ return f"System(name={self.name}, DataModel Version={self.version})"
26
+
27
+ def __repr__(self) -> str:
28
+ return str(self)
29
+
30
+ @property
31
+ def version(self):
32
+ """The version property."""
33
+ return __data_model_version__
34
+
35
+ def export_component_to_csv(
36
+ self,
37
+ component: type[Component],
38
+ fields: list | None = None,
39
+ filter_func: Callable | None = None,
40
+ fpath: PathLike | None = None,
41
+ key_mapping: dict | None = None,
42
+ unnest_key: str = "name",
43
+ **dict_writer_kwargs,
44
+ ):
45
+ """Export components into a csv.
46
+
47
+ component:
48
+ Component type to get from the system
49
+ """
50
+ # Get desired components to offload to csv
51
+ components = map(
52
+ lambda component: component.model_dump(
53
+ exclude={},
54
+ exclude_none=True,
55
+ mode="json",
56
+ context={"magnitude_only": True},
57
+ # serialize_as_any=True,
58
+ ),
59
+ self.get_components(component, filter_func=filter_func),
60
+ )
61
+ if fpath is None:
62
+ fpath = Path(f"{component.__name__}.csv")
63
+
64
+ self._export_dict_to_csv(
65
+ components,
66
+ fpath=fpath,
67
+ fields=fields,
68
+ key_mapping=key_mapping,
69
+ unnest_key=unnest_key,
70
+ **dict_writer_kwargs,
71
+ )
72
+
73
+ def _export_dict_to_csv(
74
+ self,
75
+ data: Iterable[dict],
76
+ fpath: PathLike,
77
+ fields: list | None = None,
78
+ # key_mapping: dict | None = None,
79
+ # unnest_key: str = "name",
80
+ **dict_writer_kwargs,
81
+ ):
82
+ dict_writer_kwargs = {
83
+ key: value
84
+ for key, value in dict_writer_kwargs.items()
85
+ if key in inspect.getfullargspec(csv.DictWriter).args
86
+ }
87
+
88
+ with open(str(fpath), "w", newline="") as csvfile:
89
+ writer = csv.DictWriter(csvfile, fieldnames=fields, extrasaction="ignore", **dict_writer_kwargs) # type: ignore
90
+ writer.writeheader()
91
+ for row in data:
92
+ writer.writerow(row)
93
+ return
94
+
95
+
96
+ if __name__ == "__main__":
97
+ from .logger import setup_logging
98
+ from rich.console import Console
99
+
100
+ setup_logging(level="TRACE")
101
+ logger.enable("infra_sys")
102
+
103
+ console = Console()
104
+
105
+ # from tests.models.systems import ieee_5bus
106
+ #
107
+ # system = ieee_5bus()
108
+ # logger.info("From ARTEX")
r2x/cli.py ADDED
@@ -0,0 +1,68 @@
1
+ """R2X CLI.
2
+
3
+ This scripts contains most of the logic on how we call different parts of R2X using the CLI.
4
+ """
5
+
6
+ import sys
7
+ import traceback
8
+
9
+ from .cli_functions import base_cli
10
+ from .logger import setup_logging
11
+ from .runner import init, run
12
+ from .utils import read_user_dict
13
+
14
+
15
+ def cli() -> None:
16
+ """CLI main entry point for R2X."""
17
+ parser = base_cli()
18
+ args, remaining_args = parser.parse_known_args()
19
+
20
+ if "--help" in remaining_args or len(sys.argv) == 1:
21
+ parser.print_help(sys.stderr)
22
+ sys.exit(0)
23
+
24
+ args = parser.parse_args()
25
+
26
+ cli_args = {k: v for k, v in vars(args).items() if v is not None}
27
+ user_dict = cli_args.pop("user_config", None)
28
+ setup_logging(verbosity=cli_args["verbose"])
29
+
30
+ if user_dict is not None:
31
+ user_dict = read_user_dict(user_dict)
32
+
33
+ if cli_args.get("pdb"):
34
+ import pdb
35
+
36
+ try:
37
+ pdb.run("cli_commands(cli_args, user_dict)", globals=globals(), locals=locals())
38
+ except Exception:
39
+ traceback.print_exc()
40
+ pdb.post_mortem()
41
+ else:
42
+ cli_commands(cli_args, user_dict)
43
+ return None
44
+
45
+
46
+ def cli_commands(cli_args: dict, user_dict: dict | None = None) -> None:
47
+ """Run the different translation for a configuration.
48
+
49
+ If the config object is Configuration class, we run all the different
50
+ Scenarios in parallel using multiprocessing.
51
+
52
+ Parameters
53
+ ----------
54
+ config
55
+ Configuration
56
+
57
+ Other Parameters
58
+ ----------------
59
+ kwargs
60
+ arguments passed for convenience.
61
+ """
62
+ if cli_args["command"] == "run":
63
+ run(cli_args, user_dict=user_dict)
64
+ elif cli_args["command"] == "init":
65
+ init(cli_args)
66
+ else:
67
+ raise NotImplementedError
68
+ return
r2x/cli_functions.py ADDED
@@ -0,0 +1,173 @@
1
+ """CLI helper functions."""
2
+
3
+ import argparse
4
+ import importlib
5
+ import os
6
+ from .__version__ import __version__
7
+
8
+ FILES_WITH_ARGS = [
9
+ "r2x.plugins.pcm_defaults",
10
+ "r2x.plugins.break_gens",
11
+ "r2x.plugins.emission_cap",
12
+ "r2x.plugins.hurdle_rate",
13
+ "r2x.plugins.cambium",
14
+ "r2x.parser.plexos",
15
+ "r2x.parser.reeds",
16
+ "r2x.exporter.plexos",
17
+ "r2x.exporter.sienna",
18
+ ]
19
+
20
+
21
+ class Flags(argparse.Action):
22
+ """Class to enable feature flags on the code and CLI.
23
+
24
+ This will save the feature flags in a `flags` argument in the NameSpace of
25
+ argparse
26
+ """
27
+
28
+ def __call__( # type: ignore
29
+ self,
30
+ parser: argparse.ArgumentParser,
31
+ namespace: argparse.Namespace,
32
+ values: str,
33
+ optional_str: str,
34
+ ) -> None:
35
+ """Save flags as arguments in Namespace."""
36
+ setattr(namespace, self.dest, dict())
37
+
38
+ for value in values:
39
+ # split it into key and value
40
+ key, value = value.split("=")
41
+ # assign into dictionary
42
+ getattr(namespace, self.dest)[key] = value
43
+
44
+
45
+ def get_additional_arguments(
46
+ parser: argparse.ArgumentParser,
47
+ folders: list[str] = FILES_WITH_ARGS,
48
+ ) -> argparse.ArgumentParser:
49
+ """Add plugin arguments to CLI.
50
+
51
+ Args:
52
+ parser: CLI parser object.
53
+ plugin_list: List of plugins.
54
+ folder: Folder that contains the plugin.
55
+ """
56
+ for package in folders:
57
+ package_str = package.split(".")
58
+ if not len(package_str) == 3:
59
+ msg = (
60
+ "Format of `FILES_WITH_ARGS` should be `r2x.package.script` but received {package_name}."
61
+ "Modify `FILES_WITH_ARGS` to match the format."
62
+ )
63
+ raise NotImplementedError(msg)
64
+
65
+ _, package_name, script_name = package_str
66
+ package_script = importlib.import_module(f"{package}")
67
+ if hasattr(package_script, "cli_arguments"):
68
+ script_cli_group = parser.add_argument_group(f"{package_name.upper()}: {script_name}")
69
+ package_script.cli_arguments(script_cli_group)
70
+
71
+ return parser
72
+
73
+
74
+ def base_cli() -> argparse.ArgumentParser:
75
+ """Create parser object for CLI."""
76
+ parser = argparse.ArgumentParser(
77
+ description="""Model translation framework""",
78
+ add_help=True,
79
+ prog="r2x",
80
+ )
81
+ subparsers = parser.add_subparsers(dest="command", help="Subcommands")
82
+ init_command = subparsers.add_parser("init", help="Create an empty configuration file.")
83
+ run_command = subparsers.add_parser("run", help="Run an R2X translation")
84
+
85
+ init_command.add_argument(
86
+ "-o",
87
+ nargs="?",
88
+ dest="path",
89
+ default=os.getcwd(),
90
+ help="Destination folder where the file will be copied. Defaults to current directory.",
91
+ )
92
+
93
+ group_run = run_command.add_argument_group("Options for running the code")
94
+ group_run.add_argument("--inspect", action="store_true", help="Inspect resulting infrasys system.")
95
+ group_run.add_argument("--upgrade", action="store_true", help="Run upgrader logic.")
96
+ group = group_run.add_mutually_exclusive_group(required=True)
97
+ group.add_argument(
98
+ "-i",
99
+ dest="run_folder",
100
+ help="Location of the folder with the input model data",
101
+ )
102
+ group.add_argument(
103
+ "--config",
104
+ "--user-config",
105
+ dest="user_config",
106
+ help="User configuration",
107
+ )
108
+ group_cli = run_command.add_argument_group("Arguments used with a run folder")
109
+ group_cli.add_argument(
110
+ "--name",
111
+ dest="name",
112
+ help="Scenario name",
113
+ )
114
+ group_cli.add_argument(
115
+ "--input-model",
116
+ dest="input_model",
117
+ choices=[
118
+ "plexos",
119
+ "reeds-US",
120
+ "plexos",
121
+ "infrasys",
122
+ ],
123
+ help="Input model to convert from",
124
+ )
125
+ group_cli.add_argument(
126
+ "--output-model",
127
+ dest="output_model",
128
+ choices=["plexos", "sienna", "pras"],
129
+ help="Output model to convert to",
130
+ )
131
+ group_cli.add_argument(
132
+ "-o",
133
+ nargs="?",
134
+ dest="output_folder",
135
+ help="Path to save the result translation",
136
+ )
137
+ group_cli.add_argument(
138
+ "-y",
139
+ "--year",
140
+ type=int,
141
+ nargs="+",
142
+ dest="solve_year",
143
+ help="Year to translate",
144
+ )
145
+ group_cli.add_argument(
146
+ "--scenario",
147
+ dest="scenario_name",
148
+ help="Scenario to select from cases file",
149
+ )
150
+ group_cli.add_argument(
151
+ "-ud",
152
+ "--user-dict",
153
+ dest="user_dict",
154
+ help="User provided overrides to defaults",
155
+ )
156
+ group_cli.add_argument(
157
+ "-p",
158
+ "--plugins",
159
+ dest="plugins",
160
+ nargs="*",
161
+ help="Plugins to be included in the translation",
162
+ )
163
+ group_cli.add_argument(
164
+ "--save",
165
+ action="store_true",
166
+ help="Serialize infrasys system.",
167
+ )
168
+ run_command.add_argument("--pdb", action="store_true", dest="pdb", help="Run with debugger enabled.")
169
+ run_command.add_argument("--flags", nargs="*", dest="feature_flags", action=Flags, help="Feature flags")
170
+ parser.add_argument("--verbose", "-v", action="count", default=0, help="Run with additional verbosity")
171
+ parser.add_argument("--version", "-V", action="version", version=f"R2X version: {__version__}")
172
+ _ = get_additional_arguments(run_command)
173
+ return parser
r2x/config_models.py ADDED
@@ -0,0 +1,138 @@
1
+ """Configuration handler.
2
+
3
+ This script provides the base class to save the metadata for a given ReEDS scenario.
4
+ It can either read the information directly or throught a cases file.
5
+ """
6
+
7
+ from dataclasses import field
8
+ from enum import StrEnum
9
+ from typing import Any, TypeVar
10
+
11
+ from pydantic import BaseModel
12
+
13
+ BaseModelConfigType = TypeVar("BaseModelConfigType", bound=BaseModel)
14
+
15
+
16
+ class BaseModelConfig(BaseModel):
17
+ """Configuration of the Model.
18
+
19
+ Attributes
20
+ ----------
21
+ fmap
22
+ Dictionary with file to be parse
23
+ defaults
24
+ Default configuration for the model
25
+
26
+ Raises
27
+ ------
28
+ AttributeError
29
+ """
30
+
31
+ defaults: dict[str, Any] = field(default_factory=dict)
32
+ fmap: dict[str, Any] = field(default_factory=dict)
33
+
34
+ @classmethod
35
+ def get_field_mapping(cls) -> dict[type[BaseModel], dict[str, str]]:
36
+ """Return a dict of {target_class: {target_field: source_field}}."""
37
+ raise NotImplementedError
38
+
39
+ def transform_field(self, field_name: str, target_class: type[BaseModel]) -> Any:
40
+ """Define custom field transformations."""
41
+ return getattr(self, field_name)
42
+
43
+ def to_class(
44
+ self, target_class: type[BaseModelConfigType], base_instance: BaseModel | None = None
45
+ ) -> BaseModelConfigType:
46
+ """Transform this model instance to another Pydantic model."""
47
+ field_mappings = self.get_field_mapping().get(target_class, {})
48
+
49
+ transformed_data = base_instance.model_dump() if base_instance is not None else {}
50
+
51
+ for target_field, source_field in field_mappings.items():
52
+ transformed_data[target_field] = self.transform_field(source_field, target_class)
53
+
54
+ return target_class(**transformed_data)
55
+
56
+
57
+ class ReEDSConfig(BaseModelConfig):
58
+ """ReEDs specific configuration."""
59
+
60
+ solve_year: list[int] | int | None = None
61
+ weather_year: int | None = None
62
+
63
+ @classmethod
64
+ def get_field_mapping(cls) -> dict[type[BaseModel], dict[str, str]]:
65
+ """Return a dict of {target_class: {target_field: source_field}}."""
66
+ return {
67
+ PlexosConfig: {
68
+ "model_year": "solve_year",
69
+ "horizon_year": "weather_year",
70
+ },
71
+ SiennaConfig: {"model_year": "solve_year"},
72
+ }
73
+
74
+
75
+ class PlexosConfig(BaseModelConfig):
76
+ """Plexos specific configuration."""
77
+
78
+ master_file: str | None = None
79
+ model_name: str | None = None
80
+ model_year: int | None = None
81
+ horizon_year: int | None = None
82
+
83
+
84
+ class SiennaConfig(BaseModelConfig):
85
+ """Sienna specific configuration."""
86
+
87
+ model_year: int | None = None
88
+
89
+
90
+ class InfrasysConfig(BaseModelConfig):
91
+ """Infrasys specific configuration."""
92
+
93
+ model_year: int | None = None
94
+
95
+ @classmethod
96
+ def get_field_mapping(cls) -> dict[type[BaseModel], dict[str, str]]:
97
+ """Return a dict of {target_class: {target_field: source_field}}."""
98
+ return {
99
+ PlexosConfig: {
100
+ "model_year": "model_year",
101
+ },
102
+ SiennaConfig: {"model_year": "model_year"},
103
+ }
104
+
105
+
106
+ class Models(StrEnum):
107
+ """Enum of valid models supported."""
108
+
109
+ INFRASYS = "INFRASYS"
110
+ REEDS = "REEDS-US"
111
+ PLEXOS = "PLEXOS"
112
+ SIENNA = "SIENNA"
113
+ PRAS = "PRAS"
114
+
115
+
116
+ class ParserModels(StrEnum):
117
+ """Enum of valid parser models supported."""
118
+
119
+ INFRASYS = "INFRASYS"
120
+ REEDS = "REEDS-US"
121
+ PLEXOS = "PLEXOS"
122
+ SIENNA = "SIENNA"
123
+
124
+
125
+ class ExporterModels(StrEnum):
126
+ """Enum of valid exporter models supported."""
127
+
128
+ PLEXOS = "PLEXOS"
129
+ SIENNA = "SIENNA"
130
+ INFRASYS = "INFRASYS"
131
+
132
+
133
+ MODEL_CONFIGS = {
134
+ Models.REEDS: ReEDSConfig,
135
+ Models.PLEXOS: PlexosConfig,
136
+ Models.SIENNA: SiennaConfig,
137
+ Models.INFRASYS: InfrasysConfig,
138
+ }