File size: 8,326 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
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
#!/usr/bin/env python3
"""
Convert njord's ensemble_forecasts.zarr to oceanbench ensemble format.

- state_feature → (variable, depth), depth matched to GLORYS (nearest)
- init_time → first_day_datetime (+1 day)
- lead_time → lead_day_index (0–9)
- ensemble_member kept (0–19), placed right after first_day_datetime
- stored as float32 (model output is fp32 upcast to fp64 in the input)

Dims:
  surface vars: (first_day_datetime, ensemble_member, lead_day_index, latitude, longitude)
  depth vars:   (first_day_datetime, ensemble_member, lead_day_index, depth, latitude, longitude)

Chunks: one (first_day_datetime, ensemble_member, depth) slice per chunk,
so the mean zarr's chunking with one extra member axis.

Each input chunk (one init_time x one member, all features) is read exactly
once and written into its region of the output. Already-written blocks are
skipped, so an interrupted run can simply be restarted with --resume.
"""

import argparse
import re
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path

import dask.array
import numpy as np
import xarray as xr
import zarr


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_ensemble_forecasts.zarr")

DTYPE = np.float32
FEATURE_PATTERN = re.compile(r"([a-z]+)(?:_(\d+)m)?")


def parse_arguments():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--input", type=Path, default=IN_PATH)
    parser.add_argument("--glorys", type=Path, default=GLORYS)
    parser.add_argument("--output", type=Path, default=OUT_PATH)
    parser.add_argument("--workers", type=int, default=8, help="parallel (init, member) blocks; ~3 GB RAM each")
    parser.add_argument("--resume", action="store_true", help="continue an existing output, skipping written blocks")
    parser.add_argument("--init-limit", type=int, default=None, help="only process the first N init times (testing)")
    return parser.parse_args()


def variable_layout(features, glorys_depths):
    """{var: (feature_indices, depths or None)}, depth vars sorted by depth."""
    grouped = {}
    for index, feature in enumerate(features):
        match = FEATURE_PATTERN.fullmatch(feature)
        variable, depth = match.group(1), match.group(2)
        grouped.setdefault(variable, []).append((index, None if depth is None else int(depth)))

    layout = {}
    for variable, items in grouped.items():
        if all(depth is None for _, depth in items):
            assert len(items) == 1, f"{variable}: multiple surface features"
            layout[variable] = ([items[0][0]], None)
        else:
            items = sorted((item for item in items if item[1] is not None), key=lambda item: item[1])
            nearest = [float(glorys_depths[np.abs(glorys_depths - depth).argmin()]) for _, depth in items]
            layout[variable] = ([index for index, _ in items], nearest)
    return layout


def build_template(source, layout, depths, first_day, lead_days):
    n_init, n_member = len(first_day), source.sizes["ensemble_member"]
    n_lead, n_lat, n_lon = len(lead_days), source.sizes["latitude"], source.sizes["longitude"]

    data_vars, encoding = {}, {}
    for variable, (_, variable_depths) in layout.items():
        if variable_depths is None:
            dims = ("first_day_datetime", "ensemble_member", "lead_day_index", "latitude", "longitude")
            shape = (n_init, n_member, n_lead, n_lat, n_lon)
            chunks = (1, 1, n_lead, n_lat, n_lon)
        else:
            dims = ("first_day_datetime", "ensemble_member", "lead_day_index", "depth", "latitude", "longitude")
            shape = (n_init, n_member, n_lead, len(variable_depths), n_lat, n_lon)
            chunks = (1, 1, n_lead, 1, n_lat, n_lon)
        data_vars[variable] = (dims, dask.array.full(shape, np.nan, dtype=DTYPE, chunks=chunks))
        encoding[variable] = {"chunks": chunks, "dtype": DTYPE, "_FillValue": np.nan}

    return xr.Dataset(
        data_vars,
        coords={
            "first_day_datetime": first_day,
            "ensemble_member": source.ensemble_member.values,
            "lead_day_index": lead_days,
            "depth": depths,
            "latitude": source.latitude.values,
            "longitude": source.longitude.values,
        },
    ), encoding


def block_is_written(output, init_index, member_index):
    # zarr v2, "." separator: a missing chunk file means the block is still NaN
    return (output / "zos" / f"{init_index}.{member_index}.0.0.0").exists()


def convert_block(prediction, layout, output, init_index, member_index):
    # (lead_time, state_feature, longitude, latitude) → numpy, read once
    block = prediction.isel(init_time=init_index, ensemble_member=member_index).values

    data_vars = {}
    for variable, (indices, variable_depths) in layout.items():
        values = block[:, indices]  # (lead, n, lon, lat)
        values = np.ascontiguousarray(values.transpose(0, 1, 3, 2), dtype=DTYPE)  # (lead, n, lat, lon)
        if variable_depths is None:
            data_vars[variable] = (
                ("first_day_datetime", "ensemble_member", "lead_day_index", "latitude", "longitude"),
                values[None, None, :, 0],
            )
        else:
            data_vars[variable] = (
                ("first_day_datetime", "ensemble_member", "lead_day_index", "depth", "latitude", "longitude"),
                values[None, None],
            )

    xr.Dataset(data_vars).to_zarr(
        output,
        region={
            "first_day_datetime": slice(init_index, init_index + 1),
            "ensemble_member": slice(member_index, member_index + 1),
        },
    )
    return init_index, member_index


def main():
    arguments = parse_arguments()

    print("Loading datasets...")
    source = xr.open_zarr(arguments.input)
    prediction = source["prediction"]
    glorys_depths = xr.open_zarr(arguments.glorys).depth.values

    features = [str(feature) for feature in source.state_feature.values]
    layout = variable_layout(features, glorys_depths)
    depth_lists = {tuple(depths) for _, depths in layout.values() if depths is not None}
    assert len(depth_lists) == 1, f"depth vars disagree on levels: {depth_lists}"
    depths = list(depth_lists.pop())
    print("Variables:", {variable: depths_ for variable, (_, depths_) in layout.items()})
    print("Depths:", depths)

    first_day = source.init_time.values + np.timedelta64(1, "D")
    lead_days = (source.lead_time.values / np.timedelta64(1, "D")).astype(int) - 1

    if arguments.resume and arguments.output.exists():
        print(f"Resuming {arguments.output}")
    else:
        print(f"Writing metadata to {arguments.output}")
        template, encoding = build_template(source, layout, depths, first_day, lead_days)
        template.to_zarr(arguments.output, mode="w-", compute=False, encoding=encoding)

    n_init = len(first_day) if arguments.init_limit is None else arguments.init_limit
    blocks = [
        (init_index, member_index)
        for init_index in range(n_init)
        for member_index in range(source.sizes["ensemble_member"])
        if not block_is_written(arguments.output, init_index, member_index)
    ]
    print(f"{len(blocks)} blocks to write with {arguments.workers} workers")

    start = time.time()
    with ThreadPoolExecutor(arguments.workers) as executor:
        futures = [
            executor.submit(convert_block, prediction, layout, arguments.output, init_index, member_index)
            for init_index, member_index in blocks
        ]
        for done, future in enumerate(as_completed(futures), 1):
            init_index, member_index = future.result()
            elapsed = time.time() - start
            remaining = elapsed / done * (len(blocks) - done)
            print(
                f"[{done}/{len(blocks)}] init {init_index} member {member_index} "
                f"({elapsed / 60:.1f} min elapsed, ~{remaining / 60:.0f} min left)",
                flush=True,
            )

    print("Consolidating metadata...")
    zarr.consolidate_metadata(str(arguments.output))
    print("Done.")


if __name__ == "__main__":
    main()