Debian Codegraph @

dynamicgribchunking.ipynb

raw
1 {
2 "cells": [
3 {
4 "cell_type": "markdown",
5 "metadata": {
6 "id": "n8nQijCi9wVu"
7 },
8 "source": [
9 "# GRIB2 NWP Archive aggretation using .idx files\n",
10 "\n",
11 "Work with NODD GFS data on GCP (theoretically works with AWS as well)\n",
12 "\n",
13 "1) Demonstrate building a DataTree, Index File mapping and Static Metdata data file. Use the mapping to rapidly build a on month dataset.\n",
14 "2) Demonstrate using zarr chunk_getitems hack to parallelize getting a timeseries\n",
15 " "
16 ]
17 },
18 {
19 "cell_type": "markdown",
20 "metadata": {
21 "id": "326f3vGe_HHb"
22 },
23 "source": [
24 "## Import some stuff..."
25 ]
26 },
27 {
28 "cell_type": "code",
29 "execution_count": null,
30 "metadata": {
31 "id": "3DQi8Hvg_GSD"
32 },
33 "outputs": [],
34 "source": [
35 "%load_ext autoreload\n",
36 "%autoreload 2\n",
37 "\n",
38 "import logging\n",
39 "import importlib\n",
40 "\n",
41 "importlib.reload(logging)\n",
42 "logging.basicConfig(\n",
43 " format=\"%(asctime)s.%(msecs)03dZ %(processName)s %(threadName)s %(levelname)s:%(name)s:%(message)s\",\n",
44 " datefmt=\"%Y-%m-%dT%H:%M:%S\",\n",
45 " level=logging.WARNING,\n",
46 ")\n",
47 "\n",
48 "logger = logging.getLogger(\"juypter\")"
49 ]
50 },
51 {
52 "cell_type": "code",
53 "execution_count": null,
54 "metadata": {
55 "id": "NzO2IOsm_MfL"
56 },
57 "outputs": [],
58 "source": [
59 "import datetime\n",
60 "import copy\n",
61 "import xarray as xr\n",
62 "import numpy as np\n",
63 "import pandas as pd\n",
64 "import fsspec\n",
65 "import kerchunk\n",
66 "from kerchunk.grib2 import (\n",
67 " grib_tree, scan_grib, extract_datatree_chunk_index, strip_datavar_chunks, \n",
68 " reinflate_grib_store, AggregationType, read_store, write_store, parse_grib_idx,\n",
69 " build_idx_grib_mapping, map_from_index\n",
70 ")\n",
71 "import gcsfs\n",
72 "\n",
73 "pd.set_option('display.max_columns', None)\n"
74 ]
75 },
76 {
77 "cell_type": "markdown",
78 "metadata": {
79 "id": "ueTGv6_g6plE"
80 },
81 "source": [
82 "## Extract the zarr store metadata\n",
83 "\n",
84 "\n",
85 "Pick a file, any file... Must be on GCS so that coords use the same file store as the data vars"
86 ]
87 },
88 {
89 "cell_type": "code",
90 "execution_count": null,
91 "metadata": {
92 "colab": {
93 "base_uri": "https://localhost:8080/"
94 },
95 "id": "TvOmUkr-6plE",
96 "outputId": "e61f1f20-0c43-40bb-ca6a-4c5076e76a9f"
97 },
98 "outputs": [],
99 "source": [
100 "# Pick two files to build a grib_tree with the correct dimensions\n",
101 "gfs_files = [\n",
102 " \"gs://global-forecast-system/gfs.20230928/00/atmos/gfs.t00z.pgrb2.0p25.f000\",\n",
103 " \"gs://global-forecast-system/gfs.20230928/00/atmos/gfs.t00z.pgrb2.0p25.f001\"\n",
104 "]\n",
105 "\n",
106 "# This operation reads two of the large Grib2 files from GCS\n",
107 "# scan_grib extracts the zarr kerchunk metadata for each individual grib message\n",
108 "# grib_tree builds a zarr/xarray compatible hierarchical view of the dataset\n",
109 "gfs_grib_tree_store = grib_tree([group for f in gfs_files for group in scan_grib(f)])\n",
110 "# it is slow even in parallel because it requires a huge amount of IO\n"
111 ]
112 },
113 {
114 "cell_type": "code",
115 "execution_count": null,
116 "metadata": {
117 "colab": {
118 "base_uri": "https://localhost:8080/",
119 "height": 186
120 },
121 "id": "IEOG_v8O5KVC",
122 "outputId": "4b8e9b14-efc2-440e-9953-bd15df58bcc3"
123 },
124 "outputs": [],
125 "source": [
126 "# The grib_tree can be opened directly using either zarr or xarray datatree\n",
127 "# But this is too slow to build big aggregations\n",
128 "gfs_dt = xr.open_datatree(fsspec.filesystem(\"reference\", fo=gfs_grib_tree_store).get_mapper(\"\"), engine=\"zarr\", consolidated=False)\n",
129 "gfs_dt\n"
130 ]
131 },
132 {
133 "cell_type": "markdown",
134 "metadata": {
135 "id": "R0Ew4zOIEoIw"
136 },
137 "source": [
138 "## Separating static metadata from the chunk indexes"
139 ]
140 },
141 {
142 "cell_type": "code",
143 "execution_count": null,
144 "metadata": {
145 "colab": {
146 "base_uri": "https://localhost:8080/",
147 "height": 423
148 },
149 "id": "ukcrJ9fi5NSS",
150 "outputId": "0c9b6d89-883c-4fad-d891-6c62973c115f"
151 },
152 "outputs": [],
153 "source": [
154 "# The key metadata associated with each grib message can be extracted into a table\n",
155 "gfs_kind = extract_datatree_chunk_index(gfs_dt, gfs_grib_tree_store, grib=True)\n",
156 "gfs_kind"
157 ]
158 },
159 {
160 "cell_type": "code",
161 "execution_count": null,
162 "metadata": {
163 "colab": {
164 "base_uri": "https://localhost:8080/"
165 },
166 "id": "hX7Hh3aB6plF",
167 "outputId": "ede04c84-cc23-4260-f8c2-6973f2ee56bc"
168 },
169 "outputs": [],
170 "source": [
171 "# While the static zarr metadata associated with the dataset can be seperated - created once.\n",
172 "deflated_gfs_grib_tree_store = copy.deepcopy(gfs_grib_tree_store)\n",
173 "strip_datavar_chunks(deflated_gfs_grib_tree_store)\n",
174 "\n",
175 "write_store(\"./\", deflated_gfs_grib_tree_store)\n",
176 "\n",
177 "print(\"Original references: \", len(gfs_grib_tree_store[\"refs\"]))\n",
178 "print(\"Stripped references: \", len(deflated_gfs_grib_tree_store[\"refs\"]))\n"
179 ]
180 },
181 {
182 "cell_type": "markdown",
183 "metadata": {
184 "id": "WlbvPP4G6plF"
185 },
186 "source": [
187 "## Building it faster\n",
188 "\n",
189 "Okay that was fun - I promise you can recombine these pieces but it still takes the same amount of time to run scan_grib.\n",
190 "\n",
191 "The k(erchunk) index data looks a lot like the idx files that are present for every grib file in NODD's GCS archive though...\n",
192 "\n",
193 "\n",
194 "```\n",
195 "1:0:d=2023092800:PRMSL:mean sea level:1 hour fcst:\n",
196 "2:990253:d=2023092800:CLWMR:1 hybrid level:1 hour fcst:\n",
197 "3:1079774:d=2023092800:ICMR:1 hybrid level:1 hour fcst:\n",
198 "4:1332540:d=2023092800:RWMR:1 hybrid level:1 hour fcst:\n",
199 "5:1558027:d=2023092800:SNMR:1 hybrid level:1 hour fcst:\n",
200 "6:1638489:d=2023092800:GRLE:1 hybrid level:1 hour fcst:\n",
201 "7:1673516:d=2023092800:REFD:1 hybrid level:1 hour fcst:\n",
202 "8:2471710:d=2023092800:REFD:2 hybrid level:1 hour fcst:\n",
203 "9:3270627:d=2023092800:REFC:entire atmosphere:1 hour fcst:\n",
204 "10:4144435:d=2023092800:VIS:surface:1 hour fcst:\n",
205 "```\n",
206 "\n",
207 "But the metadata isn't quiet the same... they have mangled the attributes in the : seperated attributes."
208 ]
209 },
210 {
211 "cell_type": "code",
212 "execution_count": null,
213 "metadata": {
214 "colab": {
215 "base_uri": "https://localhost:8080/",
216 "height": 628
217 },
218 "id": "XGNMVeWrHzJD",
219 "outputId": "2c270e66-38ef-4acd-bc8f-62e3b1cd4e2b"
220 },
221 "outputs": [],
222 "source": [
223 "# We can pull this out into a dataframe, that starts to look a bit like what we got above extracted from the actual grib files\n",
224 "# But this method runs in under a second reading a file that is less than 100k\n",
225 "idxdf = parse_grib_idx(\n",
226 " basename=\"gs://global-forecast-system/gfs.20230901/00/atmos/gfs.t00z.pgrb2.0p25.f006\"\n",
227 ")\n",
228 "idxdf"
229 ]
230 },
231 {
232 "cell_type": "code",
233 "execution_count": null,
234 "metadata": {
235 "colab": {
236 "base_uri": "https://localhost:8080/",
237 "height": 275
238 },
239 "id": "leAb3jXChBVQ",
240 "outputId": "d6d842d0-e575-4c29-cd72-a4f999a946ed"
241 },
242 "outputs": [],
243 "source": [
244 "# Unfortunately, some accumulation variables have duplicate attributes making them\n",
245 "# indesinguishable from the IDX file\n",
246 "idxdf.loc[idxdf['attrs'].duplicated(keep=False), :]\n"
247 ]
248 },
249 {
250 "cell_type": "code",
251 "execution_count": null,
252 "metadata": {
253 "colab": {
254 "base_uri": "https://localhost:8080/",
255 "height": 943
256 },
257 "id": "6ws0cK3gHzMK",
258 "outputId": "62e74a5a-86db-4a71-93d8-120515108b2f"
259 },
260 "outputs": [],
261 "source": [
262 "# What we need is a mapping from our grib/zarr metadata to the attributes in the idx files\n",
263 "# They are unique for each time horizon e.g. you need to build a unique mapping for the 1 hour\n",
264 "# forecast, the 2 hour forecast... the 48 hour forecast.\n",
265 "\n",
266 "# let's make one for the 6 hour horizon. This requires reading both the grib and the idx file,\n",
267 "# mapping the data for each grib message in order\n",
268 "mapping = build_idx_grib_mapping(\n",
269 " basename=\"gs://global-forecast-system/gfs.20230928/00/atmos/gfs.t00z.pgrb2.0p25.f006\",\n",
270 ")\n",
271 "mapping"
272 ]
273 },
274 {
275 "cell_type": "code",
276 "execution_count": null,
277 "metadata": {
278 "colab": {
279 "base_uri": "https://localhost:8080/",
280 "height": 614
281 },
282 "id": "CzU9fWn5HzPS",
283 "outputId": "770783d1-846a-47ce-c01f-02eea30939ef"
284 },
285 "outputs": [],
286 "source": [
287 "# Now if we parse the RunTime from the idx file name `gfs.20230901/00/`\n",
288 "# We can build a fully compatible k_index\n",
289 "mapped_index = map_from_index(\n",
290 " pd.Timestamp(\"2023-09-01T00\"),\n",
291 " mapping.loc[~mapping[\"attrs\"].duplicated(keep=\"first\"), :],\n",
292 " idxdf.loc[~idxdf[\"attrs\"].duplicated(keep=\"first\"), :]\n",
293 ")\n",
294 "mapped_index"
295 ]
296 },
297 {
298 "cell_type": "code",
299 "execution_count": null,
300 "metadata": {},
301 "outputs": [],
302 "source": [
303 "mapping.loc[mapping.varname == \"sdswrf\"]"
304 ]
305 },
306 {
307 "cell_type": "code",
308 "execution_count": null,
309 "metadata": {
310 "colab": {
311 "base_uri": "https://localhost:8080/",
312 "height": 770
313 },
314 "id": "Ny9xKXjP7n57",
315 "outputId": "15a5793b-a9df-4065-a403-1a35aa5c7cf8"
316 },
317 "outputs": [],
318 "source": [
319 "mapped_index_list = []\n",
320 "\n",
321 "deduped_mapping = mapping.loc[~mapping[\"attrs\"].duplicated(keep=\"first\"), :]\n",
322 "for date in pd.date_range(\"2023-09-01\", \"2023-09-30\"):\n",
323 " for runtime in range(0,24,6):\n",
324 " horizon=6\n",
325 " fname=f\"gs://global-forecast-system/gfs.{date.strftime('%Y%m%d')}/{runtime:02}/atmos/gfs.t{runtime:02}z.pgrb2.0p25.f{horizon:03}\"\n",
326 "\n",
327 " idxdf = parse_grib_idx(\n",
328 " basename=fname\n",
329 " )\n",
330 "\n",
331 " mapped_index = map_from_index(\n",
332 " pd.Timestamp( date + datetime.timedelta(hours=runtime)),\n",
333 " deduped_mapping,\n",
334 " idxdf.loc[~idxdf[\"attrs\"].duplicated(keep=\"first\"), :],\n",
335 " )\n",
336 " mapped_index_list.append(mapped_index)\n",
337 "\n",
338 "gfs_kind = pd.concat(mapped_index_list)\n",
339 "gfs_kind\n"
340 ]
341 },
342 {
343 "cell_type": "markdown",
344 "metadata": {
345 "id": "VF60ETYemD6N"
346 },
347 "source": [
348 "## We just aggregated a 120 GFS grib files in 18 seconds!\n",
349 "\n",
350 "Lets build it back into a data tree!\n",
351 "\n",
352 "The reinflate_grib_store interface is pretty opaque but allows building any slice of an FMRC. A good area for future improvement, but for now, since\n",
353 "we have just a single 6 hour horizon slice let's build that..."
354 ]
355 },
356 {
357 "cell_type": "code",
358 "execution_count": null,
359 "metadata": {
360 "colab": {
361 "base_uri": "https://localhost:8080/"
362 },
363 "id": "IW1M7go56plF",
364 "outputId": "17c2fa69-81f8-4d21-f260-4233e902a6ac"
365 },
366 "outputs": [],
367 "source": [
368 "axes = [\n",
369 " pd.Index(\n",
370 " [\n",
371 " pd.timedelta_range(start=\"0 hours\", end=\"6 hours\", freq=\"6h\", closed=\"right\", name=\"6 hour\"),\n",
372 " ],\n",
373 " name=\"step\"\n",
374 " ),\n",
375 " pd.date_range(\"2023-09-01T06:00\", \"2023-10T00:00\", freq=\"360min\", name=\"valid_time\")\n",
376 "]\n",
377 "axes"
378 ]
379 },
380 {
381 "cell_type": "code",
382 "execution_count": null,
383 "metadata": {
384 "colab": {
385 "base_uri": "https://localhost:8080/"
386 },
387 "id": "_M9oH4TJ6plG",
388 "outputId": "c6043655-7c8b-4981-cb5f-f5d6a903315b"
389 },
390 "outputs": [],
391 "source": [
392 "# It is fast to rebuild the datatree - but lets pull out two varables to look at...\n",
393 "\n",
394 "# If you skipped building the deflated store, read it here.\n",
395 "#deflated_gfs_grib_tree_store = read_store(\"./\")\n",
396 "\n",
397 "gfs_store = reinflate_grib_store(\n",
398 " axes=axes,\n",
399 " aggregation_type=AggregationType.HORIZON,\n",
400 " chunk_index=gfs_kind.loc[gfs_kind.varname.isin([\"sdswrf\", \"t2m\"])],\n",
401 " zarr_ref_store=deflated_gfs_grib_tree_store\n",
402 ")"
403 ]
404 },
405 {
406 "cell_type": "code",
407 "execution_count": null,
408 "metadata": {
409 "colab": {
410 "base_uri": "https://localhost:8080/",
411 "height": 1000
412 },
413 "id": "Eeml5x_d6plG",
414 "outputId": "19052d52-3ca5-4d1e-9a8a-a0608381b342"
415 },
416 "outputs": [],
417 "source": [
418 "gfs_dt = xr.open_datatree(fsspec.filesystem(\"reference\", fo=gfs_store).get_mapper(\"\"), engine=\"zarr\", consolidated=False)\n",
419 "gfs_dt"
420 ]
421 },
422 {
423 "cell_type": "code",
424 "execution_count": null,
425 "metadata": {
426 "colab": {
427 "base_uri": "https://localhost:8080/",
428 "height": 296
429 },
430 "id": "MFCPjIJnpKh4",
431 "outputId": "98c66ef2-8034-4b5e-f239-65e68c679e97"
432 },
433 "outputs": [],
434 "source": [
435 "# Reading the data - especially extracting point time series isn't any faster once you have\n",
436 "# the xarray datatree. This is just a much faster way of building the aggregations than\n",
437 "# directly running scan_grib over all the data first.\n",
438 "gfs_dt.sdswrf.avg.surface.sdswrf[0,0:10,300,400].compute()"
439 ]
440 },
441 {
442 "cell_type": "code",
443 "execution_count": null,
444 "metadata": {
445 "scrolled": true
446 },
447 "outputs": [],
448 "source": [
449 "gfs_dt.t2m.instant.heightAboveGround.t2m[0,0:10,300,400].compute()"
450 ]
451 },
452 {
453 "cell_type": "code",
454 "execution_count": null,
455 "metadata": {
456 "colab": {
457 "base_uri": "https://localhost:8080/",
458 "height": 735
459 },
460 "id": "PSYb4OasbTKG",
461 "outputId": "b4031b98-24fa-451d-e460-452dfad3695a"
462 },
463 "outputs": [],
464 "source": [
465 "gfs_dt.sdswrf.avg.surface.sdswrf[0,1,:,:].plot(figsize=(12,8))"
466 ]
467 },
468 {
469 "cell_type": "code",
470 "execution_count": null,
471 "metadata": {
472 "colab": {
473 "base_uri": "https://localhost:8080/",
474 "height": 735
475 },
476 "id": "7zAfk1IshXMH",
477 "outputId": "640f0354-d7f0-4a5f-f928-1ad1d0fcd481"
478 },
479 "outputs": [],
480 "source": [
481 "gfs_dt.sdswrf.avg.surface.sdswrf[0,2,:,:].plot(figsize=(12,8))"
482 ]
483 },
484 {
485 "cell_type": "code",
486 "execution_count": null,
487 "metadata": {
488 "colab": {
489 "base_uri": "https://localhost:8080/",
490 "height": 735
491 },
492 "id": "T3gM0XLXhoZp",
493 "outputId": "c37186b5-dbb1-4c98-c6e1-a787a5b85dae"
494 },
495 "outputs": [],
496 "source": [
497 "gfs_dt.sdswrf.avg.surface.sdswrf[0,3,:,:].plot(figsize=(12,8))"
498 ]
499 },
500 {
501 "cell_type": "markdown",
502 "metadata": {},
503 "source": [
504 "# Timeseries"
505 ]
506 },
507 {
508 "cell_type": "code",
509 "execution_count": null,
510 "metadata": {},
511 "outputs": [],
512 "source": [
513 "# from joblib import parallel_config\n",
514 "# with parallel_config(n_jobs=8):\n",
515 " #res = gfs_dt.dswrf.avg.surface.dswrf.interp(longitude=[320.5, 300.2], latitude=[20.6, 45.7], method=\"linear\")\n",
516 " \n"
517 ]
518 },
519 {
520 "cell_type": "code",
521 "execution_count": null,
522 "metadata": {},
523 "outputs": [],
524 "source": [
525 "res = gfs_dt.sdswrf.avg.surface.sdswrf.interp(longitude=[320.5], latitude=[20.6], method=\"linear\")\n",
526 "res.plot()\n"
527 ]
528 },
529 {
530 "cell_type": "code",
531 "execution_count": null,
532 "metadata": {},
533 "outputs": [],
534 "source": []
535 }
536 ],
537 "metadata": {
538 "colab": {
539 "authorship_tag": "ABX9TyPQShGkdrEd0WnSDM4SoI/N",
540 "include_colab_link": true,
541 "provenance": []
542 },
543 "kernelspec": {
544 "display_name": "Python 3 (ipykernel)",
545 "language": "python",
546 "name": "python3"
547 },
548 "language_info": {
549 "codemirror_mode": {
550 "name": "ipython",
551 "version": 3
552 },
553 "file_extension": ".py",
554 "mimetype": "text/x-python",
555 "name": "python",
556 "nbconvert_exporter": "python",
557 "pygments_lexer": "ipython3",
558 "version": "3.10.14"
559 }
560 },
561 "nbformat": 4,
562 "nbformat_minor": 4
563 }