File size: 8,337 Bytes
a8e0542
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""SWIM 2.0 ice-consistency maps -> per-cell `ice_consistency*` and `ice_frac` (planet mars).

SWIM consistency fraction is distinct from Earth permafrost extent. The rasters (7200 x 2400, equidistant cylindrical on a
3,396,190 m sphere) are already -180..180 east-positive, so there is no roll; the first column is
centred at about -180.05 deg, so pixel centres are wrapped modulo 360 before they are assigned to cells.
Each raster window is read from the local file; nothing is downloaded.

Columns
-------
ice_consistency_0_1m / _1_5m / _gt5m   cell mean of the c0_1 / c1_5 / c_5 map (-1..+1; +1 consistent with ice)
ice_consistency                        cell mean of max(c0_1, c1_5): ice within the top ~5 m
ice_frac                               share of valid pixels with max(c0_1, c1_5) > ICE_THRESHOLD
n_px, valid_frac                       pixels assigned to the cell; share of them valid in all used maps
"""
from __future__ import annotations

from pathlib import Path

import numpy as np
import pyarrow as pa

from . import _climatology as clim
from . import _cellmap as cm

SOURCE = {
    'product': 'Subsurface Water Ice Mapping (SWIM) 2.0 data products',
    'version': 'SWIM 2.0 (Dec 2020 - Feb 2021 files)',
    'url': 'https://swim.psi.edu/SWIM2Products.php',
    'licence': 'No licence text on swim.psi.edu; non-commercial use accepted (Enzo, 2026-11-13).',
    'planet': 'mars',
}
VERSION = 'v0.1'
MISSING_FLAG = 'outside_coverage'      # groups with no raster rows: every cell is poleward of 60 deg

MARS_RADIUS_M = 3396190.0
LAT_LIMIT_DEG = 60.0
NODATA = -100.0
DEPTH_FILES = {'c0_1': 'SWIM2_c0_1.tif', 'c1_5': 'SWIM2_c1_5.tif', 'c_5': 'SWIM2_c_5.tif'}
ICE_DEPTH_MAPS = ('c0_1', 'c1_5')      # "ice within the top ~5 m"; config constant
ICE_THRESHOLD = 0.0                    # ice_frac counts pixels with the combined value above this

_C = {'dtype': 'float32', 'unit': '1', 'comparison': 'within_planet'}
COLUMNS = {
    'ice_consistency_0_1m': {**_C, 'description': 'SWIM 2.0 combined ice consistency, depth 0-1 m '
                             '(-1 no ice .. +1 ice), cell mean'},
    'ice_consistency_1_5m': {**_C, 'description': 'SWIM 2.0 combined ice consistency, depth 1-5 m, cell mean'},
    'ice_consistency_gt5m': {**_C, 'description': 'SWIM 2.0 combined ice consistency, depth > 5 m, cell mean'},
    'ice_consistency': {**_C, 'description': 'cell mean of max(0-1 m, 1-5 m) consistency: ice within the '
                        'top ~5 m. Scale -1..+1, not comparable with Earth ice_frac'},
    'ice_frac': {'dtype': 'float32', 'unit': '1', 'comparison': 'planet_specific',
                 'description': 'fraction of valid pixels whose max(0-1 m, 1-5 m) consistency is > 0 '
                                '(positive modeled ice consistency within ~5 m; not permafrost area fraction)'},
    'n_px': {'dtype': 'int32', 'unit': 'count', 'comparison': 'within_planet', 'fill': 0,
             'description': 'raster pixels whose centre lies in the cell'},
    'valid_frac': {'dtype': 'float32', 'unit': '1', 'comparison': 'within_planet', 'fill': 0.0,
                   'description': 'share of those pixels that are valid (not -100 / non-finite) in the used maps'},
}
LIMITATIONS = [
    'SWIM 2.0 spans +-60 deg latitude only; cells poleward are NaN with outside_coverage.',
    'The documented +1 km areoid elevation cutoff is not encoded as nodata; whether highlands are '
    'masked is unchecked (K-C compares c-map values against elevation above 1000 m).',
    'ice_consistency* is a -1..+1 consistency score (not a fraction); ice_frac counts pixels with '
    'max(0-1 m, 1-5 m) > 0, a presence measure, so it is only loosely comparable with Earth permafrost area fraction.',
    'Pixels are ~3 km, so a 5 km cell holds only a few; n_px and valid_frac are stored.',
    'No licence text was found; non-commercial research use only.',
]


def clean(values) -> np.ndarray:
    """NaN for the declared nodata (-100) and for non-finite values."""
    v = np.asarray(values, dtype=np.float64)
    return np.where(np.isfinite(v) & (v != NODATA), v, np.nan)


def pixel_lonlat(transform, rows, cols, radius_m: float = MARS_RADIUS_M):
    """Pixel-centre (lon, lat) in degrees for 1-D ``rows`` x ``cols`` (meshgrid, shape rows x cols)."""
    x = transform.c + (np.asarray(cols) + 0.5) * transform.a
    y = transform.f + (np.asarray(rows) + 0.5) * transform.e
    lon = np.degrees(x / radius_m)
    lat = np.degrees(y / radius_m)
    return np.meshgrid(lon, lat)


def cell_stats(rows_idx, maps: dict[str, np.ndarray], n_cells: int) -> dict[str, np.ndarray]:
    """Per-cell columns from pixel arrays (same shape as ``rows_idx``; ``rows_idx`` < 0 means not in the group)."""
    clean_maps = {k: clean(v) for k, v in maps.items()}
    out: dict[str, np.ndarray] = {}
    for key, name in (('c0_1', 'ice_consistency_0_1m'), ('c1_5', 'ice_consistency_1_5m'),
                      ('c_5', 'ice_consistency_gt5m')):
        out[name], _ = cm.cell_mean(rows_idx, clean_maps[key], n_cells)
    used = np.stack([clean_maps[k] for k in ICE_DEPTH_MAPS])
    ok = np.all(np.isfinite(used), axis=0)
    combined = np.where(ok, np.max(np.where(np.isfinite(used), used, -np.inf), axis=0), np.nan)
    out['ice_consistency'], n_ok = cm.cell_mean(rows_idx, combined, n_cells)
    ice, _ = cm.cell_mean(rows_idx, np.where(ok, (combined > ICE_THRESHOLD).astype(float), np.nan), n_cells)
    out['ice_frac'] = ice
    n_px = cm.cell_count(rows_idx, n_cells)
    out['n_px'] = n_px
    with np.errstate(invalid='ignore', divide='ignore'):
        out['valid_frac'] = np.where(n_px > 0, n_ok / n_px, 0.0)
    return out


def plan(band_group, ctx):
    south, north = cm.lat_window(ctx.grid, ctx.bands)
    if south >= LAT_LIMIT_DEG or north <= -LAT_LIMIT_DEG:
        return []
    return [{'key': f'swim2_{k}', 'url': str(Path(ctx.raw_dir) / f), 'method': 'local'}
            for k, f in DEPTH_FILES.items()]


def read_window(path, south: float, north: float):
    """The raster rows covering ``south``..``north`` degrees: ``(array, transform, row0)``."""
    import rasterio
    from rasterio.windows import Window
    with rasterio.open(path) as src:
        t = src.transform
        top = np.degrees(t.f / MARS_RADIUS_M)
        step = np.degrees(-t.e / MARS_RADIUS_M)
        r0 = max(0, int(np.floor((top - north) / step)) - 1)
        r1 = min(src.height, int(np.ceil((top - south) / step)) + 1)
        if r1 <= r0:
            return None, t, 0
        data = src.read(1, window=Window(0, r0, src.width, r1 - r0))
        return data, t, r0


def reduce(band_group, items, ctx):
    cells = ctx.cells(band_group)
    south, north = cm.lat_window(ctx.grid, ctx.bands)
    maps, transform, row0 = {}, None, 0
    for fetched in items:
        key = fetched.key.removeprefix('swim2_')
        maps[key], transform, row0 = read_window(fetched.path, south, north)
    return build_rows(ctx.grid, ctx.bands, cells, maps, transform, row0)


def build_rows(grid, bands, cells, maps, transform, row0) -> pa.Table:
    n = len(cells)
    lat_c = cells['center_lat'].to_numpy(zero_copy_only=False)
    any_map = next(iter(maps.values()), None)
    if any_map is None:
        stats = cell_stats(np.zeros(0, dtype=np.int64), {k: np.zeros(0) for k in ('c0_1', 'c1_5', 'c_5')}, n)
    else:
        nrows, ncols = any_map.shape
        lon, lat = pixel_lonlat(transform, np.arange(row0, row0 + nrows), np.arange(ncols))
        rows_idx = cm.group_rows(grid, bands, lat, lon).ravel()
        stats = cell_stats(rows_idx, {k: v.ravel() for k, v in maps.items()}, n)
    outside = np.abs(lat_c) > LAT_LIMIT_DEG
    flags = clim.Flags(n)
    flags.add(outside, 'outside_coverage')
    no_pixels = ~outside & (stats['valid_frac'] <= 0)
    flags.add(no_pixels, 'no_source')
    data = {'region_id': cells['region_id']}
    for name in ('ice_consistency_0_1m', 'ice_consistency_1_5m', 'ice_consistency_gt5m',
                 'ice_consistency', 'ice_frac'):
        data[name] = pa.array(np.where(outside, np.nan, stats[name]).astype(np.float32))
    data['n_px'] = pa.array(np.where(outside, 0, stats['n_px']).astype(np.int32))
    data['valid_frac'] = pa.array(np.where(outside, 0.0, stats['valid_frac']).astype(np.float32))
    data['quality_flags'] = pa.array(flags.strings(), type=pa.string())
    return pa.table(data)