-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_forecast_frame.mo.py
More file actions
281 lines (244 loc) · 7.97 KB
/
Copy pathplot_forecast_frame.mo.py
File metadata and controls
281 lines (244 loc) · 7.97 KB
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import marimo
__generated_with = "0.16.5"
app = marimo.App(width="medium")
@app.cell
def _():
import logging
from argparse import ArgumentParser
from pathlib import Path
import cartopy.crs as ccrs
import earthkit.plots as ekp
import numpy as np
from plotting import DOMAINS
from plotting import get_projection
from plotting import StatePlotter
from plotting.colormap_defaults import CMAP_DEFAULTS
from plotting.compat import load_state_from_grib
return (
ArgumentParser,
CMAP_DEFAULTS,
Path,
StatePlotter,
ekp,
load_state_from_grib,
logging,
np,
DOMAINS,
get_projection,
ccrs,
)
@app.cell
def _(logging):
LOG = logging.getLogger(__name__)
LOG_FMT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
logging.basicConfig(level=logging.INFO, format=LOG_FMT)
return (LOG,)
@app.cell
def _(ArgumentParser, Path):
parser = ArgumentParser()
parser.add_argument(
"--input", type=str, default=None, help="Directory to grib data"
)
parser.add_argument("--date", type=str, default=None, help="reference datetime")
parser.add_argument("--outfn", type=str, help="output filename")
parser.add_argument("--leadtime", type=str, help="leadtime")
parser.add_argument("--param", type=str, help="parameter")
parser.add_argument("--region", type=str, help="name of region")
parser.add_argument(
"--extent",
type=float,
nargs=4,
default=None,
metavar=("LON_MIN", "LON_MAX", "LAT_MIN", "LAT_MAX"),
help="custom geographic extent in PlateCarree coordinates; overrides DOMAINS lookup",
)
parser.add_argument(
"--projection",
type=str,
default=None,
help="projection name (e.g. 'orthographic'); used only together with --extent",
)
parser.add_argument(
"--accu", type=int, default=1, help="accumulation period in hours"
)
args = parser.parse_args()
grib_dir = Path(args.input)
init_time = args.date
outfn = Path(args.outfn)
lead_time = args.leadtime
param = args.param
region = args.region
accu = args.accu
return (
args,
accu,
grib_dir,
init_time,
lead_time,
outfn,
param,
region,
)
@app.cell
def _(accu, grib_dir, init_time, lead_time, load_state_from_grib, param):
# load grib file
grib_file = grib_dir / f"{init_time}_{lead_time}.grib"
if param == "SP_10M":
paramlist = ["U_10M", "V_10M"]
elif param == "SP":
paramlist = ["U", "V"]
else:
paramlist = [param]
state = load_state_from_grib(grib_file, paramlist=paramlist)
# tp is accumulated from start of forecast; de-accumulate to get the period [lt-accu, lt]
if param == "TOT_PREC":
prev_lt = int(lead_time) - accu
if prev_lt > 0:
prev_grib_file = grib_dir / f"{init_time}_{prev_lt:03d}.grib"
prev_state = load_state_from_grib(prev_grib_file, paramlist=paramlist)
state["fields"]["TOT_PREC"] = (
state["fields"]["TOT_PREC"]
- prev_state["fields"]["TOT_PREC"][: len(state["fields"]["TOT_PREC"])]
)
return (state,)
@app.cell
def _(CMAP_DEFAULTS, ekp):
def get_style(param, units_override=None, accu=1):
"""Get style and colormap settings for the plot.
Needed because cmap/norm does not work in Style(colors=cmap),
still needs to be passed as arguments to tripcolor()/tricontourf().
"""
lookup = f"{param}_{accu}H" if param == "TOT_PREC" else param
cfg = CMAP_DEFAULTS[lookup]
units = units_override if units_override is not None else cfg.get("units", "")
return {
"style": ekp.styles.Style(
levels=cfg.get("bounds", cfg.get("levels", None)),
extend="both",
units=units,
colors=cfg.get("colors", None),
),
"norm": cfg.get("norm", None),
"cmap": cfg.get("cmap", None),
"levels": cfg.get("levels", None),
"vmin": cfg.get("vmin", None),
"vmax": cfg.get("vmax", None),
"colors": cfg.get("colors", None),
}
return (get_style,)
@app.cell
def _(LOG, np):
"""Preprocess fields with pint-based unit conversion and derived quantities."""
try:
import pint # type: ignore
_ureg = pint.UnitRegistry()
def _k_to_c(arr):
# robust conversion with pint, fallback if dtype unsupported
try:
return (_ureg.Quantity(arr, _ureg.kelvin).to(_ureg.degC)).magnitude
except Exception:
return arr - 273.15
def _ms_to_knots(arr):
# robust conversion with pint, fallback if dtype unsupported
try:
return (
_ureg.Quantity(arr, _ureg.meter / _ureg.second).to(_ureg.knot)
).magnitude
except Exception:
return arr * 1.943844
def _m_to_mm(arr):
# robust conversion with pint, fallback if dtype unsupported
try:
return (_ureg.Quantity(arr, _ureg.meter).to(_ureg.millimeter)).magnitude
except Exception:
return arr * 1000
except Exception:
LOG.warning("pint not available; falling back hardcoded conversions")
def _k_to_c(arr):
return arr - 273.15
def _ms_to_knots(arr):
return arr * 1.943844
def _m_to_mm(arr):
return arr * 1000
def preprocess_field(param: str, state: dict):
"""
- Temperatures: K -> °C
- Wind speed: sqrt(u^2 + v^2)
- Precipitation: m -> mm
Returns: (field_array, units_override or None)
"""
fields = state["fields"]
# temperature variables
if param in ("T_2M", "TD_2M", "T", "TD"):
return _k_to_c(fields[param]), "°C"
# 10m wind speed (allow legacy 'uv' alias)
if param == "SP_10M":
u = fields["U_10M"]
v = fields["V_10M"]
return np.sqrt(u**2 + v**2), "m/s"
# wind speed from standard-level components
if param == "SP":
u = fields["U"]
v = fields["V"]
return np.sqrt(u**2 + v**2), "m/s"
if param == "TOT_PREC":
return np.maximum(_m_to_mm(fields[param]), 0), "mm"
# default: passthrough
return fields[param], None
return (preprocess_field,)
@app.cell
def _(
LOG,
StatePlotter,
accu,
args,
get_style,
get_projection,
outfn,
param,
preprocess_field,
region,
state,
DOMAINS,
ccrs,
):
# plot individual fields
plotter = StatePlotter(
state["longitudes"],
state["latitudes"],
outfn.parent,
)
if args.extent is not None:
_projection = get_projection(args.projection or "orthographic")
_extent = args.extent
else:
_projection = DOMAINS[region]["projection"]
_extent = DOMAINS[region]["extent"]
fig = plotter.init_geoaxes(
nrows=1,
ncols=1,
projection=_projection,
bbox=_extent,
name=region,
size=(6, 6),
)
subplot = fig.add_map(row=0, column=0)
# preprocess field (unit conversion, derived quantities)
field, units_override = preprocess_field(param, state)
plotter.plot_field(
subplot, field, **get_style(args.param, units_override, accu=accu)
)
subplot.ax.add_geometries(
state["lam_envelope"],
edgecolor="black",
facecolor="none",
crs=ccrs.PlateCarree(),
)
validtime = state["valid_time"].strftime("%Y%m%d%H%M")
# leadtime = int(state["lead_time"].total_seconds() // 3600)
fig.title(f"{param}, time: {validtime}")
fig.save(outfn, bbox_inches="tight", dpi=200)
LOG.info(f"saved: {outfn}")
return
if __name__ == "__main__":
app.run()