isp-trace-parser 0.1.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.
- isp_trace_name_mapping_configs/demand_scenario_mapping.yaml +3 -0
- isp_trace_name_mapping_configs/solar_area_mapping.yaml +37 -0
- isp_trace_name_mapping_configs/solar_project_mapping.yaml +114 -0
- isp_trace_name_mapping_configs/wind_area_mapping.yaml +43 -0
- isp_trace_name_mapping_configs/wind_project_mapping.yaml +356 -0
- isp_trace_parser/__init__.py +18 -0
- isp_trace_parser/construct_reference_year_mapping.py +29 -0
- isp_trace_parser/demand_traces.py +161 -0
- isp_trace_parser/generator_to_trace_draft_mapper.py +144 -0
- isp_trace_parser/get_data.py +662 -0
- isp_trace_parser/metadata_extractors.py +73 -0
- isp_trace_parser/solar_traces.py +153 -0
- isp_trace_parser/trace_formatter.py +101 -0
- isp_trace_parser/trace_restructure_helper_functions.py +145 -0
- isp_trace_parser/wind_traces.py +216 -0
- isp_trace_parser-0.1.0.dist-info/LICENSE +675 -0
- isp_trace_parser-0.1.0.dist-info/METADATA +147 -0
- isp_trace_parser-0.1.0.dist-info/RECORD +20 -0
- isp_trace_parser-0.1.0.dist-info/WHEEL +5 -0
- isp_trace_parser-0.1.0.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def extract_solar_trace_metadata(filename):
|
|
5
|
+
# Case 1: Match filenames that have a name, a tech, followed by RefYear
|
|
6
|
+
pattern1 = re.compile(
|
|
7
|
+
r"^(?P<name>[A-Za-z0-9_\-]+)_(?P<technology>[A-Z]+)_RefYear(?P<year>\d{4})\.csv$"
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
# Case 2: Match filenames that have a rez, a name, and tech, followed by RefYear
|
|
11
|
+
pattern2 = re.compile(
|
|
12
|
+
r"^[A-Z]+_(?P<name>[A-Z0-9]+)_[A-Za-z0-9_\-]+_(?P<technology>[A-Z]+)_RefYear(?P<year>\d{4})\.csv$"
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
# Try to match with pattern 2 first
|
|
16
|
+
match2 = pattern2.match(filename)
|
|
17
|
+
if match2:
|
|
18
|
+
match_data = match2.groupdict()
|
|
19
|
+
match_data["file_type"] = "area"
|
|
20
|
+
return match_data
|
|
21
|
+
|
|
22
|
+
# Otherwise, try to match with pattern 1 (just name and year)
|
|
23
|
+
match1 = pattern1.match(filename)
|
|
24
|
+
if match1:
|
|
25
|
+
match_data = match1.groupdict()
|
|
26
|
+
match_data["file_type"] = "project"
|
|
27
|
+
return match_data
|
|
28
|
+
|
|
29
|
+
raise ValueError(f"Filename '{filename}' does not match the expected pattern")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def extract_wind_trace_metadata(filename):
|
|
33
|
+
# Case 1: Match filenames that have a simple name followed by RefYear
|
|
34
|
+
pattern1 = re.compile(r"^(?P<name>.*)_RefYear(?P<year>\d{4})\.csv$")
|
|
35
|
+
|
|
36
|
+
# Case 2: Match filenames that have a resource type and a name followed by RefYear
|
|
37
|
+
pattern2 = re.compile(
|
|
38
|
+
r"^(?P<name>[A-Z0-9]+)_(?P<resource_type>W[A-Z]+)_[A-Za-z_\-]+_RefYear(?P<year>\d{4})\.csv$"
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
# Try to match with pattern 2 first
|
|
42
|
+
match2 = pattern2.match(filename)
|
|
43
|
+
if match2:
|
|
44
|
+
match_data = match2.groupdict()
|
|
45
|
+
match_data["file_type"] = "area"
|
|
46
|
+
return match_data
|
|
47
|
+
|
|
48
|
+
# Otherwise, try to match with pattern 1 (just name and year)
|
|
49
|
+
match1 = pattern1.match(filename)
|
|
50
|
+
if match1:
|
|
51
|
+
match_data = match1.groupdict()
|
|
52
|
+
match_data["file_type"] = "project"
|
|
53
|
+
return match_data
|
|
54
|
+
|
|
55
|
+
raise ValueError(f"Filename '{filename}' does not match the expected pattern")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def extract_demand_trace_metadata(filename):
|
|
59
|
+
# Regex pattern to match the structure of the filename
|
|
60
|
+
pattern = re.compile(
|
|
61
|
+
r"^(?P<subregion>[A-Z]+)_RefYear_(?P<year>\d{4})_(?P<scenario>[A-Z_]+)_(?P<poe>POE\d{2})_(?P<type>["
|
|
62
|
+
r"A-Z_]+)\.csv$"
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
# Match the pattern against the filename
|
|
66
|
+
match = pattern.match(filename)
|
|
67
|
+
|
|
68
|
+
if match:
|
|
69
|
+
# If the filename matches the pattern, return a dictionary of captured groups
|
|
70
|
+
return match.groupdict()
|
|
71
|
+
else:
|
|
72
|
+
# If the pattern does not match, raise an error or return None
|
|
73
|
+
raise ValueError(f"Filename '{filename}' does not match the expected pattern")
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import functools
|
|
2
|
+
import os
|
|
3
|
+
from concurrent.futures import ProcessPoolExecutor
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import yaml
|
|
7
|
+
|
|
8
|
+
from isp_trace_parser.metadata_extractors import extract_solar_trace_metadata
|
|
9
|
+
from isp_trace_parser.trace_restructure_helper_functions import (
|
|
10
|
+
get_all_filepaths,
|
|
11
|
+
get_metadata_that_matches_trace_names,
|
|
12
|
+
get_unique_reference_years_in_metadata,
|
|
13
|
+
get_metadata_that_matches_reference_year,
|
|
14
|
+
get_metadata_for_writing_save_name,
|
|
15
|
+
overwrite_metadata_trace_name_with_output_name,
|
|
16
|
+
check_filter_by_metadata,
|
|
17
|
+
process_and_save_files,
|
|
18
|
+
get_unique_project_and_area_names_in_input_files,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def parse_solar_traces(
|
|
23
|
+
input_directory, parsed_directory, use_concurrency=True, filters=None
|
|
24
|
+
):
|
|
25
|
+
"""
|
|
26
|
+
Examples:
|
|
27
|
+
|
|
28
|
+
Parse whole directory of trace data.
|
|
29
|
+
|
|
30
|
+
>>> parse_solar_traces(
|
|
31
|
+
... input_directory='example_input_data/solar',
|
|
32
|
+
... parsed_directory='example_parsed_data/solar',
|
|
33
|
+
... use_concurrency=False
|
|
34
|
+
... )
|
|
35
|
+
|
|
36
|
+
"""
|
|
37
|
+
files = get_all_filepaths(input_directory)
|
|
38
|
+
file_metadata = extract_metadata_for_all_solar_files(files)
|
|
39
|
+
with open(
|
|
40
|
+
Path(__file__).parent.parent
|
|
41
|
+
/ Path("isp_trace_name_mapping_configs/solar_project_mapping.yaml"),
|
|
42
|
+
"r",
|
|
43
|
+
) as f:
|
|
44
|
+
project_name_mapping = yaml.safe_load(f)
|
|
45
|
+
with open(
|
|
46
|
+
Path(__file__).parent.parent
|
|
47
|
+
/ Path("isp_trace_name_mapping_configs/solar_area_mapping.yaml"),
|
|
48
|
+
"r",
|
|
49
|
+
) as f:
|
|
50
|
+
area_name_mapping = yaml.safe_load(f)
|
|
51
|
+
name_mappings = {**project_name_mapping, **area_name_mapping}
|
|
52
|
+
|
|
53
|
+
project_and_area_input_names = get_unique_project_and_area_names_in_input_files(
|
|
54
|
+
file_metadata
|
|
55
|
+
)
|
|
56
|
+
name_mappings = {
|
|
57
|
+
k: v for k, v in name_mappings.items() if v in project_and_area_input_names
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
project_and_area_output_names, project_and_area_input_names = zip(
|
|
61
|
+
*name_mappings.items()
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
partial_func = functools.partial(
|
|
65
|
+
restructure_solar_files,
|
|
66
|
+
all_input_file_metadata=file_metadata,
|
|
67
|
+
output_directory=parsed_directory,
|
|
68
|
+
filters=filters,
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
if use_concurrency:
|
|
72
|
+
max_workers = os.cpu_count() - 2
|
|
73
|
+
with ProcessPoolExecutor(max_workers=max_workers) as executor:
|
|
74
|
+
results = executor.map(
|
|
75
|
+
partial_func,
|
|
76
|
+
project_and_area_output_names,
|
|
77
|
+
project_and_area_input_names,
|
|
78
|
+
)
|
|
79
|
+
# Iterate through results to raise any errors that occurred.
|
|
80
|
+
for result in results:
|
|
81
|
+
result
|
|
82
|
+
else:
|
|
83
|
+
for save_name, old_trace_name in zip(
|
|
84
|
+
project_and_area_output_names, project_and_area_input_names
|
|
85
|
+
):
|
|
86
|
+
partial_func(save_name, old_trace_name)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def restructure_solar_files(
|
|
90
|
+
output_project_or_area_name,
|
|
91
|
+
input_trace_names,
|
|
92
|
+
all_input_file_metadata,
|
|
93
|
+
output_directory,
|
|
94
|
+
filters=None,
|
|
95
|
+
):
|
|
96
|
+
metadata_for_trace_files = get_metadata_that_matches_trace_names(
|
|
97
|
+
input_trace_names, all_input_file_metadata
|
|
98
|
+
)
|
|
99
|
+
reference_years = get_unique_reference_years_in_metadata(metadata_for_trace_files)
|
|
100
|
+
for year in reference_years:
|
|
101
|
+
files_for_year = get_metadata_that_matches_reference_year(
|
|
102
|
+
year, metadata_for_trace_files
|
|
103
|
+
)
|
|
104
|
+
techs = get_unique_techs_in_metadata(files_for_year)
|
|
105
|
+
for tech in techs:
|
|
106
|
+
files_for_tech = get_metadata_that_matches_tech(tech, files_for_year)
|
|
107
|
+
metadata = get_metadata_for_writing_save_name(files_for_tech)
|
|
108
|
+
metadata = overwrite_metadata_trace_name_with_output_name(
|
|
109
|
+
metadata, output_project_or_area_name
|
|
110
|
+
)
|
|
111
|
+
parse_file = check_filter_by_metadata(metadata, filters)
|
|
112
|
+
if parse_file:
|
|
113
|
+
process_and_save_files(
|
|
114
|
+
files_for_tech,
|
|
115
|
+
metadata,
|
|
116
|
+
write_output_solar_filepath,
|
|
117
|
+
output_directory,
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def write_output_solar_filepath(metadata):
|
|
122
|
+
m = metadata
|
|
123
|
+
name = m["name"].replace(" ", "_")
|
|
124
|
+
|
|
125
|
+
if m["file_type"] == "project":
|
|
126
|
+
return (
|
|
127
|
+
f"RefYear{m['year']}/{m['file_type'].capitalize()}/{name}/"
|
|
128
|
+
f"RefYear{m['year']}_{name}_{m['technology']}_HalfYear{m['hy']}.parquet"
|
|
129
|
+
)
|
|
130
|
+
else:
|
|
131
|
+
return (
|
|
132
|
+
f"RefYear{m['year']}/{m['file_type'].capitalize()}/{name}/{m['technology']}/"
|
|
133
|
+
f"RefYear{m['year']}_{name}_{m['technology']}_HalfYear{m['hy']}.parquet"
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def extract_metadata_for_all_solar_files(filenames):
|
|
138
|
+
file_metadata = [extract_solar_trace_metadata(str(f.name)) for f in filenames]
|
|
139
|
+
return dict(zip(filenames, file_metadata))
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def get_unique_techs_in_metadata(metadata_for_trace_files):
|
|
143
|
+
return list(
|
|
144
|
+
set(metadata["technology"] for metadata in metadata_for_trace_files.values())
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def get_metadata_that_matches_tech(tech, metadata_for_trace_files):
|
|
149
|
+
return {
|
|
150
|
+
f: metadata
|
|
151
|
+
for f, metadata in metadata_for_trace_files.items()
|
|
152
|
+
if metadata["technology"] == tech
|
|
153
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
from datetime import timedelta
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
import polars as pl
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def trace_formatter(trace_data: pl.DataFrame) -> pl.DataFrame:
|
|
8
|
+
"""
|
|
9
|
+
Takes trace data in the AEMO format and converts it to a format with 'Datetime' and 'Data' columns.
|
|
10
|
+
|
|
11
|
+
AEMO provides ISP trace data with separate columns for 'Year', 'Month', and 'Day', and individual data columns
|
|
12
|
+
labeled '01', '02', ..., '48', representing half-hour intervals. This function converts that data format into
|
|
13
|
+
one where a single 'Datetime' column specifies the end of each half-hour period, and another 'Data' column contains
|
|
14
|
+
the corresponding values.
|
|
15
|
+
|
|
16
|
+
Example:
|
|
17
|
+
|
|
18
|
+
Input format:
|
|
19
|
+
>>> aemo_format_data = pl.DataFrame({
|
|
20
|
+
... 'Year': [2024, 2024],
|
|
21
|
+
... 'Month': [6, 6],
|
|
22
|
+
... 'Day': [1, 2],
|
|
23
|
+
... '01': [11.2, 15.3],
|
|
24
|
+
... '02': [30.7, 20.4],
|
|
25
|
+
... '48': [17.1, 18.9]
|
|
26
|
+
... })
|
|
27
|
+
|
|
28
|
+
>>> trace_formatter(aemo_format_data)
|
|
29
|
+
shape: (6, 2)
|
|
30
|
+
┌─────────────────────┬───────┐
|
|
31
|
+
│ Datetime ┆ Value │
|
|
32
|
+
│ --- ┆ --- │
|
|
33
|
+
│ datetime[μs] ┆ f64 │
|
|
34
|
+
╞═════════════════════╪═══════╡
|
|
35
|
+
│ 2024-06-01 00:30:00 ┆ 11.2 │
|
|
36
|
+
│ 2024-06-01 01:00:00 ┆ 30.7 │
|
|
37
|
+
│ 2024-06-02 00:00:00 ┆ 17.1 │
|
|
38
|
+
│ 2024-06-02 00:30:00 ┆ 15.3 │
|
|
39
|
+
│ 2024-06-02 01:00:00 ┆ 20.4 │
|
|
40
|
+
│ 2024-06-03 00:00:00 ┆ 18.9 │
|
|
41
|
+
└─────────────────────┴───────┘
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
trace_data: A `polars.DataFrame` with 'Year', 'Month', 'Day', and columns labeled '01' to '48' representing
|
|
47
|
+
half-hour intervals.
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
A `polars.DataFrame` with:
|
|
51
|
+
- 'Datetime': A column specifying the end time of each half-hour period.
|
|
52
|
+
- 'Data': A column containing the data for each half-hour period.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
# Need both padded 1-9 and not padded because AEMO data files can have both.
|
|
56
|
+
value_vars = [f"{i:02d}" for i in range(1, 49)] + [str(i) for i in range(1, 10)]
|
|
57
|
+
value_vars = [v for v in value_vars if v in trace_data.columns]
|
|
58
|
+
|
|
59
|
+
trace_data = trace_data.unpivot(
|
|
60
|
+
index=["Year", "Month", "Day"],
|
|
61
|
+
on=value_vars,
|
|
62
|
+
variable_name="time_label",
|
|
63
|
+
value_name="Value",
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
def get_hour(time_label):
|
|
67
|
+
return timedelta(hours=int(time_label) // 2)
|
|
68
|
+
|
|
69
|
+
def get_minute(time_label):
|
|
70
|
+
return timedelta(minutes=int(time_label) % 2 * 30)
|
|
71
|
+
|
|
72
|
+
trace_data = trace_data.with_columns(
|
|
73
|
+
[
|
|
74
|
+
pl.col("time_label")
|
|
75
|
+
.map_elements(get_hour, return_dtype=pl.Duration)
|
|
76
|
+
.alias("Hour"),
|
|
77
|
+
pl.col("time_label")
|
|
78
|
+
.map_elements(get_minute, return_dtype=pl.Duration)
|
|
79
|
+
.alias("Minute"),
|
|
80
|
+
(
|
|
81
|
+
pl.col("Year").cast(pl.Utf8).str.zfill(2)
|
|
82
|
+
+ "-"
|
|
83
|
+
+ pl.col("Month").cast(pl.Utf8).str.zfill(2)
|
|
84
|
+
+ "-"
|
|
85
|
+
+ pl.col("Day").cast(pl.Utf8).str.zfill(2)
|
|
86
|
+
+ " 00:00:00"
|
|
87
|
+
)
|
|
88
|
+
.str.strptime(pl.Datetime)
|
|
89
|
+
.alias("Datetime"),
|
|
90
|
+
]
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
trace_data = (
|
|
94
|
+
trace_data.with_columns(
|
|
95
|
+
[(pl.col("Datetime") + pl.col("Hour") + pl.col("Minute")).alias("Datetime")]
|
|
96
|
+
)
|
|
97
|
+
.select(["Datetime", "Value"])
|
|
98
|
+
.sort("Datetime")
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
return trace_data
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from datetime import timedelta
|
|
3
|
+
|
|
4
|
+
import polars as pl
|
|
5
|
+
|
|
6
|
+
from isp_trace_parser.trace_formatter import trace_formatter
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def get_all_filepaths(dir):
|
|
10
|
+
dir = Path(dir)
|
|
11
|
+
if dir.is_dir():
|
|
12
|
+
return [path for path in Path(dir).rglob("*.csv") if path.is_file()]
|
|
13
|
+
else:
|
|
14
|
+
raise ValueError(f"{dir} not found.")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def read_trace_csv(file):
|
|
18
|
+
pl_types = [pl.Int64] * 3 + [pl.Float64] * 48
|
|
19
|
+
return pl.read_csv(file, schema_overrides=pl_types)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def read_and_format_traces(files):
|
|
23
|
+
traces = []
|
|
24
|
+
for f in files:
|
|
25
|
+
trace_data = read_trace_csv(f)
|
|
26
|
+
trace_data = trace_formatter(trace_data)
|
|
27
|
+
traces.append(trace_data)
|
|
28
|
+
return traces
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def calculate_average_trace(traces):
|
|
32
|
+
combined_traces = pl.concat(traces)
|
|
33
|
+
average_trace = combined_traces.group_by("Datetime").agg(
|
|
34
|
+
[pl.col("Value").mean().alias("Value")]
|
|
35
|
+
)
|
|
36
|
+
return average_trace
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def add_half_year_as_column(trace):
|
|
40
|
+
def calculate_half_year(dt):
|
|
41
|
+
dt -= timedelta(seconds=1)
|
|
42
|
+
if dt.month < 7:
|
|
43
|
+
half_year = f"{dt.year}-1"
|
|
44
|
+
else:
|
|
45
|
+
half_year = f"{dt.year}-2"
|
|
46
|
+
return half_year
|
|
47
|
+
|
|
48
|
+
trace = trace.sort("Datetime")
|
|
49
|
+
|
|
50
|
+
trace = trace.with_columns(
|
|
51
|
+
(pl.col("Datetime").map_elements(calculate_half_year, pl.String).alias("HY"))
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
return trace
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def save_half_year_chunk_of_trace(
|
|
58
|
+
chunk, file_metadata, half_year, output_directory, write_output_filepath
|
|
59
|
+
):
|
|
60
|
+
file_metadata["hy"] = half_year[0]
|
|
61
|
+
data = chunk.drop("HY")
|
|
62
|
+
path_in_output_directory = write_output_filepath(file_metadata)
|
|
63
|
+
save_filepath = Path(output_directory) / path_in_output_directory
|
|
64
|
+
save_filepath.parent.mkdir(parents=True, exist_ok=True)
|
|
65
|
+
data.write_parquet(save_filepath)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def process_and_save_files(
|
|
69
|
+
files, file_metadata, write_output_filepath, output_directory
|
|
70
|
+
):
|
|
71
|
+
traces = read_and_format_traces(files)
|
|
72
|
+
|
|
73
|
+
if len(traces) > 1:
|
|
74
|
+
trace = calculate_average_trace(traces)
|
|
75
|
+
else:
|
|
76
|
+
trace = traces[0]
|
|
77
|
+
|
|
78
|
+
trace = add_half_year_as_column(trace)
|
|
79
|
+
|
|
80
|
+
for half_year, chunk in trace.group_by("HY"):
|
|
81
|
+
save_half_year_chunk_of_trace(
|
|
82
|
+
chunk, file_metadata, half_year, output_directory, write_output_filepath
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def get_metadata_that_matches_trace_names(trace_names, all_input_file_metadata):
|
|
87
|
+
return {
|
|
88
|
+
f: metadata
|
|
89
|
+
for f, metadata in all_input_file_metadata.items()
|
|
90
|
+
if metadata["name"] in trace_names
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def get_unique_reference_years_in_metadata(metadata_for_trace_files):
|
|
95
|
+
return list(set(metadata["year"] for metadata in metadata_for_trace_files.values()))
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def get_metadata_that_matches_reference_year(year, metadata_for_trace_files):
|
|
99
|
+
return {
|
|
100
|
+
f: metadata
|
|
101
|
+
for f, metadata in metadata_for_trace_files.items()
|
|
102
|
+
if metadata["year"] == year
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def get_metadata_for_writing_save_name(metadata_for_trace_files):
|
|
107
|
+
return next(iter(metadata_for_trace_files.values()))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def overwrite_metadata_trace_name_with_output_name(metadata, save_name):
|
|
111
|
+
metadata["name"] = save_name
|
|
112
|
+
return metadata
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def check_filter_by_metadata(metadata, filters):
|
|
116
|
+
parse_file = True
|
|
117
|
+
for metadata_type, metadata_value in metadata.items():
|
|
118
|
+
# If element of the metadata is present in filter but not one the values in the
|
|
119
|
+
# list under that key then we dont parse this file.
|
|
120
|
+
if (
|
|
121
|
+
filters is not None
|
|
122
|
+
and metadata_type in filters
|
|
123
|
+
and metadata_value not in filters[metadata_type]
|
|
124
|
+
):
|
|
125
|
+
parse_file = False
|
|
126
|
+
return parse_file
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def get_unique_project_and_area_names_in_input_files(metadata_for_trace_files):
|
|
130
|
+
names = []
|
|
131
|
+
for filepath, meta_data in metadata_for_trace_files.items():
|
|
132
|
+
names.append(meta_data["name"])
|
|
133
|
+
return list(set(names))
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def filter_mapping_by_names_in_input_files(name_mapping, names_in_input_files):
|
|
137
|
+
filtered_mapping = {}
|
|
138
|
+
for output_name, input_name in name_mapping.items():
|
|
139
|
+
if isinstance(input_name, list):
|
|
140
|
+
if input_name[0] in names_in_input_files:
|
|
141
|
+
filtered_mapping[output_name] = input_name
|
|
142
|
+
else:
|
|
143
|
+
if input_name in names_in_input_files:
|
|
144
|
+
filtered_mapping[output_name] = input_name
|
|
145
|
+
return filtered_mapping
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import functools
|
|
2
|
+
import os
|
|
3
|
+
from concurrent.futures import ProcessPoolExecutor
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import yaml
|
|
7
|
+
|
|
8
|
+
from isp_trace_parser.metadata_extractors import extract_wind_trace_metadata
|
|
9
|
+
from isp_trace_parser.trace_restructure_helper_functions import (
|
|
10
|
+
get_all_filepaths,
|
|
11
|
+
get_metadata_that_matches_trace_names,
|
|
12
|
+
get_unique_reference_years_in_metadata,
|
|
13
|
+
get_metadata_that_matches_reference_year,
|
|
14
|
+
get_metadata_for_writing_save_name,
|
|
15
|
+
overwrite_metadata_trace_name_with_output_name,
|
|
16
|
+
check_filter_by_metadata,
|
|
17
|
+
process_and_save_files,
|
|
18
|
+
get_unique_project_and_area_names_in_input_files,
|
|
19
|
+
filter_mapping_by_names_in_input_files,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def parse_wind_traces(
|
|
24
|
+
input_directory, parsed_directory, use_concurrency=True, filters=None
|
|
25
|
+
):
|
|
26
|
+
"""
|
|
27
|
+
Examples:
|
|
28
|
+
|
|
29
|
+
Parse whole directory of trace data.
|
|
30
|
+
|
|
31
|
+
>>> parse_wind_traces(
|
|
32
|
+
... input_directory='example_input_data/wind',
|
|
33
|
+
... parsed_directory='example_parsed_data/wind',
|
|
34
|
+
... use_concurrency=False
|
|
35
|
+
... )
|
|
36
|
+
|
|
37
|
+
"""
|
|
38
|
+
files = get_all_filepaths(input_directory)
|
|
39
|
+
file_metadata = extract_metadata_for_all_wind_files(files)
|
|
40
|
+
|
|
41
|
+
with open(
|
|
42
|
+
Path(__file__).parent.parent
|
|
43
|
+
/ Path("isp_trace_name_mapping_configs/wind_project_mapping.yaml"),
|
|
44
|
+
"r",
|
|
45
|
+
) as f:
|
|
46
|
+
project_name_mappings = yaml.safe_load(f)
|
|
47
|
+
|
|
48
|
+
project_name_mappings = restructure_wind_project_mapping(project_name_mappings)
|
|
49
|
+
|
|
50
|
+
with open(
|
|
51
|
+
Path(__file__).parent.parent
|
|
52
|
+
/ Path("isp_trace_name_mapping_configs/wind_area_mapping.yaml"),
|
|
53
|
+
"r",
|
|
54
|
+
) as f:
|
|
55
|
+
area_name_mappings = yaml.safe_load(f)
|
|
56
|
+
|
|
57
|
+
project_and_area_input_names = get_unique_project_and_area_names_in_input_files(
|
|
58
|
+
file_metadata
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
area_name_mappings = filter_mapping_by_names_in_input_files(
|
|
62
|
+
area_name_mappings, project_and_area_input_names
|
|
63
|
+
)
|
|
64
|
+
area_output_names, area_input_names = zip(*area_name_mappings.items())
|
|
65
|
+
|
|
66
|
+
project_name_mappings = filter_mapping_by_names_in_input_files(
|
|
67
|
+
project_name_mappings, project_and_area_input_names
|
|
68
|
+
)
|
|
69
|
+
project_output_names, project_input_names = zip(*project_name_mappings.items())
|
|
70
|
+
|
|
71
|
+
area_partial_func = functools.partial(
|
|
72
|
+
restructure_wind_area_files,
|
|
73
|
+
all_input_file_metadata=file_metadata,
|
|
74
|
+
output_directory=parsed_directory,
|
|
75
|
+
filters=filters,
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
project_partial_func = functools.partial(
|
|
79
|
+
restructure_wind_project_files,
|
|
80
|
+
all_input_file_metadata=file_metadata,
|
|
81
|
+
output_directory=parsed_directory,
|
|
82
|
+
filters=filters,
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
if use_concurrency:
|
|
86
|
+
max_workers = os.cpu_count() - 2
|
|
87
|
+
|
|
88
|
+
with ProcessPoolExecutor(max_workers=max_workers) as executor:
|
|
89
|
+
results = executor.map(
|
|
90
|
+
area_partial_func, area_output_names, area_input_names
|
|
91
|
+
)
|
|
92
|
+
# Iterate through results to raise any errors that occurred.
|
|
93
|
+
for result in results:
|
|
94
|
+
result
|
|
95
|
+
|
|
96
|
+
with ProcessPoolExecutor(max_workers=max_workers) as executor:
|
|
97
|
+
results = executor.map(
|
|
98
|
+
project_partial_func, project_output_names, project_input_names
|
|
99
|
+
)
|
|
100
|
+
# Iterate through results to raise any errors that occurred.
|
|
101
|
+
for result in results:
|
|
102
|
+
result
|
|
103
|
+
|
|
104
|
+
else:
|
|
105
|
+
for save_name, old_trace_name in zip(area_output_names, area_input_names):
|
|
106
|
+
area_partial_func(save_name, old_trace_name)
|
|
107
|
+
|
|
108
|
+
for save_name, old_trace_name in zip(project_output_names, project_input_names):
|
|
109
|
+
project_partial_func(save_name, old_trace_name)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def restructure_wind_area_files(
|
|
113
|
+
output_area_name,
|
|
114
|
+
input_trace_names,
|
|
115
|
+
all_input_file_metadata,
|
|
116
|
+
output_directory,
|
|
117
|
+
filters=None,
|
|
118
|
+
):
|
|
119
|
+
metadata_for_trace_files = get_metadata_that_matches_trace_names(
|
|
120
|
+
input_trace_names, all_input_file_metadata
|
|
121
|
+
)
|
|
122
|
+
reference_years = get_unique_reference_years_in_metadata(metadata_for_trace_files)
|
|
123
|
+
for year in reference_years:
|
|
124
|
+
files_for_year = get_metadata_that_matches_reference_year(
|
|
125
|
+
year, metadata_for_trace_files
|
|
126
|
+
)
|
|
127
|
+
resource_types = get_unique_resource_types_in_metadata(files_for_year)
|
|
128
|
+
for resource_type in resource_types:
|
|
129
|
+
files_for_resource_type = get_metadata_that_matches_resource_type(
|
|
130
|
+
resource_type, files_for_year
|
|
131
|
+
)
|
|
132
|
+
metadata = get_metadata_for_writing_save_name(files_for_resource_type)
|
|
133
|
+
metadata = overwrite_metadata_trace_name_with_output_name(
|
|
134
|
+
metadata, output_area_name
|
|
135
|
+
)
|
|
136
|
+
parse_file = check_filter_by_metadata(metadata, filters)
|
|
137
|
+
if parse_file:
|
|
138
|
+
process_and_save_files(
|
|
139
|
+
files_for_resource_type,
|
|
140
|
+
metadata,
|
|
141
|
+
write_output_wind_area_filepath,
|
|
142
|
+
output_directory,
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def restructure_wind_project_files(
|
|
147
|
+
output_project_name,
|
|
148
|
+
input_trace_names,
|
|
149
|
+
all_input_file_metadata,
|
|
150
|
+
output_directory,
|
|
151
|
+
filters=None,
|
|
152
|
+
):
|
|
153
|
+
metadata_for_trace_files = get_metadata_that_matches_trace_names(
|
|
154
|
+
input_trace_names, all_input_file_metadata
|
|
155
|
+
)
|
|
156
|
+
reference_years = get_unique_reference_years_in_metadata(metadata_for_trace_files)
|
|
157
|
+
for year in reference_years:
|
|
158
|
+
files_for_year = get_metadata_that_matches_reference_year(
|
|
159
|
+
year, metadata_for_trace_files
|
|
160
|
+
)
|
|
161
|
+
metadata = get_metadata_for_writing_save_name(files_for_year)
|
|
162
|
+
metadata = overwrite_metadata_trace_name_with_output_name(
|
|
163
|
+
metadata, output_project_name
|
|
164
|
+
)
|
|
165
|
+
parse_file = check_filter_by_metadata(metadata, filters)
|
|
166
|
+
if parse_file:
|
|
167
|
+
process_and_save_files(
|
|
168
|
+
files_for_year,
|
|
169
|
+
metadata,
|
|
170
|
+
write_output_wind_project_filepath,
|
|
171
|
+
output_directory,
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def write_output_wind_project_filepath(metadata):
|
|
176
|
+
m = metadata
|
|
177
|
+
name = m["name"].replace(" ", "_")
|
|
178
|
+
return (
|
|
179
|
+
f"RefYear{m['year']}/{m['file_type'].capitalize()}/{name}/"
|
|
180
|
+
f"RefYear{m['year']}_{name}_HalfYear{m['hy']}.parquet"
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def write_output_wind_area_filepath(metadata):
|
|
185
|
+
m = metadata
|
|
186
|
+
name = m["name"].replace(" ", "_")
|
|
187
|
+
return (
|
|
188
|
+
f"RefYear{m['year']}/{m['file_type'].capitalize()}/{name}/{m['resource_type']}/"
|
|
189
|
+
f"RefYear{m['year']}_{name}_{m['resource_type']}_HalfYear{m['hy']}.parquet"
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def restructure_wind_project_mapping(project_name_mapping):
|
|
194
|
+
return {
|
|
195
|
+
name: mapping_data["CSVFile"]
|
|
196
|
+
for name, mapping_data in project_name_mapping.items()
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def extract_metadata_for_all_wind_files(filenames):
|
|
201
|
+
file_metadata = [extract_wind_trace_metadata(str(f.name)) for f in filenames]
|
|
202
|
+
return dict(zip(filenames, file_metadata))
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def get_unique_resource_types_in_metadata(metadata_for_trace_files):
|
|
206
|
+
return list(
|
|
207
|
+
set(metadata["resource_type"] for metadata in metadata_for_trace_files.values())
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def get_metadata_that_matches_resource_type(resource_type, metadata_for_trace_files):
|
|
212
|
+
return {
|
|
213
|
+
f: metadata
|
|
214
|
+
for f, metadata in metadata_for_trace_files.items()
|
|
215
|
+
if metadata["resource_type"] == resource_type
|
|
216
|
+
}
|