|
| 1 | +# /// script |
| 2 | +# requires-python = ">=3.11" |
| 3 | +# dependencies = [ |
| 4 | +# "xarray-sql", |
| 5 | +# "xarray", |
| 6 | +# "gcsfs", |
| 7 | +# "zarr>=3", |
| 8 | +# ] |
| 9 | +# |
| 10 | +# [tool.uv.sources] |
| 11 | +# xarray-sql = { path = "../../", editable = true } |
| 12 | +# /// |
| 13 | +"""Diurnal climatology — the "rechunk + grouped reduction" that is a GROUP BY. |
| 14 | +
|
| 15 | +A *climatology* is the average value for each time-of-cycle, computed |
| 16 | +independently at every location: "what is the typical temperature here at |
| 17 | +06:00?" In the array paradigm (and in the coiled/benchmarks #1545 write-up) |
| 18 | +this is the canonical painful workload — load native Zarr chunks, *rechunk* to |
| 19 | +put all of time in one chunk ("pencils"), run a grouped reduction over the |
| 20 | +calendar, then rechunk back to "pancakes" for output. |
| 21 | +
|
| 22 | +The rechunking exists only to serve the array layout. The *operation* is:: |
| 23 | +
|
| 24 | + SELECT latitude, longitude, hour_of_day, AVG("2m_temperature") |
| 25 | + GROUP BY latitude, longitude, hour_of_day |
| 26 | +
|
| 27 | +Group by location and time-of-cycle, average the rest — the same answer as |
| 28 | +``da.groupby("time.hour").mean()``. ERA5 is hourly, so grouping by hour of day |
| 29 | +gives a clean 24-bin **diurnal cycle**, one sample per day in the window. |
| 30 | +
|
| 31 | +We register the full ARCO-ERA5 archive as a lazy table, but the climatology here |
| 32 | +is computed over a *bounded window* — a few summer days over a CONUS-ish box. The |
| 33 | +``WHERE`` prunes the read, so the query touches only ``2m_temperature`` over that |
| 34 | +window and never scans the rest of the archive. The point is not that we reduce |
| 35 | +the whole record; it is that you can aim a query at a multi-decade archive and pay |
| 36 | +only for the slice it asks for. |
| 37 | +""" |
| 38 | + |
| 39 | +from __future__ import annotations |
| 40 | + |
| 41 | +import datetime |
| 42 | + |
| 43 | +import xarray as xr |
| 44 | + |
| 45 | +import xarray_sql as xql |
| 46 | + |
| 47 | +from _harness import ( |
| 48 | + CaseSkipped, |
| 49 | + assert_grid_close, |
| 50 | + measured, |
| 51 | + run_case, |
| 52 | + show_result, |
| 53 | + show_sql, |
| 54 | + timed, |
| 55 | +) |
| 56 | + |
| 57 | +_URL = "gs://gcp-public-data-arco-era5/ar/full_37-1h-0p25deg-chunk-1.zarr-v3" |
| 58 | +# A few days over a CONUS-ish box (ERA5 latitude descends; lon is 0–360°E). |
| 59 | +_START, _END = datetime.datetime(2020, 6, 1), datetime.datetime(2020, 6, 3, 23) |
| 60 | +_LAT_N, _LAT_S = 50.0, 25.0 |
| 61 | +_LON_W, _LON_E = 235.0, 290.0 |
| 62 | +_PARAMS = { |
| 63 | + "start": _START, |
| 64 | + "end": _END, |
| 65 | + "lat_s": _LAT_S, |
| 66 | + "lat_n": _LAT_N, |
| 67 | + "lon_w": _LON_W, |
| 68 | + "lon_e": _LON_E, |
| 69 | +} |
| 70 | + |
| 71 | + |
| 72 | +def main() -> None: |
| 73 | + # Open the full ARCO-ERA5 archive lazily — no data is read here. ERA5 mixes |
| 74 | + # surface (time, lat, lon) and atmospheric (… level …) variables, so register |
| 75 | + # it as two tables under an ``era5`` schema; the query below touches only the |
| 76 | + # surface table's 2m_temperature. |
| 77 | + try: |
| 78 | + import gcsfs # noqa: F401 — required by the gs:// protocol |
| 79 | + |
| 80 | + ds = xr.open_zarr(_URL, chunks=None, storage_options={"token": "anon"}) |
| 81 | + except Exception as exc: # noqa: BLE001 — any failure → skip, not crash |
| 82 | + raise CaseSkipped(f"ARCO-ERA5 unavailable ({exc})") from exc |
| 83 | + |
| 84 | + ctx = xql.XarrayContext() |
| 85 | + with timed("register full ERA5 (lazy)"): |
| 86 | + ctx.from_dataset( |
| 87 | + "era5", |
| 88 | + ds, |
| 89 | + chunks={"time": 6}, |
| 90 | + table_names={ |
| 91 | + ("time", "latitude", "longitude"): "surface", |
| 92 | + ("time", "level", "latitude", "longitude"): "atmosphere", |
| 93 | + }, |
| 94 | + ) |
| 95 | + |
| 96 | + sql = """ |
| 97 | + SELECT latitude, |
| 98 | + longitude, |
| 99 | + date_part('hour', time) AS hour, |
| 100 | + AVG("2m_temperature") - 273.15 AS clim_c |
| 101 | + FROM era5.surface |
| 102 | + WHERE time BETWEEN $start AND $end |
| 103 | + AND latitude BETWEEN $lat_s AND $lat_n |
| 104 | + AND longitude BETWEEN $lon_w AND $lon_e |
| 105 | + GROUP BY latitude, longitude, date_part('hour', time) |
| 106 | + ORDER BY latitude DESC, longitude, hour |
| 107 | + """ |
| 108 | + show_sql(sql) |
| 109 | + |
| 110 | + # A climatology is a gridded product: round-trip the result back to an |
| 111 | + # xarray Dataset keyed by (latitude, longitude, hour) — how it is used. |
| 112 | + for _ in measured("SQL diurnal climatology (lazy read)"): |
| 113 | + got = ctx.sql(sql, param_values=_PARAMS).to_dataset( |
| 114 | + dims=["latitude", "longitude", "hour"] |
| 115 | + ) |
| 116 | + |
| 117 | + # Array reference: the textbook groupby-over-the-cycle reduction, in °C — |
| 118 | + # the same lazy window, materialized only on demand. |
| 119 | + for _ in measured("xarray reference"): |
| 120 | + window = ds["2m_temperature"].sel( |
| 121 | + time=slice(_START, _END), |
| 122 | + latitude=slice(_LAT_N, _LAT_S), |
| 123 | + longitude=slice(_LON_W, _LON_E), |
| 124 | + ) |
| 125 | + ref = window.groupby("time.hour").mean("time") - 273.15 |
| 126 | + |
| 127 | + assert_grid_close( |
| 128 | + "diurnal climatology (°C)", got.clim_c, ref, rtol=1e-4, atol=1e-2 |
| 129 | + ) |
| 130 | + |
| 131 | + show_result(got) |
| 132 | + |
| 133 | + |
| 134 | +if __name__ == "__main__": |
| 135 | + raise SystemExit( |
| 136 | + run_case(main, "Climatology: GROUP BY lat, lon, hour (ARCO-ERA5)") |
| 137 | + ) |
0 commit comments