File size: 27,204 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
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
"""Helpers shared by the thermal & optical layers (tes_ti, tes_albedo, modis_lst, modis_albedo_ndvi,
modis_ati). Not a layer: it has no SOURCE and the driver never loads it by slug.

The layer modules list this file in ``CROSSWALKS`` so that a change here moves their code_version
(the driver hashes the module, itself and the CROSSWALKS files).

Contents
--------
* pixel geometry and NaN-aware bilinear sampling at a cell centroid (pixel-is-area rasters)
* MODIS scaling, fills, QC masks and UTC -> local solar time (constants are the T-A values)
* the 12-month climatology builder (download one granule, read it, apply QC, delete it)
* annual statistics from a 12-month stack, and the ATI formula
* percentile rank used by the ``ti_pct`` finalize passes
"""
from __future__ import annotations

import datetime as dt
import hashlib
import json
import math
import os
import shutil
import tempfile
import warnings
from pathlib import Path

import numpy as np

# --------------------------------------------------------------------------
# constants (T-A: data/raw/earth/thermal_optical_sources.json)
# --------------------------------------------------------------------------

YEARS = (2017, 2018, 2019, 2020, 2021)
CLIM_TAG = 'clim_2017_2021'

LST_SCALE = 0.02            # K per DN; fill 0, valid range >= 7500
LST_MIN_DN = 7500
LAND_PCT_MIN = 1            # Percent_land_in_grid valid 1..100, fill 0
VIEW_SCALE = 0.2            # hours (UTC) per DN; valid 0..120, fill 255
VIEW_MAX_DN = 120
NDVI_DIVISOR = 10000.0      # the "scale_factor" of 10000 is a divisor
NDVI_FILL = -3000
NDVI_VALID = (-2000, 10000)
NDVI_RELIABILITY_OK = (0, 1)          # 0 good, 1 marginal; 2 snow/ice, 3 cloudy, 4 estimated, -1 fill
ALBEDO_SCALE = 0.001        # fill 32767, valid 0..32766
ALBEDO_FILL = 32767
ALBEDO_QUALITY_MAX = 2      # 0 best, 1 good, 2 relatively good; 3.. and 255 dropped
SNOW_MAX_VALID = 254        # Percent_Snow valid 0..254, fill 255

# thresholds of the derived columns (stored in the SOURCE of the layers that use them)
SNOW_MONTH_PCT = 10.0       # a monthly climatology value >= this Percent_Snow is a snow month
MIN_DELTA_T_K = 5.0         # months with LSTday - LSTnight below this give no ATI
BARE_NDVI_MAX = 0.20
BARE_SNOW_FRAC_MAX = 0.5

MODIS_DOI = {'MYD11C3': '10.5067/MODIS/MYD11C3.061', 'MYD13C2': '10.5067/MODIS/MYD13C2.061',
             'MCD43C3': '10.5067/MODIS/MCD43C3.061'}


# --------------------------------------------------------------------------
# pixel geometry and sampling
# --------------------------------------------------------------------------

def pixel_rc(lat, lon, height: int, width: int):
    """Row and column of the pixel holding (lat, lon) in a global north-up raster whose corner
    extents are -180..180 / 90..-90: ``row = floor((90 - lat) / dlat)``, ``col = floor((lon + 180) / dlon)``.
    For 7200x3600 that is ``floor((90 - lat) * 20)`` and ``floor((lon + 180) * 20)``."""
    lat = np.asarray(lat, dtype=np.float64)
    lon = np.asarray(lon, dtype=np.float64)
    row = np.floor((90.0 - lat) * height / 180.0).astype(np.int64)
    col = np.floor((lon + 180.0) * width / 360.0).astype(np.int64)
    return np.clip(row, 0, height - 1), np.clip(col, 0, width - 1)


def pixel_centre_lat(row, height: int):
    return 90.0 - (np.asarray(row, dtype=np.float64) + 0.5) * 180.0 / height


def pixel_centre_lon(col, width: int):
    return -180.0 + (np.asarray(col, dtype=np.float64) + 0.5) * 360.0 / width


def nearest_at(grid, lat, lon):
    row, col = pixel_rc(lat, lon, *grid.shape)
    return grid[row, col]


def bilinear_at(grid, lat, lon):
    """NaN-aware bilinear sample of a global pixel-is-area raster at (lat, lon) points.

    Pixel centres are at index + 0.5, so the point's fractional pixel coordinate is
    ``x = (lon + 180) / dlon - 0.5``. NaN neighbours are dropped and the remaining weights
    renormalised; longitude wraps, rows clamp at the poles.

    Returns ``(value, interp_flag, valid_weight)``: ``valid_weight`` is the total bilinear weight on
    finite neighbours (1 = all four, 0 = none, value NaN); ``interp_flag`` is True when a neighbour with
    weight was NaN, so the value was interpolated from the rest.
    """
    grid = np.asarray(grid)
    h, w = grid.shape
    lat = np.atleast_1d(np.asarray(lat, dtype=np.float64))
    lon = np.atleast_1d(np.asarray(lon, dtype=np.float64))
    y = (90.0 - lat) * h / 180.0 - 0.5
    x = (lon + 180.0) * w / 360.0 - 0.5
    y0 = np.floor(y).astype(np.int64)
    x0 = np.floor(x).astype(np.int64)
    fy, fx = y - y0, x - x0
    acc = np.zeros(lat.shape)
    wsum = np.zeros(lat.shape)
    missing = np.zeros(lat.shape, dtype=bool)
    for dy, wy in ((0, 1.0 - fy), (1, fy)):
        r = np.clip(y0 + dy, 0, h - 1)
        for dx, wx in ((0, 1.0 - fx), (1, fx)):
            c = (x0 + dx) % w
            v = grid[r, c].astype(np.float64)
            wt = wy * wx
            ok = np.isfinite(v)
            acc += np.where(ok, v * wt, 0.0)
            wsum += np.where(ok, wt, 0.0)
            missing |= (~ok) & (wt > 1e-12)
    value = np.where(wsum > 1e-12, acc / np.where(wsum > 1e-12, wsum, 1.0), np.nan)
    return value, missing & (wsum > 1e-12), np.clip(wsum, 0.0, 1.0)


def sample_many(rasters: dict, names, lat, lon) -> dict:
    """``bilinear_at`` for several rasters: name -> (value, interp_flag, valid_weight)."""
    return {n: bilinear_at(rasters[n], lat, lon) for n in names}


def round_count(value):
    """NaN-aware bilinear of a count -> integer month count (0 where there is no data)."""
    return np.where(np.isfinite(value), np.rint(np.nan_to_num(value)), 0).astype(np.int8)


# --------------------------------------------------------------------------
# percentile statistics
# --------------------------------------------------------------------------

def sorted_percentiles(values, qs):
    """Row-wise NaN-aware percentiles (numpy's default linear method) of a 2-D array, vectorised.

    ``values`` is (n_cells, n_samples) with NaN for no data; returns a list of arrays, one per q in
    ``qs`` (0-100), NaN for rows with no finite sample. Works without a Python loop over cells.
    """
    values = np.asarray(values, dtype=np.float64)
    srt = np.sort(values, axis=1)                 # NaN sorts last
    n = np.isfinite(values).sum(axis=1)
    rows = np.arange(values.shape[0])
    out = []
    for q in qs:
        pos = np.maximum(n - 1, 0) * (q / 100.0)
        lo = np.floor(pos).astype(np.int64)
        hi = np.minimum(lo + 1, np.maximum(n - 1, 0))
        frac = pos - lo
        a = srt[rows, np.minimum(lo, values.shape[1] - 1)] if values.shape[1] else np.full(len(rows), np.nan)
        b = srt[rows, np.minimum(hi, values.shape[1] - 1)] if values.shape[1] else a
        out.append(np.where(n > 0, a + (b - a) * frac, np.nan))
    return out


def percentile_rank(values, reference):
    """Mid-rank percentile (0-100, ties share the average rank) of ``values`` within the finite
    entries of ``reference``. Monotone non-decreasing in ``values``; NaN where ``values`` is NaN or the
    reference is empty."""
    values = np.asarray(values, dtype=np.float64)
    ref = np.sort(np.asarray(reference, dtype=np.float64)[np.isfinite(reference)])
    if not len(ref):
        return np.full(values.shape, np.nan)
    lo = np.searchsorted(ref, values, side='left')
    hi = np.searchsorted(ref, values, side='right')
    pct = 100.0 * (lo + hi) / (2.0 * len(ref))
    return np.where(np.isfinite(values), pct, np.nan)


def join_flags(n: int, **masks) -> list[str]:
    """``quality_flags`` strings: the names of the true masks joined by ';' (driver convention)."""
    names = list(masks)
    arrays = [np.asarray(masks[k], dtype=bool) for k in names]
    return [';'.join(names[j] for j in range(len(names)) if arrays[j][i]) for i in range(n)]


def split_flags(flags) -> list[set]:
    return [set(p for p in (f or '').split(';') if p) for f in flags]


# --------------------------------------------------------------------------
# MODIS scaling, fills, QC
# --------------------------------------------------------------------------

def scale_lst(dn, land_pct=None):
    """MYD11C3 LST DN -> K (DN x 0.02). Fill 0 and DN < 7500 -> NaN; with ``land_pct`` also needs
    Percent_land_in_grid >= 1. No QC_Day/QC_Night bits are used (their legend is unverified)."""
    dn = np.asarray(dn)
    ok = dn >= LST_MIN_DN
    if land_pct is not None:
        ok &= np.asarray(land_pct) >= LAND_PCT_MIN
    return np.where(ok, dn.astype(np.float32) * np.float32(LST_SCALE), np.float32(np.nan))


def scale_view_time(dn):
    """MYD11C3 view time DN -> hours UTC (DN x 0.2). Fill 255 (valid 0..120) -> NaN."""
    dn = np.asarray(dn)
    return np.where(dn <= VIEW_MAX_DN, dn.astype(np.float32) * np.float32(VIEW_SCALE), np.float32(np.nan))


def utc_to_local_solar(hours_utc, lon_deg):
    """Local mean solar hours: ``(UTC + lon / 15) mod 24``, lon east-positive degrees (broadcasts)."""
    return np.mod(np.asarray(hours_utc, dtype=np.float32) + np.asarray(lon_deg, dtype=np.float32) / 15.0,
                  np.float32(24.0))


def scale_ndvi(dn, reliability):
    """MYD13C2 NDVI DN -> NDVI (DN / 10000). Fill -3000 and reliability other than 0 or 1 -> NaN."""
    dn = np.asarray(dn)
    rel = np.asarray(reliability)
    ok = (dn != NDVI_FILL) & (dn >= NDVI_VALID[0]) & (dn <= NDVI_VALID[1])
    ok &= (rel >= NDVI_RELIABILITY_OK[0]) & (rel <= NDVI_RELIABILITY_OK[1])
    return np.where(ok, dn.astype(np.float32) / np.float32(NDVI_DIVISOR), np.float32(np.nan))


def scale_albedo(dn, quality):
    """MCD43C3 white-sky albedo DN -> albedo (DN x 0.001). Fill 32767 and Albedo_Quality > 2 (3+, 255) -> NaN."""
    dn = np.asarray(dn)
    ok = (dn != ALBEDO_FILL) & (dn >= 0) & (np.asarray(quality) <= ALBEDO_QUALITY_MAX)
    return np.where(ok, dn.astype(np.float32) * np.float32(ALBEDO_SCALE), np.float32(np.nan))


def scale_snow(dn):
    """MCD43C3 Percent_Snow: valid 0..254, fill 255 -> NaN."""
    dn = np.asarray(dn)
    return np.where(dn <= SNOW_MAX_VALID, dn.astype(np.float32), np.float32(np.nan))


# --------------------------------------------------------------------------
# climatology builder
# --------------------------------------------------------------------------

class MonthAccumulator:
    """Per-pixel accumulation of one calendar month over the years, for named variables.

    ``linear`` variables are averaged; ``circular24`` variables (local solar hours) use the circular
    mean on a 24 h clock so 23.8 h and 0.2 h average to 0.0 h, not 12 h; ``any`` variables are OR-ed
    booleans (land masks). float32 sums are plenty for five values of ~300 K.
    """

    def __init__(self, shape):
        self.shape = tuple(shape)
        self.kind: dict[str, str] = {}
        self._a: dict[str, np.ndarray] = {}
        self._b: dict[str, np.ndarray] = {}
        self._n: dict[str, np.ndarray] = {}

    def _slot(self, name, kind):
        if name not in self.kind:
            self.kind[name] = kind
            if kind == 'any':
                self._a[name] = np.zeros(self.shape, dtype=bool)
            else:
                self._a[name] = np.zeros(self.shape, dtype=np.float32)
                self._n[name] = np.zeros(self.shape, dtype=np.uint8)
                if kind == 'circular24':
                    self._b[name] = np.zeros(self.shape, dtype=np.float32)
        elif self.kind[name] != kind:
            raise ValueError(f'{name} is {self.kind[name]}, not {kind}')

    def add_linear(self, name, arr):
        self._slot(name, 'linear')
        ok = np.isfinite(arr)
        np.add(self._a[name], arr, out=self._a[name], where=ok)
        self._n[name] += ok

    def add_circular24(self, name, hours):
        self._slot(name, 'circular24')
        ok = np.isfinite(hours)
        ang = np.where(ok, hours, 0.0).astype(np.float32) * np.float32(2 * math.pi / 24.0)
        self._a[name] += np.where(ok, np.sin(ang), 0).astype(np.float32)
        self._b[name] += np.where(ok, np.cos(ang), 0).astype(np.float32)
        self._n[name] += ok

    def add_any(self, name, mask):
        self._slot(name, 'any')
        self._a[name] |= np.asarray(mask, dtype=bool)

    def counts(self, name):
        return self._n[name]

    def results(self) -> dict:
        """name -> float32 array (NaN where nothing was seen) or uint8 0/1 for ``any`` variables."""
        out = {}
        for name, kind in self.kind.items():
            if kind == 'any':
                out[name] = self._a[name].astype(np.uint8)
                continue
            n = self._n[name]
            with np.errstate(invalid='ignore', divide='ignore'):
                if kind == 'linear':
                    val = self._a[name] / n
                else:
                    ang = np.arctan2(self._a[name], self._b[name])
                    val = np.mod(ang, 2 * math.pi) * (24.0 / (2 * math.pi))
            out[name] = np.where(n > 0, val, np.nan).astype(np.float32)
        return out


def clim_path(folder, var: str) -> Path:
    return Path(folder) / f'{var}_{CLIM_TAG}.tif'


class ClimWriter:
    """One 12-band GeoTIFF per variable (band m = calendar month m), deflate, tiled, written a month at a time."""

    def __init__(self, folder, variables: dict, shape, resume: bool = False):
        import rasterio
        from rasterio.transform import from_origin
        self.folder = Path(folder)
        self.folder.mkdir(parents=True, exist_ok=True)
        h, w = shape
        transform = from_origin(-180.0, 90.0, 360.0 / w, 180.0 / h)
        self.files = {}
        for var, dtype in variables.items():
            path = clim_path(self.folder, var)
            if resume and path.exists():
                self.files[var] = rasterio.open(path, 'r+')
                continue
            kwargs = dict(driver='GTiff', height=h, width=w, count=12, dtype=dtype, crs='EPSG:4326',
                          transform=transform, compress='deflate', tiled=True, blockxsize=256,
                          blockysize=256, interleave='band')
            if np.dtype(dtype).kind == 'f':
                kwargs.update(nodata=float('nan'), predictor=3)
            self.files[var] = rasterio.open(path, 'w', **kwargs)

    def write_month(self, month: int, arrays: dict) -> None:
        for var, f in self.files.items():
            f.write(arrays[var].astype(f.dtypes[0]), month)

    def close(self) -> None:
        for f in self.files.values():
            f.close()


def month_spec(short_name: str, year: int, month: int, *, daily_day: int | None = None,
               version: str = '061') -> dict:
    """One granule to fetch. Monthly products (MYD11C3, MYD13C2) are dated by the first of the month,
    MCD43C3 (daily, 16-day window) by ``daily_day`` of the month."""
    day = daily_day or 1
    d = dt.date(year, month, day)
    return {'short_name': short_name, 'version': version, 'year': year, 'month': month,
            'doy': d.timetuple().tm_yday, 'date': d.isoformat(),
            'end': (d + dt.timedelta(days=1 if daily_day else 27)).isoformat()}


_EA_READY = False


def earthaccess_download(spec: dict, dest) -> Path:
    """Download the one granule ``spec`` names into ``dest`` (whole granule; no OPeNDAP)."""
    global _EA_READY
    import earthaccess
    if not _EA_READY:
        for strategy in ('environment', 'netrc'):
            try:
                if earthaccess.login(strategy=strategy):
                    _EA_READY = True
                    break
            except Exception:
                continue
        if not _EA_READY:
            raise RuntimeError('earthaccess login failed: set EARTHDATA_USERNAME/PASSWORD or ~/.netrc')
    results = earthaccess.search_data(short_name=spec['short_name'], version=spec['version'],
                                      temporal=(spec['date'], spec['end']))
    token = f".A{spec['year']}{spec['doy']:03d}."
    hits = [r for r in results if token in str(r['umm'].get('GranuleUR', r))]
    if len(hits) != 1:
        raise RuntimeError(f"{spec['short_name']} {spec['date']}: expected 1 granule {token}, found {len(hits)}")
    files = earthaccess.download(hits, str(dest))
    if not files:
        raise RuntimeError(f"{spec['short_name']} {spec['date']}: earthaccess downloaded nothing")
    return Path(files[0])


def read_hdf4(path, names) -> dict:
    """Read raw (unscaled) SDS arrays from an HDF4 granule with pyhdf. Imported here so the layer
    modules still load where pyhdf is missing."""
    from pyhdf.SD import SD, SDC
    sd = SD(str(path), SDC.READ)
    try:
        return {n: np.asarray(sd.select(n).get()) for n in names}
    finally:
        sd.end()


def read_granule(spec, *, download, read, sds_names, workdir, log=print, provenance=None):
    """Download one granule into its own folder under ``workdir``, read it, delete it.

    The folder is removed even when the download or the read fails, so ``workdir`` is empty between
    granules. Returns ``(data, nbytes)``; ``nbytes`` is what was read from the network (file size)."""
    Path(workdir).mkdir(parents=True, exist_ok=True)
    tmp = tempfile.mkdtemp(prefix='granule-', dir=workdir)
    try:
        path = Path(download(spec, tmp))
        nbytes = path.stat().st_size
        if provenance is not None:
            with path.open('rb') as stream:
                provenance.update(filename=path.name, sha256=hashlib.file_digest(stream, 'sha256').hexdigest(),
                                  version=spec['version'])
        data = read(path, sds_names)
        log(f"  {spec['short_name']} {spec['date']}: {path.name} {nbytes} bytes read")
        return data, nbytes
    finally:
        shutil.rmtree(tmp, ignore_errors=True)


def default_workdir() -> Path:
    base = os.environ.get('STARMAN_MODIS_TMP')
    return Path(tempfile.mkdtemp(prefix='starman-modis-', dir=base))


def build_climatology(out_dir, *, variables: dict, specs_by_month: dict, shape, handle, sds_for,
                      download, read, workdir, log=print, after_month=None) -> dict:
    """Build the 12-month climatology GeoTIFFs for one layer, a calendar month at a time.

    ``variables``      name -> numpy dtype of its GeoTIFF
    ``specs_by_month`` {1..12: [granule spec, ...]} (all years, all products the layer reads)
    ``handle(spec, data, acc)`` applies scaling and QC and adds to the MonthAccumulator
    ``sds_for(spec)``  the SDS names to read for that granule

    Resumable at month level through ``climatology_progress.json``. Returns the progress dict
    (granules with bytes read, ``complete``).
    """
    out_dir = Path(out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    pfile = out_dir / 'climatology_progress.json'
    progress = json.loads(pfile.read_text()) if pfile.exists() else {'months_done': [], 'granules': []}
    expected = [(g['short_name'], g['date'], g['version']) for m in progress['months_done']
                for g in specs_by_month.get(m, ())]
    recorded = [(g['product'], g['date'], g.get('version', '061')) for g in progress['granules']]
    if expected != recorded or any(m not in specs_by_month for m in progress['months_done']):
        raise ValueError(f'MODIS source dates or versions differ from {pfile}; use a separate interim directory')
    files_ok = all(clim_path(out_dir, v).exists() for v in variables)
    if not files_ok:
        progress = {'months_done': [], 'granules': []}
    if progress.get('complete'):
        return progress
    writer = ClimWriter(out_dir, variables, shape, resume=bool(progress['months_done']))
    try:
        for month in sorted(specs_by_month):
            if month in progress['months_done']:
                continue
            acc = MonthAccumulator(shape)
            for spec in specs_by_month[month]:
                provenance = {}
                data, nbytes = read_granule(spec, download=download, read=read, sds_names=sds_for(spec),
                                            workdir=workdir, log=log, provenance=provenance)
                handle(spec, data, acc)
                del data
                progress['granules'].append({'product': spec['short_name'], 'date': spec['date'],
                                             'bytes': nbytes, **provenance})
            writer.write_month(month, acc.results())
            progress['months_done'].append(month)
            pfile.write_text(json.dumps(progress))
            if after_month:
                after_month(month, progress)
    finally:
        writer.close()
    progress['complete'] = len(progress['months_done']) == len(specs_by_month)
    progress['bytes_read_total'] = sum(g['bytes'] for g in progress['granules'])
    pfile.write_text(json.dumps(progress))
    return progress


def granule_checksum(progress: dict) -> str:
    granules = progress['granules']
    if all(g.get('sha256') for g in granules):
        inputs = sorted((g['product'], g['version'], g['date'], g['sha256']) for g in granules)
        label = 'granule-content-list-sha256'
    else:
        inputs = sorted((g['product'], g['date'], g['bytes']) for g in granules)
        label = 'granule-inventory-sha256'
    return f'{label}:' + hashlib.sha256(json.dumps(inputs).encode()).hexdigest()


# --------------------------------------------------------------------------
# annual statistics from 12-month stacks (axis 0 = calendar month)
# --------------------------------------------------------------------------

def _quiet():
    return warnings.catch_warnings()


def nan_reduce(fn, stack):
    with warnings.catch_warnings():
        warnings.simplefilter('ignore', RuntimeWarning)
        return fn(stack, axis=0)


def circular_mean_hours(stack):
    ok = np.isfinite(stack)
    ang = np.where(ok, stack, 0.0) * (2 * math.pi / 24.0)
    s = np.where(ok, np.sin(ang), 0).sum(axis=0)
    c = np.where(ok, np.cos(ang), 0).sum(axis=0)
    hours = np.mod(np.arctan2(s, c), 2 * math.pi) * (24.0 / (2 * math.pi))
    return np.where(ok.any(axis=0), hours, np.nan).astype(np.float32)


def lst_annual(day, night, day_view=None, night_view=None) -> dict:
    """Annual statistics from the 12-month LST climatology (K).

    ``lst_day_K`` / ``lst_night_K``   mean over the months valid for that variable
    ``lst_day_max_K`` / ``lst_night_min_K``   warmest monthly day value, coldest monthly night value
    ``lst_diurnal_K``       mean over months of (day - night), months with both
    ``lst_seasonal_range_K``  peak-to-peak range of the paired monthly (day + night) / 2 values
    ``lst_seasonal_amp_K``    half that range; both require at least two paired months
    ``n_months_valid``      months with both day and night LST
    ``lst_day_view_h`` / ``lst_night_view_h``  circular mean local solar view time (h)
    """
    both = np.isfinite(day) & np.isfinite(night)
    dm = np.where(both, day, np.nan)
    nm = np.where(both, night, np.nan)
    mean_t = (dm + nm) / 2.0
    n_months = both.sum(axis=0)
    seasonal_range = np.where(n_months >= 2, nan_reduce(np.nanmax, mean_t) - nan_reduce(np.nanmin, mean_t),
                              np.nan)
    out = {
        'lst_day_K': nan_reduce(np.nanmean, day),
        'lst_night_K': nan_reduce(np.nanmean, night),
        'lst_day_max_K': nan_reduce(np.nanmax, day),
        'lst_night_min_K': nan_reduce(np.nanmin, night),
        'lst_diurnal_K': nan_reduce(np.nanmean, dm - nm),
        'lst_seasonal_range_K': seasonal_range,
        'lst_seasonal_amp_K': seasonal_range / 2.0,
        'n_months_valid': n_months.astype(np.float32),
    }
    if day_view is not None:
        out['lst_day_view_h'] = circular_mean_hours(day_view)
    if night_view is not None:
        out['lst_night_view_h'] = circular_mean_hours(night_view)
    return {k: np.asarray(v, dtype=np.float32) for k, v in out.items()}


def albedo_ndvi_annual(albedo, snow, ndvi, snow_month_pct: float = SNOW_MONTH_PCT) -> dict:
    """Annual statistics from the 12-month albedo / snow / NDVI climatology.

    ``albedo``           median over snow-free months (Percent_Snow known and < ``snow_month_pct``)
    ``albedo_snow_frac`` share of months with a snow value that are snow months
    ``ndvi_max`` / ``ndvi_mean``  over months with a valid NDVI
    """
    snow_known = np.isfinite(snow)
    free = snow_known & (snow < snow_month_pct)
    alb = nan_reduce(np.nanmedian, np.where(free & np.isfinite(albedo), albedo, np.nan))
    n_known = snow_known.sum(axis=0)
    frac = np.where(n_known > 0, (snow_known & ~free).sum(axis=0) / np.maximum(n_known, 1), np.nan)
    return {'albedo': alb.astype(np.float32), 'albedo_snow_frac': frac.astype(np.float32),
            'ndvi_max': nan_reduce(np.nanmax, ndvi).astype(np.float32),
            'ndvi_mean': nan_reduce(np.nanmean, ndvi).astype(np.float32)}


def ati_months(day, night, albedo, snow) -> dict:
    """Apparent thermal inertia per pixel: ``ATI_m = (1 - albedo_m) / (LSTday_m - LSTnight_m)`` (1/K) for
    calendar months with known zero snow, an albedo in [0, 1], and a diurnal range of at least 5 K.

    Returns ``ati_inv_K`` (median over valid months), ``ati_n_months`` and the counts of months that
    had data but were dropped for snow (``n_snow``) or a small range (``n_small_dT``).
    """
    dT = day - night
    data = np.isfinite(day) & np.isfinite(night) & np.isfinite(albedo) & np.isfinite(snow)
    data &= (albedo >= 0.0) & (albedo <= 1.0)
    snowy = data & (snow != 0)
    small = data & ~snowy & (dT < MIN_DELTA_T_K)
    valid = data & ~snowy & ~small
    with np.errstate(invalid='ignore', divide='ignore'):
        ati = np.where(valid, (1.0 - albedo) / dT, np.nan)
    return {'ati_inv_K': nan_reduce(np.nanmedian, ati).astype(np.float32),
            'ati_n_months': valid.sum(axis=0).astype(np.float32),
            'n_snow': snowy.sum(axis=0).astype(np.float32),
            'n_small_dT': small.sum(axis=0).astype(np.float32)}


def derive_rasters(paths: dict, func, chunk_rows: int = 240) -> dict:
    """Run ``func`` over row chunks of 12-band climatology GeoTIFFs.

    ``paths``  {name: tif path}; ``func({name: (12, h, w) array}) -> {out: (h, w) array}``. Chunking keeps
    memory at a few hundred MB instead of the whole 12 x 3600 x 7200 stacks. Returns full rasters.
    """
    import rasterio
    from rasterio.windows import Window
    srcs = {k: rasterio.open(p) for k, p in paths.items()}
    try:
        first = next(iter(srcs.values()))
        h, w = first.height, first.width
        for k, s in srcs.items():
            if (s.height, s.width) != (h, w):
                raise ValueError(f'{k}: grid {s.height}x{s.width} differs from {h}x{w}')
        out: dict = {}
        for r0 in range(0, h, chunk_rows):
            r1 = min(h, r0 + chunk_rows)
            stacks = {}
            for k, s in srcs.items():
                a = s.read(window=Window(0, r0, w, r1 - r0))
                stacks[k] = a.astype(np.float32) if a.dtype.kind == 'f' else a
            res = func(stacks)
            for name, arr in res.items():
                if name not in out:
                    out[name] = np.empty((h, w), dtype=arr.dtype)
                out[name][r0:r1] = arr
        return out
    finally:
        for s in srcs.values():
            s.close()