zen-garden 2.7.17__py3-none-any.whl → 2.7.19__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.
zen_garden/__main__.py CHANGED
@@ -9,12 +9,10 @@ import sys
9
9
  import os
10
10
  import zen_garden.default_config as default_config
11
11
  import json
12
- from zen_garden.utils import copy_dataset_example
13
12
  from pathlib import Path
14
13
 
15
14
  def run_module(args=None, config = "./config.py", dataset = None,
16
- folder_output = None, job_index = None, job_index_var = "SLURM_ARRAY_TASK_ID",
17
- download_example = None):
15
+ folder_output = None, job_index = None, job_index_var = "SLURM_ARRAY_TASK_ID"):
18
16
  """
19
17
  Runs the main function of ZEN-Garden
20
18
 
@@ -28,7 +26,7 @@ def run_module(args=None, config = "./config.py", dataset = None,
28
26
  "current working directory. You can specify a config file with the --config argument. However, " \
29
27
  "note that the output directory will always be the current working directory, independent of the " \
30
28
  "dataset specified in the config file."
31
- parser = argparse.ArgumentParser(description=description, add_help=True, usage="usage: zen-garden [-h] [--config CONFIG] [--dataset DATASET] [--job_index JOB_INDEX] [--job_index_var JOB_INDEX_VAR] [-- download_example EXAMPLE_NAME]")
29
+ parser = argparse.ArgumentParser(description=description, add_help=True, usage="usage: zen-garden [-h] [--config CONFIG] [--dataset DATASET] [--job_index JOB_INDEX] [--job_index_var JOB_INDEX_VAR]")
32
30
  # TODO make json config default
33
31
  parser.add_argument("--config", required=False, type=str, default=config, help="Path to the config file used to run the pipeline (e.g., `./config.json`). Alternatively, if the config file is located in the current working directory, then the file name is alone is also acceptable (e.g. `config.json`).")
34
32
  parser.add_argument("--dataset", required=False, type=str, default=dataset, help="Path to the dataset (e.g. `./<dataset_name>`). Alternatively, if the dataset is located in the current working directory, then the folder name alone is also acceptable (e.g. `<dataset_name>`). IMPORTANT: This will overwrite the config.analysis.dataset attribute of the config file!")
@@ -37,15 +35,8 @@ def run_module(args=None, config = "./config.py", dataset = None,
37
35
  parser.add_argument("--job_index", required=False, type=str, default=job_index, help="A comma separated list (no spaces) of indices of the scenarios to run, if None, all scenarios are run in sequence")
38
36
  parser.add_argument("--job_index_var", required=False, type=str, default=job_index_var, help="Try to read out the job index from the environment variable specified here. "
39
37
  "If both --job_index and --job_index_var are specified, --job_index will be used.")
40
- parser.add_argument("--download_example", required=False, type=str, default=download_example, help="Downloads an example data set to the current working directory. The argument should be the name of a dataset example in documentation/dataset_examples. This command will copy the dataset and the config to the current folder. It will not run ZEN-garden.")
41
-
42
38
  args = parser.parse_args(args)
43
39
 
44
- # copy example dataset and run example
45
- if args.download_example is not None:
46
- example_path_cwd,config_path_cwd = copy_dataset_example(args.download_example)
47
- return
48
-
49
40
  if not os.path.exists(args.config):
50
41
  args.config = args.config.replace(".py", ".json")
51
42
 
@@ -0,0 +1,186 @@
1
+ """
2
+ This module contains code the coding for downloading the ZEN-garden
3
+ dataset examples. It defines a command line interface as well as a python
4
+ function for this purpose.
5
+ """
6
+
7
+ import argparse
8
+ import sys
9
+ import json
10
+ import warnings
11
+ import os
12
+ import sys
13
+ import requests
14
+ from importlib.metadata import metadata
15
+ import zipfile
16
+ import io
17
+
18
+
19
+ def download_example_dataset(dataset):
20
+ """
21
+ Downloads a dataset example to the current working directory. The function
22
+ downloads the ZEN-garden dataset examples from the ZEN-garden Zenodo
23
+ repository. It then extracts the dataset specified by the user and saves
24
+ it to the current working directory. In addition, it also downloads a
25
+ ``config.json`` file and a Jupyter notebook demonstrating how to analyze
26
+ the results of a model.
27
+
28
+ Args:
29
+ dataset (str): Name of the dataset to be downloaded. The following
30
+ options are currently available: "1_base_case",
31
+ "2_multi_year_optimization", "3_reduced_import_availability",
32
+ "4_PWA_nonlinear_capex", "5_multiple_time_steps_per_year",
33
+ "6_reduced_import_availability_yearly", "7_time_series_aggregation",
34
+ "8_yearly_variation", "9_myopic_foresight", "10_brown_field",
35
+ "11_multi_scenario", "12_multiple_in_output_carriers_conversion",
36
+ "13_yearly_interpolation", "14_retrofitting_and_fuel_substitution",
37
+ "15_unit_consistency_expected_error"
38
+
39
+ Returns:
40
+ tuple:
41
+ str: The local path of the copied example
42
+ str: The local path of the copied config.json
43
+
44
+ Raises:
45
+ FileNotFoundError: If either the dataset or the config file could not
46
+ be found in the Zenodo repository.
47
+
48
+ Examples:
49
+ Basic usage example:
50
+
51
+ >>> from zen_garden.dataset_examples import download_dataset_example
52
+ >>> download_dataset_example("1_base_case")
53
+
54
+ """
55
+
56
+ # retrieve Zenodo metadata
57
+ url = metadata("zen_garden").get_all("Project-URL")
58
+ url = [u.split(", ")[1] for u in url if u.split(", ")[0] == "Zenodo"][0]
59
+
60
+ # fetch Zenodo metadata
61
+ zenodo_meta = requests.get(url, allow_redirects=True)
62
+ zenodo_meta.raise_for_status()
63
+ zenodo_data = zenodo_meta.json()
64
+ zenodo_zip_url = zenodo_data["files"][0]["links"]["self"]
65
+
66
+ # download ZIP file from Zenodo
67
+ zenodo_zip = requests.get(zenodo_zip_url)
68
+ zenodo_zip = zipfile.ZipFile(io.BytesIO(zenodo_zip.content))
69
+
70
+ # define relevant paths
71
+ base_path = zenodo_zip.filelist[0].filename
72
+ example_path = f"{base_path}docs/dataset_examples/{dataset}/"
73
+ config_path = f"{base_path}docs/dataset_examples/config.json"
74
+ notebook_path = f"{base_path}docs/dataset_examples/example_notebook.ipynb"
75
+
76
+ # create local directories
77
+ local_dataset_path = os.getcwd()
78
+ if not os.path.exists(local_dataset_path):
79
+ os.mkdir(local_dataset_path)
80
+ local_example_path = os.path.join(local_dataset_path, dataset)
81
+ if not os.path.exists(local_example_path):
82
+ os.mkdir(local_example_path)
83
+
84
+ # initialize flags for extracting files
85
+ example_found = False
86
+ config_found = False
87
+ notebook_found = False
88
+
89
+ # search for example within ZIP file
90
+ for file in zenodo_zip.filelist:
91
+
92
+ # download all files in dataset example
93
+ if file.filename.startswith(example_path):
94
+ filename_ending = file.filename.split(example_path)[1]
95
+ local_folder_path = os.path.join(
96
+ local_example_path, filename_ending)
97
+ if file.is_dir():
98
+ if not os.path.exists(local_folder_path):
99
+ os.mkdir(os.path.join(local_example_path, filename_ending))
100
+ else:
101
+ local_file_path = os.path.join(
102
+ local_example_path, filename_ending)
103
+ with open(local_file_path, "wb") as f:
104
+ f.write(zenodo_zip.read(file))
105
+ example_found = True
106
+
107
+ # download config.json
108
+ elif file.filename == config_path:
109
+ with open(os.path.join(local_dataset_path, "config.json"), "wb") as f:
110
+ f.write(zenodo_zip.read(file))
111
+ config_found = True
112
+
113
+ # download jupyter notebook
114
+ elif file.filename == notebook_path:
115
+ notebook_path_local = os.path.join(
116
+ local_dataset_path, "example_notebook.ipynb")
117
+ notebook = json.loads(zenodo_zip.read(file))
118
+ for cell in notebook['cells']:
119
+ if cell['cell_type'] == 'code': # Check only code cells
120
+ for i, line in enumerate(cell['source']):
121
+ if "<dataset_name>" in line:
122
+ cell['source'][i] = line.replace(
123
+ "<dataset_name>", dataset)
124
+ with open(notebook_path_local, "w") as f:
125
+ json.dump(notebook, f)
126
+ notebook_found = True
127
+
128
+ # display status, errors, and warnings
129
+ if not example_found:
130
+ raise FileNotFoundError(
131
+ f"Example {dataset} could not be found in the dataset examples!"
132
+ )
133
+ if not config_found:
134
+ raise FileNotFoundError(
135
+ "Config.json file could not be downloaded from the dataset "
136
+ "examples!"
137
+ )
138
+ if not notebook_found:
139
+ warnings.warn(
140
+ "Example jupyter notebook could not be downloaded from the "
141
+ "dataset examples!")
142
+
143
+ # print output
144
+ print(f"Example dataset {dataset} downloaded to {local_example_path}")
145
+
146
+ # return
147
+ return local_example_path, os.path.join(local_dataset_path, "config.json")
148
+
149
+
150
+ def cli_download_example_dataset():
151
+ """
152
+ Creates a command line interface for downloading the dataset examples.
153
+ The function parses a single required argument ``--dataset`` that
154
+ specifies the name of the dataset to be downloaded. It then invokes
155
+ the function function ``download_example_dataset`` with that argument.
156
+
157
+ The ``[project.scripts]`` section of the pyproject.toml declares that
158
+ this function will be called whenever a user enters ``zen-example`` into
159
+ the command prompt. This function is therefore creates the ``zen-example``
160
+ command line entry point.
161
+
162
+ Examples:
163
+ Basic usage in a command line prompt:
164
+
165
+ >>> zen-example --dataset="1_base_case"
166
+
167
+ """
168
+ # parse the args
169
+ description = "Downloads an example dataset for ZEN-garden to the current" \
170
+ "working directory"
171
+
172
+ parser = argparse.ArgumentParser(
173
+ description=description,
174
+ add_help=True,
175
+ usage="usage: zen-example [--dataset DATASET]")
176
+
177
+ parser.add_argument(
178
+ "--dataset",
179
+ required=True,
180
+ type=str,
181
+ help="Name of the dataset to download, e.g. '1_base_case'")
182
+
183
+ args = parser.parse_args(sys.argv[1:])
184
+
185
+ # download the example
186
+ download_example_dataset(args.dataset)
@@ -337,13 +337,21 @@ class Results:
337
337
  """
338
338
  Calculates the total values of a component for a all scenarios.
339
339
 
340
- :param component_name: Name of the component
340
+ :param component_name: Name of the component. Should not be used for dual variables!
341
341
  :param year: Filter the results by a given year
342
342
  :param scenario_name: Filter the results by a given scenario
343
343
  :param keep_raw: Keep the raw values of the rolling horizon optimization
344
344
  :param index: slicing index of the resulting dataframe
345
345
  :return: Total values of the component
346
346
  """
347
+
348
+ # Throw error if used for a dual variable
349
+ if component_name in self.get_component_names("dual"):
350
+ raise ValueError(
351
+ "This method does not support the extraction of " \
352
+ "dual variables. Please use the methods " \
353
+ "`get_dual()` or `get_full_ts()` instead.")
354
+
347
355
  if scenario_name is None:
348
356
  scenario_names = list(self.solution_loader.scenarios)
349
357
  else:
zen_garden/utils.py CHANGED
@@ -46,74 +46,6 @@ def get_inheritors(klass):
46
46
  return subclasses
47
47
 
48
48
 
49
- def copy_dataset_example(example):
50
- """ copies a dataset example to the current working directory
51
-
52
- :param example: The name of the example to copy
53
- :return: The local path of the copied example
54
- :return: The local path of the copied config.json
55
- """
56
- import requests
57
- from importlib.metadata import metadata
58
- import zipfile
59
- import io
60
- url = metadata("zen_garden").get_all("Project-URL")
61
- url = [u.split(", ")[1] for u in url if u.split(", ")[0] == "Zenodo"][0]
62
- zenodo_meta = requests.get(url,allow_redirects=True)
63
- zenodo_meta.raise_for_status()
64
- zenodo_data = zenodo_meta.json()
65
- zenodo_zip_url = zenodo_data["files"][0]["links"]["self"]
66
- zenodo_zip = requests.get(zenodo_zip_url)
67
- zenodo_zip = zipfile.ZipFile(io.BytesIO(zenodo_zip.content))
68
- base_path = zenodo_zip.filelist[0].filename
69
- example_path = f"{base_path}docs/dataset_examples/{example}/"
70
- config_path = f"{base_path}docs/dataset_examples/config.json"
71
- notebook_path = f"{base_path}docs/dataset_examples/example_notebook.ipynb"
72
- #local_dataset_path = os.path.join(os.getcwd(), "dataset_examples")
73
- local_dataset_path = os.getcwd()
74
- if not os.path.exists(local_dataset_path):
75
- os.mkdir(local_dataset_path)
76
- local_example_path = os.path.join(local_dataset_path, example)
77
- if not os.path.exists(local_example_path):
78
- os.mkdir(local_example_path)
79
- example_found = False
80
- config_found = False
81
- notebook_found = False
82
- for file in zenodo_zip.filelist:
83
- if file.filename.startswith(example_path):
84
- filename_ending = file.filename.split(example_path)[1]
85
- local_folder_path = os.path.join(local_example_path, filename_ending)
86
- if file.is_dir():
87
- if not os.path.exists(local_folder_path):
88
- os.mkdir(os.path.join(local_example_path, filename_ending))
89
- else:
90
- local_file_path = os.path.join(local_example_path, filename_ending)
91
- with open(local_file_path, "wb") as f:
92
- f.write(zenodo_zip.read(file))
93
- example_found = True
94
- elif file.filename == config_path:
95
- with open(os.path.join(local_dataset_path, "config.json"), "wb") as f:
96
- f.write(zenodo_zip.read(file))
97
- config_found = True
98
- elif file.filename == notebook_path:
99
- notebook_path_local = os.path.join(local_dataset_path, "example_notebook.ipynb")
100
- notebook = json.loads(zenodo_zip.read(file))
101
- for cell in notebook['cells']:
102
- if cell['cell_type'] == 'code': # Check only code cells
103
- for i, line in enumerate(cell['source']):
104
- if "<dataset_name>" in line:
105
- cell['source'][i] = line.replace("<dataset_name>", example)
106
- with open(notebook_path_local, "w") as f:
107
- json.dump(notebook, f)
108
- notebook_found = True
109
- assert example_found, f"Example {example} could not be downloaded from the dataset examples!"
110
- assert config_found, f"Config.json file could not be downloaded from the dataset examples!"
111
- if not notebook_found:
112
- logging.warning("Example jupyter notebook could not be downloaded from the dataset examples!")
113
- logging.info(f"Example dataset {example} downloaded to {local_example_path}")
114
- return local_example_path, os.path.join(local_dataset_path, "config.json")
115
-
116
-
117
49
  # linopy helpers
118
50
  # --------------
119
51
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zen_garden
3
- Version: 2.7.17
3
+ Version: 2.7.19
4
4
  Summary: ZEN-garden is an optimization model of energy systems and value chains.
5
5
  Author: Alissa Ganter, Johannes Burger, Francesco De Marco, Lukas Kunz, Lukas Schmidt-Engelbertz, Christoph Funke, Paolo Gabrielli, Giovanni Sansavini
6
6
  Author-email: Jacob Mannhardt <zen-garden@ethz.ch>
@@ -1,9 +1,10 @@
1
1
  zen_garden/__init__.py,sha256=Jc8WQzHjL74sk4xOnbv1i68Bt6RuzXPkh9WYn3Jl_LE,376
2
- zen_garden/__main__.py,sha256=M6iRgRP7L2sgTStLoRhixAGRLBh4Q9OkxhFUy6Zn4GQ,4614
2
+ zen_garden/__main__.py,sha256=pailOU1J-bXMI6IVA6_lqTzrs44uomeG6YGZpEEWg00,3940
3
3
  zen_garden/_internal.py,sha256=K648bT1O8gD9uIrfmqPXP5lDdlkJd3-Ai111_IyIc1w,5347
4
+ zen_garden/dataset_examples.py,sha256=R3urCRReXqlo195wxsLh6tIViQIrucRSx9NdeZhCSV4,6883
4
5
  zen_garden/default_config.py,sha256=ozz2LBSGSaMH8alEAzh-6ziM9IE9zXM9PfRD3nulAIs,8663
5
6
  zen_garden/optimization_setup.py,sha256=Rv_IciR_Y9GF-OaPDDAvTQ2huTuAt94jrWpcDJCQgWQ,42176
6
- zen_garden/utils.py,sha256=skTvbc0zRps1Q0EZFdJGPnG8RUeo_Xv2IraOR4SXdQU,58453
7
+ zen_garden/utils.py,sha256=ZRz2-Fi_X-MxPeGLIf8NHLZY__qliQ3gJiD-BAznrNY,54995
7
8
  zen_garden/visualization.py,sha256=zZApEFtwdA1NpDKTvrZS9lyeiT__s6lR7QVaj6mUCmg,110
8
9
  zen_garden/model/__init__.py,sha256=7QIygxkUlNsOBbJPr5VdAxcJQCz6t_FSlD1uytUhuDE,48
9
10
  zen_garden/model/component.py,sha256=NeMV47l6Ec_ij_jburCx4cz6lI5k1-b6t0_DfuWFhhY,40488
@@ -23,15 +24,15 @@ zen_garden/postprocess/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3
23
24
  zen_garden/postprocess/comparisons.py,sha256=uyEtV0Q8_YPzJi4b12DWiqYU-kKJz6I3Li-I7_6RURY,13239
24
25
  zen_garden/postprocess/postprocess.py,sha256=0_1iy028iZmvf2egXUFO2ZS13HmkacMt7A5eTI0iCE4,29644
25
26
  zen_garden/postprocess/results/__init__.py,sha256=363lzC0uRJ5F42cOEhD9jxMPCioTt8WRt0qwZG0IizY,49
26
- zen_garden/postprocess/results/results.py,sha256=jdJprpSbfs62TZKcHbkfCvSkpG-8fTRXTWoXew9M9AQ,40585
27
+ zen_garden/postprocess/results/results.py,sha256=AkkvPLYotMlDANp2Fn2A3rmZajTX0q_evivxHzTw4CY,40958
27
28
  zen_garden/postprocess/results/solution_loader.py,sha256=ChEV4kUi4m5h3Q6B8oxf9wPdEmrH_CNTs5BRNR8UZQs,31252
28
29
  zen_garden/preprocess/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
29
30
  zen_garden/preprocess/extract_input_data.py,sha256=PWKdel7s488SELseyAaoFkwXpzJU4MZg0pW0wO2ZHoI,51523
30
31
  zen_garden/preprocess/parameter_change_log.py,sha256=WNhLYTyuaFkUl_e4QH36W1chpqg00m7zg__PawPogAY,387
31
32
  zen_garden/preprocess/time_series_aggregation.py,sha256=v8xRRk4I9WZ2yi7V3I_Ersj2RV1T2WIKslx8ohkMfWI,32112
32
33
  zen_garden/preprocess/unit_handling.py,sha256=OGIHFyDdUmGU-GEGHkJGJ9RmKfDBy5-HmuBQmtYAK5Q,63043
33
- zen_garden-2.7.17.dist-info/entry_points.txt,sha256=s6s3kCqiMPeJ5r83yKBgxa79Qm6aQFoQWfIPJbz0iTg,128
34
- zen_garden-2.7.17.dist-info/licenses/LICENSE.txt,sha256=_kEtxPe9gWOwMzdiy8nLzgABiPdMvUS0kaSCOIrEA_E,1101
35
- zen_garden-2.7.17.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
36
- zen_garden-2.7.17.dist-info/METADATA,sha256=LAT2cCJ7p2v9StGXNxyXTN0F3EAht0FoWszqlmPbIrY,5649
37
- zen_garden-2.7.17.dist-info/RECORD,,
34
+ zen_garden-2.7.19.dist-info/entry_points.txt,sha256=KzNcbWW-Z52ic1Y2UsnfrLF57DWkgQvEwxkyfSwolJA,197
35
+ zen_garden-2.7.19.dist-info/licenses/LICENSE.txt,sha256=_kEtxPe9gWOwMzdiy8nLzgABiPdMvUS0kaSCOIrEA_E,1101
36
+ zen_garden-2.7.19.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
37
+ zen_garden-2.7.19.dist-info/METADATA,sha256=kjsLCoKIL1HRY4hRcYUrjfw0ToGF2qUgYycieumF_6w,5649
38
+ zen_garden-2.7.19.dist-info/RECORD,,
@@ -1,4 +1,5 @@
1
1
  [console_scripts]
2
+ zen-example=zen_garden.dataset_examples:cli_download_example_dataset
2
3
  zen-garden=zen_garden.__main__:run_module
3
4
  zen-visualization=zen_garden.visualization:parse_arguments_and_run
4
5