File size: 3,658 Bytes
b4b7048 | 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 | #!/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.") |