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
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
"""Materialize compact ML tensors from indexed event windows."""

from __future__ import annotations

import json
import time
import zlib
from pathlib import Path
from typing import Any

import numpy as np
from numpy.lib.npyio import NpzFile

from e_jepa_ttc.data.evttc import (
    NAVIGATION_FEATURE_NAMES,
    read_events_window,
    read_manifest,
    read_navigation_window_features,
)
from e_jepa_ttc.data.types import EventBatch
from e_jepa_ttc.representations.corruptions import EventCorruptionSpec, corrupt_event_batch
from e_jepa_ttc.representations.voxel_grid import encode_voxel_grid
from e_jepa_ttc.utils.io import ensure_parent, read_structured, write_structured


def validate_voxel_cache(cache: NpzFile) -> None:
    if "cache_format_version" not in cache.files or int(cache["cache_format_version"]) < 2:
        msg = "Training requires cache_format_version >= 2."
        raise ValueError(msg)
    for key in [
        "normalization",
        "source_manifest_sha256",
        "split_manifest_sha256",
        "preprocessing_config_sha256",
    ]:
        if key not in cache.files:
            msg = f"Cache missing required metadata field: {key}"
            raise ValueError(msg)

    # Sparse occupancy audit (Requirement 4.4)
    x = cache["x"]
    if x.size > 0:
        # Check a small random sample (up to 100 windows) to ensure it's not completely empty.
        # Use a fixed seed for deterministic audit behaviour.
        rng = np.random.default_rng(42)
        idx = rng.choice(x.shape[0], size=min(x.shape[0], 100), replace=False)
        sample = x[idx]
        if np.count_nonzero(sample) == 0:
            msg = (
                "Sparse occupancy audit failed: "
                "Sampled cache tensors are completely zero (no events)."
            )
            raise ValueError(msg)


def _load_windows(index_path: str | Path) -> list[dict[str, Any]]:
    data = read_structured(index_path)
    windows = data.get("windows")
    if not isinstance(windows, list):
        msg = f"Index {index_path} does not contain a windows list."
        raise ValueError(msg)
    return [dict(item) for item in windows]


def _downsample_events(events: EventBatch, *, width: int, height: int) -> EventBatch:
    if events.width == width and events.height == height:
        return events
    if events.num_events == 0:
        return EventBatch.empty(
            width=width,
            height=height,
            sequence_id=events.sequence_id,
            t_start_us=events.t_start_us,
            t_end_us=events.t_end_us,
        )
    x = np.floor(events.x.astype(np.float64) * width / events.width).astype(np.int32)
    y = np.floor(events.y.astype(np.float64) * height / events.height).astype(np.int32)
    x = np.clip(x, 0, width - 1)
    y = np.clip(y, 0, height - 1)
    return EventBatch(
        x=x,
        y=y,
        t_us=events.t_us,
        polarity=events.polarity,
        width=width,
        height=height,
        sequence_id=events.sequence_id,
        t_start_us=events.t_start_us,
        t_end_us=events.t_end_us,
    )


def _metadata_channels(events: EventBatch, *, width: int, height: int) -> np.ndarray:
    duration_s = max(events.duration_us / 1_000_000.0, 1e-6)
    log_count = np.float32(np.log1p(events.num_events))
    log_rate = np.float32(np.log1p(events.num_events / duration_s))
    meta = np.empty((2, height, width), dtype=np.float32)
    meta[0].fill(log_count)
    meta[1].fill(log_rate)
    return meta


def _constant_channels(values: np.ndarray, *, width: int, height: int) -> np.ndarray:
    channels = np.empty((int(values.shape[0]), height, width), dtype=np.float32)
    for idx, value in enumerate(values.astype(np.float32, copy=False)):
        channels[idx].fill(value)
    return channels


def _hash_file(filepath: str | Path) -> str:
    import hashlib

    h = hashlib.sha256()
    with open(filepath, "rb") as f:
        for chunk in iter(lambda: f.read(8192 * 1024), b""):
            h.update(chunk)
    return h.hexdigest()


def _hash_dict(config: dict[str, Any]) -> str:
    import hashlib

    serialized = json.dumps(config, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(serialized.encode("utf-8")).hexdigest()


def build_voxel_cache(
    *,
    manifest_path: str | Path,
    split_path: str | Path,
    index_path: str | Path,
    output_path: str | Path,
    width: int = 160,
    height: int = 90,
    bins: int = 5,
    normalize: bool = True,
    metadata_channels: bool = False,
    navigation_channels: bool = False,
    limit: int | None = None,
    exclude_splits: list[str] | None = None,
    include_splits: list[str] | None = None,
    corruption: EventCorruptionSpec | None = None,
) -> dict[str, Any]:
    """Build an `.npz` cache with voxel tensors and labels."""

    if width <= 0 or height <= 0 or bins <= 0:
        msg = "width, height and bins must be positive."
        raise ValueError(msg)

    sequences = {sequence.sequence_id: sequence for sequence in read_manifest(manifest_path)}
    split_data = read_structured(split_path).get("splits", {})
    if not isinstance(split_data, dict):
        msg = f"Split file {split_path} does not contain splits."
        raise ValueError(msg)
    split_for_sequence = {
        str(sequence_id): str(split_name)
        for split_name, sequence_ids in split_data.items()
        for sequence_id in sequence_ids
    }

    corruption_spec = corruption or EventCorruptionSpec()
    windows = _load_windows(index_path)
    input_window_count = len(windows)
    excluded_split_names = sorted(set(exclude_splits or []))
    included_split_names = sorted(set(include_splits or []))
    known_split_names = {*split_data, "unassigned"}
    unknown_exclusions = set(excluded_split_names) - known_split_names
    unknown_inclusions = set(included_split_names) - known_split_names
    if unknown_exclusions or unknown_inclusions:
        unknown = sorted(unknown_exclusions | unknown_inclusions)
        raise ValueError(f"Unknown included/excluded splits: {unknown}.")
    if set(excluded_split_names) & set(included_split_names):
        raise ValueError("The same split cannot be both included and excluded.")
    if included_split_names:
        included = set(included_split_names)
        windows = [
            window
            for window in windows
            if split_for_sequence.get(str(window["sequence_id"]), "unassigned") in included
        ]
    if excluded_split_names:
        excluded = set(excluded_split_names)
        windows = [
            window
            for window in windows
            if split_for_sequence.get(str(window["sequence_id"]), "unassigned") not in excluded
        ]
    if limit is not None:
        windows = windows[:limit]
    if not windows:
        raise ValueError("No cache windows remain after split exclusion and limit filtering.")
    channels = (
        bins * 2
        + (2 if metadata_channels else 0)
        + (len(NAVIGATION_FEATURE_NAMES) if navigation_channels else 0)
    )
    x_out = np.empty((len(windows), channels, height, width), dtype=np.float16)
    y_ttc = np.empty((len(windows),), dtype=np.float32)
    timestamps = np.empty((len(windows),), dtype=np.int64)
    context_start_us = np.empty((len(windows),), dtype=np.int64)
    context_end_us = np.empty((len(windows),), dtype=np.int64)
    sequence_ids: list[str] = []
    splits: list[str] = []
    event_counts = np.empty((len(windows),), dtype=np.int32)
    source_event_counts = np.empty((len(windows),), dtype=np.int32)
    source_context_start_us = np.empty((len(windows),), dtype=np.int64)
    source_context_end_us = np.empty((len(windows),), dtype=np.int64)
    collapsed_count = 0

    start_time = time.perf_counter()
    for idx, window in enumerate(windows):
        sequence_id = str(window["sequence_id"])
        sequence = sequences[sequence_id]
        event_hdf5 = sequence.resolve("event_hdf5")
        if event_hdf5 is None:
            msg = f"Sequence {sequence_id} has no event_hdf5."
            raise ValueError(msg)
        requested_start_us = int(window["context_start_us"])
        requested_end_us = int(window["context_end_us"])
        read_start_us = requested_start_us
        if corruption_spec.kind == "temporal_window_scale":
            source_duration_us = requested_end_us - requested_start_us
            scaled_duration_us = max(
                1,
                int(round(source_duration_us * corruption_spec.severity)),
            )
            read_start_us = max(0, requested_end_us - scaled_duration_us)
        events = read_events_window(
            event_hdf5,
            t_start_us=read_start_us,
            t_end_us=requested_end_us,
            sequence_id=sequence_id,
        )
        source_event_counts[idx] = events.num_events
        source_context_start_us[idx] = requested_start_us
        source_context_end_us[idx] = requested_end_us
        if corruption_spec.kind not in {"none", "temporal_window_scale"}:
            identity = f"{sequence_id}:{window['timestamp_us']}".encode()
            events = corrupt_event_batch(
                events,
                corruption_spec,
                seed_offset=zlib.crc32(identity),
            )
        small = _downsample_events(events, width=width, height=height)
        voxel = encode_voxel_grid(small, bins=bins, normalize=normalize)
        if metadata_channels:
            voxel = np.concatenate([voxel, _metadata_channels(events, width=width, height=height)])
        if navigation_channels:
            navigation = read_navigation_window_features(
                event_hdf5,
                t_start_us=events.t_start_us,
                t_end_us=events.t_end_us,
            )
            voxel = np.concatenate(
                [voxel, _constant_channels(navigation, width=width, height=height)]
            )
        if events.num_events > 0 and np.count_nonzero(voxel) == 0:
            collapsed_count += 1

        x_out[idx] = voxel.astype(np.float16)
        y_ttc[idx] = float(window["ttc_seconds"])
        timestamps[idx] = int(window["timestamp_us"])
        context_start_us[idx] = events.t_start_us
        context_end_us[idx] = events.t_end_us
        sequence_ids.append(sequence_id)
        splits.append(split_for_sequence.get(sequence_id, "unassigned"))
        event_counts[idx] = events.num_events

    output = ensure_parent(output_path)
    np.savez(
        output,
        x=x_out,
        y_ttc=y_ttc,
        timestamp_us=timestamps,
        context_start_us=context_start_us,
        context_end_us=context_end_us,
        source_context_start_us=source_context_start_us,
        source_context_end_us=source_context_end_us,
        sequence_id=np.array(sequence_ids),
        split=np.array(splits),
        event_count=event_counts,
        source_event_count=source_event_counts,
        width=np.array(width, dtype=np.int32),
        height=np.array(height, dtype=np.int32),
        bins=np.array(bins, dtype=np.int32),
        normalize=np.array(normalize, dtype=np.bool_),
        metadata_channels=np.array(metadata_channels, dtype=np.bool_),
        navigation_channels=np.array(navigation_channels, dtype=np.bool_),
        navigation_feature_names=np.array(NAVIGATION_FEATURE_NAMES),
        future_window_semantics=np.array("disjoint_window_start_after_context_plus_horizon"),
        cache_format_version=np.array(2, dtype=np.int64),
        normalization=np.array("non_centered_occupied_p95_scale" if normalize else "none"),
        excluded_splits=np.array(excluded_split_names),
        included_splits=np.array(included_split_names),
        corruption_kind=np.array(corruption_spec.kind),
        corruption_severity=np.array(corruption_spec.severity, dtype=np.float64),
        corruption_seed=np.array(corruption_spec.seed, dtype=np.int64),
        source_manifest_sha256=np.array(_hash_file(manifest_path)),
        split_manifest_sha256=np.array(_hash_file(split_path)),
        preprocessing_config_sha256=np.array(
            _hash_dict(
                {
                    "width": width,
                    "height": height,
                    "bins": bins,
                    "normalize": normalize,
                    "metadata_channels": metadata_channels,
                    "navigation_channels": navigation_channels,
                    "excluded_splits": excluded_split_names,
                    "included_splits": included_split_names,
                    "corruption": {
                        "kind": corruption_spec.kind,
                        "severity": corruption_spec.severity,
                        "seed": corruption_spec.seed,
                    },
                }
            )
        ),
    )

    cache_sha256 = _hash_file(output)

    validation_sidecar = {
        "status": (
            "passed"
            if collapsed_count == 0
            else (
                "passed_with_expected_corruption_empty_samples"
                if corruption_spec.kind != "none"
                else "failed"
            )
        ),
        "cache_format_version": 2,
        "normalize": normalize,
        "normalization": "non_centered_occupied_p95_scale" if normalize else "none",
        "sidecar_sha256_matches": True,
        "sparse_event_audit_passed": collapsed_count == 0,
        "nonempty_samples_collapsed_to_zero": collapsed_count,
        "cache_sha256": cache_sha256,
        "excluded_splits": excluded_split_names,
        "included_splits": included_split_names,
        "corruption": {
            "kind": corruption_spec.kind,
            "severity": corruption_spec.severity,
            "seed": corruption_spec.seed,
        },
    }

    # Validation sidecar output to output's parent dir (usually artifacts/features)
    # But since cache could be specific to the invocation, maybe write next to it
    sidecar_path = output.with_name("cache_validation.json")
    write_structured(sidecar_path, validation_sidecar)

    summary = {
        "output": output.as_posix(),
        "cache_format_version": 2,
        "window_count": int(len(windows)),
        "input_window_count": int(input_window_count),
        "excluded_splits": excluded_split_names,
        "included_splits": included_split_names,
        "shape": list(x_out.shape),
        "dtype": str(x_out.dtype),
        "width": width,
        "height": height,
        "bins": bins,
        "normalize": normalize,
        "normalization": "non_centered_occupied_p95_scale" if normalize else "none",
        "metadata_channels": metadata_channels,
        "navigation_channels": navigation_channels,
        "navigation_feature_names": list(NAVIGATION_FEATURE_NAMES),
        "future_window_semantics": "disjoint_window_start_after_context_plus_horizon",
        "corruption": {
            "kind": corruption_spec.kind,
            "severity": corruption_spec.severity,
            "seed": corruption_spec.seed,
        },
        "seconds": time.perf_counter() - start_time,
        "mean_events_per_window": float(np.mean(event_counts)) if len(event_counts) else 0.0,
        "mean_source_events_per_window": (
            float(np.mean(source_event_counts)) if len(source_event_counts) else 0.0
        ),
        "cache_sha256": cache_sha256,
    }
    write_structured(output.with_suffix(".summary.json"), summary)
    return summary


def remap_cache_splits(
    *,
    cache_path: str | Path,
    split_path: str | Path,
    output_path: str | Path,
) -> dict[str, Any]:
    """Copy an NPZ cache while replacing split labels by sequence id."""

    cache = np.load(cache_path, allow_pickle=False)
    if "sequence_id" not in cache.files or "split" not in cache.files:
        msg = "Cache must contain sequence_id and split arrays."
        raise ValueError(msg)
    split_data = read_structured(split_path).get("splits", {})
    if not isinstance(split_data, dict):
        msg = f"Split file {split_path} does not contain splits."
        raise ValueError(msg)
    split_for_sequence = {
        str(sequence_id): str(split_name)
        for split_name, sequence_ids in split_data.items()
        for sequence_id in sequence_ids
    }
    sequence_ids = cache["sequence_id"].astype(str)
    old_split = cache["split"].astype(str)
    new_split = np.array(
        [split_for_sequence.get(str(sequence_id), "unassigned") for sequence_id in sequence_ids],
        dtype=str,
    )
    arrays = {key: cache[key] for key in cache.files if key != "split"}
    output = ensure_parent(output_path)
    np.savez(output, **arrays, split=new_split)
    old_counts = {
        str(name): int(np.sum(old_split == name)) for name in sorted(set(old_split.tolist()))
    }
    new_counts = {
        str(name): int(np.sum(new_split == name)) for name in sorted(set(new_split.tolist()))
    }
    summary = {
        "input": Path(cache_path).as_posix(),
        "output": output.as_posix(),
        "split": Path(split_path).as_posix(),
        "window_count": int(new_split.shape[0]),
        "old_split_counts": old_counts,
        "new_split_counts": new_counts,
        "unassigned_count": int(np.sum(new_split == "unassigned")),
    }
    write_structured(output.with_suffix(".summary.json"), summary)
    return summary