File size: 14,032 Bytes
d922ac9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Check that offset-0 windows reproduce the published 5 km terrain table.

The whole claim behind the quarter-cell design is that a window composed from
additive quarter statistics is not an approximation of the 5 km cell it covers
but the *same number*. ``offset_id == 0`` covers exactly the cell it is
anchored on, so every column in :data:`quarter_cells.EXACT_COLUMNS` must come
back bit-identical to the published terrain table, and only the six
percentile-derived columns may differ at all.

Comparison is on raw bit patterns, not on ``==``. Two reasons, both learned
here: ``NaN == NaN`` is false, and Earth is mostly ocean, so a value-wise
comparison reports every all-NaN column as a mismatch (that is exactly how a
first pass at verifying terrain-v0.2 appeared to find 20 broken columns). A
bit comparison instead demands that a NaN payload match too, which is strictly
stronger than equality.

One column is expected to differ and is reported separately rather than as a
failure: ``roughness_detrended_std`` solves a plane from sums here and from a
second pass over residuals in the extractor. The two disagree only in the last
bits, and only where the roughness is small enough that the residual sum of
squares is itself near cancellation. The script measures where the difference
lives instead of asserting it is zero.

Approximate columns are reported as ABSOLUTE error. Relative error is
meaningless on flat ice, where the published value is itself near zero and any
denominator built from it explodes.

Usage:
    python validate_windows.py --planet earth \
        --windows <dir of band_group=*.parquet> \
        --terrain <dir of band_group=*.parquet> [--json report.json]
"""
from __future__ import annotations

import argparse
import json
from pathlib import Path

import numpy as np
import pyarrow.parquet as pq

import quarter_cells as qc

# The two count columns of EXACT_COLUMNS, named here only so the comparison
# can say which ones are integers rather than float bit patterns.
COUNT_COLUMNS = ('n_native_samples', 'n_valid_native_samples')

# Below this roughness the plane-from-sums and plane-from-residuals paths are
# allowed to disagree in the last bits; above it they must not disagree at all.
ROUGHNESS_FLOOR = 0.01


def _bits(values: np.ndarray) -> np.ndarray:
    """A float array as the unsigned integer of the same width.

    Lets NaN compare equal to an identical NaN, and unequal to a NaN with a
    different payload, which plain ``==`` cannot express.
    """
    values = np.asarray(values)
    if values.dtype == np.float32:
        return values.view(np.uint32)
    if values.dtype == np.float64:
        return values.view(np.uint64)
    return values


def group_numbers(directory: Path) -> list[int]:
    return sorted(int(p.stem.split('=')[1])
                  for p in Path(directory).glob('band_group=*.parquet'))


def _key(band: np.ndarray, column: np.ndarray) -> np.ndarray:
    """One integer per cell, so the join is a sort rather than a merge."""
    return band.astype(np.int64) * (1 << 32) + column.astype(np.int64)


class Accumulator:
    """Running totals over all band groups."""

    def __init__(self):
        self.exact = {name: {'compared': 0, 'mismatched': 0, 'max_abs_diff': 0.0}
                      for name in qc.EXACT_COLUMNS}
        self.errors = {name: [] for name in qc.APPROXIMATE_COLUMNS}
        self.rough_above = {'compared': 0, 'mismatched': 0, 'max_abs_diff': 0.0}
        self.rough_below = {'compared': 0, 'mismatched': 0, 'max_abs_diff': 0.0}
        self.rows = 0
        self.terrain_rows = 0
        self.terrain_measured = 0
        self.windows_without_cell = 0
        self.measured_without_window = 0
        self.groups = 0
        # The cells behind rough_above['mismatched'], so a release can check
        # that the exceptions it accepts are exactly the ones that exist.
        self.rough_above_cells = []

    def exact_column(self, name: str, left: np.ndarray, right: np.ndarray) -> None:
        slot = self.exact[name]
        slot['compared'] += int(left.size)
        differs = _bits(left) != _bits(right)
        slot['mismatched'] += int(differs.sum())
        if differs.any():
            slot['max_abs_diff'] = max(slot['max_abs_diff'],
                                       _finite_max_abs(left, right, differs))

    def roughness(self, left: np.ndarray, right: np.ndarray,
                  band: np.ndarray | None = None,
                  column: np.ndarray | None = None) -> None:
        """Split the one expected difference by the size of the value.

        With ``band`` and ``column`` the cells that differ at or above the
        floor are also recorded (at most MAX_CELLS_LISTED in all).
        """
        differs = _bits(left) != _bits(right)
        with np.errstate(invalid='ignore'):
            small = np.nan_to_num(np.abs(right), nan=0.0) < ROUGHNESS_FLOOR
        for mask, slot in ((~small, self.rough_above), (small, self.rough_below)):
            slot['compared'] += int(mask.sum())
            hit = differs & mask
            slot['mismatched'] += int(hit.sum())
            if hit.any():
                slot['max_abs_diff'] = max(slot['max_abs_diff'],
                                           _finite_max_abs(left, right, hit))
        if band is not None and column is not None:
            for i in np.flatnonzero(differs & ~small):
                if len(self.rough_above_cells) >= MAX_CELLS_LISTED:
                    break
                self.rough_above_cells.append({
                    'band': int(band[i]), 'column': int(column[i]),
                    'window': _json_float(left[i]), 'terrain': _json_float(right[i])})


MAX_CELLS_LISTED = 100


def _json_float(value) -> float | None:
    """A float JSON can carry: NaN and inf become null."""
    value = float(value)
    return value if np.isfinite(value) else None


def _finite_max_abs(left, right, mask) -> float:
    """Largest finite |difference| among the masked entries.

    A NaN that differs only in payload has no meaningful magnitude, and a
    value present on one side and NaN on the other has no finite difference
    either; both are already counted as mismatches.
    """
    a = np.asarray(left, dtype=np.float64)[mask]
    b = np.asarray(right, dtype=np.float64)[mask]
    diff = np.abs(a - b)
    good = np.isfinite(diff)
    return float(diff[good].max()) if good.any() else 0.0


def compare_group(window_path: Path, terrain_path: Path, acc: Accumulator) -> dict:
    windows = pq.read_table(window_path)
    terrain = pq.read_table(terrain_path)

    offset = windows['offset_id'].to_numpy()
    windows = windows.filter(offset == 0)

    w_key = _key(windows['band'].to_numpy(), windows['column'].to_numpy())
    t_key = _key(terrain['band'].to_numpy(), terrain['column'].to_numpy())

    order = np.argsort(t_key)
    sorted_key = t_key[order]
    position = np.searchsorted(sorted_key, w_key)
    position = np.clip(position, 0, sorted_key.size - 1)
    found = sorted_key[position] == w_key
    t_index = order[position]

    acc.rows += int(found.sum())
    acc.terrain_rows += terrain.num_rows
    acc.windows_without_cell += int((~found).sum())
    acc.groups += 1

    # A cell the extractor measured must have an offset-0 window. A cell it
    # did not measure has nothing to reproduce, so its absence is correct.
    measured = np.asarray(terrain['n_valid_samples_200m'].to_numpy()) > 0
    acc.terrain_measured += int(measured.sum())
    matched = np.zeros(terrain.num_rows, dtype=bool)
    matched[t_index[found]] = True
    acc.measured_without_window += int((measured & ~matched).sum())

    w_rows = np.flatnonzero(found)
    t_rows = t_index[found]
    for name in qc.EXACT_COLUMNS:
        left = windows[name].to_numpy(zero_copy_only=False)[w_rows]
        right = terrain[name].to_numpy(zero_copy_only=False)[t_rows]
        if name == 'roughness_detrended_std':
            acc.roughness(left, right,
                          windows['band'].to_numpy()[w_rows],
                          windows['column'].to_numpy()[w_rows])
        else:
            acc.exact_column(name, left, right)

    for name in qc.APPROXIMATE_COLUMNS:
        left = np.asarray(windows[name].to_numpy(zero_copy_only=False)[w_rows],
                          dtype=np.float64)
        right = np.asarray(terrain[name].to_numpy(zero_copy_only=False)[t_rows],
                           dtype=np.float64)
        diff = np.abs(left - right)
        # Both NaN is agreement, not an error; one-sided NaN is counted by the
        # coverage numbers above and cannot be summarised as a magnitude.
        acc.errors[name].append(diff[np.isfinite(diff)].astype(np.float32))

    return {'group': int(window_path.stem.split('=')[1]),
            'windows': int(found.sum())}


def summarise(acc: Accumulator) -> dict:
    exact = {}
    for name, slot in acc.exact.items():
        if name == 'roughness_detrended_std':
            continue
        exact[name] = dict(slot)
    approximate = {}
    for name, parts in acc.errors.items():
        values = (np.concatenate(parts) if parts
                  else np.zeros(0, dtype=np.float32))
        approximate[name] = {
            'compared': int(values.size),
            'max_abs_error': float(values.max()) if values.size else 0.0,
            'p99_abs_error': (float(np.percentile(values, 99))
                              if values.size else 0.0),
        }
    clean = all(v['mismatched'] == 0 for v in exact.values())
    rough_ok = acc.rough_above['mismatched'] == 0
    return {
        'groups': acc.groups,
        'offset0_windows_compared': acc.rows,
        'terrain_rows': acc.terrain_rows,
        'terrain_rows_measured': acc.terrain_measured,
        'measured_cells_without_a_window': acc.measured_without_window,
        'windows_without_a_terrain_row': acc.windows_without_cell,
        'exact_columns': exact,
        'roughness_detrended_std': {
            f'at_or_above_{ROUGHNESS_FLOOR}_m': dict(acc.rough_above),
            f'below_{ROUGHNESS_FLOOR}_m': dict(acc.rough_below),
        },
        # Kept out of roughness_detrended_std above: report() reads every
        # entry there as a {compared, mismatched, max_abs_diff} slot.
        'roughness_above_floor_cells': list(acc.rough_above_cells),
        'approximate_columns': approximate,
        'verdict': ('PASS' if clean and rough_ok
                    and acc.measured_without_window == 0
                    and acc.windows_without_cell == 0 else 'FAIL'),
    }


def report(summary: dict) -> None:
    print(f"\ngroups compared          {summary['groups']}")
    print(f"offset-0 windows         {summary['offset0_windows_compared']:,}")
    print(f"terrain rows             {summary['terrain_rows']:,} "
          f"({summary['terrain_rows_measured']:,} with a valid sample)")
    print(f"measured cells with no window   "
          f"{summary['measured_cells_without_a_window']:,}")
    print(f"windows with no terrain row     "
          f"{summary['windows_without_a_terrain_row']:,}")

    print('\nEXACT columns (bit-identical required)')
    print(f"  {'column':<28} {'compared':>12} {'mismatched':>11}  {'max |diff|':>11}")
    for name, slot in summary['exact_columns'].items():
        flag = '' if slot['mismatched'] == 0 else '   <-- MISMATCH'
        print(f"  {name:<28} {slot['compared']:>12,} {slot['mismatched']:>11,}"
              f"  {slot['max_abs_diff']:>11.3e}{flag}")

    print('\nroughness_detrended_std (the one understood exception)')
    for where, slot in summary['roughness_detrended_std'].items():
        print(f"  {where:<28} {slot['compared']:>12,} {slot['mismatched']:>11,}"
              f"  {slot['max_abs_diff']:>11.3e}")

    for cell in summary.get('roughness_above_floor_cells', [])[:10]:
        print(f"    band {cell['band']} col {cell['column']}: "
              f"window {cell['window']} vs terrain {cell['terrain']}")

    print('\nAPPROXIMATE columns (absolute error vs published)')
    print(f"  {'column':<28} {'compared':>12} {'max abs':>12} {'p99 abs':>12}")
    for name, slot in summary['approximate_columns'].items():
        print(f"  {name:<28} {slot['compared']:>12,} "
              f"{slot['max_abs_error']:>12.4g} {slot['p99_abs_error']:>12.4g}")
    print(f"\nverdict: {summary['verdict']}")


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--planet', choices=('mars', 'earth'), required=True)
    parser.add_argument('--windows', type=Path, required=True)
    parser.add_argument('--terrain', type=Path, required=True)
    parser.add_argument('--groups', type=str, default=None,
                        help='inclusive START-END over band groups')
    parser.add_argument('--json', type=Path, default=None)
    args = parser.parse_args(argv)

    available = group_numbers(args.windows)
    have_terrain = set(group_numbers(args.terrain))
    if args.groups:
        low, high = (int(v) for v in args.groups.split('-'))
        available = [g for g in available if low <= g <= high]
    missing = [g for g in available if g not in have_terrain]
    if missing:
        print(f'no terrain table for group(s): {missing}')
        return 2
    if not available:
        print('no window band groups found')
        return 2

    acc = Accumulator()
    for group in available:
        stats = compare_group(args.windows / f'band_group={group:03d}.parquet',
                              args.terrain / f'band_group={group:03d}.parquet',
                              acc)
        print(f"group {stats['group']:03d}: {stats['windows']:,} offset-0 windows",
              flush=True)

    summary = summarise(acc)
    report(summary)
    if args.json:
        args.json.parent.mkdir(parents=True, exist_ok=True)
        args.json.write_text(json.dumps(summary, indent=2, sort_keys=True))
        print(f'wrote {args.json}')
    return 0 if summary['verdict'] == 'PASS' else 1


if __name__ == '__main__':
    raise SystemExit(main())