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.
@@ -0,0 +1,161 @@
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 import trace_formatter
9
+ from isp_trace_parser.trace_restructure_helper_functions import (
10
+ get_all_filepaths,
11
+ check_filter_by_metadata,
12
+ read_trace_csv,
13
+ add_half_year_as_column,
14
+ save_half_year_chunk_of_trace,
15
+ )
16
+ from isp_trace_parser.metadata_extractors import extract_demand_trace_metadata
17
+
18
+
19
+ def parse_demand_traces(
20
+ input_directory: str | Path,
21
+ parsed_directory: str | Path,
22
+ use_concurrency: bool = True,
23
+ filters: dict[str : list[str]] = None,
24
+ ):
25
+ """Takes a directory with AEMO demand trace data and reformats the data, saving it to a new directory.
26
+
27
+ AEMO demand trace data comes in CSVs with columns specifying the year, day, and month, and data columns
28
+ (labeled 01, 02, ... 48) storing the demand values for each half hour of the day. The file name of the CSV
29
+ contains metadata in the following format "<subregionID>_RefYear_<reference year>_<scenario>_<poe>_<data type>.csv".
30
+ For example, "CNSW_RefYear_2011_HYDROGEN_EXPORT_POE10_OPSO_MODELLING.csv".
31
+
32
+ The trace parser reformats the data, modifies the file naming convention to match the IASR workbook, and stores
33
+ the data files with a directory structure that mirrors the new file naming convention. Firstly, the data format is
34
+ changed to a two column format with a column "Datetime" specifying the end of the half hour period the measurement
35
+ is for in the format %Y-%m-%d %HH:%MM%:%SS, and a column "Value" specifying the measurement value. The data is saved
36
+ in parquet format in half-yearly chunks to improved read speeds. The files are saved in with following
37
+ directory structure and naming convention:
38
+
39
+ "<scenario>/RefYear<reference year>/<subregion ID>/<poe>/<data type>/"
40
+ "<scenario>_RefYear<reference year>_<subregion ID>_<poe>_<data type>_HalfYear<year>-<half of year>.parquet"
41
+
42
+ With the scenario name mapped from the name used in the raw AEMO trace data to the name used in the IASR workbook.
43
+ For one half-yearly chunk of the CSV example above the parsed filepath would be:
44
+
45
+ "Green_Energy_Exports/RefYear2011/CNSW/POE10/OPSO_MODELLING/"
46
+ "Green_Energy_Exports_RefYear2011_CNSW_POE10_OPSO_MODELLING_HalfYear2020-1.parquet"
47
+
48
+ By default, all trace data in the input directory is parsed. However, a filters dictionary can be provided to
49
+ filter the traces to pass based on metadata. If a metadata type is present in the filters then only traces a
50
+ metadata value present in the corresponding filter list will be passed, see examples below.
51
+
52
+ Examples:
53
+
54
+ Parse whole directory of trace data.
55
+
56
+ >>> parse_demand_traces(
57
+ ... input_directory='example_input_data/demand',
58
+ ... parsed_directory='example_parsed_data/demand',
59
+ ... use_concurrency=False
60
+ ... )
61
+
62
+ Parse only a subset of the input traces.
63
+
64
+ Excluding one type of metadata (key) from the
65
+ filter will result in no filtering on
66
+ that component of the metadata and more elements can
67
+ be added to each list in the filter to selectively
68
+ expand which traces are parsed.
69
+
70
+ >>> metadata_filters={
71
+ ... 'scenario': ['Green Energy Exports'],
72
+ ... 'subregion': ['CNSW'],
73
+ ... 'poe': ['POE10'],
74
+ ... 'type': ['OPSO_MODELLING']
75
+ ... }
76
+
77
+ >>> parse_demand_traces(
78
+ ... input_directory='example_input_data/demand',
79
+ ... parsed_directory='example_parsed_data/demand',
80
+ ... filters=metadata_filters,
81
+ ... use_concurrency=False
82
+ ... )
83
+
84
+
85
+ Args:
86
+ input_directory: str or pathlib.Path, path to data to parse.
87
+ parsed_directory: str or pathlib.Path, path to directory where parsed tarces will be saved.
88
+ use_concurrency: boolean, default True, specifies whether to use parallel processing
89
+ filters: dict{str: list[str]}, dict that specifies which traces to parse, if a component
90
+ of the metadata is missing from the dict no filtering on that component occurs. See example.
91
+
92
+ Returns: None
93
+ """
94
+ files = get_all_filepaths(input_directory)
95
+
96
+ with open(
97
+ Path(__file__).parent.parent
98
+ / Path("isp_trace_name_mapping_configs/demand_scenario_mapping.yaml"),
99
+ "r",
100
+ ) as f:
101
+ demand_scenario_mapping = yaml.safe_load(f)
102
+
103
+ partial_func = functools.partial(
104
+ restructure_demand_file,
105
+ demand_scenario_mapping=demand_scenario_mapping,
106
+ output_directory=parsed_directory,
107
+ filters=filters,
108
+ )
109
+
110
+ if use_concurrency:
111
+ max_workers = os.cpu_count() - 2
112
+ with ProcessPoolExecutor(max_workers=max_workers) as executor:
113
+ results = executor.map(partial_func, files)
114
+ # Iterate through results to raise any errors that occurred.
115
+ for result in results:
116
+ result
117
+ else:
118
+ for file in files:
119
+ partial_func(file)
120
+
121
+
122
+ def restructure_demand_file(
123
+ input_filepath, demand_scenario_mapping, output_directory, filters
124
+ ):
125
+ file_metadata = extract_demand_trace_metadata(input_filepath.name)
126
+ file_metadata["scenario"] = get_save_scenario_for_demand_trace(
127
+ file_metadata, demand_scenario_mapping
128
+ )
129
+ parse_file = check_filter_by_metadata(file_metadata, filters)
130
+ if parse_file:
131
+ trace = read_trace_csv(input_filepath)
132
+ trace = trace_formatter(trace)
133
+ trace = add_half_year_as_column(trace)
134
+ for half_year, chunk in trace.group_by("HY"):
135
+ save_half_year_chunk_of_trace(
136
+ chunk,
137
+ file_metadata,
138
+ half_year,
139
+ output_directory,
140
+ write_new_demand_filepath,
141
+ )
142
+
143
+
144
+ def get_save_scenario_for_demand_trace(file_metadata, demand_scenario_mapping):
145
+ return demand_scenario_mapping[file_metadata["scenario"]]
146
+
147
+
148
+ def write_new_demand_filepath(metadata):
149
+ m = metadata
150
+ subregion = m["subregion"].replace(" ", "_")
151
+ scenario = m["scenario"].replace(" ", "_")
152
+
153
+ return (
154
+ f"{scenario}/RefYear{m['year']}/{subregion}/{m['poe']}/{m['type']}/"
155
+ f"{scenario}_RefYear{m['year']}_{subregion}_{m['poe']}_{m['type']}_HalfYear{m['hy']}.parquet"
156
+ )
157
+
158
+
159
+ def extract_metadata_for_all_demand_files(filenames):
160
+ file_metadata = [extract_demand_trace_metadata(str(f.name)) for f in filenames]
161
+ return dict(zip(filenames, file_metadata))
@@ -0,0 +1,144 @@
1
+ import os
2
+
3
+ import pandas as pd
4
+ from fuzzywuzzy import process, fuzz
5
+ from isp_workbook_parser import Parser, TableConfig
6
+
7
+ from isp_trace_parser.metadata_extractors import (
8
+ extract_solar_trace_metadata,
9
+ extract_wind_trace_metadata,
10
+ )
11
+
12
+
13
+ def get_all_generators(workbook_filepath):
14
+ workbook = Parser(workbook_filepath)
15
+ existing_gens = workbook.get_table("existing_generator_summary")
16
+ existing_gens["Status"] = "existing"
17
+ committed_gens = workbook.get_table("committed_generator_summary")
18
+ committed_gens["Status"] = "committed"
19
+ anticipated_gens = workbook.get_table("anticipated_projects_summary")
20
+ anticipated_gens["Status"] = "anticipated"
21
+ additional_gens = workbook.get_table("additional_projects_summary")
22
+ additional_gens["Status"] = "additional"
23
+
24
+ existing_gens = existing_gens.rename(
25
+ columns={existing_gens.columns.values[0]: "Generator"}
26
+ )
27
+ committed_gens = committed_gens.rename(
28
+ columns={committed_gens.columns.values[0]: "Generator"}
29
+ )
30
+ anticipated_gens = anticipated_gens.rename(
31
+ columns={anticipated_gens.columns.values[0]: "Generator"}
32
+ )
33
+ additional_gens = additional_gens.rename(
34
+ columns={additional_gens.columns.values[0]: "Generator"}
35
+ )
36
+
37
+ all_gens = pd.concat(
38
+ [existing_gens, committed_gens, anticipated_gens, additional_gens]
39
+ )
40
+
41
+ all_gens = all_gens.loc[:, ["Generator", "Technology type"]]
42
+
43
+ return all_gens
44
+
45
+
46
+ def gets_rezs(workbook_filepath):
47
+ table_config = TableConfig(
48
+ name="rezs",
49
+ sheet_name="Renewable Energy Zones",
50
+ header_rows=7,
51
+ end_row=50,
52
+ column_range="B:G",
53
+ )
54
+ workbook = Parser(workbook_filepath)
55
+ rezs = workbook.get_table_from_config(table_config)
56
+ rezs = rezs.loc[:, ["Name"]]
57
+ return rezs
58
+
59
+
60
+ def find_best_match(plant_name, csv_files):
61
+ best_match = process.extractOne(plant_name, csv_files, scorer=fuzz.token_set_ratio)
62
+ best_match = best_match[0] if best_match else None
63
+ best_match = best_match
64
+ return best_match
65
+
66
+
67
+ def find_best_match_two_columns(row, csv_files):
68
+ match1 = process.extractOne(row["Generator"], csv_files)
69
+ best_match_plant_name = match1[0] if match1 else None
70
+ score_plant_name = match1[1] if match1 else None
71
+
72
+ match2 = process.extractOne(row["DUID"], csv_files)
73
+ best_match_duid = match2[0] if match2 else None
74
+ score_duid = match2[1] if match2 else None
75
+
76
+ if score_plant_name > score_duid:
77
+ best_match = best_match_plant_name
78
+ else:
79
+ best_match = best_match_duid
80
+ return best_match
81
+
82
+
83
+ def draft_solar_generator_to_trace_mapping(solar_generators, solar_trace_directory):
84
+ csv_file_names = [
85
+ f for f in os.listdir(solar_trace_directory) if f.endswith(".csv")
86
+ ]
87
+ csv_file_metadata = [extract_solar_trace_metadata(f) for f in csv_file_names]
88
+ csv_project_names = [
89
+ f["name"] for f in csv_file_metadata if f["file_type"] == "project"
90
+ ]
91
+ solar_generators["CSVFile"] = solar_generators["Generator"].apply(
92
+ lambda x: find_best_match(x, csv_project_names)
93
+ )
94
+ solar_generators = solar_generators.set_index("Generator")["CSVFile"].to_dict()
95
+ return solar_generators
96
+
97
+
98
+ def draft_solar_rez_mapping(rezs, rezs_trace_directory):
99
+ csv_file_names = [f for f in os.listdir(rezs_trace_directory) if f.endswith(".csv")]
100
+ csv_file_metadata = [extract_solar_trace_metadata(f) for f in csv_file_names]
101
+ csv_rez_names = [f["name"] for f in csv_file_metadata if f["file_type"] == "area"]
102
+ rezs["CSVFile"] = rezs["Name"].apply(lambda x: find_best_match(x, csv_rez_names))
103
+ rezs = rezs.set_index("Name")["CSVFile"].to_dict()
104
+ return rezs
105
+
106
+
107
+ def draft_wind_generator_to_trace_mapping(
108
+ wind_generators, wind_duids_and_station_names, wind_trace_directory
109
+ ):
110
+ csv_file_names = [f for f in os.listdir(wind_trace_directory) if f.endswith(".csv")]
111
+ csv_file_metadata = [extract_wind_trace_metadata(f) for f in csv_file_names]
112
+ csv_project_names = [
113
+ f["name"] for f in csv_file_metadata if f["file_type"] == "project"
114
+ ]
115
+
116
+ wind_station_names = list(wind_duids_and_station_names["Station Name"])
117
+
118
+ wind_generators["Station Name"] = wind_generators["Generator"].apply(
119
+ lambda x: find_best_match(x, wind_station_names)
120
+ )
121
+ wind_generators = pd.merge(
122
+ wind_generators, wind_duids_and_station_names, how="left", on="Station Name"
123
+ )
124
+ wind_generators = wind_generators.drop_duplicates(["Generator"])
125
+
126
+ wind_generators["CSVFile"] = wind_generators.apply(
127
+ lambda x: find_best_match_two_columns(x, csv_project_names), axis=1
128
+ )
129
+
130
+ wind_generators = wind_generators.loc[
131
+ :, ["Generator", "Station Name", "DUID", "CSVFile"]
132
+ ]
133
+
134
+ wind_generators = wind_generators.set_index("Generator").to_dict(orient="index")
135
+ return wind_generators
136
+
137
+
138
+ def draft_wind_rez_mapping(rezs, rezs_trace_directory):
139
+ csv_file_names = [f for f in os.listdir(rezs_trace_directory) if f.endswith(".csv")]
140
+ csv_file_metadata = [extract_wind_trace_metadata(f) for f in csv_file_names]
141
+ csv_rez_names = [f["name"] for f in csv_file_metadata if f["file_type"] == "area"]
142
+ rezs["CSVFile"] = rezs["Name"].apply(lambda x: find_best_match(x, csv_rez_names))
143
+ rezs = rezs.set_index("Name")["CSVFile"].to_dict()
144
+ return rezs