NREL-erad 0.0.0a0__py3-none-any.whl → 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 (37) hide show
  1. erad/__init__.py +1 -0
  2. erad/constants.py +20 -20
  3. erad/cypher_queries/load_data_v1.cypher +211 -211
  4. erad/data/World_Earthquakes_1960_2016.csv +23410 -23410
  5. erad/db/assets/critical_infras.py +170 -170
  6. erad/db/assets/distribution_lines.py +101 -101
  7. erad/db/credential_model.py +20 -20
  8. erad/db/disaster_input_model.py +23 -23
  9. erad/db/inject_earthquake.py +52 -52
  10. erad/db/inject_flooding.py +53 -53
  11. erad/db/neo4j_.py +162 -162
  12. erad/db/utils.py +13 -13
  13. erad/exceptions.py +68 -68
  14. erad/metrics/check_microgrid.py +208 -208
  15. erad/metrics/metric.py +178 -178
  16. erad/programs/backup.py +61 -61
  17. erad/programs/microgrid.py +44 -44
  18. erad/scenarios/abstract_scenario.py +102 -102
  19. erad/scenarios/common.py +92 -92
  20. erad/scenarios/earthquake_scenario.py +161 -161
  21. erad/scenarios/fire_scenario.py +160 -160
  22. erad/scenarios/flood_scenario.py +493 -493
  23. erad/scenarios/flows.csv +671 -0
  24. erad/scenarios/utilities.py +75 -75
  25. erad/scenarios/wind_scenario.py +89 -89
  26. erad/utils/ditto_utils.py +252 -252
  27. erad/utils/hifld_utils.py +147 -147
  28. erad/utils/opendss_utils.py +357 -357
  29. erad/utils/overpass.py +76 -76
  30. erad/utils/util.py +178 -178
  31. erad/visualization/plot_graph.py +218 -218
  32. {NREL_erad-0.0.0a0.dist-info → nrel_erad-1.0.0.dist-info}/METADATA +65 -61
  33. nrel_erad-1.0.0.dist-info/RECORD +42 -0
  34. {NREL_erad-0.0.0a0.dist-info → nrel_erad-1.0.0.dist-info}/WHEEL +1 -2
  35. {NREL_erad-0.0.0a0.dist-info → nrel_erad-1.0.0.dist-info/licenses}/LICENSE.txt +28 -28
  36. NREL_erad-0.0.0a0.dist-info/RECORD +0 -42
  37. NREL_erad-0.0.0a0.dist-info/top_level.txt +0 -1
erad/utils/ditto_utils.py CHANGED
@@ -1,252 +1,252 @@
1
- """ Utility functions for dealing with SMART DS dataset.
2
-
3
- Examples:
4
-
5
- >>> from erad import ditto_utils
6
- >>> ditto_utils.download_smartds_data('P4R', '.')
7
-
8
- """
9
-
10
- # standard libraries
11
- from pathlib import Path
12
- import shutil
13
- import logging
14
- from typing import List
15
-
16
- # third-party libraries
17
- import boto3
18
- from botocore import UNSIGNED
19
- from botocore.config import Config
20
- from ditto.store import Store
21
- from ditto.readers.opendss.read import Reader
22
- from ditto.network.network import Network
23
- from ditto.models.power_source import PowerSource
24
- import networkx as nx
25
- from networkx.readwrite import json_graph
26
-
27
-
28
- # internal libraries
29
- from erad.constants import SMARTDS_VALID_AREAS, SMARTDS_VALID_YEARS
30
- from erad.exceptions import SMARTDSInvalidInput, DittoException
31
- from erad.utils.util import timeit, write_file, path_validation
32
- from erad.utils.util import read_file, setup_logging
33
-
34
-
35
- logger = logging.getLogger(__name__)
36
-
37
-
38
- @timeit
39
- def download_aws_dir(
40
- bucket: str, path: str, target: str, unsigned=True, **kwargs
41
- ) -> None:
42
- """Utility function download data from AWS S3 directory.
43
-
44
- Args:
45
- bucket (str): Name of the bucket.
46
- path (str): S3 bucket prefix
47
- target (str): Path for downloading the data
48
- unsigned (bool): Indicate whether to use credential or not
49
- kwargs (dict): Keyword arguments accepted by `boto3.client`
50
- """
51
-
52
- target = Path(target)
53
- if unsigned:
54
- client = boto3.client("s3", config=Config(signature_version=UNSIGNED))
55
- else:
56
- if kwargs:
57
- client = boto3.client("s3", **kwargs)
58
- else:
59
- client = boto3.client("s3")
60
-
61
- # Handle missing / at end of prefix
62
- if not path.endswith("/"):
63
- path += "/"
64
-
65
- paginator = client.get_paginator("list_objects_v2")
66
- for result in paginator.paginate(Bucket=bucket, Prefix=path):
67
-
68
- # Download each file individually
69
- for key in result["Contents"]:
70
-
71
- # Calculate relative path
72
- rel_path = key["Key"][len(path) :]
73
-
74
- # Skip paths ending in /
75
- if not key["Key"].endswith("/"):
76
- local_file_path = target / rel_path
77
- local_file_path.parent.mkdir(parents=True, exist_ok=True)
78
- client.download_file(bucket, key["Key"], str(local_file_path))
79
-
80
-
81
- @timeit
82
- def download_smartds_data(
83
- smartds_region: str,
84
- output_path: str = "./smart_ds_downloads",
85
- year: int = 2018,
86
- area: str = "SFO",
87
- s3_bucket_name: str = "oedi-data-lake",
88
- folder_name: str = "opendss_no_loadshapes",
89
- cache_folder: str = "cache",
90
- ) -> str:
91
- """Utility function to download SMARTDS data from AWS S3 bucket.
92
-
93
- Args:
94
- smartds_region (str): SMARTDS region name
95
- output_path (str): Path for downloaded data
96
- year (int): Valid year input for downloading the data
97
- area (str): Valid SMARTDS area
98
- s3_bucket_name (str): S3 bucket name storing the SMARTDS data
99
- folder_name (str): S3 bucket folder to download
100
- cache_folder (str): Folder path for caching the results
101
-
102
- Raises:
103
- SMARTDSInvalidInput: Raises this error if year and/or area
104
- provided is not valid.
105
-
106
- Returns:
107
- str: Folder path containing downloaded data.
108
- """
109
- if year not in SMARTDS_VALID_YEARS or area not in SMARTDS_VALID_AREAS:
110
- raise SMARTDSInvalidInput(
111
- f"Not valid input! year= {year} area={area}, \
112
- valid_years={SMARTDS_VALID_YEARS}, valid_areas={SMARTDS_VALID_AREAS}"
113
- )
114
-
115
- output_path = Path(output_path)
116
- cache_folder = Path(cache_folder)
117
-
118
- output_path.mkdir(exist_ok=True)
119
- cache_folder.mkdir(exist_ok=True)
120
-
121
- cache_key = (
122
- f"{smartds_region}__{year}__{area}__{s3_bucket_name}_{folder_name}"
123
- )
124
- cache_data_folder = cache_folder / cache_key
125
- output_folder = output_path / cache_key
126
-
127
- if cache_data_folder.exists():
128
- logger.info(f"Cache hit for {cache_data_folder}")
129
- shutil.copytree(cache_data_folder, output_folder, dirs_exist_ok=True)
130
-
131
- else:
132
- logger.info(
133
- f"Cache missed reaching to AWS for downloading the data ..."
134
- )
135
- output_folder.mkdir(exist_ok=True)
136
- prefix = f"SMART-DS/v1.0/{year}/{area}/{smartds_region}/scenarios/base_timeseries/{folder_name}/"
137
- download_aws_dir(s3_bucket_name, prefix, output_folder)
138
- shutil.copytree(output_folder, cache_data_folder, dirs_exist_ok=False)
139
-
140
- logger.info(f"Check the folder {output_folder} for downloaded data")
141
- return output_folder
142
-
143
-
144
- @timeit
145
- def _create_networkx_from_ditto(
146
- output_path: str, file_name: str, **kwargs
147
- ) -> List:
148
- """Creates networkx graph from OpenDSS model using Ditto.
149
-
150
- Args:
151
- output_path (str): Path to store the networkx
152
- data in json file format
153
- file_name (str): JSON file name used to export
154
- the network
155
- kwargs (dict): Keyword arguments accepted
156
- by Ditto
157
-
158
- Raises:
159
- DittoException: Raises if multiple sources are found.
160
-
161
-
162
- Returns:
163
- List: Pair of networkx graph and
164
- path containing JSON file
165
- """
166
- file_name = Path(file_name).stem
167
- logger.debug(
168
- "Attempting to create NetworkX representation from OpenDSS \
169
- files using DiTTo"
170
- )
171
-
172
- path_validation(output_path)
173
-
174
- store = Store()
175
- reader = Reader(
176
- master_file=kwargs["master_file"],
177
- buscoordinates_file=kwargs["buscoordinates_file"],
178
- coordinates_delimiter=kwargs["coordinates_delimiter"],
179
- )
180
- reader.parse(store)
181
-
182
- all_sources = []
183
- for i in store.models:
184
- if isinstance(i, PowerSource) and i.connecting_element is not None:
185
- all_sources.append(i)
186
- elif isinstance(i, PowerSource):
187
- print(
188
- "Warning - a PowerSource element has a None connecting element"
189
- )
190
-
191
- if len(all_sources) > 1:
192
- raise DittoException(
193
- f"This feeder has lots of sources {len(all_sources)}"
194
- )
195
-
196
- ditto_graph = Network()
197
- ditto_graph.build(store, all_sources[0].connecting_element)
198
- ditto_graph.set_attributes(store)
199
-
200
- data = dict(ditto_graph.graph.nodes.data())
201
- data_new = {}
202
- for node, node_data in data.items():
203
- try:
204
- data_new[node] = node_data["positions"][0]._trait_values
205
- except Exception as e:
206
- connecting_node = node_data["connecting_element"]
207
- data_new[node] = data[connecting_node]["positions"][0]._trait_values
208
-
209
- adj_file = file_name + ".adjlist"
210
- nx.write_adjlist(ditto_graph.graph, output_path / adj_file)
211
- g = nx.read_adjlist(output_path / adj_file)
212
- nx.set_node_attributes(g, data_new)
213
-
214
- data = json_graph.adjacency_data(g)
215
- json_file = file_name + ".json"
216
- output_file = output_path / json_file
217
- write_file(data, output_file)
218
-
219
- logger.debug(
220
- f"Successfully created json file representing the network \
221
- check the file {output_file}"
222
- )
223
-
224
- return (g, output_file)
225
-
226
-
227
- def create_networkx_from_ditto(
228
- output_path: str, file_name: str, **kwargs
229
- ) -> None:
230
- """Creates networkx graph from OpenDSS model using Ditto.
231
-
232
- Args:
233
- output_path (str): Path to store the networkx
234
- data in json file format
235
- file_name (str): JSON file name used to export
236
- the network
237
- kwargs (dict): Keyword arguments accepted
238
- by Ditto
239
- """
240
- try:
241
- output_path = Path(output_path)
242
- return _create_networkx_from_ditto(output_path, file_name, **kwargs)
243
- finally:
244
- for file_path in output_path.iterdir():
245
- if file_path.suffix == ".adjlist":
246
- file_path.unlink(missing_ok=True)
247
-
248
-
249
- def create_networkx_from_json(json_file_path: str):
250
- """Returns networkx graph from JSON file."""
251
- content = read_file(json_file_path)
252
- return json_graph.adjacency_graph(content)
1
+ """ Utility functions for dealing with SMART DS dataset.
2
+
3
+ Examples:
4
+
5
+ >>> from erad import ditto_utils
6
+ >>> ditto_utils.download_smartds_data('P4R', '.')
7
+
8
+ """
9
+
10
+ # standard libraries
11
+ from pathlib import Path
12
+ import shutil
13
+ import logging
14
+ from typing import List
15
+
16
+ # third-party libraries
17
+ import boto3
18
+ from botocore import UNSIGNED
19
+ from botocore.config import Config
20
+ from ditto.store import Store
21
+ from ditto.readers.opendss.read import Reader
22
+ from ditto.network.network import Network
23
+ from ditto.models.power_source import PowerSource
24
+ import networkx as nx
25
+ from networkx.readwrite import json_graph
26
+
27
+
28
+ # internal libraries
29
+ from erad.constants import SMARTDS_VALID_AREAS, SMARTDS_VALID_YEARS
30
+ from erad.exceptions import SMARTDSInvalidInput, DittoException
31
+ from erad.utils.util import timeit, write_file, path_validation
32
+ from erad.utils.util import read_file, setup_logging
33
+
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+
38
+ @timeit
39
+ def download_aws_dir(
40
+ bucket: str, path: str, target: str, unsigned=True, **kwargs
41
+ ) -> None:
42
+ """Utility function download data from AWS S3 directory.
43
+
44
+ Args:
45
+ bucket (str): Name of the bucket.
46
+ path (str): S3 bucket prefix
47
+ target (str): Path for downloading the data
48
+ unsigned (bool): Indicate whether to use credential or not
49
+ kwargs (dict): Keyword arguments accepted by `boto3.client`
50
+ """
51
+
52
+ target = Path(target)
53
+ if unsigned:
54
+ client = boto3.client("s3", config=Config(signature_version=UNSIGNED))
55
+ else:
56
+ if kwargs:
57
+ client = boto3.client("s3", **kwargs)
58
+ else:
59
+ client = boto3.client("s3")
60
+
61
+ # Handle missing / at end of prefix
62
+ if not path.endswith("/"):
63
+ path += "/"
64
+
65
+ paginator = client.get_paginator("list_objects_v2")
66
+ for result in paginator.paginate(Bucket=bucket, Prefix=path):
67
+
68
+ # Download each file individually
69
+ for key in result["Contents"]:
70
+
71
+ # Calculate relative path
72
+ rel_path = key["Key"][len(path) :]
73
+
74
+ # Skip paths ending in /
75
+ if not key["Key"].endswith("/"):
76
+ local_file_path = target / rel_path
77
+ local_file_path.parent.mkdir(parents=True, exist_ok=True)
78
+ client.download_file(bucket, key["Key"], str(local_file_path))
79
+
80
+
81
+ @timeit
82
+ def download_smartds_data(
83
+ smartds_region: str,
84
+ output_path: str = "./smart_ds_downloads",
85
+ year: int = 2018,
86
+ area: str = "SFO",
87
+ s3_bucket_name: str = "oedi-data-lake",
88
+ folder_name: str = "opendss_no_loadshapes",
89
+ cache_folder: str = "cache",
90
+ ) -> str:
91
+ """Utility function to download SMARTDS data from AWS S3 bucket.
92
+
93
+ Args:
94
+ smartds_region (str): SMARTDS region name
95
+ output_path (str): Path for downloaded data
96
+ year (int): Valid year input for downloading the data
97
+ area (str): Valid SMARTDS area
98
+ s3_bucket_name (str): S3 bucket name storing the SMARTDS data
99
+ folder_name (str): S3 bucket folder to download
100
+ cache_folder (str): Folder path for caching the results
101
+
102
+ Raises:
103
+ SMARTDSInvalidInput: Raises this error if year and/or area
104
+ provided is not valid.
105
+
106
+ Returns:
107
+ str: Folder path containing downloaded data.
108
+ """
109
+ if year not in SMARTDS_VALID_YEARS or area not in SMARTDS_VALID_AREAS:
110
+ raise SMARTDSInvalidInput(
111
+ f"Not valid input! year= {year} area={area}, \
112
+ valid_years={SMARTDS_VALID_YEARS}, valid_areas={SMARTDS_VALID_AREAS}"
113
+ )
114
+
115
+ output_path = Path(output_path)
116
+ cache_folder = Path(cache_folder)
117
+
118
+ output_path.mkdir(exist_ok=True)
119
+ cache_folder.mkdir(exist_ok=True)
120
+
121
+ cache_key = (
122
+ f"{smartds_region}__{year}__{area}__{s3_bucket_name}_{folder_name}"
123
+ )
124
+ cache_data_folder = cache_folder / cache_key
125
+ output_folder = output_path / cache_key
126
+
127
+ if cache_data_folder.exists():
128
+ logger.info(f"Cache hit for {cache_data_folder}")
129
+ shutil.copytree(cache_data_folder, output_folder, dirs_exist_ok=True)
130
+
131
+ else:
132
+ logger.info(
133
+ f"Cache missed reaching to AWS for downloading the data ..."
134
+ )
135
+ output_folder.mkdir(exist_ok=True)
136
+ prefix = f"SMART-DS/v1.0/{year}/{area}/{smartds_region}/scenarios/base_timeseries/{folder_name}/"
137
+ download_aws_dir(s3_bucket_name, prefix, output_folder)
138
+ shutil.copytree(output_folder, cache_data_folder, dirs_exist_ok=False)
139
+
140
+ logger.info(f"Check the folder {output_folder} for downloaded data")
141
+ return output_folder
142
+
143
+
144
+ @timeit
145
+ def _create_networkx_from_ditto(
146
+ output_path: str, file_name: str, **kwargs
147
+ ) -> List:
148
+ """Creates networkx graph from OpenDSS model using Ditto.
149
+
150
+ Args:
151
+ output_path (str): Path to store the networkx
152
+ data in json file format
153
+ file_name (str): JSON file name used to export
154
+ the network
155
+ kwargs (dict): Keyword arguments accepted
156
+ by Ditto
157
+
158
+ Raises:
159
+ DittoException: Raises if multiple sources are found.
160
+
161
+
162
+ Returns:
163
+ List: Pair of networkx graph and
164
+ path containing JSON file
165
+ """
166
+ file_name = Path(file_name).stem
167
+ logger.debug(
168
+ "Attempting to create NetworkX representation from OpenDSS \
169
+ files using DiTTo"
170
+ )
171
+
172
+ path_validation(output_path)
173
+
174
+ store = Store()
175
+ reader = Reader(
176
+ master_file=kwargs["master_file"],
177
+ buscoordinates_file=kwargs["buscoordinates_file"],
178
+ coordinates_delimiter=kwargs["coordinates_delimiter"],
179
+ )
180
+ reader.parse(store)
181
+
182
+ all_sources = []
183
+ for i in store.models:
184
+ if isinstance(i, PowerSource) and i.connecting_element is not None:
185
+ all_sources.append(i)
186
+ elif isinstance(i, PowerSource):
187
+ print(
188
+ "Warning - a PowerSource element has a None connecting element"
189
+ )
190
+
191
+ if len(all_sources) > 1:
192
+ raise DittoException(
193
+ f"This feeder has lots of sources {len(all_sources)}"
194
+ )
195
+
196
+ ditto_graph = Network()
197
+ ditto_graph.build(store, all_sources[0].connecting_element)
198
+ ditto_graph.set_attributes(store)
199
+
200
+ data = dict(ditto_graph.graph.nodes.data())
201
+ data_new = {}
202
+ for node, node_data in data.items():
203
+ try:
204
+ data_new[node] = node_data["positions"][0]._trait_values
205
+ except Exception as e:
206
+ connecting_node = node_data["connecting_element"]
207
+ data_new[node] = data[connecting_node]["positions"][0]._trait_values
208
+
209
+ adj_file = file_name + ".adjlist"
210
+ nx.write_adjlist(ditto_graph.graph, output_path / adj_file)
211
+ g = nx.read_adjlist(output_path / adj_file)
212
+ nx.set_node_attributes(g, data_new)
213
+
214
+ data = json_graph.adjacency_data(g)
215
+ json_file = file_name + ".json"
216
+ output_file = output_path / json_file
217
+ write_file(data, output_file)
218
+
219
+ logger.debug(
220
+ f"Successfully created json file representing the network \
221
+ check the file {output_file}"
222
+ )
223
+
224
+ return (g, output_file)
225
+
226
+
227
+ def create_networkx_from_ditto(
228
+ output_path: str, file_name: str, **kwargs
229
+ ) -> None:
230
+ """Creates networkx graph from OpenDSS model using Ditto.
231
+
232
+ Args:
233
+ output_path (str): Path to store the networkx
234
+ data in json file format
235
+ file_name (str): JSON file name used to export
236
+ the network
237
+ kwargs (dict): Keyword arguments accepted
238
+ by Ditto
239
+ """
240
+ try:
241
+ output_path = Path(output_path)
242
+ return _create_networkx_from_ditto(output_path, file_name, **kwargs)
243
+ finally:
244
+ for file_path in output_path.iterdir():
245
+ if file_path.suffix == ".adjlist":
246
+ file_path.unlink(missing_ok=True)
247
+
248
+
249
+ def create_networkx_from_json(json_file_path: str):
250
+ """Returns networkx graph from JSON file."""
251
+ content = read_file(json_file_path)
252
+ return json_graph.adjacency_graph(content)