shrecc 0.0.5.dev2__tar.gz → 0.1.0.dev2__tar.gz

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 (52) hide show
  1. shrecc-0.1.0.dev2/MANIFEST.in +1 -0
  2. {shrecc-0.0.5.dev2/shrecc.egg-info → shrecc-0.1.0.dev2}/PKG-INFO +77 -14
  3. shrecc-0.1.0.dev2/README.md +113 -0
  4. {shrecc-0.0.5.dev2 → shrecc-0.1.0.dev2}/pyproject.toml +19 -6
  5. {shrecc-0.0.5.dev2 → shrecc-0.1.0.dev2}/shrecc/__init__.py +5 -4
  6. shrecc-0.1.0.dev2/shrecc/_legacy_database.py +156 -0
  7. shrecc-0.0.5.dev2/shrecc/treatment.py → shrecc-0.1.0.dev2/shrecc/_legacy_treatment.py +8 -31
  8. shrecc-0.1.0.dev2/shrecc/_legacy_tyndp.py +258 -0
  9. shrecc-0.1.0.dev2/shrecc/activity_mapping.py +24 -0
  10. shrecc-0.1.0.dev2/shrecc/data/__init__.py +1 -0
  11. shrecc-0.1.0.dev2/shrecc/data/el_map_all_norm_w_ned.csv +808 -0
  12. shrecc-0.1.0.dev2/shrecc/data/tyndp/__init__.py +1 -0
  13. shrecc-0.1.0.dev2/shrecc/data/tyndp/remind-eu-topology.json +295 -0
  14. shrecc-0.1.0.dev2/shrecc/data/tyndp/tyndp_activities.csv +43 -0
  15. shrecc-0.1.0.dev2/shrecc/data/tyndp/tyndp_connections.csv +144 -0
  16. shrecc-0.1.0.dev2/shrecc/data/tyndp/tyndp_countries.csv +84 -0
  17. {shrecc-0.0.5.dev2 → shrecc-0.1.0.dev2}/shrecc/database.py +209 -291
  18. shrecc-0.1.0.dev2/shrecc/download.py +34 -0
  19. shrecc-0.1.0.dev2/shrecc/energy_charts.py +774 -0
  20. shrecc-0.1.0.dev2/shrecc/mapping.py +526 -0
  21. shrecc-0.1.0.dev2/shrecc/pipeline.py +746 -0
  22. shrecc-0.1.0.dev2/shrecc/premise_mapping.py +1034 -0
  23. shrecc-0.1.0.dev2/shrecc/result_store.py +263 -0
  24. shrecc-0.1.0.dev2/shrecc/solver.py +438 -0
  25. shrecc-0.1.0.dev2/shrecc/treatment.py +35 -0
  26. shrecc-0.1.0.dev2/shrecc/treatment_fiona.py +69 -0
  27. shrecc-0.1.0.dev2/shrecc/tyndp.py +1538 -0
  28. {shrecc-0.0.5.dev2 → shrecc-0.1.0.dev2/shrecc.egg-info}/PKG-INFO +77 -14
  29. shrecc-0.1.0.dev2/shrecc.egg-info/SOURCES.txt +46 -0
  30. {shrecc-0.0.5.dev2 → shrecc-0.1.0.dev2}/shrecc.egg-info/requires.txt +14 -3
  31. shrecc-0.1.0.dev2/tests/test_architecture.py +44 -0
  32. {shrecc-0.0.5.dev2 → shrecc-0.1.0.dev2}/tests/test_database.py +217 -28
  33. shrecc-0.1.0.dev2/tests/test_energy_charts.py +142 -0
  34. shrecc-0.0.5.dev2/tests/test_download.py → shrecc-0.1.0.dev2/tests/test_energy_charts_api.py +99 -34
  35. shrecc-0.1.0.dev2/tests/test_mapping.py +220 -0
  36. shrecc-0.1.0.dev2/tests/test_pipeline.py +432 -0
  37. shrecc-0.1.0.dev2/tests/test_premise_mapping.py +783 -0
  38. shrecc-0.1.0.dev2/tests/test_result_store.py +97 -0
  39. shrecc-0.1.0.dev2/tests/test_solver.py +138 -0
  40. {shrecc-0.0.5.dev2 → shrecc-0.1.0.dev2}/tests/test_treatment.py +38 -14
  41. shrecc-0.1.0.dev2/tests/test_tyndp_scenario.py +464 -0
  42. shrecc-0.0.5.dev2/MANIFEST.in +0 -2
  43. shrecc-0.0.5.dev2/README.md +0 -59
  44. shrecc-0.0.5.dev2/shrecc/download.py +0 -340
  45. shrecc-0.0.5.dev2/shrecc.egg-info/SOURCES.txt +0 -19
  46. {shrecc-0.0.5.dev2 → shrecc-0.1.0.dev2}/LICENSE +0 -0
  47. {shrecc-0.0.5.dev2 → shrecc-0.1.0.dev2}/setup.cfg +0 -0
  48. {shrecc-0.0.5.dev2 → shrecc-0.1.0.dev2}/shrecc/data/el_map_all_norm.csv +0 -0
  49. {shrecc-0.0.5.dev2 → shrecc-0.1.0.dev2}/shrecc/data/generation_units_by_country.csv +0 -0
  50. {shrecc-0.0.5.dev2 → shrecc-0.1.0.dev2}/shrecc/data/techs_agg.json +0 -0
  51. {shrecc-0.0.5.dev2 → shrecc-0.1.0.dev2}/shrecc.egg-info/dependency_links.txt +0 -0
  52. {shrecc-0.0.5.dev2 → shrecc-0.1.0.dev2}/shrecc.egg-info/top_level.txt +0 -0
@@ -0,0 +1 @@
1
+ recursive-include shrecc/data *.csv *.json
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: shrecc
3
- Version: 0.0.5.dev2
3
+ Version: 0.1.0.dev2
4
4
  Summary: SHRECC: Smooth Hourly Resolution Electricity Consumption Calculation
5
5
  Author-email: Sabina Bednářová <sabina.bednarova@list.lu>
6
6
  Maintainer-email: Sabina Bednářová <sabina.bednarova@list.lu>
@@ -27,12 +27,14 @@ Requires-Dist: pandas<3,>=2
27
27
  Requires-Dist: numpy<3
28
28
  Requires-Dist: numpy>2; python_version >= "3.13"
29
29
  Requires-Dist: requests>=2.32
30
- Requires-Dist: fs
31
30
  Requires-Dist: scipy>=1.14
32
31
  Requires-Dist: appdirs
32
+ Requires-Dist: packaging
33
+ Requires-Dist: tqdm
34
+ Requires-Dist: xarray
35
+ Requires-Dist: python-calamine>=0.6.2
33
36
  Provides-Extra: testing
34
- Requires-Dist: shrecc; extra == "testing"
35
- Requires-Dist: pytest; extra == "testing"
37
+ Requires-Dist: pytest>=8; extra == "testing"
36
38
  Requires-Dist: pytest-cov; extra == "testing"
37
39
  Requires-Dist: python-coveralls; extra == "testing"
38
40
  Provides-Extra: dev
@@ -45,6 +47,12 @@ Requires-Dist: pytest-randomly; extra == "dev"
45
47
  Requires-Dist: setuptools; extra == "dev"
46
48
  Requires-Dist: ruff>=0.11.12; extra == "dev"
47
49
  Requires-Dist: black>=25.1.0; extra == "dev"
50
+ Provides-Extra: premise
51
+ Requires-Dist: premise; extra == "premise"
52
+ Provides-Extra: notebooks
53
+ Requires-Dist: jupyterlab; extra == "notebooks"
54
+ Requires-Dist: jupyter-black>=0.4.0; extra == "notebooks"
55
+ Requires-Dist: matplotlib>=3.10.9; extra == "notebooks"
48
56
  Provides-Extra: docs
49
57
  Requires-Dist: furo==2024.1.29; extra == "docs"
50
58
  Requires-Dist: myst_parser==2.0.0; extra == "docs"
@@ -56,6 +64,7 @@ Requires-Dist: myst-parser>=2.0.0; extra == "docs"
56
64
  Requires-Dist: sphinx-design>=0.6.1; extra == "docs"
57
65
  Requires-Dist: sphinx-copybutton>=0.5.2; extra == "docs"
58
66
  Requires-Dist: sphinx-autoapi>=3.5.0; extra == "docs"
67
+ Requires-Dist: astroid<4; extra == "docs"
59
68
  Requires-Dist: sphinx-notfound-page>=1.1.0; extra == "docs"
60
69
  Requires-Dist: myst-nb>=1.2.0; extra == "docs"
61
70
  Dynamic: license-file
@@ -66,22 +75,29 @@ Simple Hourly Resolution Electricity Consumption Calculation
66
75
 
67
76
  ## Description
68
77
 
69
- SHRECC package is a python package directly compatible with Brightway2 or Brightway2.5 to create time-aware electricity databases. For any given year and countries (check availability on https://api.energy-charts.info/), download and prepare data for low-voltage electricity consumption.
78
+ SHRECC creates time-resolved electricity-consumption databases for Brightway.
79
+ It uses measured Energy Charts data for historical years and ENTSO-E TYNDP
80
+ scenario data for prospective years, while exposing the same workflow for both.
70
81
 
71
82
  ## Features
72
83
 
73
- - **High-resolution electricity mixes** – Generates electricity life cycle inventories (LCIs) with **hourly** resolution, enhancing accuracy for life cycle assessment (LCA).
74
- - **Brightway2/2.5 compatibility** – Seamlessly integrates with Brightway, allowing direct use in existing LCA models.
75
- - **Dynamic temporal representation** – Users can select electricity mixes by **hour, month, or season**, addressing fluctuations in renewable energy generation and consumption.
76
- - **Automated data retrieval** – Pulls electricity production, trade, and consumption data from the **Energy Charts API**, ensuring up-to-date datasets.
77
- - **Ecoinvent matching** – Aligns with **ecoinvent classifications**, converting from ENTSO-E datasets.
78
- - **User-controlled updates** – Enables **one-time or recurring** updates, allowing continuous tracking of electricity mix evolution over time.
79
- - **Optimized impact assessments** – Helps reduce uncertainty and improve **decision-making for electricity-intensive technologies** by considering real-time electricity mix variations.
84
+ - Hourly production, trade, consumption-volume, and consumption-mix results.
85
+ - One reduced country-network solver shared by Energy Charts and TYNDP data.
86
+ - Historical ecoinvent allocation and prospective premise/IAM mapping.
87
+ - Hourly, daily, weekly, monthly, and explicit timestamp selections.
88
+ - Inspectable intermediate results before any Brightway database is changed.
89
+ - Resumable source acquisition and compressed, time-chunked result caches.
90
+ - Brightway 2 and 2.5 database writing through `NewDatabase`.
91
+ - Multi-year runs with a separate, year-labelled foreground database for each
92
+ requested year.
80
93
 
81
94
  ## Documentation
82
95
 
83
96
  The full documentation is hosted at [Read the Docs page for shrecc](https://shrecc.readthedocs.io/en/latest/)
84
97
 
98
+ The internal data flow and module responsibilities are summarized in
99
+ [docs/architecture.md](https://git.list.lu/shrecc_project/SHRECC/-/blob/main/docs/architecture.md).
100
+
85
101
  ## Installation
86
102
 
87
103
  `shrecc` can be installed from pypi or from source.
@@ -95,6 +111,12 @@ You can install it with pip (or any other pypi compatible util like `uv` or `poe
95
111
  pip install shrecc
96
112
  ```
97
113
 
114
+ Install optional premise geography support or the notebook environment with:
115
+
116
+ ```
117
+ pip install "shrecc[premise,notebooks]"
118
+ ```
119
+
98
120
  ### From source
99
121
 
100
122
  To install shrecc from source, clone the code and then install the package and if necessary the dependencies manually.
@@ -102,8 +124,49 @@ To install shrecc from source, clone the code and then install the package and i
102
124
 
103
125
  ## Usage
104
126
 
105
- You can find usage examples in the Jupyter notebook in this repo: [notebooks/example.ipynb](notebooks/example.ipynb)
106
- _and_ in the documentation at [read the docs](https://shrecc.readthedocs.io/en/latest/content/notebooks/notebooks.html).
127
+ The repository contains a minimal
128
+ [getting-started notebook](https://git.list.lu/shrecc_project/shrecc/-/blob/develop/notebooks/1_shrecc_get_started.ipynb)
129
+ and a more detailed
130
+ [analysis notebook](https://git.list.lu/shrecc_project/SHRECC/-/blob/develop/notebooks/2_shrecc_analysis.ipynb).
131
+ Both are also available in the documentation (only for main releases) at
132
+ [read the docs](https://shrecc.readthedocs.io/en/latest/content/notebooks/).
133
+
134
+ The harmonized historical/prospective workflow is available through
135
+ `NewDatabase`:
136
+
137
+ ```python
138
+ from shrecc import NewDatabase
139
+
140
+ electricity = NewDatabase(
141
+ scenario="DE",
142
+ years=[2035, 2040, 2050],
143
+ climate_year=2009,
144
+ bg_db_name={
145
+ 2035: "premise-remind-eu-2035",
146
+ 2040: "premise-remind-eu-2040",
147
+ 2050: "premise-remind-eu-2050",
148
+ },
149
+ my_db_name="shrecc_tyndp_DE_june_noon",
150
+ countries=["ES", "FR", "DE", "IT", "PT", "BE", "NL", "LU", "AT", "CH"],
151
+ time_range=["2040-06-01 00:00:00", "2040-06-30 23:00:00"],
152
+ hour_range=[10, 14],
153
+ project_name="SHRECCei311",
154
+ source="auto",
155
+ )
156
+
157
+ electricity.create()
158
+ electricity.write()
159
+ ```
160
+
161
+ For a multi-year run, the month/day/time selection is reused for each year and
162
+ `write()` creates one foreground database per year. A year suffix is added to
163
+ `my_db_name` automatically unless explicit year-specific names are supplied.
164
+ Foreground activity names and metadata also record their model year.
165
+
166
+ Intermediate canonical results and mapped tables remain available on the class
167
+ instance through `results(year)` and `table(year)`. Use
168
+ `mapping_report(year)` to inspect any historical technologies assigned to a
169
+ country-specific high-voltage fallback activity.
107
170
 
108
171
 
109
172
  ## Contributing
@@ -0,0 +1,113 @@
1
+ # SHRECC
2
+
3
+ Simple Hourly Resolution Electricity Consumption Calculation
4
+
5
+ ## Description
6
+
7
+ SHRECC creates time-resolved electricity-consumption databases for Brightway.
8
+ It uses measured Energy Charts data for historical years and ENTSO-E TYNDP
9
+ scenario data for prospective years, while exposing the same workflow for both.
10
+
11
+ ## Features
12
+
13
+ - Hourly production, trade, consumption-volume, and consumption-mix results.
14
+ - One reduced country-network solver shared by Energy Charts and TYNDP data.
15
+ - Historical ecoinvent allocation and prospective premise/IAM mapping.
16
+ - Hourly, daily, weekly, monthly, and explicit timestamp selections.
17
+ - Inspectable intermediate results before any Brightway database is changed.
18
+ - Resumable source acquisition and compressed, time-chunked result caches.
19
+ - Brightway 2 and 2.5 database writing through `NewDatabase`.
20
+ - Multi-year runs with a separate, year-labelled foreground database for each
21
+ requested year.
22
+
23
+ ## Documentation
24
+
25
+ The full documentation is hosted at [Read the Docs page for shrecc](https://shrecc.readthedocs.io/en/latest/)
26
+
27
+ The internal data flow and module responsibilities are summarized in
28
+ [docs/architecture.md](https://git.list.lu/shrecc_project/SHRECC/-/blob/main/docs/architecture.md).
29
+
30
+ ## Installation
31
+
32
+ `shrecc` can be installed from pypi or from source.
33
+
34
+ ### From pypi
35
+
36
+ The package is published at [pypi.org/projects/shrecc](https://pypi.org/project/shrecc).
37
+ You can install it with pip (or any other pypi compatible util like `uv` or `poetry` as follows:
38
+
39
+ ```
40
+ pip install shrecc
41
+ ```
42
+
43
+ Install optional premise geography support or the notebook environment with:
44
+
45
+ ```
46
+ pip install "shrecc[premise,notebooks]"
47
+ ```
48
+
49
+ ### From source
50
+
51
+ To install shrecc from source, clone the code and then install the package and if necessary the dependencies manually.
52
+
53
+
54
+ ## Usage
55
+
56
+ The repository contains a minimal
57
+ [getting-started notebook](https://git.list.lu/shrecc_project/shrecc/-/blob/develop/notebooks/1_shrecc_get_started.ipynb)
58
+ and a more detailed
59
+ [analysis notebook](https://git.list.lu/shrecc_project/SHRECC/-/blob/develop/notebooks/2_shrecc_analysis.ipynb).
60
+ Both are also available in the documentation (only for main releases) at
61
+ [read the docs](https://shrecc.readthedocs.io/en/latest/content/notebooks/).
62
+
63
+ The harmonized historical/prospective workflow is available through
64
+ `NewDatabase`:
65
+
66
+ ```python
67
+ from shrecc import NewDatabase
68
+
69
+ electricity = NewDatabase(
70
+ scenario="DE",
71
+ years=[2035, 2040, 2050],
72
+ climate_year=2009,
73
+ bg_db_name={
74
+ 2035: "premise-remind-eu-2035",
75
+ 2040: "premise-remind-eu-2040",
76
+ 2050: "premise-remind-eu-2050",
77
+ },
78
+ my_db_name="shrecc_tyndp_DE_june_noon",
79
+ countries=["ES", "FR", "DE", "IT", "PT", "BE", "NL", "LU", "AT", "CH"],
80
+ time_range=["2040-06-01 00:00:00", "2040-06-30 23:00:00"],
81
+ hour_range=[10, 14],
82
+ project_name="SHRECCei311",
83
+ source="auto",
84
+ )
85
+
86
+ electricity.create()
87
+ electricity.write()
88
+ ```
89
+
90
+ For a multi-year run, the month/day/time selection is reused for each year and
91
+ `write()` creates one foreground database per year. A year suffix is added to
92
+ `my_db_name` automatically unless explicit year-specific names are supplied.
93
+ Foreground activity names and metadata also record their model year.
94
+
95
+ Intermediate canonical results and mapped tables remain available on the class
96
+ instance through `results(year)` and `table(year)`. Use
97
+ `mapping_report(year)` to inspect any historical technologies assigned to a
98
+ country-specific high-voltage fallback activity.
99
+
100
+
101
+ ## Contributing
102
+
103
+ Please take a look at the [DEVELOPPING.md](https://git.list.lu/shrecc_project/shrecc/-/blob/main/DEVELOPPING.md) file for details on how to contribute code to the repository.
104
+
105
+ ## License
106
+
107
+ Copyright © 2025 Luxembourg Institute of Science and Technology
108
+ Licensed under the MIT License.
109
+
110
+ ## Authors
111
+
112
+ * Sabina Bednářová (<sabina.bednarova@list.lu>)
113
+ * Thomas Gibon (<thomas.gibon@list.lu>)
@@ -37,9 +37,12 @@ dependencies = [
37
37
  "numpy<3",
38
38
  'numpy>2;python_version>="3.13"',
39
39
  "requests>=2.32",
40
- "fs",
41
40
  "scipy>=1.14",
42
41
  "appdirs",
42
+ "packaging",
43
+ "tqdm",
44
+ "xarray",
45
+ "python-calamine>=0.6.2",
43
46
  ]
44
47
  license="MIT"
45
48
  license-files = ["LICENSE"]
@@ -50,11 +53,8 @@ homepage = "https://git.list.lu/shrecc_project/SHRECC"
50
53
  tracker = "https://git.list.lu/shrecc_project/SHRECC/issues"
51
54
 
52
55
  [project.optional-dependencies]
53
- # Getting recursive dependencies to work is a pain, this
54
- # seems to work, at least for now
55
56
  testing = [
56
- "shrecc",
57
- "pytest",
57
+ "pytest>=8",
58
58
  "pytest-cov",
59
59
  "python-coveralls"
60
60
  ]
@@ -69,6 +69,14 @@ dev = [
69
69
  "ruff>=0.11.12",
70
70
  "black>=25.1.0",
71
71
  ]
72
+ premise = [
73
+ "premise",
74
+ ]
75
+ notebooks = [
76
+ "jupyterlab",
77
+ "jupyter-black>=0.4.0",
78
+ "matplotlib>=3.10.9",
79
+ ]
72
80
  docs = [
73
81
  "furo==2024.1.29",
74
82
  "myst_parser==2.0.0",
@@ -80,13 +88,18 @@ docs = [
80
88
  "sphinx-design>=0.6.1",
81
89
  "sphinx-copybutton>=0.5.2",
82
90
  "sphinx-autoapi>=3.5.0",
91
+ "astroid<4",
83
92
  "sphinx-notfound-page>=1.1.0",
84
93
  "myst-nb>=1.2.0",
85
94
  ]
86
95
 
87
96
  [tool.setuptools]
88
97
  include-package-data = true
89
- packages = ["shrecc"]
98
+ packages = ["shrecc", "shrecc.data", "shrecc.data.tyndp"]
99
+
100
+ [tool.setuptools.package-data]
101
+ "shrecc.data" = ["*.csv", "*.json"]
102
+ "shrecc.data.tyndp" = ["*.csv", "*.json"]
90
103
 
91
104
  [tool.setuptools.dynamic]
92
105
  version = {attr = "shrecc.__version__"}
@@ -1,4 +1,4 @@
1
- # Copyright © 2024 Luxembourg Institute of Science and Technology
1
+ # Copyright © 2024-2026 Luxembourg Institute of Science and Technology
2
2
  # Licensed under the MIT License (see LICENSE file for details).
3
3
  # Authors: [Sabina Bednářová, Thomas Gibon]
4
4
 
@@ -7,13 +7,14 @@
7
7
 
8
8
  __all__ = (
9
9
  "__version__",
10
+ "NewDatabase",
10
11
  "create_database",
11
12
  "filt_cutoff",
12
13
  "get_data",
13
14
  "data_processing",
14
15
  )
15
16
  from .database import create_database, filt_cutoff
16
- from .download import get_data
17
- from .treatment import data_processing
17
+ from .energy_charts import data_processing, get_data
18
+ from .pipeline import NewDatabase
18
19
 
19
- __version__ = "0.0.5.dev2"
20
+ __version__ = "0.1.0.dev2"
@@ -0,0 +1,156 @@
1
+ """Historical file-based database-table preparation retained for compatibility."""
2
+
3
+ from datetime import datetime
4
+ from importlib.resources import files
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+
10
+ from shrecc.mapping import load_ecoinvent_mapping as load_mapping_data
11
+ from shrecc.result_store import (
12
+ load_pickle as load_from_pickle,
13
+ save_pickle as save_to_pickle,
14
+ )
15
+
16
+
17
+ def load_time_series_data(path_to_data, year):
18
+ """Load a legacy sparse consumption matrix and restore its labels."""
19
+ path_to_data = Path(path_to_data)
20
+ filename = path_to_data / f"{year}" / f"indices_{year}.pkl"
21
+ indices = load_from_pickle(filename)
22
+ Z_cons_sp = load_from_pickle(path_to_data / f"{year}" / f"Z_cons_{year}.pkl")
23
+ Z_cons = pd.DataFrame(
24
+ np.float32(Z_cons_sp.todense()),
25
+ index=indices["index"],
26
+ columns=indices["columns"],
27
+ )
28
+ return Z_cons.reorder_levels(["time", "source", "country"], axis=1).sort_index(
29
+ axis=1
30
+ )
31
+
32
+
33
+ def prepare_consumption_data(Z_cons):
34
+ """Remove legacy trade rows and arrange rows for activity mapping."""
35
+ Z_cons = Z_cons.sort_index()
36
+
37
+ if "trade" in Z_cons.index.get_level_values("source"):
38
+ Z_cons_to_multiply = Z_cons.drop("trade", axis=0).copy()
39
+ else:
40
+ Z_cons_to_multiply = Z_cons.copy()
41
+ Z_cons_to_multiply.index.names = ["source", "geography_mix"]
42
+
43
+ return Z_cons_to_multiply.swaplevel()
44
+
45
+
46
+ def apply_mapping(Z_cons_to_multiply, el_map_all_norm):
47
+ """Apply the historical matrix-form technology mapping."""
48
+ el_map_to_multiply = el_map_all_norm.reindex(
49
+ Z_cons_to_multiply.index, axis=1
50
+ ).astype("float32")
51
+ el_map_to_multiply["NIE"] = el_map_all_norm["GB"][
52
+ el_map_to_multiply["NIE"].columns
53
+ ].astype("float32")
54
+ el_map_to_multiply["UK"] = el_map_all_norm["GB"][
55
+ el_map_to_multiply["UK"].columns
56
+ ].astype("float32")
57
+
58
+ el_map_to_multiply = el_map_to_multiply.fillna(0)
59
+ LCI_cons = el_map_to_multiply.dot(Z_cons_to_multiply)
60
+ return LCI_cons.fillna(0) if LCI_cons.isna().sum().sum() else LCI_cons
61
+
62
+
63
+ def tech_mapping(year, path_to_data, path_to_mapping=None):
64
+ """Map a legacy consumption matrix and normalize each mix to one kWh."""
65
+ now = datetime.now()
66
+ print(f"{now} Mapping technologies...")
67
+ if path_to_mapping:
68
+ el_map_all_norm = load_mapping_data(path_to_mapping)
69
+ else:
70
+ el_map_all_norm = load_mapping_data(files("shrecc.data"))
71
+ Z_cons = load_time_series_data(path_to_data, year)
72
+ Z_cons_to_multiply = prepare_consumption_data(Z_cons)
73
+ filename = Path(path_to_data / f"{year}" / f"LCI_cons_scaled_{year}.pkl")
74
+ if filename.exists():
75
+ LCI_cons_scaled = load_from_pickle(filename)
76
+ else:
77
+ LCI_cons = apply_mapping(Z_cons_to_multiply, el_map_all_norm)
78
+ mapped_total = LCI_cons.sum()
79
+ filename = Path(path_to_data / f"{year}" / f"Z_load_{year}.pkl")
80
+ load = load_from_pickle(filename)
81
+ load_difference_row = (
82
+ "RER",
83
+ "electricity, high voltage, European attribute mix",
84
+ "electricity, high voltage",
85
+ "kWh",
86
+ )
87
+
88
+ load_stacked = load.stack()
89
+ load_stacked.index.names = ["country", "time"]
90
+ load_stacked = load_stacked[load_stacked != 0]
91
+ merged = load_stacked.reset_index(name="load_value").merge(
92
+ mapped_total.reset_index(), how="inner", on=["time", "country"]
93
+ )
94
+ merged.rename(columns={0: "sum"}, inplace=True)
95
+ merged["difference"] = merged["load_value"] - merged["sum"]
96
+ merged = merged[merged["difference"] > 0]
97
+ merged.set_index(["time", "source", "country"], inplace=True)
98
+
99
+ LCI_cons.sort_index(inplace=True)
100
+ LCI_cons.sort_index(axis=1, inplace=True)
101
+ LCI_cons.loc[load_difference_row] = merged["difference"]
102
+ LCI_cons.loc[load_difference_row] = LCI_cons.loc[
103
+ load_difference_row
104
+ ].fillna(0)
105
+ LCI_cons_scaled = LCI_cons / LCI_cons.sum()
106
+ save_to_pickle(
107
+ LCI_cons_scaled,
108
+ Path(path_to_data / f"{year}" / f"LCI_cons_scaled_{year}.pkl"),
109
+ )
110
+ now = datetime.now()
111
+ print(f"{now} Technologies mapped.")
112
+ return LCI_cons_scaled
113
+
114
+
115
+ def filter_by_countries(dataframe, countries):
116
+ """Filter a legacy activity table to selected consumer countries."""
117
+ if "country" not in dataframe.columns.names:
118
+ print("Couldnt find country to filter")
119
+ return None
120
+
121
+ return dataframe.loc[
122
+ :, dataframe.columns.get_level_values("country").isin(countries)
123
+ ]
124
+
125
+
126
+ def filter_by_times(dataframe, times):
127
+ """Filter a legacy activity table to specific timestamps."""
128
+ available_times = pd.to_datetime(dataframe.columns.get_level_values("time"))
129
+ requested_times = pd.to_datetime(times)
130
+ return dataframe.loc[:, available_times.isin(requested_times)]
131
+
132
+
133
+ def filter_by_range(dataframe, general_range, refined_range, freq):
134
+ """Filter and aggregate a legacy activity table over a time range."""
135
+ df_filt = dataframe.loc[:, general_range[0] : general_range[1]]
136
+ if refined_range and len(refined_range) > 1:
137
+ timestamp = pd.date_range(
138
+ start=general_range[0], end=general_range[1], freq=freq
139
+ )
140
+ timestamps_range = timestamp[
141
+ (timestamp.hour >= refined_range[0]) & (timestamp.hour <= refined_range[1])
142
+ ]
143
+ df_filt = df_filt.loc[
144
+ :,
145
+ pd.to_datetime(df_filt.columns.get_level_values("time")).isin(
146
+ timestamps_range
147
+ ),
148
+ ]
149
+ elif refined_range and len(refined_range) == 1:
150
+ timestamp = pd.date_range(
151
+ start=general_range[0], end=general_range[1], freq=freq
152
+ )
153
+ df_filt = df_filt.loc[
154
+ :, pd.to_datetime(df_filt.columns.get_level_values("time")).isin(timestamp)
155
+ ]
156
+ return df_filt.T.groupby(level="country").mean().T
@@ -2,7 +2,8 @@
2
2
  # Licensed under the MIT License (see LICENSE file for details).
3
3
  # Authors: [Sabina Bednářová, Thomas Gibon]
4
4
 
5
- import pickle
5
+ """Historical full-matrix treatment retained for validation."""
6
+
6
7
  from datetime import datetime
7
8
  from importlib.resources import files
8
9
  from pathlib import Path
@@ -14,8 +15,13 @@ from pypardiso import spsolve
14
15
  from scipy.linalg import block_diag
15
16
  from scipy.sparse import coo_array, csc_matrix, csr_matrix, identity
16
17
 
18
+ from shrecc.result_store import (
19
+ load_pickle as load_from_pickle,
20
+ save_pickle as save_to_pickle,
21
+ )
22
+
17
23
 
18
- def data_processing(data_df, year, path_to_data=None):
24
+ def _legacy_data_processing(data_df, year, path_to_data=None):
19
25
  """
20
26
  Processes data, adds missing countries, and correctly divides them between consumption and demand.
21
27
 
@@ -141,35 +147,6 @@ def data_processing(data_df, year, path_to_data=None):
141
147
  print(f"{now} ..all done!")
142
148
 
143
149
 
144
- def save_to_pickle(obj, filename):
145
- """
146
- Saves an object to a pickle file.
147
-
148
- Args:
149
- obj: The object to be saved.
150
- filename (Path): Path to the filename where the object will be saved.
151
-
152
- Returns:
153
- None
154
- """
155
- with open(filename, "wb") as f:
156
- pickle.dump(obj, f)
157
-
158
-
159
- def load_from_pickle(filename):
160
- """
161
- Loads an object from a pickle file.
162
-
163
- Args:
164
- filename (Path): Path to the filename where the object will be saved.
165
-
166
- Returns:
167
- object: The object loaded from the pickle file.
168
- """
169
- with open(filename, "rb") as f:
170
- return pickle.load(f)
171
-
172
-
173
150
  def add_missing_elements(df, existing_elements, all_elements, axis=0, fill_value=0):
174
151
  """
175
152
  Adds missing elements (rows or columns) to a dataframe.