File size: 18,484 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
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
"""Merge quarter-cell tables into 5 km windows at a 2.5 km stride.

Reads the ``quarter-v0.1`` tables one band group at a time and writes the
``terrain-v0.3`` window table. No raster is touched and nothing is downloaded:
every number here comes out of the quarter tables, which is the point of
storing additive statistics in the first place.

Each 5 km cell anchors four windows:

===========  =======================================================
offset_id    what it covers
===========  =======================================================
0            the cell itself, reproducing the published 5 km values
1            its eastern half and the next column's western half
2            its southern half and band - 1's (southern neighbour) northern half
3            both, the diagonal step
===========  =======================================================

Band numbers run SOUTH to NORTH (band 0 touches the south pole), so "the next
band south" is ``band - 1``. Offsets 2 and 3 reach into it, and its columns do
not line up with this one's. They use that band's *anchor* quarters - its
northern half, indexed on this band's column edges when it was written - so
the window stays a rectangle. The first band of a group finds them in the
previous group's file.

Usage:
    python compose_windows.py --planet earth --quarters DIR --out DIR
"""
from __future__ import annotations

import argparse
import datetime as dt
import json
import math
from pathlib import Path

import numpy as np
import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.parquet as pq

import quarter_cells as qc
import terrain_features as tf
from planetary_grid import PLANETS, PlanetBandGrid

FLOAT_COLUMNS = [name for name in tf.FLOAT_FEATURES]
EARTH_EXTRA = ('ns_samples_averaged', 'water_mask_frac')


def scales_for(planet: str):
    """``(lon_scale(lat), lat_scale(lat))`` in metres per degree.

    Imported from the drivers rather than restated, so the window table cannot
    drift away from the geometry the quarters were measured in.
    """
    if planet == 'mars':
        radius = PLANETS['mars']['a_m']
        return (lambda lat: math.radians(1.0) * radius * np.cos(np.deg2rad(lat)),
                lambda lat: math.radians(1.0) * radius)
    import earth_terrain as et
    return (lambda lat: math.radians(1.0) * et.prime_vertical_radius(lat)
            * np.cos(np.deg2rad(lat)),
            lambda lat: math.radians(1.0) * float(et.meridional_radius(lat)))


def empty_part(n: int, columns, has_earth: bool) -> dict:
    """A quarter that holds nothing, for cells the extractor never wrote."""
    part = {name: np.zeros(n, dtype=np.float64) for name in columns}
    for name in ('elev_min', 'elev_max', 'slope_min', 'slope_max'):
        part[name] = np.full(n, np.nan)
    part['elev_hist_level'] = np.full(n, qc.LEVEL_MIN, dtype=np.int64)
    part['elev_hist_first'] = np.zeros(n, dtype=np.int64)
    part['slope_hist_level'] = np.full(n, qc.LEVEL_MIN, dtype=np.int64)
    part['slope_hist_first'] = np.zeros(n, dtype=np.int64)
    for name in qc.QUARTER_LIST_COLUMNS:
        part[name] = np.zeros((n, qc.N_BINS), dtype=np.int64)
    return part


def scatter(table: pa.Table, n_cells: int, has_earth: bool) -> dict:
    """Dense per-column arrays for one (qrow, qcol) slice of one band."""
    columns = list(qc.SCALARS) + (list(qc.EARTH_SCALARS) if has_earth else [])
    columns += [f'm_{name}' for name in qc.MOMENTS]
    columns += ['plane_z0', 'origin_lon', 'origin_lat', 'lat_scale']
    part = empty_part(n_cells, columns, has_earth)
    if table.num_rows == 0:
        return part
    index = table['column'].to_numpy()
    for name in columns:
        if name in table.column_names:
            part[name][index] = table[name].to_numpy(zero_copy_only=False)
    for name in qc.QUARTER_INT_COLUMNS:
        part[name][index] = table[name].to_numpy()
    for name in qc.QUARTER_LIST_COLUMNS:
        flat = np.asarray(table[name].combine_chunks().flatten().to_numpy(
            zero_copy_only=False), dtype=np.int64)
        part[name][index] = flat.reshape(table.num_rows, qc.N_BINS)
    return part


def split_band(table: pa.Table, band: int, n_cells: int, has_earth: bool):
    """The band's own four quarter slices, keyed by ``(qrow, qcol)``."""
    mask = (table['band'].to_numpy() == band) & (table['anchor_band'].to_numpy() == band)
    rows = table.filter(pa.array(mask))
    qrow, qcol = rows['qrow'].to_numpy(), rows['qcol'].to_numpy()
    return {(r, c): scatter(rows.filter(pa.array((qrow == r) & (qcol == c))),
                            n_cells, has_earth)
            for r in (0, 1) for c in (0, 1)}


def anchor_slices(table: pa.Table, band: int, n_cells: int, has_earth: bool):
    """The band to the SOUTH's northern quarters, already on this band's columns.

    Bands are numbered south to north, so that is ``band - 1``: its northern
    half is the strip directly below this band's southern half.
    """
    mask = ((table['band'].to_numpy() == band - 1)
            & (table['anchor_band'].to_numpy() == band))
    rows = table.filter(pa.array(mask))
    qcol = rows['qcol'].to_numpy()
    return {c: scatter(rows.filter(pa.array(qcol == c)), n_cells, has_earth)
            for c in (0, 1)}


def roll(part: dict) -> dict:
    """Shift a per-column array one column west, wrapping at +-180 degrees."""
    return {k: np.roll(v, -1, axis=0) for k, v in part.items()}


def compose_band(own, anchor, *, band: int, n_cells: int, lon_step: float,
                 center_lat: float, south_lat: float, lat_scale, has_partner: bool):
    """Every window anchored on this band, as one record per offset.

    ``anchor`` holds band - 1's northern quarters on this band's columns, and
    ``has_partner`` says whether that band was measured at all; offsets 2 and
    3 are only composed when it was.
    """
    cells = np.arange(n_cells)
    west = -180.0 + lon_step * (cells + 0.5)
    east = -180.0 + lon_step * (cells + 1.0)
    here = np.full(n_cells, float(lat_scale(center_lat)))
    boundary = np.full(n_cells, float(lat_scale(south_lat)))

    plans = {
        0: ([own[(0, 0)], own[(0, 1)], own[(1, 0)], own[(1, 1)]],
            (west, np.full(n_cells, center_lat), here)),
        1: ([own[(0, 1)], own[(1, 1)], roll(own[(0, 0)]), roll(own[(1, 0)])],
            (east, np.full(n_cells, center_lat), here)),
    }
    if has_partner:
        # this band's southern half over band - 1's northern half, both on
        # this band's column edges, referenced at the boundary between them
        plans[2] = ([own[(1, 0)], own[(1, 1)], anchor[0], anchor[1]],
                    (west, np.full(n_cells, south_lat), boundary))
        plans[3] = ([own[(1, 1)], roll(own[(1, 0)]), anchor[1], roll(anchor[0])],
                    (east, np.full(n_cells, south_lat), boundary))
    out = {}
    for offset_id, (parts, reference) in plans.items():
        out[offset_id] = qc.compose_windows_array(parts, reference)
    return out


def build_table(records, planet: str, provenance: dict) -> pa.Table:
    """One Parquet table for a band group, empty windows dropped."""
    prefix = PLANETS[planet]['prefix']
    bands, columns, offsets, rows = [], [], [], []
    for band, offset_id, record in records:
        # A window with no valid sample measures nothing. The grid and terrain
        # tables already record that a cell is open ocean, so writing four
        # all-NaN rows per such cell would roughly treble the Earth table to
        # say nothing new.
        keep = np.asarray(record['n_valid_samples_200m']) > 0
        if not keep.any():
            continue
        index = np.flatnonzero(keep)
        bands.append(np.full(index.size, band, dtype=np.int32))
        columns.append(index.astype(np.int32))
        offsets.append(np.full(index.size, offset_id, dtype=np.int8))
        rows.append({k: np.asarray(v)[index] for k, v in record.items()
                     if np.ndim(v) == 1})
    if not rows:
        bands = [np.zeros(0, dtype=np.int32)]
        columns = [np.zeros(0, dtype=np.int32)]
        offsets = [np.zeros(0, dtype=np.int8)]
        rows = [{}]
    band_array = np.concatenate(bands)
    column_array = np.concatenate(columns)
    offset_array = np.concatenate(offsets)

    def gather(name, dtype):
        parts = [r[name] for r in rows if name in r]
        return (np.concatenate(parts).astype(dtype) if parts
                else np.zeros(0, dtype=dtype))

    data = {
        'grid_version': tf._constant(tf.GRID_VERSION, band_array.size),
        'window_id': pa.array([qc.window_id(prefix, int(b), int(c), int(o))
                               for b, c, o in zip(band_array, column_array, offset_array)]),
        'region_id': pa.array([f'{prefix}_{int(b):04d}_{int(c):05d}'
                               for b, c in zip(band_array, column_array)]),
        'planet': tf._constant(planet, band_array.size),
        'band': pa.array(band_array),
        'column': pa.array(column_array),
        'offset_id': pa.array(offset_array),
        'offset_row': pa.array(np.array([qc.OFFSETS[int(o)][0] for o in offset_array],
                                        dtype=np.int8)),
        'offset_col': pa.array(np.array([qc.OFFSETS[int(o)][1] for o in offset_array],
                                        dtype=np.int8)),
    }
    names = list(FLOAT_COLUMNS)
    if planet == 'earth':
        names += list(EARTH_EXTRA)
    for name in names:
        data[name] = pa.array(gather(name, np.float64).astype(np.float32))
    for name in ('n_native_samples', 'n_valid_native_samples'):
        data[name] = pa.array(gather(name, np.int64))
    data['feature_version'] = tf._constant(qc.WINDOW_VERSION, band_array.size)
    data['quarter_version'] = tf._constant(qc.QUARTER_VERSION, band_array.size)
    data['code_version'] = tf._constant(provenance['code_version'], band_array.size)
    # Two hashes, because two programs made these numbers: the extractor that
    # measured the quarters and the composer that merged them.
    data['quarter_code_version'] = tf._constant(
        provenance.get('quarter_code_version', ''), band_array.size)
    data['computed_at'] = tf._constant(provenance['computed_at'], band_array.size)
    table = pa.table(data)
    return table.replace_schema_metadata({
        'feature_version': qc.WINDOW_VERSION,
        'quarter_version': qc.QUARTER_VERSION,
        'grid_version': tf.GRID_VERSION,
        'exact_columns': json.dumps(list(qc.EXACT_COLUMNS)),
        'approximate_columns': json.dumps(list(qc.APPROXIMATE_COLUMNS)),
        'provenance': json.dumps(provenance, sort_keys=True),
    })


def group_path(out_dir: Path, group: int) -> Path:
    return Path(out_dir) / qc.WINDOW_VERSION / f'band_group={group:03d}.parquet'


def quarter_group_path(quarter_dir: Path, group: int) -> Path:
    return Path(quarter_dir) / f'band_group={group:03d}.parquet'


def covered_bands(path: Path) -> set[int]:
    """Every band a quarter file's run covered, open-ocean bands included.

    Earth stores that list in the file metadata, where ``--resume`` reads it.
    A file without it says nothing, and callers fall back to the bands that
    actually wrote rows.
    """
    try:
        metadata = pq.read_schema(path).metadata or {}
        return {int(b) for b in json.loads(metadata[b'bands'].decode())}
    except (KeyError, ValueError, TypeError):
        return set()


def quarter_versions(table: pa.Table) -> list[str]:
    """The distinct, non-empty ``quarter_code_version`` values of a table."""
    if 'quarter_code_version' not in table.column_names or table.num_rows == 0:
        return []
    return sorted(v for v in pc.unique(table['quarter_code_version']).to_pylist() if v)


def compose_group(planet: str, grid: PlanetBandGrid, quarter_dir: Path,
                  group: int, provenance: dict) -> tuple[pa.Table, dict]:
    path = quarter_group_path(quarter_dir, group)
    table = pq.read_table(path)
    problems = qc.audit_quarter_table(table, str(path))
    if problems:
        raise SystemExit('refusing to compose:\n  ' + '\n  '.join(problems))
    n_bands = len(grid.column_counts)
    present = set(table['band'].to_numpy().tolist())
    # Every band the run covered, not just those that wrote a row: a band of
    # open ocean still bounds the southward windows of the band above it.
    covered = covered_bands(path) | present
    own_bands = sorted(b for b in covered
                       if b // tf.BANDS_PER_GROUP == group and 0 <= b < n_bands)
    # Bands run south to north, so the first band of a group pairs with the
    # LAST band of the previous group for its southward windows. Only that
    # band's anchor rows are wanted, and a quarter file runs to hundreds of
    # megabytes, so the filter goes into the read. Without that file the
    # first band's offsets 2 and 3 are skipped, and counted.
    previous = quarter_group_path(quarter_dir, group - 1)
    if own_bands and own_bands[0] > 0 and group > 0 and previous.exists():
        first = own_bands[0]
        spill = pq.read_table(previous, filters=[('band', '=', first - 1),
                                                 ('anchor_band', '=', first)])
        covered |= covered_bands(previous) | set(spill['band'].to_numpy().tolist())
        if spill.num_rows:
            table = pa.concat_tables([table, spill], promote_options='default')
    versions = quarter_versions(table)
    problems = qc.audit_quarter_versions(versions)
    if problems:
        raise SystemExit(f'refusing to compose group {group:03d}:\n  '
                         + '\n  '.join(problems))
    stamped = dict(provenance, quarter_code_version=versions[0] if versions else '')
    stats = {'group': group, 'bands': len(own_bands),
             'quarter_code_version': stamped['quarter_code_version'],
             'bands_without_a_southern_partner': 0}
    if table.num_rows == 0:
        # a header-only file - every band above 84 N on Earth - holds nothing
        return build_table([], planet, stamped), stats
    _, lat_scale = scales_for(planet)
    has_earth = 'n_native_water' in table.column_names
    records, skipped = [], 0
    for band in own_bands:
        n_cells = int(grid.column_counts[band])
        cell = grid.cell(band, 0)
        has_partner = band > 0 and (band - 1) in covered
        if band > 0 and not has_partner:
            skipped += 1
        own = split_band(table, band, n_cells, has_earth)
        anchor = anchor_slices(table, band, n_cells, has_earth)
        composed = compose_band(
            own, anchor, band=band, n_cells=n_cells, lon_step=360.0 / n_cells,
            center_lat=cell['center_lat'], south_lat=cell['lat_min'],
            lat_scale=lat_scale, has_partner=has_partner)
        for offset_id, record in composed.items():
            records.append((band, offset_id, record))
    stats['bands_without_a_southern_partner'] = skipped
    return build_table(records, planet, stamped), stats


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--planet', choices=('mars', 'earth'), required=True)
    parser.add_argument('--quarters', type=Path, required=True,
                        help='directory holding band_group=NNN.parquet')
    parser.add_argument('--out', type=Path, required=True)
    parser.add_argument('--groups', type=str, default=None,
                        help='inclusive START-END over band groups')
    parser.add_argument('--resume', action='store_true')
    parser.add_argument('--require-all-groups', action='store_true',
                        help='refuse unless every band group of the planet has a '
                             'quarter file (a planet-scale compose must not '
                             'quietly become a partial one)')
    args = parser.parse_args(argv)

    grid = PlanetBandGrid.build(args.planet)
    available = sorted(int(p.stem.split('=')[1])
                       for p in Path(args.quarters).glob('band_group=*.parquet'))
    if args.require_all_groups:
        n_groups = -(-len(grid.column_counts) // tf.BANDS_PER_GROUP)
        missing = sorted(set(range(n_groups)) - set(available))
        if missing:
            print(f'refusing to compose: {len(missing)} of {n_groups} band groups '
                  'have no quarter file: ' + ', '.join(f'{g:03d}' for g in missing),
                  flush=True)
            return 2
    if args.groups:
        low, high = (int(v) for v in args.groups.split('-'))
        available = [g for g in available if low <= g <= high]
    if not available:
        print('no quarter band groups found', flush=True)
        return 2

    # One release from one extractor. Checked across every group before any
    # window is written: per group, a mix would only surface halfway through.
    versions = set()
    for group in available:
        path = quarter_group_path(args.quarters, group)
        if 'quarter_code_version' in pq.read_schema(path).names:
            versions.update(quarter_versions(
                pq.read_table(path, columns=['quarter_code_version'])))
    problems = qc.audit_quarter_versions(versions)
    if problems:
        print('refusing to compose:\n  ' + '\n  '.join(problems), flush=True)
        return 2

    # The window table names the code that composed it, not the code that
    # read the DEM: the quarters already carry that, and these two files are
    # the only ones whose arithmetic can change a window's numbers.
    provenance = {
        'code_version': tf.code_version(Path(__file__),
                                        Path(__file__).with_name('quarter_cells.py')),
        'computed_at': dt.datetime.now(dt.timezone.utc).replace(
            microsecond=0).isoformat().replace('+00:00', 'Z'),
    }
    total = 0
    for group in available:
        destination = group_path(args.out, group)
        if args.resume and destination.exists():
            print(f'group {group:03d}: already done', flush=True)
            continue
        table, stats = compose_group(args.planet, grid, args.quarters, group,
                                     provenance)
        tf.write_atomic(table, destination)
        total += table.num_rows
        print(f"group {group:03d}: {table.num_rows:,} windows from "
              f"{stats['bands']} bands", flush=True)
    print(f'done: {total:,} windows in {len(available)} group(s)', flush=True)
    return 0


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