File size: 24,905 Bytes
a82ed15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
from __future__ import annotations

import argparse
import hashlib
import json
import math
import random
import shutil
import struct
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Annotated, Any

import pyarrow as pa
import rumi
import taco
from pydantic import BaseModel, Field

ROOT = Path(__file__).resolve().parents[1]
DATA_ROOT = ROOT / "data"
MANIFEST_PATH = ROOT / "manifest.json"
CHECKSUMS_PATH = ROOT / "checksums.sha256"
LOCK_PATH = ROOT / "source-lock.json"
GENERATOR_SEED = 20260909
SPLITS = ("train", "train", "train", "validation", "test", "test")
TimestampUTC = Annotated[datetime, pa.timestamp("us", tz="UTC")]


class FixtureSample(BaseModel):
    case_id: str = Field(description="Logical fixture case identifier")
    sample_key: str = Field(description="Stable sample key inside the fixture case")
    synthetic: bool = Field(description="Whether semantic metadata is synthetic")
    seed: int = Field(description="Deterministic seed used for synthetic metadata")


class RumiAsset(BaseModel):
    header: bytes = Field(description="External Rumi header required for stateless reads")
    source_fixture: str = Field(description="Name of the pinned upstream Rumi fixture")
    data_sha256: str = Field(description="SHA-256 checksum of the Rumi container")
    header_sha256: str = Field(description="SHA-256 checksum of the external Rumi header")
    array_sha256: str = Field(description="SHA-256 checksum of the decoded logical array")
    shape: list[int] = Field(description="Logical Rumi array shape")
    dtype: str = Field(description="Logical Rumi array data type")
    frame_layout: str = Field(description="Rumi frame layout")


class GeoPoint(BaseModel):
    longitude: float = Field(ge=-180, le=180, description="Synthetic longitude in degrees")
    latitude: float = Field(ge=-90, le=90, description="Synthetic latitude in degrees")
    synthetic: bool = Field(description="Whether the point is synthetic")


class TemporalInfo(BaseModel):
    time_start: TimestampUTC = Field(description="Synthetic interval start")
    time_end: TimestampUTC | None = Field(default=None, description="Synthetic interval end")
    synthetic: bool = Field(description="Whether the temporal metadata is synthetic")


@dataclass(frozen=True)
class SourceFixture:
    name: str
    data: Path
    header: Path
    manifest: dict[str, Any]

    def metadata(self) -> RumiAsset:
        return RumiAsset(
            header=self.header.read_bytes(),
            source_fixture=self.name,
            data_sha256=self.manifest["data_sha256"],
            header_sha256=self.manifest["header_sha256"],
            array_sha256=self.manifest["array_sha256"],
            shape=self.manifest["shape"],
            dtype=self.manifest["dtype"],
            frame_layout=self.manifest["frame_layout"],
        )


@dataclass(frozen=True)
class AssetRecipe:
    path: str | None
    source: str


@dataclass(frozen=True)
class CaseDefinition:
    number: int
    slug: str
    description: str
    structure: tuple[str, ...] | None
    coordinate_profile: str
    task: str
    recipes: tuple[tuple[AssetRecipe, ...], ...]

    @property
    def case_id(self) -> str:
        return f"{self.number:02d}-{self.slug}"


def _asset(path: str | None, source: str) -> AssetRecipe:
    return AssetRecipe(path, source)


def _cases() -> tuple[CaseDefinition, ...]:
    s2 = ("s2-00-tile", "s2-01-tile", "s2-02-tile")
    single = ("s2-00-tile", "s2-01-tile", "s2-02-tile", "s1-00", "worldcover-00", "emit-00")
    secondary = ("worldcover-00", "s1-00", "alphaearth-00", "worldcover-00", "s1-00", "emit-00")
    sequence_sources = ("s2-00-tile", "s2-00-planar", "s2-00-chunky", "s2-01-tile", "s2-02-tile")
    sequence_lengths = (2, 3, 4, 5, 2, 4)
    optional_counts = (0, 1, 2, 0, 2, 1)

    return (
        CaseDefinition(
            1,
            "single-rumi",
            "Null-structure samples with no coordinate metadata.",
            None,
            "none",
            "other",
            tuple((_asset(None, source),) for source in single),
        ),
        CaseDefinition(
            2,
            "paired-rumi",
            "Fixed Rumi pairs with synthetic point coordinates.",
            ("primary.rumi", "secondary.rumi"),
            "point",
            "other",
            tuple(
                (_asset("primary.rumi", s2[index % len(s2)]), _asset("secondary.rumi", secondary[index]))
                for index in range(6)
            ),
        ),
        CaseDefinition(
            3,
            "multisensor",
            "Optical and radar-shaped assets with regular synthetic STAC grids.",
            ("optical.rumi", "radar.rumi"),
            "stac",
            "classification",
            tuple((_asset("optical.rumi", s2[index % len(s2)]), _asset("radar.rumi", "s1-00")) for index in range(6)),
        ),
        CaseDefinition(
            4,
            "change-detection",
            "Nested before/after/label-shaped assets with synthetic irregular footprints.",
            ("before/image.rumi", "after/image.rumi", "change.rumi"),
            "istac",
            "change-detection",
            tuple(
                (
                    _asset("before/image.rumi", s2[index % len(s2)]),
                    _asset("after/image.rumi", s2[(index + 1) % len(s2)]),
                    _asset("change.rumi", "worldcover-00"),
                )
                for index in range(6)
            ),
        ),
        CaseDefinition(
            5,
            "fixed-time-series",
            "Three fixed time steps with regular synthetic STAC intervals.",
            ("t0.rumi", "t1.rumi", "t2.rumi"),
            "stac-interval",
            "regression",
            tuple(
                (
                    _asset("t0.rumi", "s2-00-tile"),
                    _asset("t1.rumi", "s2-01-tile"),
                    _asset("t2.rumi", "s2-02-tile"),
                )
                for _ in range(6)
            ),
        ),
        CaseDefinition(
            6,
            "variable-sequence",
            "Variable-length Rumi sequences without coordinate metadata.",
            ("frame*[2,5].rumi",),
            "none",
            "classification",
            tuple(
                tuple(
                    _asset(f"frame{position}.rumi", sequence_sources[(sample + position) % len(sequence_sources)])
                    for position in range(length)
                )
                for sample, length in enumerate(sequence_lengths)
            ),
        ),
        CaseDefinition(
            7,
            "optional-assets",
            "A required image plus zero to two optional assets and nullable synthetic points.",
            ("image.rumi", "aux*[0,2].rumi"),
            "optional-point",
            "other",
            tuple(
                (
                    _asset("image.rumi", s2[index % len(s2)]),
                    *(
                        _asset(f"aux{position}.rumi", ("s1-00", "worldcover-00")[position])
                        for position in range(optional_counts[index])
                    ),
                )
                for index in range(6)
            ),
        ),
        CaseDefinition(
            8,
            "nested-fusion",
            "Nested input and target folders carrying synthetic folder-level STAC metadata.",
            ("inputs/optical.rumi", "inputs/radar.rumi", "targets/landcover.rumi"),
            "folder-stac",
            "segmentation",
            tuple(
                (
                    _asset("inputs/optical.rumi", s2[index % len(s2)]),
                    _asset("inputs/radar.rumi", "s1-00"),
                    _asset("targets/landcover.rumi", "worldcover-00"),
                )
                for index in range(6)
            ),
        ),
        CaseDefinition(
            9,
            "high-dimensional",
            "Single named cubes with synthetic temporal-only metadata.",
            ("cube.rumi",),
            "temporal-only",
            "other",
            tuple(
                (_asset("cube.rumi", source),)
                for source in ("era5-t2m-00-time", "alphaearth-00", "emit-00", "worldcover-00", "s1-00", "s2-00-tile")
            ),
        ),
        CaseDefinition(
            10,
            "layout-equivalence",
            "Equivalent Rumi tile, planar, and chunky encodings sharing one synthetic STAC grid.",
            ("scene.rumi",),
            "shared-stac",
            "other",
            tuple(
                (_asset("scene.rumi", source),)
                for source in (
                    "s2-00-tile",
                    "s2-00-planar",
                    "s2-00-chunky",
                    "s2-00-tile",
                    "s2-00-planar",
                    "s2-00-chunky",
                )
            ),
        ),
    )


def _digest(path: Path) -> str:
    value = hashlib.sha256()
    with path.open("rb") as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b""):
            value.update(chunk)
    return value.hexdigest()


def _seed(case_id: str, sample_index: int, salt: str = "sample") -> int:
    value = f"{GENERATOR_SEED}:{case_id}:{sample_index}:{salt}".encode()
    return int.from_bytes(hashlib.sha256(value).digest()[:8], "big") % (2**63 - 1)


def _point(longitude: float, latitude: float) -> bytes:
    return struct.pack("<BIdd", 1, 1, longitude, latitude)


def _polygon(west: float, south: float, east: float, north: float) -> bytes:
    ring = ((west, south), (east, south), (east, north), (west, north), (west, south))
    return struct.pack("<BIII", 1, 3, 1, len(ring)) + b"".join(struct.pack("<dd", x, y) for x, y in ring)


def _mercator(longitude: float, latitude: float) -> tuple[float, float]:
    radius = 6_378_137.0
    x = radius * math.radians(longitude)
    y = radius * math.log(math.tan(math.pi / 4 + math.radians(latitude) / 2))
    return x, y


def _spatial_values(case_id: str, sample_index: int, salt: str = "sample") -> dict[str, Any]:
    rng = random.Random(_seed(case_id, sample_index, salt))
    longitude = rng.uniform(-165.0, 165.0)
    latitude = rng.uniform(-70.0, 70.0)
    crs = "EPSG:4326" if rng.randrange(2) == 0 else "EPSG:3857"
    if crs == "EPSG:4326":
        center_x, center_y = longitude, latitude
        pixel_size = rng.uniform(0.0001, 0.005)
    else:
        center_x, center_y = _mercator(longitude, latitude)
        pixel_size = rng.uniform(5.0, 100.0)
    start = datetime(2020, 1, 1, tzinfo=timezone.utc) + timedelta(
        days=rng.randrange(0, 365 * 6), hours=rng.randrange(0, 24)
    )
    return {
        "longitude": longitude,
        "latitude": latitude,
        "crs": crs,
        "center_x": center_x,
        "center_y": center_y,
        "pixel_size": pixel_size,
        "time_start": start,
    }


def _stac(
    case_id: str,
    sample_index: int,
    shape: list[int],
    *,
    interval: bool = False,
    shared: bool = False,
    folder: bool = False,
    salt: str = "sample",
) -> taco.metadata.sample.STAC:
    spatial_index = 0 if shared else sample_index
    values = _spatial_values(case_id, spatial_index, salt)
    height, width = shape[-2:]
    west = values["center_x"] - width * values["pixel_size"] / 2
    north = values["center_y"] + height * values["pixel_size"] / 2
    model = taco.metadata.folder.STAC if folder else taco.metadata.sample.STAC
    kwargs: dict[str, Any] = {}
    if interval:
        kwargs["time_end"] = values["time_start"] + timedelta(hours=6 + sample_index)
    return model(
        crs=values["crs"],
        tensor_shape=shape,
        geotransform=(west, values["pixel_size"], 0.0, north, 0.0, -values["pixel_size"]),
        time_start=values["time_start"],
        centroid=_point(values["longitude"], values["latitude"]),
        **kwargs,
    )


def _istac(case_id: str, sample_index: int) -> taco.metadata.sample.ISTAC:
    values = _spatial_values(case_id, sample_index)
    radius = 0.1 if values["crs"] == "EPSG:4326" else 10_000.0
    return taco.metadata.sample.ISTAC(
        crs=values["crs"],
        geometry=_polygon(
            values["center_x"] - radius,
            values["center_y"] - radius,
            values["center_x"] + radius,
            values["center_y"] + radius,
        ),
        centroid=_point(values["longitude"], values["latitude"]),
        time_start=values["time_start"],
        time_end=values["time_start"] + timedelta(days=1 + sample_index),
    )


def _temporal(case_id: str, sample_index: int) -> TemporalInfo:
    values = _spatial_values(case_id, sample_index)
    return TemporalInfo(
        time_start=values["time_start"],
        time_end=values["time_start"] + timedelta(hours=sample_index + 1),
        synthetic=True,
    )


def _sample_groups(case: CaseDefinition) -> dict[str, Any]:
    groups: dict[str, Any] = {
        "fixture": FixtureSample,
        "ml": taco.metadata.sample.Split,
    }
    if case.structure is None:
        groups["rumi"] = RumiAsset
    if case.coordinate_profile == "point":
        groups["geo"] = GeoPoint
    elif case.coordinate_profile in {"stac", "stac-interval", "shared-stac"}:
        groups["stac"] = taco.metadata.sample.STAC
    elif case.coordinate_profile == "istac":
        groups["istac"] = taco.metadata.sample.ISTAC
    elif case.coordinate_profile == "optional-point":
        groups["geo"] = GeoPoint | None
    elif case.coordinate_profile == "temporal-only":
        groups["temporal"] = TemporalInfo
    return groups


def _contract(case: CaseDefinition) -> taco.Contract:
    levels = [taco.Level("sample", **_sample_groups(case))]
    if case.structure is not None:
        if case.number == 4:
            levels.extend(
                (
                    taco.Level("children", rumi=RumiAsset | None),
                    taco.Level("children/before", rumi=RumiAsset),
                    taco.Level("children/after", rumi=RumiAsset),
                )
            )
        elif case.number == 8:
            levels.extend(
                (
                    taco.Level("children", stac=taco.metadata.folder.STAC),
                    taco.Level("children/inputs", rumi=RumiAsset),
                    taco.Level("children/targets", rumi=RumiAsset),
                )
            )
        else:
            levels.append(taco.Level("children", rumi=RumiAsset))
    return taco.Contract(structure=case.structure, metadata=taco.MetadataSchema(*levels))


def _collection(case: CaseDefinition) -> taco.Collection:
    return taco.Collection(
        contract=_contract(case),
        id=case.case_id,
        dataset_version="1.0.0",
        title=f"TACO fixture: {case.slug}",
        description=case.description + " Payload contents and semantic metadata are test-only.",
        licenses=["other"],
        providers=["Asterisk Labs"],
        tasks=[case.task],
    )


def _metadata(
    case: CaseDefinition,
    sample_index: int,
    sources: dict[str, SourceFixture],
) -> taco.Metadata:
    recipe = case.recipes[sample_index]
    seed = _seed(case.case_id, sample_index)
    groups: dict[str, BaseModel] = {
        "fixture": FixtureSample(
            case_id=case.case_id,
            sample_key=f"sample-{sample_index}",
            synthetic=True,
            seed=seed,
        ),
        "ml": taco.metadata.sample.Split(split=SPLITS[sample_index]),
    }
    first = sources[recipe[0].source]
    if case.structure is None:
        groups["rumi"] = first.metadata()
    if case.coordinate_profile == "point":
        values = _spatial_values(case.case_id, sample_index)
        groups["geo"] = GeoPoint(longitude=values["longitude"], latitude=values["latitude"], synthetic=True)
    elif case.coordinate_profile == "stac":
        groups["stac"] = _stac(case.case_id, sample_index, first.manifest["shape"])
    elif case.coordinate_profile == "stac-interval":
        groups["stac"] = _stac(case.case_id, sample_index, first.manifest["shape"], interval=True)
    elif case.coordinate_profile == "istac":
        groups["istac"] = _istac(case.case_id, sample_index)
    elif case.coordinate_profile == "optional-point" and sample_index % 3 != 2:
        values = _spatial_values(case.case_id, sample_index)
        groups["geo"] = GeoPoint(longitude=values["longitude"], latitude=values["latitude"], synthetic=True)
    elif case.coordinate_profile == "temporal-only":
        groups["temporal"] = _temporal(case.case_id, sample_index)
    elif case.coordinate_profile == "shared-stac":
        groups["stac"] = _stac(case.case_id, sample_index, first.manifest["shape"], shared=True)
    return taco.Metadata(**groups)


def _samples(case: CaseDefinition, sources: dict[str, SourceFixture]) -> tuple[taco.Sample, ...]:
    samples = []
    for sample_index, recipes in enumerate(case.recipes):
        assets = [
            taco.Asset(
                sources[recipe.source].data,
                path=recipe.path,
                metadata=None if case.structure is None else taco.Metadata(rumi=sources[recipe.source].metadata()),
            )
            for recipe in recipes
        ]
        folders: list[taco.Folder] = []
        if case.number == 8:
            first_shape = sources[recipes[0].source].manifest["shape"]
            folders = [
                taco.Folder(
                    path,
                    metadata=taco.Metadata(
                        stac=_stac(
                            case.case_id,
                            sample_index,
                            first_shape,
                            folder=True,
                            salt=f"folder:{path}",
                        )
                    ),
                )
                for path in ("inputs", "targets")
            ]
        samples.append(
            taco.Sample(
                assets=assets,
                metadata=_metadata(case, sample_index, sources),
                folders=folders,
            )
        )
    return tuple(samples)


def _load_sources(source_root: Path) -> tuple[dict[str, SourceFixture], dict[str, Any]]:
    lock = json.loads(LOCK_PATH.read_text(encoding="utf-8"))
    manifest_path = source_root / "manifest.json"
    if not manifest_path.is_file():
        raise FileNotFoundError(f"Rumi fixture manifest not found: {manifest_path}")
    actual_manifest_hash = _digest(manifest_path)
    if actual_manifest_hash != lock["manifest_sha256"]:
        raise RuntimeError(
            f"Rumi manifest checksum mismatch: {actual_manifest_hash}; expected {lock['manifest_sha256']}"
        )
    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    sources = {}
    for item in manifest["fixtures"]:
        data = source_root / item["data"]
        header = source_root / item["header"]
        if _digest(data) != item["data_sha256"]:
            raise RuntimeError(f"Rumi data checksum mismatch: {data}")
        if _digest(header) != item["header_sha256"]:
            raise RuntimeError(f"Rumi header checksum mismatch: {header}")
        sources[item["name"]] = SourceFixture(item["name"], data, header, item)
    return sources, lock


def _write(
    collection: taco.Collection,
    output: Path,
    samples: tuple[taco.Sample, ...],
    **options: Any,
) -> taco.writer.BuildResult:
    with taco.open_writer(collection, output, **options) as writer:
        writer.extend(samples)
        return writer.run()


def _relative(path: Path) -> str:
    return path.resolve().relative_to(ROOT).as_posix()


def _dataset_record(
    case: CaseDefinition,
    topology: str,
    entrypoint: Path,
    parts: tuple[Path, ...] = (),
) -> dict[str, Any]:
    return {
        "id": f"{case.case_id}/{topology}",
        "case": case.case_id,
        "topology": topology,
        "container": "folder" if topology == "folder" else ("zip" if topology == "single-zip" else "tacocat"),
        "path": _relative(entrypoint),
        "parts": [_relative(path) for path in parts],
        "samples": len(case.recipes),
        "assets": sum(len(recipe) for recipe in case.recipes),
    }


def _case_record(case: CaseDefinition) -> dict[str, Any]:
    return {
        "id": case.case_id,
        "description": case.description,
        "structure": None if case.structure is None else list(case.structure),
        "coordinate_profile": case.coordinate_profile,
        "task": case.task,
        "samples": [
            {
                "sample_key": f"sample-{index}",
                "split": SPLITS[index],
                "seed": _seed(case.case_id, index),
                "assets": [{"path": asset.path, "source_fixture": asset.source} for asset in assets],
            }
            for index, assets in enumerate(case.recipes)
        ],
    }


def _build_case(case: CaseDefinition, sources: dict[str, SourceFixture]) -> list[dict[str, Any]]:
    collection = _collection(case)
    samples = _samples(case, sources)
    root = DATA_ROOT / case.case_id
    records = []

    folder = _write(collection, root / "folder", samples)
    records.append(_dataset_record(case, "folder", folder.path))

    single = _write(collection, root / "single-zip" / "dataset.zip", samples)
    records.append(_dataset_record(case, "single-zip", single.path))

    by_size = _write(collection, root / "by-size" / "dataset.zip", samples, partition_size=1)
    records.append(_dataset_record(case, "by-size", by_size.path, by_size.parts))

    by_split = _write(collection, root / "by-split" / "dataset.zip", samples, partition_by="ml:split")
    records.append(_dataset_record(case, "by-split", by_split.path, by_split.parts))

    manual_root = root / "manual-catalog"
    manual_parts = []
    for label, subset in zip(("one", "two", "three"), (samples[:1], samples[1:3], samples[3:]), strict=True):
        result = _write(collection, manual_root / f"part-{label}.zip", subset)
        manual_parts.append(result.path)
    catalog = taco.consolidate(manual_parts, output=manual_root)
    records.append(_dataset_record(case, "manual-catalog", catalog, tuple(manual_parts)))
    return records


def _write_checksums() -> None:
    files = sorted(path for path in DATA_ROOT.rglob("*") if path.is_file())
    files.append(MANIFEST_PATH)
    lines = [f"{_digest(path)}  {_relative(path)}" for path in files]
    CHECKSUMS_PATH.write_text("\n".join(lines) + "\n", encoding="utf-8")


def build(source_root: Path, *, clean: bool) -> dict[str, Any]:
    source_root = source_root.expanduser().resolve()
    if clean and DATA_ROOT.exists():
        if DATA_ROOT.parent != ROOT or DATA_ROOT.name != "data" or not LOCK_PATH.is_file():
            raise RuntimeError(f"refusing to clean unsafe output path: {DATA_ROOT}")
        shutil.rmtree(DATA_ROOT)
    if DATA_ROOT.exists() and any(DATA_ROOT.iterdir()):
        raise FileExistsError(f"output is not empty; rerun with --clean: {DATA_ROOT}")
    DATA_ROOT.mkdir(parents=True, exist_ok=True)

    sources, lock = _load_sources(source_root)
    cases = _cases()
    selected = {asset.source for case in cases for sample in case.recipes for asset in sample}
    missing = sorted(selected - set(sources))
    if missing:
        raise RuntimeError(f"Rumi source fixtures are missing: {missing}")

    datasets = []
    for case in cases:
        print(f"building {case.case_id}", flush=True)
        datasets.extend(_build_case(case, sources))

    manifest = {
        "schema_version": 1,
        "generator_seed": GENERATOR_SEED,
        "taco_version": taco.__version__,
        "rumi_version": rumi.__version__,
        "source": lock,
        "logical_cases": [_case_record(case) for case in cases],
        "datasets": datasets,
        "source_fixtures": {
            name: {
                key: fixture.manifest[key]
                for key in ("data_sha256", "header_sha256", "array_sha256", "shape", "dtype", "frame_layout")
            }
            for name, fixture in sorted(sources.items())
            if name in selected
        },
    }
    if len(datasets) != 50:
        raise AssertionError(f"expected 50 datasets, built {len(datasets)}")
    MANIFEST_PATH.write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    _write_checksums()
    return manifest


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--source",
        type=Path,
        default=ROOT.parent / "rumi-api-fixtures",
        help="checkout of the pinned rumi-api-fixtures dataset",
    )
    parser.add_argument("--clean", action="store_true", help="replace the generated data directory")
    args = parser.parse_args()
    manifest = build(args.source, clean=args.clean)
    print(f"built {len(manifest['datasets'])} dataset entrypoints in {DATA_ROOT}")


if __name__ == "__main__":
    main()