starman / code-windows /quarter_cells.py
enzeeoai's picture
Super-squash history (latest files kept, was 8ef726a569)
d922ac9
Raw History Blame Contribute Delete
52.3 kB
"""Additive 2.5 km quarter-cell statistics, and the composer that merges them. The ``latband5km-v1`` terrain tables answer one question per 5 km cell. An analog search run against them cannot see a match that straddles a cell edge, because no row ever describes the terrain spanning that edge. This module fixes that without a second trip over the source DEMs: it splits every cell into 2x2 quarter-cells of ~2.5 km, stores only statistics that are *additive* over pixels, and then composes any 2x2 block of quarters back into one 5 km window. Sliding the block by one quarter in each direction gives a 2.5 km stride, so every point on the planet sits near the middle of some window. Two versions live here, both new, neither replacing ``FEATURE_VERSION``: * ``QUARTER_VERSION`` - the quarter table. A merge input, not a product. * ``WINDOW_VERSION`` - the composed window table. It carries the ``terrain-v0.2`` column set plus ``offset_id``. What merges exactly and what does not ------------------------------------- Counts, sums, extremes and threshold counts are additive, so means, standard deviations, ranges, threshold fractions and local relief come back exact. Detrended roughness is exact too, because a least-squares plane is determined by sufficient statistics that are themselves sums (see :func:`merge_moments`). Percentiles are *not* additive and never can be; they are approximated from mergeable histograms and are the only approximate columns in the output. Two geometric facts drive the design, and both are easy to get wrong: 1. **A north-south half-step is not a 2x2 merge of a band's own quarters.** Adjacent bands hold different numbers of longitude columns (on Earth only 5.1% of band pairs agree), so their cell edges can sit half a cell apart in longitude. Pairing quarters across a band boundary by index or by nearest centre yields a sheared quadrilateral, not a 5 km window. Band numbers run SOUTH to NORTH (band 0 touches the south pole), so a band's northern half borders ``band + 1``. A band therefore also emits its northern quarters indexed on the *next* band's column edges - the ``anchor`` grid. Both halves of a cross-band window then share one set of column edges and the window is an exact rectangle. 2. **A quarter cannot know which window will claim it.** Each quarter belongs to four different windows, so its plane-fit moments cannot be stored relative to "the window origin". They are stored relative to the quarter's own parent cell, together with the origin metadata needed to move them, and :func:`shift_moments` translates them exactly at merge time. """ from __future__ import annotations import os from pathlib import Path import numpy as np import pyarrow.parquet as pq from terrain_features import ( ELEV_PERCENTILES, SLOPE_PERCENTILES, SLOPE_THRESHOLDS, _sum, code_version as _feature_code_version, ) QUARTER_VERSION = 'quarter-v0.1' # Histogram counts are int32. A bin counts analysis pixels, a few hundred at # most, and the two histograms would otherwise be 71% of every row. The # dtype is also how a reader tells a current file from one written before # this was true, so :func:`audit_quarter_table` checks it. HISTOGRAM_TYPE = 'int32' WINDOW_VERSION = 'terrain-v0.3' N_BINS = 64 # How many pixels of a band to turn into plane-fit moments at a time. Purely # a memory bound: the sums are exact however the pixels are sliced. MOMENT_CHUNK = 1 << 20 # Dyadic levels are powers of two in metres. 2**-4 = 6.25 cm is finer than any # DEM here resolves; 2**13 = 8192 m covers the full Mars elevation span in a # single bin, so the search below always terminates. LEVEL_MIN, LEVEL_MAX = -4, 13 # Slope is bounded in [0, 90] degrees, so one fixed set of edges would work. # It was tried and measured: 64 edges spread over the whole range, denser at # the shallow end, left the slope percentiles wrong by up to 0.9 degrees on # gentle terrain, because that is simply the width of a bin there. Flatness is # the thing an analog search is most often asked about, so slope gets the same # dyadic treatment as elevation and the error falls with the terrain instead # of staying fixed. # The 15 plane-fit sufficient statistics. The first ten are the classical # normal-equation sums. The five ``s`` terms carry the metres-per-degree # longitude scale, which varies across a window because the meridians # converge; without them a cross-band merge could not move the longitude # origin exactly. See :func:`shift_moments`. MOMENTS = ('n', 'x', 'y', 'z', 'xx', 'yy', 'xy', 'xz', 'yz', 'zz', 's', 'ss', 'sx', 'sy', 'sz') # Everything a quarter stores, besides the moments, the histograms and its id. SCALARS = ( 'n_samples_200m', 'n_valid_samples_200m', 'n_native_samples', 'n_valid_native_samples', 'elev_sum', 'elev_sumsq', 'elev_min', 'elev_max', 'slope_n', 'slope_sum', 'slope_sumsq', 'slope_min', 'slope_max', *[f'slope_n_gt_{t}' for t in SLOPE_THRESHOLDS], 'relief_n', 'relief_sum', # k * n_samples_200m, so the merge is a sum and the window reports the # pixel-weighted averaging factor rather than one band's value. 'ew_samples_weighted', ) # Earth carries a water mask and a second, north-south averaging factor. # Mars has neither, and simply never puts these in a quarter record. EARTH_SCALARS = ('ns_samples_weighted', 'n_native_water', 'n_native_water_unknown') # Columns the composer reproduces exactly, and the six it approximates. EXACT_COLUMNS = ( 'n_samples_200m', 'n_valid_samples_200m', 'valid_frac_200m', 'n_native_samples', 'n_valid_native_samples', 'elev_min', 'elev_max', 'elev_mean', 'elev_range', 'slope_mean', 'slope_std', *[f'slope_frac_gt_{t}' for t in SLOPE_THRESHOLDS], 'local_relief_1km', 'roughness_detrended_std', ) APPROXIMATE_COLUMNS = ( 'elev_p05', 'elev_p95', 'elev_range_robust', 'slope_median', 'slope_p90', 'slope_p99', ) # -------------------------------------------------------------------------- # quarter assignment # -------------------------------------------------------------------------- def qcol_of_block(block_lons: np.ndarray, lon_step: float) -> np.ndarray: """West (0) or east (1) half of its own column, from the block centre. Splitting on the centre longitude rather than on a block index is what keeps the rule meaningful when a column's blocks arrive in several segments: Earth reads a band in longitude chunks, and the ten zone-straddling bands read it at two different pixel widths at once. An index-based split would cut those segments in different places. """ offset = (np.asarray(block_lons, dtype=np.float64) + 180.0) / lon_step return (np.floor((offset - np.floor(offset)) * 2.0).astype(np.int64) .clip(0, 1)) def cell_of_block(block_lons: np.ndarray, lon_step: float, n_cells: int) -> np.ndarray: """Grid column owning each block, by block centre longitude.""" lons = (np.asarray(block_lons, dtype=np.float64) + 180.0) % 360.0 return np.clip((lons / lon_step).astype(np.int64), 0, n_cells - 1) def qrow_of_row(row_lats: np.ndarray, center_lat: float) -> np.ndarray: """North (0) or south (1) half of the band, from the row centre latitude.""" return (np.asarray(row_lats, dtype=np.float64) < center_lat).astype(np.int64) def slot_index(qrow: np.ndarray, cell: np.ndarray, qcol: np.ndarray, n_cells: int) -> np.ndarray: """Flat quarter slot, ordered so that a column's four quarters are adjacent.""" return (np.asarray(qrow) * n_cells + np.asarray(cell)) * 2 + np.asarray(qcol) # -------------------------------------------------------------------------- # dyadic histograms # -------------------------------------------------------------------------- def dyadic_level(low: np.ndarray, high: np.ndarray, n_bins: int = N_BINS) -> np.ndarray: """Smallest level whose 2**level bins hold [low, high] in ``n_bins`` bins. Bin edges are the multiples of ``2**level``, anchored at zero and never at the data, which is the whole point: two quarters that chose different levels still have *aligned* edges, so coarsening one to the other's level is an exact regrouping of counts rather than a reinterpolation. """ low = np.asarray(low, dtype=np.float64) high = np.asarray(high, dtype=np.float64) level = np.full(low.shape, LEVEL_MIN, dtype=np.int64) good = np.isfinite(low) & np.isfinite(high) for _ in range(LEVEL_MAX - LEVEL_MIN + 1): width = np.ldexp(1.0, level) span = np.floor(high / width) - np.floor(low / width) fits = (span < n_bins) | (level >= LEVEL_MAX) if np.all(fits | ~good): break level = np.where(fits | ~good, level, level + 1) return np.where(good, level, LEVEL_MIN) def build_histogram(values: np.ndarray, slots: np.ndarray, n_slots: int, level: np.ndarray, n_bins: int = N_BINS ) -> tuple[np.ndarray, np.ndarray]: """Counts per slot on that slot's dyadic level, plus each slot's first bin.""" counts = np.zeros((n_slots, n_bins), dtype=np.int32) first = np.zeros(n_slots, dtype=np.int64) if values.size == 0: return counts, first width = np.ldexp(1.0, level) bin_of = np.floor(values / width[slots]).astype(np.int64) first_per_slot = np.full(n_slots, np.iinfo(np.int64).max, dtype=np.int64) np.minimum.at(first_per_slot, slots, bin_of) first = np.where(first_per_slot == np.iinfo(np.int64).max, 0, first_per_slot) offset = np.clip(bin_of - first[slots], 0, n_bins - 1) np.add.at(counts, (slots, offset), 1) return counts, first def merge_histograms(levels, firsts, counts, n_bins: int = N_BINS ) -> tuple[int, int, np.ndarray]: """Regroup several dyadic histograms onto one common level, exactly. Every level-``K`` bin is the union of whole level-``k`` bins for ``k <= K`` because all edges are multiples of a power of two anchored at zero, so this loses no information beyond the deliberate widening of the bins. """ parts = [(int(k), int(f), np.asarray(c, dtype=np.int64)) for k, f, c in zip(levels, firsts, counts) if np.sum(c) > 0] if not parts: return LEVEL_MIN, 0, np.zeros(n_bins, dtype=np.int64) target = max(k for k, _, _ in parts) while True: lows, highs = [], [] for k, f, c in parts: used = np.flatnonzero(c) shift = target - k lows.append((f + int(used[0])) >> shift) highs.append((f + int(used[-1])) >> shift) low, high = min(lows), max(highs) if high - low < n_bins or target >= LEVEL_MAX: break target += 1 out = np.zeros(n_bins, dtype=np.int64) for k, f, c in parts: shift = target - k used = np.flatnonzero(c) bins = ((f + used) >> shift) - low np.add.at(out, np.clip(bins, 0, n_bins - 1), c[used]) return target, low, out def histogram_percentiles(level: int, first: int, counts: np.ndarray, probs) -> np.ndarray: """Linear-interpolated percentiles of the distribution the counts describe. Within a bin the mass is taken as uniform. The error is therefore bounded by one bin width, which is what the caller reports as the approximation error. """ counts = np.asarray(counts, dtype=np.int64) total = int(counts.sum()) out = np.full(len(probs), np.nan) if total == 0: return out width = float(np.ldexp(1.0, level)) lower = (first + np.arange(len(counts))) * width upper = lower + width cumulative = np.concatenate([[0], np.cumsum(counts)]) for i, prob in enumerate(probs): target = (total - 1) * (prob / 100.0) index = int(np.searchsorted(cumulative[1:], target + 1e-12, side='left')) index = min(index, len(counts) - 1) inside = counts[index] if inside <= 0: out[i] = lower[index] continue within = (target - cumulative[index]) / inside out[i] = lower[index] + np.clip(within, 0.0, 1.0) * (upper[index] - lower[index]) return out # -------------------------------------------------------------------------- # the per-quarter reduction # -------------------------------------------------------------------------- def _finite(flat_values, flat_slots): keep = np.isfinite(flat_values) return flat_values[keep], flat_slots[keep] def _row_chunks(n_rows: int, n_cols: int): """Row slices holding about ``MOMENT_CHUNK`` pixels each.""" step = max(1, MOMENT_CHUNK // max(n_cols, 1)) for low in range(0, n_rows, step): yield slice(low, min(low + step, n_rows)) def quarter_features(segments, n_slots: int, *, slots_of_segment, origin_lon: np.ndarray, origin_lat: float, lon_scale, lat_scale: float) -> dict: """Reduce analysis segments to additive statistics on ``n_slots`` quarters. ``slots_of_segment(segment)`` returns the flat quarter slot of every analysis pixel of that segment, shaped like its elevation array, or ``None`` to skip the segment entirely. A negative slot means the pixel belongs to no quarter of this indexing; the anchor grid uses that to drop a band's southern rows. ``origin_lon`` is the reference longitude of each slot in degrees, ``origin_lat`` the reference latitude shared by the whole band, and ``lon_scale(lat)`` / ``lat_scale`` convert degrees to metres. The plane-fit moments are stored against that reference, and :func:`shift_moments` moves them to any other one exactly. A band is walked in row slices, twice, and nothing the size of the band is ever held. That is not tidiness: an equatorial Earth band is five million pixels, and materialising the fifteen plane-fit products of all of them at once needs about 600 MB in a single worker. """ out = {name: np.zeros(n_slots, dtype=np.float64) for name in SCALARS} out['elev_min'] = np.full(n_slots, np.inf) out['elev_max'] = np.full(n_slots, -np.inf) out['slope_min'] = np.full(n_slots, np.inf) out['slope_max'] = np.full(n_slots, -np.inf) moments = {name: np.zeros(n_slots, dtype=np.float64) for name in MOMENTS} def walk(segment): """Yield (rows, slot, owned) per row slice, slots already computed.""" slots = slots_of_segment(segment) if slots is None: return slots = np.asarray(slots) n_rows, n_cols = segment.elevation.shape for rows in _row_chunks(n_rows, n_cols): flat = (slots[rows].ravel() if slots.ndim == 2 else np.broadcast_to(slots, (rows.stop - rows.start, n_cols)).ravel()) owned = flat >= 0 if owned.any(): yield rows, flat[owned], owned # pass one: counts, sums and extremes, which fix z0 and the bin levels for segment in segments: for rows, slot, owned in walk(segment): out['n_samples_200m'] += np.bincount(slot, minlength=n_slots)[:n_slots] elevation = segment.elevation[rows].ravel()[owned] finite = np.isfinite(elevation) if finite.any(): values, cells = elevation[finite], slot[finite] out['n_valid_samples_200m'] += np.bincount(cells, minlength=n_slots)[:n_slots] out['elev_sum'] += _sum(cells, values, n_slots) out['elev_sumsq'] += _sum(cells, values * values, n_slots) np.minimum.at(out['elev_min'], cells, values) np.maximum.at(out['elev_max'], cells, values) slope = segment.slope[rows].ravel()[owned] finite = np.isfinite(slope) if finite.any(): values, cells = slope[finite], slot[finite] out['slope_n'] += np.bincount(cells, minlength=n_slots)[:n_slots] out['slope_sum'] += _sum(cells, values, n_slots) out['slope_sumsq'] += _sum(cells, values * values, n_slots) np.minimum.at(out['slope_min'], cells, values) np.maximum.at(out['slope_max'], cells, values) for threshold in SLOPE_THRESHOLDS: out[f'slope_n_gt_{threshold}'] += _sum( cells, (values > threshold).astype(np.float64), n_slots) relief = segment.relief[rows].ravel()[owned] finite = np.isfinite(relief) if finite.any(): values, cells = relief[finite], slot[finite] out['relief_n'] += np.bincount(cells, minlength=n_slots)[:n_slots] out['relief_sum'] += _sum(cells, values, n_slots) for name in ('elev_min', 'elev_max', 'slope_min', 'slope_max'): out[name][~np.isfinite(out[name])] = np.nan # The elevation offset keeps the central moments away from cancellation. # Raw Mars elevations reach 21 km, where sum(z*z) over a window is ~3e11 # and Szz = sum(z*z) - (sum z)**2/n loses the low bits of a smooth # plateau's roughness. Rounding to a whole metre keeps the offset exactly # representable, so moving it later is exact. with np.errstate(invalid='ignore'): z0 = np.where(out['n_valid_samples_200m'] > 0, np.round(out['elev_sum'] / np.maximum(out['n_valid_samples_200m'], 1)), 0.0) # Bins are multiples of 2**level anchored at zero, never at the data, so # two quarters that chose different levels still have aligned edges and a # merge is a regrouping rather than a reinterpolation. elev_level = dyadic_level(out['elev_min'], out['elev_max']) slope_level = dyadic_level(out['slope_min'], out['slope_max']) elev_hist = np.zeros((n_slots, N_BINS), dtype=np.int32) slope_hist = np.zeros((n_slots, N_BINS), dtype=np.int32) elev_first = np.full(n_slots, np.iinfo(np.int64).max, dtype=np.int64) slope_first = np.full(n_slots, np.iinfo(np.int64).max, dtype=np.int64) # pass two: the plane-fit moments and the first bin of each histogram for segment in segments: for rows, slot, owned in walk(segment): elevation = segment.elevation[rows].ravel()[owned] finite = np.isfinite(elevation) if not finite.any(): continue cells = slot[finite] part = elevation[finite] n_cols = segment.elevation.shape[1] lat = np.repeat(segment.row_lats[rows], n_cols)[owned][finite] lon = np.broadcast_to(segment.block_lons, (rows.stop - rows.start, n_cols)).ravel()[owned][finite] scale = lon_scale(lat) x = ((lon - origin_lon[cells] + 180.0) % 360.0 - 180.0) * scale del lon y = (lat - origin_lat) * lat_scale del lat z = part - z0[cells] moments['n'] += np.bincount(cells, minlength=n_slots)[:n_slots] # one product at a time, so only one lives beside x, y and z for name, left, right in ( ('x', x, None), ('y', y, None), ('z', z, None), ('xx', x, x), ('yy', y, y), ('xy', x, y), ('xz', x, z), ('yz', y, z), ('zz', z, z), ('s', scale, None), ('ss', scale, scale), ('sx', scale, x), ('sy', scale, y), ('sz', scale, z)): moments[name] += _sum(cells, left if right is None else left * right, n_slots) del x, y, z, scale np.minimum.at(elev_first, cells, np.floor(part / np.ldexp(1.0, elev_level[cells])).astype(np.int64)) slope = segment.slope[rows].ravel()[owned] finite_slope = np.isfinite(slope) if finite_slope.any(): cells_s, values_s = slot[finite_slope], slope[finite_slope] np.minimum.at(slope_first, cells_s, np.floor(values_s / np.ldexp(1.0, slope_level[cells_s])).astype(np.int64)) big = np.iinfo(np.int64).max elev_first = np.where(elev_first == big, 0, elev_first) slope_first = np.where(slope_first == big, 0, slope_first) # pass three: the counts themselves, now that each histogram's first bin # is known. Only the bin index is ever materialised. for segment in segments: for rows, slot, owned in walk(segment): elevation = segment.elevation[rows].ravel()[owned] finite = np.isfinite(elevation) if finite.any(): cells, values = slot[finite], elevation[finite] offset = np.clip( np.floor(values / np.ldexp(1.0, elev_level[cells])).astype(np.int64) - elev_first[cells], 0, N_BINS - 1) np.add.at(elev_hist, (cells, offset), 1) slope = segment.slope[rows].ravel()[owned] finite = np.isfinite(slope) if finite.any(): cells, values = slot[finite], slope[finite] offset = np.clip( np.floor(values / np.ldexp(1.0, slope_level[cells])).astype(np.int64) - slope_first[cells], 0, N_BINS - 1) np.add.at(slope_hist, (cells, offset), 1) out['plane_z0'] = z0 out['origin_lon'] = np.asarray(origin_lon, dtype=np.float64) out['origin_lat'] = np.full(n_slots, float(origin_lat)) out['lat_scale'] = np.full(n_slots, float(lat_scale)) for name, value in moments.items(): out[f'm_{name}'] = value out['elev_hist_level'] = elev_level out['elev_hist_first'] = elev_first out['elev_hist'] = elev_hist out['slope_hist_level'] = slope_level out['slope_hist_first'] = slope_first out['slope_hist'] = slope_hist return out # -------------------------------------------------------------------------- # exact translation of the plane-fit moments # -------------------------------------------------------------------------- def shift_moments(moments: dict, d_lon: float, alpha: float, beta: float, gamma: float) -> dict: """Move one quarter's moments to another origin, with no loss. Three independent changes of reference, all affine and therefore exact on sums: * ``d_lon`` degrees of longitude. Because a degree of longitude is worth fewer metres further from the equator, ``x`` moves by ``d_lon * s`` per pixel rather than by a constant - which is exactly why the ``s`` moments are carried. * ``y -> alpha*y + beta``, which re-references latitude. ``alpha`` is not 1 across a band boundary because the metres-per-degree scale is evaluated at each band's own centre. * ``gamma`` metres of elevation offset. The fitted plane, and so the roughness, is invariant to the choice of origin; the arithmetic here only has to be exact, not meaningful. """ m = {name: np.asarray(moments[name], dtype=np.float64) for name in MOMENTS} n = m['n'] out = {'n': n, 's': m['s'], 'ss': m['ss']} # longitude first: x' = x - d_lon*s x = m['x'] - d_lon * m['s'] xx = m['xx'] - 2.0 * d_lon * m['sx'] + d_lon * d_lon * m['ss'] xy = m['xy'] - d_lon * m['sy'] xz = m['xz'] - d_lon * m['sz'] sx = m['sx'] - d_lon * m['ss'] # elevation: z' = z + gamma z = m['z'] + gamma * n zz = m['zz'] + 2.0 * gamma * m['z'] + gamma * gamma * n xz = xz + gamma * x yz = m['yz'] + gamma * m['y'] sz = m['sz'] + gamma * m['s'] # latitude: y' = alpha*y + beta y = alpha * m['y'] + beta * n yy = alpha * alpha * m['yy'] + 2.0 * alpha * beta * m['y'] + beta * beta * n xy = alpha * xy + beta * x yz = alpha * yz + beta * z sy = alpha * m['sy'] + beta * m['s'] out.update(x=x, y=y, z=z, xx=xx, yy=yy, xy=xy, xz=xz, yz=yz, zz=zz, sx=sx, sy=sy, sz=sz) return out def merge_moments(parts) -> dict: """Add moments that already share one origin.""" return {name: float(sum(float(p[name]) for p in parts)) for name in MOMENTS} def roughness_from_moments(m: dict) -> float: """Standard deviation of residuals from the least-squares plane. Solved in central-moment form, which is the well-conditioned way to get there from sums: the normal equations are built on deviations from the centroid, so the constant term drops out and only the 2x2 system in the two gradients remains. """ n = m['n'] if n < 4: return float('nan') mean_x, mean_y, mean_z = m['x'] / n, m['y'] / n, m['z'] / n sxx = m['xx'] - n * mean_x * mean_x syy = m['yy'] - n * mean_y * mean_y sxy = m['xy'] - n * mean_x * mean_y sxz = m['xz'] - n * mean_x * mean_z syz = m['yz'] - n * mean_y * mean_z szz = m['zz'] - n * mean_z * mean_z normal = np.array([[sxx, sxy], [sxy, syy]], dtype=np.float64) rhs = np.array([sxz, syz], dtype=np.float64) # pinv, like the direct path, keeps a single row or column of pixels # solvable instead of returning NaN for it. coefficients = np.linalg.pinv(normal) @ rhs residual = szz - float(coefficients @ rhs) return float(np.sqrt(max(residual, 0.0) / n)) # -------------------------------------------------------------------------- # the window composer # -------------------------------------------------------------------------- def compose_window(quarters, reference=None) -> dict: """Merge any block of quarter records into one 5 km window record. Pure: it touches no raster and no file, and it does not care whether the quarters came from one band or from two. ``reference`` is ``(lon_deg, lat_deg, metres_per_degree_north)``, the coordinate origin the plane is fitted in. It is part of the contract, not an implementation detail: a degree of longitude shrinks towards the poles, so ``x = (lon - origin) * metres_per_degree(lat)`` is not merely shifted when the origin moves, and two origins give two genuinely different - if nearly identical - planes. Fixing it at the window's own centre is what makes a merged window equal a direct computation on the same pixels rather than approximately equal. Passing ``None`` falls back to the first quarter's origin, which for offset 0 is already the window centre. Returns the ``terrain-v0.2`` column set. The six percentile columns are approximations from merged histograms; everything else is exact. """ quarters = [q for q in quarters if q is not None] if not quarters: raise ValueError('a window needs at least one quarter') present = [q for q in quarters if q['n_valid_samples_200m'] > 0] row = {} keys = set(SCALARS) | set(EARTH_SCALARS) for name in keys: if any(name in q for q in quarters): row[name] = float(sum(float(q.get(name, 0.0)) for q in quarters)) row['elev_min'] = min((float(q['elev_min']) for q in present), default=np.nan) row['elev_max'] = max((float(q['elev_max']) for q in present), default=np.nan) row['slope_min'] = min((float(q['slope_min']) for q in present if np.isfinite(q['slope_min'])), default=np.nan) row['slope_max'] = max((float(q['slope_max']) for q in present if np.isfinite(q['slope_max'])), default=np.nan) n_pixels = row['n_samples_200m'] n_valid = row['n_valid_samples_200m'] row['valid_frac_200m'] = n_valid / n_pixels if n_pixels > 0 else np.nan if n_valid > 0: row['elev_mean'] = row['elev_sum'] / n_valid row['elev_range'] = row['elev_max'] - row['elev_min'] else: row['elev_mean'] = row['elev_range'] = np.nan slope_n = row['slope_n'] if slope_n > 0: mean = row['slope_sum'] / slope_n row['slope_mean'] = mean variance = row['slope_sumsq'] / slope_n - mean * mean row['slope_std'] = float(np.sqrt(max(variance, 0.0))) for threshold in SLOPE_THRESHOLDS: row[f'slope_frac_gt_{threshold}'] = row[f'slope_n_gt_{threshold}'] / slope_n else: row['slope_mean'] = row['slope_std'] = np.nan for threshold in SLOPE_THRESHOLDS: row[f'slope_frac_gt_{threshold}'] = np.nan row['local_relief_1km'] = (row['relief_sum'] / row['relief_n'] if row['relief_n'] > 0 else np.nan) row['ew_samples_averaged'] = (row['ew_samples_weighted'] / n_pixels if n_pixels > 0 else np.nan) if 'ns_samples_weighted' in row: row['ns_samples_averaged'] = (row['ns_samples_weighted'] / n_pixels if n_pixels > 0 else np.nan) if 'n_native_water' in row: native = row['n_native_samples'] row['water_mask_frac'] = (np.nan if native <= 0 or row['n_native_water_unknown'] > 0 else row['n_native_water'] / native) # plane fit: bring every quarter onto the first one's origin, then add if present: if reference is None: ref_lon = float(present[0]['origin_lon']) ref_lat = float(present[0]['origin_lat']) ref_scale = float(present[0]['lat_scale']) else: ref_lon, ref_lat, ref_scale = (float(v) for v in reference) ref_z0 = float(present[0]['plane_z0']) moved = [] for q in present: own_scale = float(q['lat_scale']) # y_ref = (lat - ref_lat)*ref_scale, y_own = (lat - own_lat)*own_scale, # so y_ref = (ref_scale/own_scale)*y_own + (own_lat - ref_lat)*ref_scale. # One division, exactly as compose_windows_array does it: 1/(a/b) # and b/a can differ in the last bit, and the two composers are # supposed to be the same arithmetic. alpha = ref_scale / own_scale if own_scale else 1.0 beta = (float(q['origin_lat']) - ref_lat) * ref_scale moved.append(shift_moments( {name: q[f'm_{name}'] for name in MOMENTS}, d_lon=(ref_lon - float(q['origin_lon']) + 180.0) % 360.0 - 180.0, alpha=alpha, beta=beta, gamma=float(q['plane_z0']) - ref_z0)) total = merge_moments(moved) row['roughness_detrended_std'] = roughness_from_moments(total) else: row['roughness_detrended_std'] = np.nan # percentiles, the only approximate columns if present: level, first, counts = merge_histograms( [q['elev_hist_level'] for q in present], [q['elev_hist_first'] for q in present], [q['elev_hist'] for q in present]) p05, p95 = histogram_percentiles(level, first, counts, ELEV_PERCENTILES) row['elev_p05'], row['elev_p95'] = p05, p95 row['elev_range_robust'] = row['elev_p95'] - row['elev_p05'] row['elev_hist_level'] = level else: row['elev_p05'] = row['elev_p95'] = row['elev_range_robust'] = np.nan row['elev_hist_level'] = LEVEL_MIN with_slope = [q for q in quarters if np.sum(q['slope_hist']) > 0] if with_slope: level, first, counts = merge_histograms( [q['slope_hist_level'] for q in with_slope], [q['slope_hist_first'] for q in with_slope], [q['slope_hist'] for q in with_slope]) median, p90, p99 = histogram_percentiles(level, first, counts, SLOPE_PERCENTILES) row['slope_median'], row['slope_p90'], row['slope_p99'] = median, p90, p99 row['slope_hist_level'] = level else: row['slope_median'] = row['slope_p90'] = row['slope_p99'] = np.nan row['slope_hist_level'] = LEVEL_MIN return row # -------------------------------------------------------------------------- # band-level helpers the drivers call # -------------------------------------------------------------------------- def own_grid_slots(segment, *, n_cells: int, lon_step: float, center_lat: float): """Quarter slot of every analysis pixel, on the band's own column grid.""" cell = cell_of_block(segment.block_lons, lon_step, n_cells) qcol = qcol_of_block(segment.block_lons, lon_step) qrow = qrow_of_row(segment.row_lats, center_lat) return slot_index(qrow[:, None], cell[None, :], qcol[None, :], n_cells) def anchor_grid_slots(segment, *, n_cells_anchor: int, lon_step_anchor: float, center_lat: float): """Slots for this band's NORTHERN rows on the next band's column grid. This is the whole north-south stride. Bands are numbered south to north, so the northern rows of ``band`` border ``band + 1``, and the anchor grid is that band's. Bands do not share column counts, so a window spanning a band boundary has to pick one band's edges and index both halves against them; the southern band's northern half is therefore reduced a second time here. Rows south of the band centre return no slot and are dropped, and the result is only one quarter row tall. ``None`` means the segment has no northern row at all, and every consumer must skip it. """ keep = qrow_of_row(segment.row_lats, center_lat) == 0 if not keep.any(): return None cell = cell_of_block(segment.block_lons, lon_step_anchor, n_cells_anchor) qcol = qcol_of_block(segment.block_lons, lon_step_anchor) slots = slot_index(np.zeros(1, dtype=np.int64)[:, None], cell[None, :], qcol[None, :], n_cells_anchor) return np.where(keep[:, None], np.broadcast_to(slots, segment.elevation.shape), -1) def slot_origin_lon(n_cells: int, lon_step: float, n_slots: int) -> np.ndarray: """Reference longitude of each slot: the centre of the cell it belongs to.""" slots = np.arange(n_slots, dtype=np.int64) cell = (slots // 2) % n_cells return -180.0 + lon_step * (cell + 0.5) # -------------------------------------------------------------------------- # table schemas # -------------------------------------------------------------------------- # A quarter is addressed by its parent cell plus which quarter of it this is. # ``anchor_band`` is the band whose column edges ``column`` counts against: it # equals ``band`` for a band's own quarters and ``band + 1`` - the band to the # north, since bands are numbered south to north - for the northern quarters # re-indexed for cross-band windows. ``quarter_id`` is deterministic and # permanent, like ``region_id``. QUARTER_KEY_COLUMNS = ('quarter_id', 'planet', 'band', 'anchor_band', 'column', 'qrow', 'qcol') # Float64 throughout, deliberately: these are merge inputs, and rounding a sum # of squares to float32 before it is merged would put the error back into the # columns the whole design exists to keep exact. QUARTER_FLOAT_COLUMNS = ( *SCALARS, *EARTH_SCALARS, *[f'm_{name}' for name in MOMENTS], 'plane_z0', 'origin_lon', 'origin_lat', 'lat_scale', ) QUARTER_LIST_COLUMNS = ('elev_hist', 'slope_hist') QUARTER_INT_COLUMNS = ('elev_hist_level', 'elev_hist_first', 'slope_hist_level', 'slope_hist_first') # The composed window table: the terrain-v0.2 feature columns, plus the three # that say which window this is. WINDOW_KEY_COLUMNS = ('window_id', 'planet', 'band', 'column', 'offset_id', 'offset_row', 'offset_col') def quarter_id(prefix: str, band: int, anchor_band: int, column: int, qrow: int, qcol: int) -> str: """``M_0123_04567_q10`` - parent cell, then the quarter inside it. A trailing ``a`` marks a quarter indexed on the next band's (``band + 1``) column edges, so the two indexings of the same pixels can never be confused. """ suffix = 'a' if anchor_band != band else '' return f'{prefix}_{band:04d}_{column:05d}_q{qrow}{qcol}{suffix}' def window_id(prefix: str, band: int, column: int, offset_id: int) -> str: """``M_0123_04567_w3`` - the anchor cell, then which of the four windows.""" return f'{prefix}_{band:04d}_{column:05d}_w{offset_id}' # offset_id -> (row offset, column offset) in quarter units. 0 is the existing # 5 km cell; the other three slide the window half a cell east, south, or both. OFFSETS = {0: (0, 0), 1: (0, 1), 2: (1, 0), 3: (1, 1)} # -------------------------------------------------------------------------- # the same composer, vectorised over a whole band # -------------------------------------------------------------------------- # # :func:`compose_window` is the readable definition and the one the tests # compare against. It is also far too slow for a planet: Earth has about 20 # million cells and so about 80 million windows, which at Python speed is # days. Everything below does exactly the same arithmetic with one array # operation per band instead of one call per window, and # ``test_quarter_cells`` pins the two against each other. def roughness_from_moments_array(m: dict) -> np.ndarray: """Batched :func:`roughness_from_moments`. The 2x2 system is solved in closed form. Where it is singular - a quarter holding a single row or column of pixels - the minimum-norm solution is used instead, which is what ``pinv`` returns in the scalar path and gives the same residual, because the fitted values are unique even when the gradients are not. """ n = np.asarray(m['n'], dtype=np.float64) safe = np.maximum(n, 1.0) mean_x, mean_y, mean_z = m['x'] / safe, m['y'] / safe, m['z'] / safe sxx = m['xx'] - n * mean_x * mean_x syy = m['yy'] - n * mean_y * mean_y sxy = m['xy'] - n * mean_x * mean_y sxz = m['xz'] - n * mean_x * mean_z syz = m['yz'] - n * mean_y * mean_z szz = m['zz'] - n * mean_z * mean_z determinant = sxx * syy - sxy * sxy scale = np.maximum(np.abs(sxx * syy), np.abs(sxy * sxy)) regular = np.abs(determinant) > np.finfo(np.float64).eps * 8.0 * np.maximum(scale, 1e-300) with np.errstate(invalid='ignore', divide='ignore'): safe_det = np.where(regular, determinant, 1.0) b1 = np.where(regular, (syy * sxz - sxy * syz) / safe_det, 0.0) b2 = np.where(regular, (sxx * syz - sxy * sxz) / safe_det, 0.0) only_x = ~regular & (sxx > 0) only_y = ~regular & ~only_x & (syy > 0) b1 = np.where(only_x, sxz / np.where(sxx > 0, sxx, 1.0), b1) b2 = np.where(only_y, syz / np.where(syy > 0, syy, 1.0), b2) residual = szz - (b1 * sxz + b2 * syz) out = np.sqrt(np.maximum(residual, 0.0) / safe) return np.where(n >= 4, out, np.nan) def _used_range(counts: np.ndarray) -> tuple[np.ndarray, np.ndarray]: """First and last non-empty bin of each row, as offsets from its start.""" occupied = counts > 0 any_row = occupied.any(axis=-1) first = np.argmax(occupied, axis=-1) last = counts.shape[-1] - 1 - np.argmax(occupied[..., ::-1], axis=-1) return np.where(any_row, first, 0), np.where(any_row, last, 0) def merge_histograms_array(levels: np.ndarray, firsts: np.ndarray, counts: np.ndarray, n_bins: int = N_BINS): """Batched :func:`merge_histograms` over ``(n_windows, n_parts, n_bins)``.""" levels = np.asarray(levels, dtype=np.int64) firsts = np.asarray(firsts, dtype=np.int64) counts = np.asarray(counts, dtype=np.int64) n_windows, n_parts, _ = counts.shape present = counts.sum(axis=2) > 0 offset_low, offset_high = _used_range(counts) low_bin = firsts + offset_low high_bin = firsts + offset_high target = np.where(present.any(axis=1), np.max(np.where(present, levels, LEVEL_MIN), axis=1), LEVEL_MIN) big = np.iinfo(np.int64).max // 4 for _ in range(LEVEL_MAX - LEVEL_MIN + 1): shift = np.maximum(target[:, None] - levels, 0) low = np.min(np.where(present, low_bin >> shift, big), axis=1) high = np.max(np.where(present, high_bin >> shift, -big), axis=1) too_wide = present.any(axis=1) & (high - low >= n_bins) & (target < LEVEL_MAX) if not too_wide.any(): break target = target + too_wide low = np.where(present.any(axis=1), low, 0) out = np.zeros((n_windows, n_bins), dtype=np.int64) shift = np.maximum(target[:, None] - levels, 0) bins = np.arange(n_bins, dtype=np.int64) destination = ((firsts[:, :, None] + bins) >> shift[:, :, None]) - low[:, None, None] destination = np.clip(destination, 0, n_bins - 1) rows = np.broadcast_to(np.arange(n_windows)[:, None, None], counts.shape) keep = np.broadcast_to(present[:, :, None], counts.shape) & (counts > 0) np.add.at(out, (rows[keep], destination[keep]), counts[keep]) return target, low, out def histogram_percentiles_array(level, first, counts: np.ndarray, probs ) -> np.ndarray: """Batched :func:`histogram_percentiles`. Returns ``(len(probs), n_rows)``.""" counts = np.asarray(counts, dtype=np.int64) n_rows, n_bins = counts.shape total = counts.sum(axis=1) cumulative = np.concatenate([np.zeros((n_rows, 1), dtype=np.int64), np.cumsum(counts, axis=1)], axis=1) width = np.ldexp(1.0, np.asarray(level, dtype=np.int64))[:, None] lower = (np.asarray(first, dtype=np.int64)[:, None] + np.arange(n_bins)) * width upper = lower + width out = np.full((len(probs), n_rows), np.nan) has = total > 0 if not has.any(): return out for i, prob in enumerate(probs): target = (total - 1) * (prob / 100.0) index = np.clip(np.sum(cumulative[:, 1:] < target[:, None] + 1e-12, axis=1), 0, n_bins - 1) rows = np.arange(n_rows) inside = counts[rows, index] base = cumulative[rows, index] with np.errstate(invalid='ignore', divide='ignore'): within = np.where(inside > 0, (target - base) / np.maximum(inside, 1), 0.0) value = lower[rows, index] + np.clip(within, 0.0, 1.0) * ( upper[rows, index] - lower[rows, index]) out[i] = np.where(has, value, np.nan) return out def compose_windows_array(parts, reference) -> dict: """Batched :func:`compose_window`. ``parts`` is a sequence of per-quarter dicts whose values are arrays over windows; ``reference`` is ``(lon, lat, metres_per_degree_north)``, each an array over windows. Absent quarters are those with no valid samples; their moments are zero, so they add nothing and need no masking. """ n_windows = len(np.asarray(reference[0])) present = np.stack([np.asarray(q['n_valid_samples_200m']) > 0 for q in parts]) row = {} keys = set(SCALARS) | set(EARTH_SCALARS) for name in keys: if any(name in q for q in parts): row[name] = sum(np.asarray(q.get(name, 0.0), dtype=np.float64) for q in parts) def extreme(name, op, empty): stack = np.stack([np.where(present[i], np.asarray(q[name], dtype=np.float64), empty) for i, q in enumerate(parts)]) value = op.reduce(stack, axis=0) return np.where(present.any(axis=0), value, np.nan) row['elev_min'] = extreme('elev_min', np.fmin, np.inf) row['elev_max'] = extreme('elev_max', np.fmax, -np.inf) n_pixels, n_valid = row['n_samples_200m'], row['n_valid_samples_200m'] with np.errstate(invalid='ignore', divide='ignore'): row['valid_frac_200m'] = np.where(n_pixels > 0, n_valid / np.maximum(n_pixels, 1), np.nan) row['elev_mean'] = np.where(n_valid > 0, row['elev_sum'] / np.maximum(n_valid, 1), np.nan) row['elev_range'] = row['elev_max'] - row['elev_min'] slope_n = row['slope_n'] has_slope = slope_n > 0 safe_slope = np.maximum(slope_n, 1) mean = np.where(has_slope, row['slope_sum'] / safe_slope, np.nan) row['slope_mean'] = mean variance = np.where(has_slope, row['slope_sumsq'] / safe_slope - mean * mean, np.nan) row['slope_std'] = np.sqrt(np.maximum(variance, 0.0)) for threshold in SLOPE_THRESHOLDS: row[f'slope_frac_gt_{threshold}'] = np.where( has_slope, row[f'slope_n_gt_{threshold}'] / safe_slope, np.nan) row['local_relief_1km'] = np.where( row['relief_n'] > 0, row['relief_sum'] / np.maximum(row['relief_n'], 1), np.nan) row['ew_samples_averaged'] = np.where( n_pixels > 0, row['ew_samples_weighted'] / np.maximum(n_pixels, 1), np.nan) if 'ns_samples_weighted' in row: row['ns_samples_averaged'] = np.where( n_pixels > 0, row['ns_samples_weighted'] / np.maximum(n_pixels, 1), np.nan) if 'n_native_water' in row: native = row['n_native_samples'] row['water_mask_frac'] = np.where( (native > 0) & (row['n_native_water_unknown'] == 0), row['n_native_water'] / np.maximum(native, 1), np.nan) ref_lon, ref_lat, ref_scale = (np.asarray(v, dtype=np.float64) for v in reference) first_present = np.argmax(present, axis=0) ref_z0 = np.choose(first_present, [np.asarray(q['plane_z0'], dtype=np.float64) for q in parts]) ref_z0 = np.where(present.any(axis=0), ref_z0, 0.0) total = {name: np.zeros(n_windows) for name in MOMENTS} for i, q in enumerate(parts): own_scale = np.asarray(q['lat_scale'], dtype=np.float64) # an absent quarter's lat_scale is 0 (compose_windows.empty_part); the # division is masked out below, so silence its warning only with np.errstate(divide='ignore', invalid='ignore'): alpha = np.where(own_scale != 0, ref_scale / own_scale, 1.0) beta = (np.asarray(q['origin_lat'], dtype=np.float64) - ref_lat) * ref_scale moved = shift_moments( {name: np.where(present[i], np.asarray(q[f'm_{name}'], dtype=np.float64), 0.0) for name in MOMENTS}, d_lon=(ref_lon - np.asarray(q['origin_lon'], dtype=np.float64) + 180.0) % 360.0 - 180.0, alpha=alpha, beta=beta, gamma=np.where(present[i], np.asarray(q['plane_z0'], dtype=np.float64) - ref_z0, 0.0)) for name in MOMENTS: total[name] = total[name] + np.where(present[i], moved[name], 0.0) row['roughness_detrended_std'] = roughness_from_moments_array(total) level, low, counts = merge_histograms_array( np.stack([np.asarray(q['elev_hist_level']) for q in parts], axis=1), np.stack([np.asarray(q['elev_hist_first']) for q in parts], axis=1), np.stack([np.asarray(q['elev_hist']) for q in parts], axis=1)) p05, p95 = histogram_percentiles_array(level, low, counts, ELEV_PERCENTILES) row['elev_p05'], row['elev_p95'] = p05, p95 row['elev_range_robust'] = p95 - p05 row['elev_hist_level'] = level slope_level, slope_low, slope_counts = merge_histograms_array( np.stack([np.asarray(q['slope_hist_level']) for q in parts], axis=1), np.stack([np.asarray(q['slope_hist_first']) for q in parts], axis=1), np.stack([np.asarray(q['slope_hist']) for q in parts], axis=1)) median, p90, p99 = histogram_percentiles_array( slope_level, slope_low, slope_counts, SLOPE_PERCENTILES) row['slope_median'], row['slope_p90'], row['slope_p99'] = median, p90, p99 row['slope_hist_level'] = slope_level return row class QuarterWriter: """Append a band's quarter rows straight to the Parquet file. A band group holds up to a hundred bands, and near the equator that is nearly five million quarter rows. Building them all before writing needs about 6.5 GB in one worker, and eight workers run at once: that is an OOM kill, and it is what this class exists to avoid. Rows are handed to the file one band at a time and dropped immediately, so the peak is one band. The file is written beside its target and renamed on close, so a reader never sees a partial one - the same contract as ``write_atomic``. """ def __init__(self, path): import uuid self.path = Path(path) self.temporary = self.path.with_name( f'.{self.path.name}.{os.getpid()}.{uuid.uuid4().hex[:8]}.tmp') self._writer = None self.rows = 0 def write(self, table) -> None: if table is None or table.num_rows == 0: return if self._writer is None: self.path.parent.mkdir(parents=True, exist_ok=True) self._writer = pq.ParquetWriter(self.temporary, table.schema, compression='zstd') self._writer.write_table(table) self.rows += table.num_rows def close(self, empty=None) -> int: """Finish the file. ``empty`` builds a header-only table if no band produced a row, so ``--resume`` still sees the group as finished.""" try: if self._writer is None: if empty is None: return 0 table = empty() self.path.parent.mkdir(parents=True, exist_ok=True) self._writer = pq.ParquetWriter(self.temporary, table.schema, compression='zstd') self._writer.write_table(table) self._writer.close() self._writer = None os.replace(self.temporary, self.path) finally: if self._writer is not None: self._writer.close() if self.temporary.exists(): self.temporary.unlink() return self.rows # -------------------------------------------------------------------------- # provenance and file audit # -------------------------------------------------------------------------- def quarter_code_version(driver) -> str: """SHA-256 over the driver, the shared feature module, and this one. A terrain row's ``code_version`` covers the driver and ``terrain_features.py``. That is right for the terrain table and wrong for this one: every number in a quarter row is decided here, so a change to this file that left the driver alone would otherwise leave no trace in the data it changed. The two hashes are deliberately different values. """ here = Path(__file__).resolve() return _feature_code_version(driver, here.with_name('terrain_features.py'), here) def audit_quarter_table(table, path: str = '') -> list[str]: """Reasons this quarter file must not be composed, or an empty list. Composing is where a stale file does its damage, because the result looks like every other window and carries no sign of where it came from. The histogram dtype and the presence of ``quarter_code_version`` both date a file, so they are checked before anything reads it rather than trusted. """ where = f'{path}: ' if path else '' problems = [] names = set(table.column_names) for name in QUARTER_LIST_COLUMNS: if name not in names: problems.append(f'{where}no {name} column') continue field_type = table.schema.field(name).type value_type = getattr(field_type, 'value_type', None) if value_type is None or str(value_type) != HISTOGRAM_TYPE: problems.append( f'{where}{name} holds {value_type}, not {HISTOGRAM_TYPE}; ' 'this file predates the streaming writer and was built by ' 'code that is no longer in the tree') if 'quarter_code_version' not in names: problems.append(f'{where}no quarter_code_version column, so the code ' 'that produced these numbers cannot be identified') return problems def audit_quarter_versions(versions) -> list[str]: """One release must come from one version of this module.""" distinct = sorted({v for v in versions if v}) if len(distinct) > 1: return [f'{len(distinct)} different quarter_code_version values across ' f'the files: {", ".join(v[:12] for v in distinct)}'] return []
"""Additive 2.5 km quarter-cell statistics, and the composer that merges them.
The ``latband5km-v1`` terrain tables answer one question per 5 km cell. An
analog search run against them cannot see a match that straddles a cell edge,
because no row ever describes the terrain spanning that edge. This module
fixes that without a second trip over the source DEMs: it splits every cell
into 2x2 quarter-cells of ~2.5 km, stores only statistics that are *additive*
over pixels, and then composes any 2x2 block of quarters back into one 5 km
window. Sliding the block by one quarter in each direction gives a 2.5 km
stride, so every point on the planet sits near the middle of some window.
Two versions live here, both new, neither replacing ``FEATURE_VERSION``:
* ``QUARTER_VERSION`` - the quarter table. A merge input, not a product.
* ``WINDOW_VERSION`` - the composed window table. It carries the
``terrain-v0.2`` column set plus ``offset_id``.
What merges exactly and what does not
-------------------------------------
Counts, sums, extremes and threshold counts are additive, so means, standard
deviations, ranges, threshold fractions and local relief come back exact.
Detrended roughness is exact too, because a least-squares plane is determined
by sufficient statistics that are themselves sums (see :func:`merge_moments`).
Percentiles are *not* additive and never can be; they are approximated from
mergeable histograms and are the only approximate columns in the output.
Two geometric facts drive the design, and both are easy to get wrong:
1. **A north-south half-step is not a 2x2 merge of a band's own quarters.**
Adjacent bands hold different numbers of longitude columns (on Earth only
5.1% of band pairs agree), so their cell edges can sit half a cell apart in
longitude. Pairing quarters across a band boundary by index or by nearest
centre yields a sheared quadrilateral, not a 5 km window. Band numbers run
SOUTH to NORTH (band 0 touches the south pole), so a band's northern half
borders ``band + 1``. A band therefore also emits its northern quarters
indexed on the *next* band's column edges - the ``anchor`` grid. Both
halves of a cross-band window then share one set of column edges and the
window is an exact rectangle.
2. **A quarter cannot know which window will claim it.** Each quarter belongs
to four different windows, so its plane-fit moments cannot be stored
relative to "the window origin". They are stored relative to the quarter's
own parent cell, together with the origin metadata needed to move them, and
:func:`shift_moments` translates them exactly at merge time.
"""
from __future__ import annotations
import os
from pathlib import Path
import numpy as np
import pyarrow.parquet as pq
from terrain_features import (
ELEV_PERCENTILES, SLOPE_PERCENTILES, SLOPE_THRESHOLDS, _sum,
code_version as _feature_code_version,
)
QUARTER_VERSION = 'quarter-v0.1'
# Histogram counts are int32. A bin counts analysis pixels, a few hundred at
# most, and the two histograms would otherwise be 71% of every row. The
# dtype is also how a reader tells a current file from one written before
# this was true, so :func:`audit_quarter_table` checks it.
HISTOGRAM_TYPE = 'int32'
WINDOW_VERSION = 'terrain-v0.3'
N_BINS = 64
# How many pixels of a band to turn into plane-fit moments at a time. Purely
# a memory bound: the sums are exact however the pixels are sliced.
MOMENT_CHUNK = 1 << 20
# Dyadic levels are powers of two in metres. 2**-4 = 6.25 cm is finer than any
# DEM here resolves; 2**13 = 8192 m covers the full Mars elevation span in a
# single bin, so the search below always terminates.
LEVEL_MIN, LEVEL_MAX = -4, 13
# Slope is bounded in [0, 90] degrees, so one fixed set of edges would work.
# It was tried and measured: 64 edges spread over the whole range, denser at
# the shallow end, left the slope percentiles wrong by up to 0.9 degrees on
# gentle terrain, because that is simply the width of a bin there. Flatness is
# the thing an analog search is most often asked about, so slope gets the same
# dyadic treatment as elevation and the error falls with the terrain instead
# of staying fixed.
# The 15 plane-fit sufficient statistics. The first ten are the classical
# normal-equation sums. The five ``s`` terms carry the metres-per-degree
# longitude scale, which varies across a window because the meridians
# converge; without them a cross-band merge could not move the longitude
# origin exactly. See :func:`shift_moments`.
MOMENTS = ('n', 'x', 'y', 'z', 'xx', 'yy', 'xy', 'xz', 'yz', 'zz',
's', 'ss', 'sx', 'sy', 'sz')
# Everything a quarter stores, besides the moments, the histograms and its id.
SCALARS = (
'n_samples_200m', 'n_valid_samples_200m',
'n_native_samples', 'n_valid_native_samples',
'elev_sum', 'elev_sumsq', 'elev_min', 'elev_max',
'slope_n', 'slope_sum', 'slope_sumsq', 'slope_min', 'slope_max',