noaaplotter 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.
- noaaplotter/__init__.py +20 -0
- noaaplotter/__main__.py +8 -0
- noaaplotter/cli/__init__.py +186 -0
- noaaplotter/figures/__init__.py +5 -0
- noaaplotter/figures/plotly_daily.py +258 -0
- noaaplotter/figures/plotly_monthly.py +51 -0
- noaaplotter/noaaplotter.py +726 -0
- noaaplotter/scripts/download_data.py +150 -0
- noaaplotter/scripts/plot_daily.py +108 -0
- noaaplotter/scripts/plot_monthly.py +72 -0
- noaaplotter/sources/__init__.py +17 -0
- noaaplotter/sources/base.py +97 -0
- noaaplotter/sources/cds.py +168 -0
- noaaplotter/sources/open_meteo.py +108 -0
- noaaplotter/utils/__init__.py +0 -0
- noaaplotter/utils/config.py +30 -0
- noaaplotter/utils/dataset.py +418 -0
- noaaplotter/utils/download_utils.py +232 -0
- noaaplotter/utils/plot_utils.py +49 -0
- noaaplotter/utils/utils.py +110 -0
- noaaplotter-1.0.0.dist-info/METADATA +220 -0
- noaaplotter-1.0.0.dist-info/RECORD +26 -0
- noaaplotter-1.0.0.dist-info/WHEEL +5 -0
- noaaplotter-1.0.0.dist-info/entry_points.txt +5 -0
- noaaplotter-1.0.0.dist-info/licenses/LICENSE +21 -0
- noaaplotter-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Open-Meteo Archive API source (ERA5, no API key).
|
|
2
|
+
|
|
3
|
+
Returns the canonical NOAA daily-summaries schema so it can be used exactly
|
|
4
|
+
like a NOAA station file. Coverage is ERA5 back to 1940; single geographic
|
|
5
|
+
point (lat/lon). Snow is reported in cm (SNWD).
|
|
6
|
+
"""
|
|
7
|
+
import polars as pl
|
|
8
|
+
import requests
|
|
9
|
+
|
|
10
|
+
API_URL = "https://archive-api.open-meteo.com/v1/archive"
|
|
11
|
+
|
|
12
|
+
_DAILY_VARS = [
|
|
13
|
+
"temperature_2m_mean", # -> TAVG
|
|
14
|
+
"temperature_2m_min", # -> TMIN
|
|
15
|
+
"temperature_2m_max", # -> TMAX
|
|
16
|
+
"precipitation_sum", # -> PRCP (mm)
|
|
17
|
+
"snowfall_sum", # -> SNOW (cm)
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
CHUNK_DAYS = 92 # generous sub-chunk to stay well within rate limits
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def fetch_open_meteo(latitude, longitude, start, end, name="Open-Meteo ERA5"):
|
|
24
|
+
"""Fetch daily ERA5 data for a point.
|
|
25
|
+
|
|
26
|
+
:param latitude: geographic latitude (degrees)
|
|
27
|
+
:param longitude: geographic longitude (degrees)
|
|
28
|
+
:param start: "yyyy-mm-dd"
|
|
29
|
+
:param end: "yyyy-mm-dd"
|
|
30
|
+
:param name: station NAME label written into the data
|
|
31
|
+
:return: polars DataFrame with canonical schema (TAVG/TMIN/TMAX/PRCP/SNOW)
|
|
32
|
+
"""
|
|
33
|
+
from datetime import datetime, timedelta
|
|
34
|
+
|
|
35
|
+
dt_start = datetime.strptime(start, "%Y-%m-%d")
|
|
36
|
+
dt_end = datetime.strptime(end, "%Y-%m-%d")
|
|
37
|
+
station_id = f"{latitude:.4f},{longitude:.4f}"
|
|
38
|
+
|
|
39
|
+
frames = []
|
|
40
|
+
cur = dt_start
|
|
41
|
+
while cur <= dt_end:
|
|
42
|
+
chunk_end = min(cur + timedelta(days=CHUNK_DAYS - 1), dt_end)
|
|
43
|
+
frames.append(_fetch_chunk(latitude, longitude, cur, chunk_end, station_id))
|
|
44
|
+
cur = chunk_end + timedelta(days=1)
|
|
45
|
+
|
|
46
|
+
df = pl.concat(frames) if frames else _empty()
|
|
47
|
+
return df.with_columns(pl.lit(name).alias("NAME"))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _empty():
|
|
51
|
+
return pl.DataFrame(
|
|
52
|
+
{
|
|
53
|
+
"STATION": [None], "NAME": [None],
|
|
54
|
+
"DATE": pl.Series([], dtype=pl.Date),
|
|
55
|
+
"TAVG": [None], "TMAX": [None], "TMIN": [None],
|
|
56
|
+
"PRCP": [None], "SNOW": [None],
|
|
57
|
+
}
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _fetch_chunk(latitude, longitude, dt_start, dt_end, station_id):
|
|
62
|
+
params = {
|
|
63
|
+
"latitude": latitude,
|
|
64
|
+
"longitude": longitude,
|
|
65
|
+
"start_date": dt_start.strftime("%Y-%m-%d"),
|
|
66
|
+
"end_date": dt_end.strftime("%Y-%m-%d"),
|
|
67
|
+
"daily": ",".join(_DAILY_VARS),
|
|
68
|
+
"timezone": "UTC",
|
|
69
|
+
}
|
|
70
|
+
r = requests.get(API_URL, params=params, timeout=60)
|
|
71
|
+
if r.status_code != 200:
|
|
72
|
+
raise RuntimeError(f"Open-Meteo request failed ({r.status_code}): {r.text[:300]}")
|
|
73
|
+
d = r.json()
|
|
74
|
+
if "error" in d:
|
|
75
|
+
raise RuntimeError(f"Open-Meteo error: {d['error']} — {d.get('reason', '')}")
|
|
76
|
+
|
|
77
|
+
daily = d.get("daily", {})
|
|
78
|
+
dates = daily.get("time", [])
|
|
79
|
+
if not dates:
|
|
80
|
+
return _empty()
|
|
81
|
+
out = pl.DataFrame(
|
|
82
|
+
{
|
|
83
|
+
"STATION": [station_id] * len(dates),
|
|
84
|
+
"DATE": pl.Series(dates, dtype=pl.Date),
|
|
85
|
+
"TAVG": _col(daily, "temperature_2m_mean", len(dates)),
|
|
86
|
+
"TMAX": _col(daily, "temperature_2m_max", len(dates)),
|
|
87
|
+
"TMIN": _col(daily, "temperature_2m_min", len(dates)),
|
|
88
|
+
"PRCP": _col(daily, "precipitation_sum", len(dates)),
|
|
89
|
+
"SNOW": _col(daily, "snowfall_sum", len(dates)),
|
|
90
|
+
}
|
|
91
|
+
)
|
|
92
|
+
return out
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _col(daily, key, n):
|
|
96
|
+
vals = daily.get(key)
|
|
97
|
+
if vals is None:
|
|
98
|
+
return [None] * n
|
|
99
|
+
return [v if v is not None else None for v in vals]
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def save_to_parquet(df, output_file):
|
|
103
|
+
"""Write a canonical-schema frame to parquet (numeric columns kept numeric)."""
|
|
104
|
+
for c in ("TAVG", "TMAX", "TMIN", "PRCP", "SNOW"):
|
|
105
|
+
if c in df.columns:
|
|
106
|
+
df = df.with_columns(pl.col(c).cast(pl.Float64, strict=False))
|
|
107
|
+
df.write_parquet(output_file)
|
|
108
|
+
return output_file
|
|
File without changes
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
Central API token handling.
|
|
4
|
+
|
|
5
|
+
Tokens are read from the process environment first, then from a local
|
|
6
|
+
.env file (git-ignored) in the working directory. CLI arguments and
|
|
7
|
+
direct function arguments always take precedence over both.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
from dotenv import load_dotenv
|
|
14
|
+
except ImportError: # pragma: no cover
|
|
15
|
+
load_dotenv = None
|
|
16
|
+
|
|
17
|
+
if load_dotenv is not None:
|
|
18
|
+
load_dotenv()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def get_noaa_token(cli_token=""):
|
|
22
|
+
"""Return NOAA CDO API token: CLI arg, else env / .env."""
|
|
23
|
+
return cli_token or os.environ.get("NOAA_API_TOKEN", "")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def get_cds_credentials(cli_token=""):
|
|
27
|
+
"""Return (token, url) for the CDS API: CLI arg, else env / .env."""
|
|
28
|
+
token = cli_token or os.environ.get("CDS_API_TOKEN", "")
|
|
29
|
+
url = os.environ.get("CDS_API_URL", "https://cds.climate.copernicus.eu/api")
|
|
30
|
+
return token, url
|
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
|
|
4
|
+
########################
|
|
5
|
+
# Credits here
|
|
6
|
+
# author: Ingmar Nitze, Alfred Wegener Institute for Polar and Marine Research
|
|
7
|
+
# contact: ingmar.nitze@awi.de
|
|
8
|
+
# version: 2020-12-09
|
|
9
|
+
|
|
10
|
+
########################
|
|
11
|
+
import os
|
|
12
|
+
|
|
13
|
+
import polars as pl
|
|
14
|
+
|
|
15
|
+
from .utils import parse_dates
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class NOAAPlotterDailySummariesDataset(object):
|
|
19
|
+
"""
|
|
20
|
+
Load daily weather observations (NOAA daily summaries format) and
|
|
21
|
+
prepare the columns used by the plotting functions.
|
|
22
|
+
Internal data is a polars DataFrame; expose a pandas view via `data`.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(self, input_filepath=None, location=None, remove_feb29=False):
|
|
26
|
+
self.input_switch = None
|
|
27
|
+
self.input_filepath = input_filepath
|
|
28
|
+
self.location = location
|
|
29
|
+
self.noaa_token = None
|
|
30
|
+
self.noaa_location = None
|
|
31
|
+
self.remove_feb29 = remove_feb29
|
|
32
|
+
self.data = None
|
|
33
|
+
self._check_data_loading()
|
|
34
|
+
if self.input_switch == "file":
|
|
35
|
+
self._load_file()
|
|
36
|
+
elif self.input_switch == "noaa_api":
|
|
37
|
+
self._load_noaa()
|
|
38
|
+
self._validate_location()
|
|
39
|
+
self._update_datatypes()
|
|
40
|
+
self._get_datestring()
|
|
41
|
+
self._get_tmean()
|
|
42
|
+
self._remove_feb29()
|
|
43
|
+
self._filter_to_location()
|
|
44
|
+
|
|
45
|
+
def print_locations(self):
|
|
46
|
+
"""
|
|
47
|
+
Print all locations names
|
|
48
|
+
"""
|
|
49
|
+
print(self.data["NAME"].unique())
|
|
50
|
+
|
|
51
|
+
def _check_data_loading(self):
|
|
52
|
+
"""
|
|
53
|
+
function check if all requirements for loading options are met
|
|
54
|
+
File loading:
|
|
55
|
+
* input_filepath
|
|
56
|
+
"""
|
|
57
|
+
if os.path.exists(self.input_filepath):
|
|
58
|
+
self.input_switch = "file"
|
|
59
|
+
elif self.noaa_token and self.noaa_location:
|
|
60
|
+
self.input_switch = "noaa_api"
|
|
61
|
+
else:
|
|
62
|
+
raise ImportError(
|
|
63
|
+
"Please enter either correct file path or noaa station_id and API token"
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
def _load_file(self):
|
|
67
|
+
"""
|
|
68
|
+
load file into a polars DataFrame
|
|
69
|
+
:return:
|
|
70
|
+
"""
|
|
71
|
+
if self.input_filepath.endswith(".parquet"):
|
|
72
|
+
data = pl.read_parquet(self.input_filepath)
|
|
73
|
+
else:
|
|
74
|
+
data = pl.read_csv(self.input_filepath)
|
|
75
|
+
if "__index_level_0__" in data.columns:
|
|
76
|
+
data = data.drop("__index_level_0__")
|
|
77
|
+
# Observed values can be stored as strings (e.g. CSV or legacy parquet
|
|
78
|
+
# exports); coerce to float so numeric ops (TMEAN, stats) work.
|
|
79
|
+
# Casting an already-numeric column to Float64 is a no-op.
|
|
80
|
+
for c in ("PRCP", "SNOW", "TAVG", "TMAX", "TMIN", "SNWD"):
|
|
81
|
+
if c in data.columns:
|
|
82
|
+
data = data.with_columns(
|
|
83
|
+
pl.col(c).cast(pl.Float64, strict=False)
|
|
84
|
+
)
|
|
85
|
+
self._pl = data
|
|
86
|
+
|
|
87
|
+
def _load_noaa(self):
|
|
88
|
+
"""
|
|
89
|
+
load data through NOAA API
|
|
90
|
+
"""
|
|
91
|
+
pass
|
|
92
|
+
|
|
93
|
+
def _validate_location(self):
|
|
94
|
+
"""
|
|
95
|
+
raise error and message if location name cannot be found
|
|
96
|
+
:return:
|
|
97
|
+
"""
|
|
98
|
+
names = self._pl["NAME"].unique().to_list()
|
|
99
|
+
if not self.location and len(names) > 1:
|
|
100
|
+
raise ValueError(
|
|
101
|
+
"There is more than one location in the dataset. Please choose a location using the -loc option! "
|
|
102
|
+
"Valid Location identifiers: {0} ".format(names)
|
|
103
|
+
)
|
|
104
|
+
if self.location:
|
|
105
|
+
mask = self._pl["NAME"].str.to_lowercase().str.contains(
|
|
106
|
+
self.location.lower(), literal=False
|
|
107
|
+
)
|
|
108
|
+
if mask.sum() == 0:
|
|
109
|
+
raise ValueError(
|
|
110
|
+
"Location Name is not valid! Valid Location identifiers: {0}".format(names)
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
def _update_datatypes(self):
|
|
114
|
+
"""
|
|
115
|
+
define 'DATE' as datetime
|
|
116
|
+
:return:
|
|
117
|
+
"""
|
|
118
|
+
if self._pl["DATE"].dtype == pl.String:
|
|
119
|
+
self._pl = self._pl.with_columns(pl.col("DATE").str.to_datetime())
|
|
120
|
+
|
|
121
|
+
def _get_datestring(self):
|
|
122
|
+
"""
|
|
123
|
+
write specific date formats
|
|
124
|
+
:return:
|
|
125
|
+
"""
|
|
126
|
+
self._pl = self._pl.with_columns(
|
|
127
|
+
pl.col("DATE").dt.strftime("%m-%d").alias("DATE_MD"),
|
|
128
|
+
pl.col("DATE").dt.strftime("%Y-%m").alias("DATE_YM"),
|
|
129
|
+
pl.col("DATE").dt.strftime("%m").alias("DATE_M"),
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
def _get_tmean(self):
|
|
133
|
+
"""
|
|
134
|
+
calculate mean daily temperature from min and max
|
|
135
|
+
:return:
|
|
136
|
+
"""
|
|
137
|
+
# TODO: check for cases where TMIN and TMAX are empty (e.g. Schonefeld). There TAVG is the main field
|
|
138
|
+
self._pl = self._pl.with_columns(
|
|
139
|
+
pl.mean_horizontal(["TMIN", "TMAX"]).alias("TMEAN")
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
def _remove_feb29(self):
|
|
143
|
+
"""
|
|
144
|
+
Function to remove February 29 from the data
|
|
145
|
+
:return:
|
|
146
|
+
"""
|
|
147
|
+
if self.remove_feb29:
|
|
148
|
+
self._pl = self._pl.filter(pl.col("DATE_MD") != "02-29")
|
|
149
|
+
|
|
150
|
+
def _filter_to_location(self):
|
|
151
|
+
"""
|
|
152
|
+
Filter dataset to the defined location
|
|
153
|
+
:return:
|
|
154
|
+
"""
|
|
155
|
+
if self.location:
|
|
156
|
+
filt = self._pl["NAME"].str.to_lowercase().str.contains(
|
|
157
|
+
self.location.lower(), literal=False
|
|
158
|
+
)
|
|
159
|
+
if filt.sum() > 0:
|
|
160
|
+
self._pl = self._pl.filter(filt)
|
|
161
|
+
else:
|
|
162
|
+
raise ValueError("Location Name is not valid")
|
|
163
|
+
|
|
164
|
+
# pandas view for the plotting code
|
|
165
|
+
self.data = self._pl.to_pandas()
|
|
166
|
+
|
|
167
|
+
def filter_to_climate(self, climate_start, climate_end):
|
|
168
|
+
"""
|
|
169
|
+
Function to create filtered dataset covering the defined climate normal period
|
|
170
|
+
:return:
|
|
171
|
+
"""
|
|
172
|
+
df_clim = self.data[
|
|
173
|
+
(self.data["DATE"] >= climate_start) & (self.data["DATE"] <= climate_end)
|
|
174
|
+
]
|
|
175
|
+
return df_clim
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
class NOAAPlotterDailyClimateDataset(object):
|
|
179
|
+
# TODO: make main class sub subclasses for daily/monthly
|
|
180
|
+
def __init__(
|
|
181
|
+
self,
|
|
182
|
+
daily_dataset,
|
|
183
|
+
start="1981-01-01",
|
|
184
|
+
end="2010-12-31",
|
|
185
|
+
filtersize=7,
|
|
186
|
+
impute_feb29=True,
|
|
187
|
+
):
|
|
188
|
+
"""
|
|
189
|
+
:param start:
|
|
190
|
+
:param end:
|
|
191
|
+
:param filtersize:
|
|
192
|
+
:param impute_feb29:
|
|
193
|
+
"""
|
|
194
|
+
self.start = parse_dates(start)
|
|
195
|
+
self.end = parse_dates(end)
|
|
196
|
+
self.filtersize = filtersize
|
|
197
|
+
self.impute_feb29 = impute_feb29
|
|
198
|
+
self.daily_dataset = daily_dataset
|
|
199
|
+
self.data_daily = None
|
|
200
|
+
self.data = None
|
|
201
|
+
self.date_range_valid = False
|
|
202
|
+
|
|
203
|
+
# validate date range
|
|
204
|
+
self._validate_date_range()
|
|
205
|
+
# filter daily to date range
|
|
206
|
+
self._filter_to_climate()
|
|
207
|
+
# calculate daily statistics
|
|
208
|
+
self._calculate_climate_statistics()
|
|
209
|
+
# mean imputation for 29 February
|
|
210
|
+
self._impute_feb29()
|
|
211
|
+
# filter if desired
|
|
212
|
+
self._run_filter()
|
|
213
|
+
# make completeness report
|
|
214
|
+
|
|
215
|
+
def _validate_date_range(self):
|
|
216
|
+
if self.daily_dataset.data["DATE"].max() >= self.end:
|
|
217
|
+
if self.daily_dataset.data["DATE"].min() <= self.end:
|
|
218
|
+
self.date_range_valid = True
|
|
219
|
+
else:
|
|
220
|
+
raise ("Dataset is insufficient to calculate climate normals!")
|
|
221
|
+
|
|
222
|
+
def _filter_to_climate(self):
|
|
223
|
+
"""
|
|
224
|
+
calculate climate dataset
|
|
225
|
+
:return:
|
|
226
|
+
"""
|
|
227
|
+
df_clim = self.daily_dataset.data[
|
|
228
|
+
(self.daily_dataset.data["DATE"] >= self.start)
|
|
229
|
+
& (self.daily_dataset.data["DATE"] <= self.end)
|
|
230
|
+
]
|
|
231
|
+
df_clim = df_clim[(df_clim["DATE_MD"] != "02-29")]
|
|
232
|
+
self.data_daily = df_clim
|
|
233
|
+
|
|
234
|
+
def _calculate_climate_statistics(self):
|
|
235
|
+
"""
|
|
236
|
+
Function to calculate major statistics (polars).
|
|
237
|
+
:param self.data_daily:
|
|
238
|
+
:type self.data_daily: pandas.DataFrame (converted to polars)
|
|
239
|
+
:return:
|
|
240
|
+
"""
|
|
241
|
+
d = pl.from_pandas(self.data_daily)
|
|
242
|
+
aggs = [
|
|
243
|
+
pl.col("TMEAN").mean().alias("tmean_doy_mean"),
|
|
244
|
+
pl.col("TMEAN").std().alias("tmean_doy_std"),
|
|
245
|
+
pl.col("TMEAN").max().alias("tmean_doy_max"),
|
|
246
|
+
pl.col("TMEAN").min().alias("tmean_doy_min"),
|
|
247
|
+
pl.col("TMAX").max().alias("tmax_doy_max"),
|
|
248
|
+
pl.col("TMAX").std().alias("tmax_doy_std"),
|
|
249
|
+
pl.col("TMIN").min().alias("tmin_doy_min"),
|
|
250
|
+
pl.col("TMIN").std().alias("tmin_doy_std"),
|
|
251
|
+
]
|
|
252
|
+
if "SNOW" in d.columns:
|
|
253
|
+
aggs.append(pl.col("SNOW").mean().alias("snow_doy_mean"))
|
|
254
|
+
df_out = (
|
|
255
|
+
d.group_by("DATE_MD", maintain_order=True)
|
|
256
|
+
.agg(aggs)
|
|
257
|
+
.sort("DATE_MD")
|
|
258
|
+
.to_pandas()
|
|
259
|
+
.set_index("DATE_MD")
|
|
260
|
+
)
|
|
261
|
+
self.data = df_out
|
|
262
|
+
|
|
263
|
+
def _impute_feb29(self):
|
|
264
|
+
"""
|
|
265
|
+
Function for mean imputation of February 29.
|
|
266
|
+
:return:
|
|
267
|
+
"""
|
|
268
|
+
if self.impute_feb29:
|
|
269
|
+
self.data.loc["02-29"] = self.data.loc["02-28":"03-01"].mean(axis=0)
|
|
270
|
+
self.data.sort_index(inplace=True)
|
|
271
|
+
|
|
272
|
+
def _run_filter(self):
|
|
273
|
+
"""
|
|
274
|
+
Function to run rolling mean filter on climate series to smooth out
|
|
275
|
+
short fluctuations (polars).
|
|
276
|
+
:return:
|
|
277
|
+
"""
|
|
278
|
+
if self.filtersize % 2 != 0:
|
|
279
|
+
f = self.filtersize
|
|
280
|
+
# include_index=True: the DATE_MD index is needed for the wraparound
|
|
281
|
+
# frame to be sliced back with it
|
|
282
|
+
d = pl.from_pandas(self.data, include_index=True)
|
|
283
|
+
# wraparound window: pandas rolling(7) with min_periods=7 gives
|
|
284
|
+
# NaN for the first f-1 rows of the extended frame, which are
|
|
285
|
+
# sliced away below. pandas only rolls numeric columns; DATE_MD
|
|
286
|
+
# passes through unchanged.
|
|
287
|
+
extended = pl.concat([d.tail(f), d, d.head(f)], how="vertical")
|
|
288
|
+
rolled = extended.with_columns(
|
|
289
|
+
pl.selectors.numeric().rolling_mean(window_size=f, min_samples=f)
|
|
290
|
+
)
|
|
291
|
+
self.data = (
|
|
292
|
+
rolled.slice(f, len(d)).to_pandas().set_index("DATE_MD")
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
def _make_report(self):
|
|
296
|
+
"""
|
|
297
|
+
Function to create report on climate data completeness
|
|
298
|
+
:return:
|
|
299
|
+
"""
|
|
300
|
+
# input climate series (e.g. 1981-01-01 - 2010-12-31)
|
|
301
|
+
pass
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
class NOAAPlotterMonthlyClimateDataset(object):
|
|
305
|
+
def __init__(
|
|
306
|
+
self, daily_dataset, start="1981-01-01", end="2010-12-31", impute_feb29=True
|
|
307
|
+
):
|
|
308
|
+
self.daily_dataset = daily_dataset
|
|
309
|
+
self.monthly_aggregate = None
|
|
310
|
+
self.start = parse_dates(start)
|
|
311
|
+
self.end = parse_dates(end)
|
|
312
|
+
self.impute_feb29 = impute_feb29
|
|
313
|
+
self._validate_date_range()
|
|
314
|
+
|
|
315
|
+
def _validate_date_range(self):
|
|
316
|
+
if self.daily_dataset.data["DATE"].max() >= self.end:
|
|
317
|
+
if self.daily_dataset.data["DATE"].min() <= self.end:
|
|
318
|
+
self.date_range_valid = True
|
|
319
|
+
else:
|
|
320
|
+
raise ("Dataset is insufficient to calculate climate normals!")
|
|
321
|
+
|
|
322
|
+
def _filter_to_climate(self):
|
|
323
|
+
"""
|
|
324
|
+
calculate climate dataset
|
|
325
|
+
:return:
|
|
326
|
+
"""
|
|
327
|
+
df_clim = self.daily_dataset.data[
|
|
328
|
+
(self.daily_dataset.data["DATE"] >= self.start)
|
|
329
|
+
& (self.daily_dataset.data["DATE"] <= self.end)
|
|
330
|
+
]
|
|
331
|
+
df_clim = df_clim[(df_clim["DATE_MD"] != "02-29")]
|
|
332
|
+
self.data_daily = df_clim
|
|
333
|
+
|
|
334
|
+
def filter_to_date(self):
|
|
335
|
+
"""
|
|
336
|
+
calculate climate dataset
|
|
337
|
+
:return:
|
|
338
|
+
"""
|
|
339
|
+
df_clim = self.daily_dataset.data[
|
|
340
|
+
(self.daily_dataset.data["DATE"] >= self.start)
|
|
341
|
+
& (self.daily_dataset.data["DATE"] <= self.end)
|
|
342
|
+
]
|
|
343
|
+
df_clim = df_clim[(df_clim["DATE_MD"] != "02-29")]
|
|
344
|
+
return df_clim
|
|
345
|
+
|
|
346
|
+
def _impute_feb29(self):
|
|
347
|
+
"""
|
|
348
|
+
Function for mean imputation of February 29.
|
|
349
|
+
:return:
|
|
350
|
+
"""
|
|
351
|
+
pass
|
|
352
|
+
|
|
353
|
+
def calculate_monthly_statistics(self):
|
|
354
|
+
"""
|
|
355
|
+
Function to calculate monthly statistics (polars).
|
|
356
|
+
:return:
|
|
357
|
+
"""
|
|
358
|
+
d = pl.from_pandas(self.filter_to_date())
|
|
359
|
+
aggs = [
|
|
360
|
+
pl.col("TMEAN").mean().alias("tmean_doy_mean"),
|
|
361
|
+
pl.col("TMEAN").std().alias("tmean_doy_std"),
|
|
362
|
+
pl.col("TMAX").max().alias("tmax_doy_max"),
|
|
363
|
+
pl.col("TMAX").std().alias("tmax_doy_std"),
|
|
364
|
+
pl.col("TMIN").min().alias("tmin_doy_min"),
|
|
365
|
+
pl.col("TMIN").std().alias("tmin_doy_std"),
|
|
366
|
+
]
|
|
367
|
+
if "SNOW" in d.columns:
|
|
368
|
+
aggs.append(pl.col("SNOW").mean().alias("snow_doy_mean"))
|
|
369
|
+
aggs.append(pl.col("PRCP").sum().alias("prcp_sum"))
|
|
370
|
+
df_out = (
|
|
371
|
+
d.group_by("DATE_YM", maintain_order=True)
|
|
372
|
+
.agg(aggs)
|
|
373
|
+
.sort("DATE_YM")
|
|
374
|
+
.to_pandas()
|
|
375
|
+
.set_index("DATE_YM")
|
|
376
|
+
)
|
|
377
|
+
self.monthly_aggregate = df_out
|
|
378
|
+
|
|
379
|
+
def calculate_monthly_climate(self):
|
|
380
|
+
"""
|
|
381
|
+
Function to calculate monthly climate statistics (polars).
|
|
382
|
+
:return:
|
|
383
|
+
"""
|
|
384
|
+
d = pl.from_pandas(self.filter_to_date())
|
|
385
|
+
d = d.with_columns(
|
|
386
|
+
pl.col("DATE").dt.month().alias("Month"),
|
|
387
|
+
pl.col("DATE").dt.year().alias("Year"),
|
|
388
|
+
)
|
|
389
|
+
# unique year count for the (bug-compatible) precipitation scaling
|
|
390
|
+
n_years = d["Year"].n_unique()
|
|
391
|
+
aggs = [
|
|
392
|
+
pl.col("TMEAN").mean().alias("tmean_doy_mean"),
|
|
393
|
+
pl.col("TMEAN").std().alias("tmean_doy_std"),
|
|
394
|
+
pl.col("TMAX").max().alias("tmax_doy_max"),
|
|
395
|
+
pl.col("TMAX").std().alias("tmax_doy_std"),
|
|
396
|
+
pl.col("TMIN").min().alias("tmin_doy_min"),
|
|
397
|
+
pl.col("TMIN").std().alias("tmin_doy_std"),
|
|
398
|
+
]
|
|
399
|
+
if "SNOW" in d.columns:
|
|
400
|
+
aggs.append(pl.col("SNOW").mean().alias("snow_doy_mean"))
|
|
401
|
+
aggs.append((pl.col("PRCP").mean() * 30).alias("prcp_sum"))
|
|
402
|
+
df_out = (
|
|
403
|
+
d.group_by("Month", maintain_order=True)
|
|
404
|
+
.agg(aggs)
|
|
405
|
+
.sort("Month")
|
|
406
|
+
.to_pandas()
|
|
407
|
+
.set_index("Month")
|
|
408
|
+
)
|
|
409
|
+
self.monthly_climate = df_out
|
|
410
|
+
|
|
411
|
+
def _make_report(self):
|
|
412
|
+
"""
|
|
413
|
+
Function to create report on climate data completeness
|
|
414
|
+
:return:
|
|
415
|
+
"""
|
|
416
|
+
# input climate series (e.g. 1981-01-01 - 2010-12-31)
|
|
417
|
+
|
|
418
|
+
pass
|