njord-forecasts / prepare_forecasts.py
deinal's picture
Add files using upload-large-folder tool
b4b7048 verified
Raw History Blame Contribute Delete
3.66 kB
#!/usr/bin/env python3
"""
Convert njord's ensemble_forecasts.zarr to oceanbench format.
- state_feature → (variable, depth)
- depth matched to GLORYS (nearest)
- init_time → first_day_datetime (+1 day)
- lead_time → lead_day_index (0–9)
"""
from pathlib import Path
import re
import numpy as np
import xarray as xr
import dask
from dask.diagnostics import ProgressBar
# paths
IN_PATH = Path("wandb/run-20260427_093242-jzw1ec8r/files/ensemble_forecasts.zarr")
GLORYS = Path("../ocean-data/data/glorys_1_4.zarr")
OUT_PATH = Path("../oceanbench/njord_forecasts.zarr")
print("Loading datasets...")
ds = xr.open_zarr(IN_PATH)
ds = ds.drop_vars("target")
ds = ds.mean("ensemble_member")
glorys = xr.open_zarr(GLORYS)
glorys_depths = glorys.depth.values
print("Parsing state_feature...")
features = ds.state_feature.values
pattern = re.compile(r"([a-z]+)(?:_(\d+)m)?")
parsed = []
for f in features:
m = pattern.match(f)
var = m.group(1)
depth = m.group(2)
depth = int(depth) if depth is not None else None
parsed.append((f, var, depth))
# group by variable
vars_dict = {}
for f, var, depth in parsed:
vars_dict.setdefault(var, []).append((f, depth))
# nearest depth
def nearest_depth(d):
idx = np.abs(glorys_depths - d).argmin()
return float(glorys_depths[idx])
print("Building dataset...")
out = {}
for var, items in vars_dict.items():
print(f"Processing {var}...")
# sort by depth (None first)
items = sorted(items, key=lambda x: (-1 if x[1] is None else x[1]))
if all(d is None for _, d in items):
# e.g. zos, siconc, etc.
da = ds["prediction"].sel(state_feature=[f for f, _ in items])
# remove state_feature dim
da = da.squeeze("state_feature", drop=True)
# Ensure the coordinate is completely dropped just in case
if "state_feature" in da.coords:
da = da.drop_vars("state_feature")
out[var] = da
else:
# variables with depth
depths = []
arrays = []
for f, d in items:
if d is None:
continue
new_d = nearest_depth(d)
depths.append(new_d)
# Drop the state_feature coordinate immediately after selecting
arr = ds["prediction"].sel(state_feature=f).drop_vars("state_feature")
arrays.append(arr)
# stack into depth dimension
da = xr.concat(arrays, dim="depth")
da = da.assign_coords(depth=("depth", depths))
out[var] = da
ds_out = xr.Dataset(out)
print("Fixing coordinates...")
# init_time → first_day_datetime (+1 day)
ds_out = ds_out.assign_coords(
first_day_datetime = ds.init_time + np.timedelta64(1, "D")
).swap_dims({"init_time": "first_day_datetime"}).drop_vars("init_time")
# lead_time → lead_day_index
# added .values to extract the underlying numpy array
lead_days = (ds.lead_time.values / np.timedelta64(1, "D")).astype(int) - 1
ds_out = ds_out.assign_coords(
lead_day_index=("lead_time", lead_days)
).swap_dims({"lead_time": "lead_day_index"}).drop_vars("lead_time")
# reorder dims
for var in ds_out.data_vars:
dims = list(ds_out[var].dims)
# enforce standard order
new_order = [
"first_day_datetime",
"lead_day_index",
]
if "depth" in dims:
new_order.append("depth")
new_order += ["latitude", "longitude"]
ds_out[var] = ds_out[var].transpose(*new_order)
# save to zarr
print(f"Saving to {OUT_PATH} ...")
with dask.config.set(scheduler="threads", num_workers=10):
with ProgressBar():
ds_out.to_zarr(OUT_PATH, mode="w")
print("Done.")