starman / code /layers /tes_ti.py
enzeeoai's picture
Publish verified Core native layers and full geomorphometry
a8e0542 verified
Raw History Blame Contribute Delete
15.2 kB
"""Layer ``tes_ti`` (Mars): TES thermal inertia (Putzig & Mellon 2007, PDS TIMAP) per grid cell.
Source: four local raw files in ``data/raw/mars/tes_ti/`` (T-A manifest ``source_manifest.json``):
``global_ti_{night,day}_2007.img`` big-endian int16 and ``global_ti_msk_{night,day}_2007.img`` int8, each
7200 x 3600, 20 px/deg, simple cylindrical, planetocentric, east-positive -180..180, pixel-is-area, no
scale or offset. GDAL cannot open them, so they are read with numpy.
Pixel index: ``row = floor((90 - lat) * 20)``, ``col = floor((lon + 180) * 20)``; no coordinate conversion.
TI = 0 is "no data" (always inside mask 0, polar rows) and becomes NaN, never a value. Mask 0 means the pixel
was infilled by interpolation.
Per cell, pixel-centre assignment of the night TI (a pixel belongs to the cell holding its centre):
``ti_tiu_mean/_std/_p10/_p50/_p90``; ``ti_day_tiu_mean`` from the day map over the same pixels.
``ti_pct`` is the percentile of ``ti_tiu_p50`` in the whole-planet distribution, so ``finalize()`` computes it
and the driver publishes it as the extra set ``ti_pct``.
"""
from __future__ import annotations
import math
from pathlib import Path
import numpy as np
import pyarrow as pa
try:
from . import thermal_common as tc
except ImportError: # loaded by file path
import thermal_common as tc
VERSION = 'v0.2'
NIGHT_IMG = 'global_ti_night_2007.img'
DAY_IMG = 'global_ti_day_2007.img'
NIGHT_MSK = 'global_ti_msk_night_2007.img'
DAY_MSK = 'global_ti_msk_day_2007.img'
HEIGHT, WIDTH = 3600, 7200
PPD = 20
INTERP_FRAC_FLAG = 0.5 # ti_interp_frac above this: flag `interpolated`
INTERP_FRAC_REFERENCE = 0.5 # cells with ti_interp_frac >= this are left out of the ti_pct reference set
POLAR_LAT = 80.0
LOW_COVERAGE = 0.5 # valid_frac below this: flag `low_coverage`
SOURCE = {
'product': 'TES Thermal Inertia Maps (TIMAP), Putzig & Mellon 2007',
'version': 'MGS-M-TES-5-TIMAP-V1.0 (2007-01-30)',
'url': 'https://pds-geosciences.wustl.edu/mgs/mgs-m-tes-5-timap-v1/mgst_9001/data/',
'licence': 'NASA PDS; no restriction text on the page (not verified further); non-commercial use approved '
'2026-11-13; attribution text UNVERIFIED',
'planet': 'mars',
'files': [NIGHT_IMG, DAY_IMG, NIGHT_MSK, DAY_MSK],
'interp_frac_flag': INTERP_FRAC_FLAG,
'interp_frac_reference': INTERP_FRAC_REFERENCE,
}
TIU = 'J m-2 K-1 s-1/2 (tiu)'
COLUMNS = {
'ti_tiu_mean': {'dtype': 'float32', 'unit': TIU, 'comparison': 'planet_specific',
'description': 'Mean night-side TES thermal inertia of the pixels whose centres fall in the '
'cell (TI = 0 no-data pixels excluded).'},
'ti_tiu_std': {'dtype': 'float32', 'unit': TIU, 'comparison': 'planet_specific',
'description': 'Population standard deviation of the night TI pixels in the cell.'},
'ti_tiu_p10': {'dtype': 'float32', 'unit': TIU, 'comparison': 'planet_specific',
'description': '10th percentile of the night TI pixels in the cell.'},
'ti_tiu_p50': {'dtype': 'float32', 'unit': TIU, 'comparison': 'planet_specific',
'description': 'Median of the night TI pixels in the cell.'},
'ti_tiu_p90': {'dtype': 'float32', 'unit': TIU, 'comparison': 'planet_specific',
'description': '90th percentile of the night TI pixels in the cell.'},
'ti_day_tiu_mean': {'dtype': 'float32', 'unit': TIU, 'comparison': 'planet_specific',
'description': 'Mean day-side TES thermal inertia over the same pixels (TI = 0 excluded).'},
'ti_interp_frac': {'dtype': 'float32', 'unit': 'fraction', 'comparison': 'planet_specific', 'fill': 0.0,
'description': 'Share of the valid night TI pixels (TI > 0) that were infilled by '
'interpolation (mask 0). Coverage field, never scored. '
'Earth twin: none (coverage).'},
'n_px': {'dtype': 'int32', 'unit': 'pixels', 'comparison': 'planet_specific', 'fill': 0,
'description': 'Number of 20 px/deg pixels whose centres fall in the cell. Coverage field, never '
'scored. Earth twin: none (coverage).'},
'valid_frac': {'dtype': 'float32', 'unit': 'fraction', 'comparison': 'planet_specific', 'fill': 0.0,
'description': 'Share of the cell pixels with night TI > 0. Coverage field, never scored. '
'Earth twin: valid_frac (coverage).'},
}
EXTRA_COLUMNS = {
'ti_pct': {
'ti_pct': {'dtype': 'float32', 'unit': 'percentile (0-100)', 'comparison': 'within_planet',
'description': 'Percentile rank (0-100, ties share the mid rank) of ti_tiu_p50 within the '
'whole-planet distribution of Mars cells with a valid TI and ti_interp_frac < 0.5. '
'Cells outside that reference set are ranked against it too and carry the '
'interpolated flag. The Earth ATI rank uses a separate property and reference mask.'},
},
}
MISSING_FLAG = 'no_source'
CROSSWALKS = ['thermal_common.py'] # hashed into code_version
LIMITATIONS = [
'TES TI map release is 2007. 6.4% of pixels in the day map and 7.6% in the night map are '
'interpolated (area-weighted).',
'TI = 0 marks no data (polar rows and gaps); it is NaN here, not zero inertia.',
'TI = 4999 appears to be an undocumented cap (113 day and 140 night pixels at the cap).',
'Cells are summarised by pixel-centre assignment of 2.96 km pixels; cells with no pixel centre use the pixel '
'under the cell centre (flag centroid_px).',
'Seasonal frost near the poles biases TI; cells poleward of 80 degrees carry the `polar` flag.',
'Earth ATI is an independent thermal-response proxy. Cross-planet rank equivalence is unvalidated.',
'Attribution text of the PDS product has not been read from the source page.',
]
# --------------------------------------------------------------------------
# reading
# --------------------------------------------------------------------------
def read_img(path, dtype, height=HEIGHT, width=WIDTH) -> np.ndarray:
"""A raw PDS3 .img as a native-endian array. TIMAP TI is big-endian int16, masks are int8."""
path = Path(path)
dt = np.dtype(dtype)
expect = height * width * dt.itemsize
size = path.stat().st_size
if size != expect:
raise ValueError(f'{path.name}: {size} bytes, expected {expect} for {height}x{width} {dt}')
arr = np.fromfile(path, dtype=dt).reshape(height, width)
return arr.astype(dt.newbyteorder('='))
def load(folder, height=HEIGHT, width=WIDTH) -> dict:
folder = Path(folder)
return {
'night': read_img(folder / NIGHT_IMG, '>i2', height, width),
'day': read_img(folder / DAY_IMG, '>i2', height, width),
'msk_night': read_img(folder / NIGHT_MSK, '>i1', height, width),
}
def prepare(ctx) -> None:
"""Read the four local IMGs once (they are in ctx.raw_dir); pin their SHA-256 as the source checksum."""
import hashlib
for name in (NIGHT_IMG, DAY_IMG, NIGHT_MSK, DAY_MSK):
if not (Path(ctx.raw_dir) / name).exists():
raise FileNotFoundError(f'{Path(ctx.raw_dir) / name} is missing (T-A raw file)')
ctx.state['tes_ti'] = load(ctx.raw_dir)
digests = [ctx.record_source_file(Path(ctx.raw_dir) / n) for n in (NIGHT_IMG, DAY_IMG, NIGHT_MSK, DAY_MSK)]
ctx.source_checksum = 'files-sha256:' + hashlib.sha256(''.join(digests).encode()).hexdigest()
def plan(band_group, ctx):
"""One virtual item: the data is already in memory (prepare)."""
return [{'key': 'tes_ti_global', 'method': 'none', 'url': None}]
# --------------------------------------------------------------------------
# zonal statistics
# --------------------------------------------------------------------------
def pixel_ranges(lat_min, lat_max, lon_min, lon_max, height=HEIGHT, width=WIDTH):
"""Pixel index ranges whose centres lie in ``[lat_min, lat_max) x [lon_min, lon_max)``.
Returns ``(r0, r1, c0, c1)``: rows ``r0:r1`` (scalars, from the band's latitudes) and per-cell column
arrays ``c0:c1``. Centre of row r is ``90 - (r + 0.5) * 180 / height``, of column c ``-180 + (c + 0.5) *
360 / width``. Rounding to 9 places keeps exact boundaries from flipping on float noise."""
dlat, dlon = 180.0 / height, 360.0 / width
a = round((90.0 - float(lat_max)) / dlat - 0.5, 9) # centre < lat_max <=> r > a
b = round((90.0 - float(lat_min)) / dlat - 0.5, 9) # centre >= lat_min <=> r <= b
r0, r1 = int(math.floor(a)) + 1, int(math.floor(b)) + 1
r0, r1 = max(r0, 0), min(r1, height)
u = np.round((np.asarray(lon_min, dtype=np.float64) + 180.0) / dlon - 0.5, 9)
v = np.round((np.asarray(lon_max, dtype=np.float64) + 180.0) / dlon - 0.5, 9)
c0 = np.clip(np.ceil(u).astype(np.int64), 0, width)
c1 = np.clip(np.ceil(v).astype(np.int64), 0, width)
return r0, r1, c0, np.maximum(c1, c0)
def band_stats(night, day, msk_night, r0, r1, c0, c1) -> dict:
"""Statistics of the pixels in rows ``r0:r1`` and per-cell columns ``c0:c1`` (arrays, one per cell)."""
n_cells = len(c0)
nr = r1 - r0
width = night.shape[1]
span = c1 - c0
maxw = int(span.max()) if n_cells else 0
idx = c0[:, None] + np.arange(maxw)[None, :]
inb = idx < c1[:, None]
idx = np.minimum(idx, width - 1)
def gather(arr):
slab = arr[r0:r1] # (nr, width)
out = slab[:, idx] # (nr, n_cells, maxw)
return np.moveaxis(out, 0, 1).reshape(n_cells, nr * maxw)
in_px = np.tile(inb, (1, nr)) if nr else np.zeros((n_cells, 0), dtype=bool)
ti_n = gather(night).astype(np.float64)
ti_d = gather(day).astype(np.float64)
msk = gather(msk_night)
valid = in_px & (ti_n > 0) # TI = 0 is no data
valid_d = in_px & (ti_d > 0)
ti = np.where(valid, ti_n, np.nan)
n_px = in_px.sum(axis=1)
n_valid = valid.sum(axis=1)
with np.errstate(invalid='ignore', divide='ignore'):
mean = np.where(n_valid > 0, np.where(valid, ti_n, 0).sum(axis=1) / n_valid, np.nan)
dev = np.where(valid, ti_n - mean[:, None], 0.0)
std = np.where(n_valid > 0, np.sqrt((dev ** 2).sum(axis=1) / n_valid), np.nan)
n_valid_d = valid_d.sum(axis=1)
day_mean = np.where(n_valid_d > 0, np.where(valid_d, ti_d, 0).sum(axis=1) / n_valid_d, np.nan)
interp = np.where(n_valid > 0, (valid & (msk == 0)).sum(axis=1) / n_valid, np.nan)
valid_frac = np.where(n_px > 0, n_valid / n_px, 0.0)
p10, p50, p90 = tc.sorted_percentiles(ti, (10, 50, 90))
return {'ti_tiu_mean': mean, 'ti_tiu_std': std, 'ti_tiu_p10': p10, 'ti_tiu_p50': p50, 'ti_tiu_p90': p90,
'ti_day_tiu_mean': day_mean, 'ti_interp_frac': interp, 'n_px': n_px, 'valid_frac': valid_frac}
def cell_stats(arrays: dict, cells: dict) -> tuple[dict, np.ndarray]:
"""Statistics for every cell. ``cells`` holds numpy arrays ``band, lat_min, lat_max, lon_min, lon_max``.
Cells of one band share their rows, so each band is one vectorised pass. A band or cell with no pixel
centre falls back to the pixel under the cell centre (``centroid_px``).
Returns ``(columns, fallback_mask)`` in the order of ``cells``."""
night, day, msk = arrays['night'], arrays['day'], arrays['msk_night']
h, w = night.shape
n = len(cells['band'])
names = list(COLUMNS)
out = {k: np.full(n, np.nan if k not in ('n_px',) else 0, dtype=np.float64) for k in names}
fallback = np.zeros(n, dtype=bool)
bands = np.asarray(cells['band'])
for band in np.unique(bands):
sel = np.flatnonzero(bands == band)
r0, r1, c0, c1 = pixel_ranges(cells['lat_min'][sel][0], cells['lat_max'][sel][0],
cells['lon_min'][sel], cells['lon_max'][sel], h, w)
bad = (c1 <= c0)
if r1 <= r0:
lat_c = float(cells['lat_min'][sel][0] + cells['lat_max'][sel][0]) / 2
r0, _ = tc.pixel_rc(lat_c, 0.0, h, w)
r0 = int(r0)
r1 = r0 + 1
bad = np.ones(len(sel), dtype=bool)
if bad.any():
lon_c = (np.asarray(cells['lon_min'])[sel] + np.asarray(cells['lon_max'])[sel]) / 2
_, cc = tc.pixel_rc(0.0, lon_c, h, w)
c0 = np.where(bad, cc, c0)
c1 = np.where(bad, cc + 1, c1)
fallback[sel] = bad
res = band_stats(night, day, msk, r0, r1, c0, c1)
for k in names:
out[k][sel] = res[k]
return out, fallback
def quality_flags(columns: dict, center_lat, fallback) -> list[str]:
n = len(center_lat)
interp = np.nan_to_num(columns['ti_interp_frac'], nan=0.0)
return tc.join_flags(n, interpolated=interp > INTERP_FRAC_FLAG,
polar=np.abs(np.asarray(center_lat)) > POLAR_LAT,
low_coverage=columns['valid_frac'] < LOW_COVERAGE,
centroid_px=fallback)
def reduce(band_group, items, ctx):
if 'tes_ti' not in ctx.state:
ctx.state['tes_ti'] = load(ctx.raw_dir)
cells = ctx.cells(band_group)
arrs = {k: cells[k].to_numpy(zero_copy_only=False) for k in
('band', 'lat_min', 'lat_max', 'lon_min', 'lon_max', 'center_lat')}
cols, fallback = cell_stats(ctx.state['tes_ti'], arrs)
table = {'region_id': cells['region_id']}
for name, spec in COLUMNS.items():
table[name] = pa.array(cols[name].astype(np.int32 if name == 'n_px' else np.float32))
table['quality_flags'] = pa.array(quality_flags(cols, arrs['center_lat'], fallback), type=pa.string())
return pa.table(table)
# --------------------------------------------------------------------------
# whole-planet pass
# --------------------------------------------------------------------------
def finalize(ctx) -> None:
"""``ti_pct``: percentile of ti_tiu_p50 over all Mars cells with valid TI and ti_interp_frac < 0.5."""
groups = list(ctx.band_groups)
held = []
for g in groups:
t = ctx.read_layer(g, ['region_id', 'ti_tiu_p50', 'ti_interp_frac'])
held.append((t['region_id'], t['ti_tiu_p50'].to_numpy(zero_copy_only=False).astype(np.float64),
t['ti_interp_frac'].to_numpy(zero_copy_only=False).astype(np.float64)))
reference = np.concatenate([p[np.isfinite(p) & (np.nan_to_num(f, nan=1.0) < INTERP_FRAC_REFERENCE)]
for _, p, f in held]) if held else np.array([])
for g, (rid, p50, interp) in zip(groups, held):
pct = tc.percentile_rank(p50, reference)
outside = np.isfinite(p50) & ~(np.nan_to_num(interp, nan=1.0) < INTERP_FRAC_REFERENCE)
flags = tc.join_flags(len(p50), interpolated=outside)
ctx.write_extra('ti_pct', g, pa.table({'region_id': rid,
'ti_pct': pa.array(pct.astype(np.float32)),
'quality_flags': pa.array(flags, type=pa.string())}))