Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

stitch_data.py 6.7 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
  1. """Build daily-level feature sets, stitching together weather datasets and defining features.
  2. """
  3. import numpy as np
  4. import pandas as pd
  5. import geopandas as gpd
  6. from dask import dataframe as dd
  7. from loguru import logger
  8. from shapely.ops import nearest_points
  9. from src.data.gfs.utils import grb2gdf
  10. from src.conf import settings
  11. start_year = 2017
  12. end_year = 2019
  13. OUTPUT_DIR = settings.DATA_DIR / "processed/training/"
  14. if __name__ == "__main__":
  15. df = pd.concat(
  16. [
  17. pd.read_parquet(settings.DATA_DIR / f"processed/caiso_hourly/{y}.parquet")
  18. for y in range(2017, 2020)
  19. ]
  20. )
  21. df.index = df.index.tz_convert("US/Pacific")
  22. # Preprocessed hourly data is in MWh, so we can simply sum up to resample to days
  23. df = df.groupby(pd.Grouper(freq="D")).sum()
  24. df.reset_index(inplace=True)
  25. # By construction, we are interested in Feb to May (inclusive)
  26. season_filter = df["timestamp"].dt.month.isin(range(2, 6))
  27. df = df[season_filter]
  28. # Define whether something is a weekday/weekend
  29. df["is_weekday"] = df["timestamp"].dt.weekday.isin([5, 6])
  30. # Integrate forecast data
  31. gfs_data_files = (
  32. settings.DATA_DIR
  33. / f"interim/gfs/ca/gfs_3_201[7-9][01][2-5]*_0000_{i*3:03}.parquet"
  34. for i in range(5, 10)
  35. )
  36. forecasts = [*(gfs_data_files)]
  37. dayahead_weather = dd.read_parquet(forecasts).compute()
  38. # Add UTC timezone and convert to US/Pacific
  39. dayahead_weather["timestamp"] = (
  40. dayahead_weather["valid_time"].dt.tz_localize("UTC").dt.tz_convert("US/Pacific")
  41. )
  42. dayahead_weather = grb2gdf(dayahead_weather)
  43. # Include powerplant data
  44. counties = gpd.read_file(
  45. settings.DATA_DIR / "processed/geography/CA_Counties/CA_Counties_TIGER2016.shp"
  46. )
  47. weather_point_measurements = dayahead_weather["geometry"].geometry.unary_union
  48. powerplants = pd.read_parquet(
  49. settings.DATA_DIR / f"processed/geography/powerplants.parquet"
  50. )
  51. # Add geometry
  52. powerplants = gpd.GeoDataFrame(
  53. powerplants,
  54. geometry=gpd.points_from_xy(powerplants["longitude"], powerplants["latitude"]),
  55. crs="EPSG:4326",
  56. )
  57. powerplants["geometry"] = (
  58. powerplants["geometry"]
  59. .apply(lambda x: nearest_points(x, weather_point_measurements))
  60. .str.get(1)
  61. )
  62. # In order to integrate powerplant data, we have to merge on the powerplant's closest county location.
  63. powerplants = gpd.tools.sjoin(
  64. powerplants.to_crs("EPSG:4326"),
  65. counties[["GEOID", "geometry"]].to_crs("EPSG:4326"),
  66. op="within",
  67. how="left",
  68. )
  69. powerplants["online_date"] = powerplants["online_date"].dt.tz_localize("US/Pacific")
  70. powerplants["retire_date"] = powerplants["retire_date"].dt.tz_localize("US/Pacific")
  71. # Now group over GEOIDs, and sum up the capacity
  72. # For each month, we have to only associate capacity for powerplants that were online.
  73. weather_orig = dayahead_weather.copy()
  74. capacities = {}
  75. results = []
  76. for date, weather_df in dayahead_weather.groupby(
  77. pd.Grouper(key="timestamp", freq="MS"), as_index=False
  78. ):
  79. if weather_df.empty:
  80. logger.warning("Weather data for {date} is empty!", date=date)
  81. continue
  82. logger.debug("Assigning capacity for weather points as of {date}.", date=date)
  83. valid_plants = (powerplants["online_date"] <= date) & (
  84. powerplants["retire_date"].isnull() | (powerplants["retire_date"] > date)
  85. )
  86. valid_plants = powerplants[valid_plants]
  87. county_mw = valid_plants.groupby("GEOID", as_index=False)["capacity_mw"].sum()
  88. weather_df = weather_df.merge(county_mw, on="GEOID", how="left")
  89. weather_df["capacity_mw"] = weather_df["capacity_mw"].fillna(0)
  90. results.append(weather_df)
  91. # Note that this is still on the original df grain as we did not aggregate the groupby!
  92. dayahead_weather = pd.concat(results, ignore_index=True)
  93. # Roll-up to dailies
  94. daily_capacity = (
  95. dayahead_weather.groupby(by=["GEOID", pd.Grouper(key="timestamp", freq="D")])[
  96. "capacity_mw"
  97. ]
  98. .mean()
  99. .reset_index()
  100. .groupby(by=pd.Grouper(key="timestamp", freq="D"))["capacity_mw"]
  101. .sum()
  102. )
  103. county_level_dailies = dayahead_weather.groupby(
  104. by=["GEOID", pd.Grouper(key="timestamp", freq="D")], as_index=True
  105. ).agg(
  106. t_min=("t", "min"),
  107. t_max=("t", "max"),
  108. t_mean=("t", "mean"),
  109. dswrf_mean=("dswrf", "mean"),
  110. dswrf_max=("dswrf", "max"),
  111. capacity_mw=("capacity_mw", "mean"),
  112. ).reset_index()
  113. def weighted_mean_factory(weight_col):
  114. def weighted_avg(s):
  115. if s.empty:
  116. return 0.0
  117. else:
  118. return np.average(s, weights=dayahead_weather.loc[s.index, weight_col])
  119. weighted_avg.__name__ = f"{weight_col}_wmean"
  120. return weighted_avg
  121. # GFS is missing certain days for one reason or another.
  122. # Furthermore, pandas timestamps fill in timesteps to build a full frequency datetime
  123. # Since we don't have continuity in time, we ignore those.
  124. dayahead_daily = (
  125. county_level_dailies.groupby(by=pd.Grouper(key="timestamp", freq="D"),)
  126. .agg(
  127. t_mean=pd.NamedAgg(column="t_mean", aggfunc="mean"), # K
  128. t_wmean=pd.NamedAgg(
  129. column="t_mean", aggfunc=weighted_mean_factory("capacity_mw")
  130. ), # K
  131. t_wmax=pd.NamedAgg(
  132. column="t_max", aggfunc=weighted_mean_factory("capacity_mw")
  133. ), # K
  134. t_wmin=pd.NamedAgg(
  135. column="t_min", aggfunc=weighted_mean_factory("capacity_mw")
  136. ), # K
  137. t_absmax=pd.NamedAgg(column="t_max", aggfunc="max",), # K
  138. t_absmin=pd.NamedAgg(column="t_min", aggfunc="min",), # K
  139. dswrf_mean=pd.NamedAgg(column="dswrf_mean", aggfunc="mean"), # W/m^2
  140. dswrf_absmax=pd.NamedAgg(column="dswrf_max", aggfunc="max"), # W/m^2
  141. dswrf_wmean=pd.NamedAgg(
  142. column="dswrf_mean", aggfunc=weighted_mean_factory("capacity_mw")
  143. ), # W/m^2
  144. capacity_mw=pd.NamedAgg(column="capacity_mw", aggfunc="sum"), # MW
  145. )
  146. .dropna(subset=["t_mean", "dswrf_mean"], how="any")
  147. )
  148. dayahead_daily["installed_capacity"] = dayahead_daily.index.map(daily_capacity)
  149. daily_feature_data = df.merge(dayahead_daily, on="timestamp", how="inner")
  150. daily_feature_data["solar_capacity_factor"] = daily_feature_data["solar"] / (
  151. daily_feature_data["installed_capacity"] * 24
  152. )
  153. daily_feature_data.to_parquet(
  154. OUTPUT_DIR / "0_labeled_data_daily.parquet", engine="fastparquet"
  155. )
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...