File size: 25,572 Bytes
602ad90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
610
611
612
613
614
615
616
"""Phase 2 deliverable for the P3 cloud-cover-bias paper: the results table + the
publication figures.

Everything drawn here is regenerated from the committed parquets and the analysis
scripts' own logic -- no number is retyped from the spec. The four analysis scripts
(analyze_phase1/phase2, crop_stress_overlay) print the statistics; this script turns
the same joins into figures and one consolidated CSV so the paper's Results section
has a single provenance.

Outputs (all under ../figures/, git-tracked):
    fig_study_area_map.png            -- locator map: the six ADM1 study zones on Africa
                                         (fetches Natural Earth + geoBoundaries once,
                                         cached under figures/.mapcache/; --no-map skips)
    fig1_weekly_coverage_heatmap.png  -- usable-observation frequency, zone x ISO week
    fig2_spatial_coverage_maps.png    -- per-pixel mean usable frequency, six zone panels
                                         (needs pixel_level_moderate_2022_2024.parquet;
                                         skipped with a note if that git-ignored file
                                         is absent -- rebuild via run_pixel_level_study.sh)
    fig3_rainfall_correlation.png     -- CHIRPS weekly rainfall vs usable_pct, six panels
    fig4_crop_stress_overlay.png      -- stress-window vs other-week usable_pct, by zone
    fig5_zonal_boxplots.png           -- weekly usable_pct distribution by zone/region
    phase2_results_table.csv          -- one row per zone, every Phase 2 statistic

Usage:
    python make_figures.py
    python make_figures.py --no-pixel     # skip fig2 even if the pixel parquet exists
"""

from __future__ import annotations

import argparse
import json
import urllib.request
from pathlib import Path

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats

import crop_stress_overlay as cso

HERE = Path(__file__).parent
DATA_DIR = HERE.parent / "data"
FIG_DIR = HERE.parent / "figures"
MAP_CACHE = FIG_DIR / ".mapcache"

# Natural Earth 1:110m admin-0 — small, stable, standard basemap for a locator figure.
NE_URL = ("https://raw.githubusercontent.com/nvkelso/natural-earth-vector/"
          "master/geojson/ne_110m_admin_0_countries.geojson")

# Table 1 order (by region: North, West, West, East, Central, Southern) so the numbered
# markers on the map cross-reference 1:1 with the study-zone table in the paper.
# Columns: (ISO3, geoBoundaries shapeName, parquet label, legend display name).
ZONE_TABLE_ORDER = [
    ("EGY", "Beheira Governorate", "EGY/Beheira Governorate", "Beheira"),
    ("NGA", "Kano", "NGA/Kano", "Kano"),
    ("GHA", "Upper East Region", "GHA/Upper East Region", "Upper East"),
    ("KEN", "Uasin Gishu", "KEN/Uasin Gishu", "Uasin Gishu"),
    ("COD", "Kasai-Oriental", "COD/Kasai-Oriental", "Kasaï-Oriental"),
    ("ZWE", "Mashonaland Central", "ZWE/Mashonaland Central", "Mashonaland Central"),
]

OBS_INPUT = "weekly_usable_observation_frequency_2022_2024.parquet"
CHIRPS_INPUT = "chirps_weekly_rainfall_2022_2024.parquet"
PIXEL_INPUT = "pixel_level_moderate_2022_2024.parquet"

HEADLINE_TIER = "moderate"
BLIND_SPOT_THRESHOLD_PCT = 50.0

# Zones ordered along the Phase 0 climate gradient: humid/high-cloud (worst-observed)
# -> arid (best-observed). This is the ascending-mean order from analyze_phase1.py and
# is the reading order for every per-zone figure here, so the gradient is visible as a
# gradient rather than needing to be pointed out.
ZONE_ORDER = [
    "COD/Kasai-Oriental",
    "GHA/Upper East Region",
    "NGA/Kano",
    "KEN/Uasin Gishu",
    "ZWE/Mashonaland Central",
    "EGY/Beheira Governorate",
]

# Short labels for tick/axis use -- the parquet's `zone` values are verbose.
ZONE_SHORT = {
    "COD/Kasai-Oriental": "Kasaï-Oriental\n(COD, Central)",
    "GHA/Upper East Region": "Upper East\n(GHA, West)",
    "NGA/Kano": "Kano\n(NGA, West)",
    "KEN/Uasin Gishu": "Uasin Gishu\n(KEN, East)",
    "ZWE/Mashonaland Central": "Mash. Central\n(ZWE, Southern)",
    "EGY/Beheira Governorate": "Beheira\n(EGY, North)",
}

REGION_COLOR = {
    "Central Africa": "#4c72b0",
    "West Africa": "#c44e52",
    "East Africa": "#dd8452",
    "Southern Africa": "#8172b3",
    "North Africa": "#55a868",
}
ZONE_REGION = {
    "COD/Kasai-Oriental": "Central Africa",
    "GHA/Upper East Region": "West Africa",
    "NGA/Kano": "West Africa",
    "KEN/Uasin Gishu": "East Africa",
    "ZWE/Mashonaland Central": "Southern Africa",
    "EGY/Beheira Governorate": "North Africa",
}

# Sequential-through-diverging: red below ~50% "blind spot", green well above it. The
# decision-relevant threshold (a whole week of unusable cropland) sits at the colour
# transition on purpose.
COVERAGE_CMAP = "RdYlGn"


def house_style() -> None:
    mpl.rcParams.update({
        "figure.dpi": 120,
        "savefig.dpi": 200,
        "savefig.bbox": "tight",
        "font.size": 9,
        "axes.titlesize": 10,
        "axes.titleweight": "bold",
        "axes.spines.top": False,
        "axes.spines.right": False,
        "axes.grid": True,
        "grid.alpha": 0.25,
        "grid.linewidth": 0.5,
        "legend.frameon": False,
    })


def load_weekly() -> pd.DataFrame:
    df = pd.read_parquet(DATA_DIR / OBS_INPUT)
    return df[df.tier == HEADLINE_TIER].copy()


def load_weekly_with_rain() -> pd.DataFrame:
    obs = load_weekly()
    rain = pd.read_parquet(DATA_DIR / CHIRPS_INPUT)
    merged = obs.merge(
        rain[["zone", "iso_year", "iso_week", "rainfall_mm_sum"]],
        on=["zone", "iso_year", "iso_week"], how="inner",
    )
    if len(merged) != len(obs):
        raise SystemExit(
            f"CHIRPS join dropped rows ({len(obs)} -> {len(merged)}); the zone/week keys "
            "should match exactly (see analyze_phase2.py)."
        )
    return merged.sort_values(["zone", "iso_year", "iso_week"]).reset_index(drop=True)


def sig_stars(p: float) -> str:
    if p < 1e-3:
        return "***"
    if p < 1e-2:
        return "**"
    if p < 0.05:
        return "*"
    return "n.s."


# --- Figure: study-area locator map ----------------------------------------------


def _load_africa():
    """Natural Earth admin-0, African countries only, as a GeoDataFrame (cached)."""
    import geopandas as gpd

    MAP_CACHE.mkdir(parents=True, exist_ok=True)
    path = MAP_CACHE / "ne_110m_admin_0_countries.geojson"
    if not path.exists():
        print(f"  downloading Natural Earth admin-0 -> {path.name}")
        urllib.request.urlretrieve(NE_URL, path)
    gdf = gpd.read_file(path)
    return gdf[gdf["CONTINENT"] == "Africa"].copy()


def _load_zone_geoms() -> dict:
    """The six ADM1 study-zone polygons from geoBoundaries (cached as one FeatureCollection)."""
    from shapely.geometry import mapping, shape

    MAP_CACHE.mkdir(parents=True, exist_ok=True)
    path = MAP_CACHE / "study_zones.geojson"
    if path.exists():
        fc = json.loads(path.read_text())
        return {f["properties"]["label"]: shape(f["geometry"]) for f in fc["features"]}

    print("  fetching six ADM1 study-zone polygons from geoBoundaries")
    feats, geoms = [], {}
    for iso3, name, label, _disp in ZONE_TABLE_ORDER:
        geom = _fetch_admin1_zone(iso3, name)
        geoms[label] = geom
        feats.append({"type": "Feature", "properties": {"label": label},
                      "geometry": mapping(geom)})
    path.write_text(json.dumps({"type": "FeatureCollection", "features": feats}))
    return geoms


def fig_study_area_map() -> bool:
    try:
        africa = _load_africa()
        zone_geoms = _load_zone_geoms()
    except Exception as e:  # network or geopandas missing
        print(f"  study-area map SKIPPED: {e}")
        return False

    import geopandas as gpd

    fig, ax = plt.subplots(figsize=(5.4, 5.8))
    study_iso3 = {z[0] for z in ZONE_TABLE_ORDER}
    africa.plot(ax=ax, color="#ececec", edgecolor="white", linewidth=0.5)
    africa[africa["ADM0_A3"].isin(study_iso3)].plot(
        ax=ax, color="#d8d8d8", edgecolor="white", linewidth=0.5)

    zgdf = gpd.GeoDataFrame(
        {"label": list(zone_geoms)}, geometry=list(zone_geoms.values()), crs="EPSG:4326")
    zgdf["region"] = zgdf.label.map(ZONE_REGION)
    zgdf["color"] = zgdf.region.map(REGION_COLOR)

    # Manual label offsets (deg lon/lat) to keep the six callouts off each other and off
    # the coast; markers sit on the true centroid, text is pulled to open space.
    offsets = {
        "EGY/Beheira Governorate": (14, 6),
        "NGA/Kano": (-2, 12),
        "GHA/Upper East Region": (-15, 4),
        "KEN/Uasin Gishu": (13, 2),
        "COD/Kasai-Oriental": (-14, -6),
        "ZWE/Mashonaland Central": (10, -6),
    }
    for i, (iso3, name, label, _disp) in enumerate(ZONE_TABLE_ORDER, start=1):
        row = zgdf[zgdf.label == label].iloc[0]
        row_gdf = zgdf[zgdf.label == label]
        row_gdf.plot(ax=ax, color=row.color, edgecolor="#222", linewidth=0.7, zorder=4)
        c = row.geometry.centroid
        dx, dy = offsets[label]
        ax.annotate(
            str(i), xy=(c.x, c.y), xytext=(c.x + dx, c.y + dy),
            textcoords="data", fontsize=9, fontweight="bold", ha="center", va="center",
            color="white",
            bbox=dict(boxstyle="circle,pad=0.28", fc=row.color, ec="#222", lw=0.7),
            arrowprops=dict(arrowstyle="-", color="#222", lw=0.7, shrinkA=6, shrinkB=2),
            zorder=5)

    ax.set_xlim(-20, 54)
    ax.set_ylim(-37, 39)
    ax.set_aspect("equal")
    ax.set_axis_off()

    legend_lines = [
        f"{i}.  {disp}, {iso3}  —  {ZONE_REGION[label].replace(' Africa','')}"
        for i, (iso3, name, label, disp) in enumerate(ZONE_TABLE_ORDER, start=1)]
    ax.text(-19, -36, "\n".join(legend_lines), fontsize=7.5, va="bottom", ha="left",
            family="monospace",
            bbox=dict(boxstyle="round,pad=0.5", fc="white", ec="#bbb", lw=0.6))
    # No in-figure title: the LaTeX caption carries it (kept consistent with the other
    # paper figures).

    fig.savefig(FIG_DIR / "fig_study_area_map.png", bbox_inches="tight")
    plt.close(fig)
    return True


# --- Figure 1: weekly coverage heatmap --------------------------------------------


def fig_weekly_heatmap(weekly: pd.DataFrame) -> None:
    wide = (
        weekly.assign(yw=lambda d: d.iso_year * 100 + d.iso_week)
        .pivot_table(index="zone", columns="yw", values="usable_pct")
        .reindex(ZONE_ORDER)
    )
    cols = list(wide.columns)
    mat = wide.to_numpy()

    fig, ax = plt.subplots(figsize=(13, 3.8), constrained_layout=True)
    im = ax.imshow(mat, aspect="auto", cmap=COVERAGE_CMAP, vmin=0, vmax=100,
                   interpolation="nearest")

    ax.set_yticks(range(len(ZONE_ORDER)))
    ax.set_yticklabels([ZONE_SHORT[z].replace("\n", " ") for z in ZONE_ORDER], fontsize=8)

    # X ticks at the first week of each year, plus light separators.
    years = sorted(weekly.iso_year.unique())
    for yr in years[1:]:
        idx = next(i for i, c in enumerate(cols) if c // 100 == yr)
        ax.axvline(idx - 0.5, color="white", lw=1.5)
    tick_idx, tick_lab = [], []
    for yr in years:
        idxs = [i for i, c in enumerate(cols) if c // 100 == yr]
        tick_idx.append(int(np.mean(idxs)))
        tick_lab.append(str(yr))
    ax.set_xticks(tick_idx)
    ax.set_xticklabels(tick_lab)
    ax.set_xlabel("ISO week (2022–2024, 156 weeks per zone)")
    ax.grid(False)
    # No title — the paper's LaTeX caption carries the description.

    cbar = fig.colorbar(im, ax=ax, pad=0.012, fraction=0.03)
    cbar.set_label("% of cropland usably observed that week (SCL quality mask)")
    cbar.ax.axhline(BLIND_SPOT_THRESHOLD_PCT, color="black", lw=1)

    fig.savefig(FIG_DIR / "fig1_weekly_coverage_heatmap.png")
    plt.close(fig)


# --- Figure 2: spatial per-pixel coverage maps -----------------------------------


def fig_spatial_maps() -> bool:
    path = DATA_DIR / PIXEL_INPUT
    if not path.exists():
        print(f"  fig2 SKIPPED: {PIXEL_INPUT} not found (git-ignored; 1.4 GB). "
              "Rebuild with run_pixel_level_study.sh.")
        return False

    px = pd.read_parquet(path, columns=["zone", "lon", "lat", "usable_frequency"])

    fig, axes = plt.subplots(2, 3, figsize=(13, 8.6), constrained_layout=True)
    last_coll = None
    for ax, zone in zip(axes.flat, ZONE_ORDER):
        g = px[px.zone == zone]
        hb = ax.hexbin(g.lon, g.lat, C=g.usable_frequency * 100, reduce_C_function=np.mean,
                       gridsize=55, cmap=COVERAGE_CMAP, vmin=0, vmax=100, linewidths=0.1)
        last_coll = hb
        ax.set_title(f"{ZONE_SHORT[zone].splitlines()[0]}  ·  mean {g.usable_frequency.mean()*100:.0f}%",
                     loc="left")
        ax.set_xlabel("lon")
        ax.set_ylabel("lat")
        ax.set_aspect("equal", adjustable="datalim")
        ax.grid(False)

    cbar = fig.colorbar(last_coll, ax=axes, fraction=0.03, pad=0.02)
    cbar.set_label("mean weekly usable-observation frequency, 2022–2024 (%)")
    fig.suptitle("Per-pixel usable-observation frequency within each zone's cropland "
                 "(vertical banding = adjacent Sentinel-2 orbit/tile overlaps, more looks per week)",
                 fontweight="bold", fontsize=10)
    fig.savefig(FIG_DIR / "fig2_spatial_coverage_maps.png")
    plt.close(fig)
    return True


# --- Figure 3: rainfall vs usable_pct --------------------------------------------


def fig_rainfall_correlation(mr: pd.DataFrame) -> dict[str, dict]:
    stats_by_zone: dict[str, dict] = {}
    fig, axes = plt.subplots(2, 3, figsize=(13, 8.4), sharey=True, constrained_layout=True)
    for ax, zone in zip(axes.flat, ZONE_ORDER):
        g = mr[mr.zone == zone]
        color = REGION_COLOR[ZONE_REGION[zone]]
        ax.scatter(g.rainfall_mm_sum, g.usable_pct, s=14, alpha=0.6, color=color,
                   edgecolor="none")
        r, rp = stats.pearsonr(g.rainfall_mm_sum, g.usable_pct)
        rho, rhop = stats.spearmanr(g.rainfall_mm_sum, g.usable_pct)
        stats_by_zone[zone] = {"pearson_r": r, "pearson_p": rp,
                               "spearman_rho": rho, "spearman_p": rhop}
        # OLS trend line for the eye; the reported statistic is the correlation, not this fit.
        if g.rainfall_mm_sum.nunique() > 1:
            b, a = np.polyfit(g.rainfall_mm_sum, g.usable_pct, 1)
            xs = np.linspace(g.rainfall_mm_sum.min(), g.rainfall_mm_sum.max(), 50)
            ys = a + b * xs
            keep = (ys >= 0) & (ys <= 100)
            ax.plot(xs[keep], ys[keep], color="black", lw=1.2)
        ax.set_title(ZONE_SHORT[zone].splitlines()[0], loc="left")
        ax.set_xlabel("CHIRPS weekly rainfall (mm)")
        ax.set_ylabel("usable-observation frequency (%)")
        ax.set_ylim(-3, 103)
        ns = "" if rp < 0.05 else " (n.s.)"
        ax.text(0.96, 0.06,
                f"Pearson r = {r:+.2f}{ns}\nSpearman ρ = {rho:+.2f}",
                transform=ax.transAxes, ha="right", va="bottom", fontsize=8,
                bbox=dict(boxstyle="round,pad=0.3", fc="white", ec="0.7", lw=0.5))
    # No suptitle — the paper's LaTeX caption carries the description.
    fig.savefig(FIG_DIR / "fig3_rainfall_correlation.png")
    plt.close(fig)
    return stats_by_zone


# --- Figure 4: crop-stress-window overlay ---------------------------------------


def _circular_block_perm_p(usable: np.ndarray, label: np.ndarray, n_perm: int = 5000,
                           seed: int = 0) -> float:
    """Two-sided p for the (other - stress) gap from circular shifts of the contiguous
    stress-window label — respects the block structure and temporal autocorrelation."""
    rng = np.random.default_rng(seed)
    obs = usable[~label].mean() - usable[label].mean()
    n = len(label)
    ge = 0
    for _ in range(n_perm):
        pl = np.roll(label, rng.integers(1, n))
        if abs(usable[~pl].mean() - usable[pl].mean()) >= abs(obs) - 1e-9:
            ge += 1
    return (ge + 1) / (n_perm + 1)


def fig_crop_stress(overlaid: pd.DataFrame) -> dict:
    zones = [z for z in ZONE_ORDER if z in overlaid.zone.unique()]
    fig, ax = plt.subplots(figsize=(12, 4.8), constrained_layout=True)

    width = 0.38
    rows = {}
    for i, zone in enumerate(zones):
        g = overlaid[overlaid.zone == zone].sort_values(["iso_year", "iso_week"])
        stress = g[g.in_stress_window].usable_pct
        other = g[~g.in_stress_window].usable_pct
        p = _circular_block_perm_p(g.usable_pct.values, g.in_stress_window.values, seed=i)
        rows[zone] = {
            "n_stress_weeks": len(stress), "n_other_weeks": len(other),
            "stress_mean": stress.mean(), "other_mean": other.mean(),
            "stress_gap_pt": other.mean() - stress.mean(),
            "stress_pct_below_50": 100 * (stress < 50).mean(),
            "other_pct_below_50": 100 * (other < 50).mean(),
            "stress_blockperm_p": p,
        }
        ax.bar(i - width / 2, other.mean(), width, color="#9ecae1",
               label="rest of the year" if i == 0 else None)
        ax.bar(i + width / 2, stress.mean(), width, color="#c44e52",
               label="estimated mid-season window" if i == 0 else None)
        top = max(other.mean(), stress.mean())
        ax.text(i, top + 2.5, f"p={p:.2f}", ha="center", fontsize=8)

    # Pooled pair at the far right, each zone's window shifted independently.
    stress = overlaid[overlaid.in_stress_window].usable_pct
    other = overlaid[~overlaid.in_stress_window].usable_pct
    rng = np.random.default_rng(99)
    zarr = {z: overlaid[overlaid.zone == z].sort_values(["iso_year", "iso_week"]) for z in zones}
    obs_gap = other.mean() - stress.mean()
    ge = 0
    for _ in range(5000):
        us, lb = [], []
        for z in zones:
            gz = zarr[z]
            us.append(gz.usable_pct.values)
            lb.append(np.roll(gz.in_stress_window.values, rng.integers(1, len(gz))))
        u = np.concatenate(us); l = np.concatenate(lb)
        if abs(u[~l].mean() - u[l].mean()) >= abs(obs_gap) - 1e-9:
            ge += 1
    pp = (ge + 1) / 5001
    pooled_x = len(zones) + 0.6
    ax.bar(pooled_x - width / 2, other.mean(), width, color="#9ecae1")
    ax.bar(pooled_x + width / 2, stress.mean(), width, color="#c44e52")
    ax.text(pooled_x, max(other.mean(), stress.mean()) + 2.5, f"p={pp:.2f}",
            ha="center", fontsize=8, fontweight="bold")
    pooled = {
        "n_stress_weeks": len(stress), "n_other_weeks": len(other),
        "stress_mean": stress.mean(), "other_mean": other.mean(),
        "stress_gap_pt": obs_gap,
        "stress_pct_below_50": 100 * (stress < 50).mean(),
        "other_pct_below_50": 100 * (other < 50).mean(),
        "stress_blockperm_p": pp,
    }

    ax.axvline(len(zones) - 0.2, color="0.8", lw=1)
    ax.set_xticks(list(range(len(zones))) + [pooled_x])
    ax.set_xticklabels([ZONE_SHORT[z].splitlines()[0] for z in zones] + ["ALL ZONES\n(pooled)"],
                       fontsize=8)
    ax.set_ylabel("mean usable-observation frequency (%)")
    ax.set_ylim(0, 105)
    ax.legend(loc="lower left")
    # p = circular block-permutation of the window label (see paper §4.3).
    ax.grid(axis="x", visible=False)
    fig.savefig(FIG_DIR / "fig4_crop_stress_overlay.png")
    plt.close(fig)

    rows["ALL ZONES (pooled)"] = pooled
    return rows


# --- Figure 5: zonal boxplots --------------------------------------------------


def fig_zonal_boxplots(weekly: pd.DataFrame) -> None:
    fig, ax = plt.subplots(figsize=(10, 4.6), constrained_layout=True)
    data = [weekly[weekly.zone == z].usable_pct.values for z in ZONE_ORDER]
    bp = ax.boxplot(data, patch_artist=True, showfliers=True,
                    flierprops=dict(marker=".", markersize=3, alpha=0.4),
                    medianprops=dict(color="black", lw=1.4), widths=0.6)
    for patch, zone in zip(bp["boxes"], ZONE_ORDER):
        patch.set_facecolor(REGION_COLOR[ZONE_REGION[zone]])
        patch.set_alpha(0.8)
    ax.axhline(BLIND_SPOT_THRESHOLD_PCT, color="0.4", ls="--", lw=1)
    ax.annotate("blind-spot threshold", xy=(0.995, BLIND_SPOT_THRESHOLD_PCT),
                xycoords=("axes fraction", "data"), xytext=(0, 3), textcoords="offset points",
                ha="right", va="bottom", fontsize=8, color="0.4")
    ax.set_xticklabels([ZONE_SHORT[z] for z in ZONE_ORDER], fontsize=8)
    ax.set_ylabel("weekly usable-observation frequency (%)")
    ax.set_ylim(-3, 103)
    ax.grid(axis="x", visible=False)

    H, p = stats.kruskal(*[weekly[weekly.region == r].usable_pct.values
                           for r in weekly.region.unique()])
    ax.set_title(f"Weekly usable-observation frequency by zone, humid → arid  "
                 f"(Kruskal–Wallis across 5 regions: H = {H:.1f}, p = {p:.1e})", loc="left")
    fig.savefig(FIG_DIR / "fig5_zonal_boxplots.png")
    plt.close(fig)


# --- consolidated results table ----------------------------------------------------


def results_table(weekly: pd.DataFrame, rain_stats: dict, stress_rows: dict) -> pd.DataFrame:
    recs = []
    for zone in ZONE_ORDER:
        g = weekly[weekly.zone == zone]
        by_year = g.groupby("iso_year").usable_pct.mean()
        rec = {
            "zone": zone,
            "region": ZONE_REGION[zone],
            "mean_usable_pct": g.usable_pct.mean(),
            "median_usable_pct": g.usable_pct.median(),
            "std_usable_pct": g.usable_pct.std(),
            "pct_weeks_below_50": 100 * (g.usable_pct < BLIND_SPOT_THRESHOLD_PCT).mean(),
            "year_range_pt": by_year.max() - by_year.min(),
            "rainfall_pearson_r": rain_stats[zone]["pearson_r"],
            "rainfall_pearson_p": rain_stats[zone]["pearson_p"],
            "rainfall_spearman_rho": rain_stats[zone]["spearman_rho"],
        }
        rec.update({k: stress_rows[zone][k] for k in (
            "n_stress_weeks", "stress_mean", "other_mean", "stress_gap_pt",
            "stress_pct_below_50", "other_pct_below_50", "stress_blockperm_p")})
        recs.append(rec)

    pooled = stress_rows["ALL ZONES (pooled)"]
    recs.append({
        "zone": "ALL ZONES (pooled)", "region": "-",
        "mean_usable_pct": weekly.usable_pct.mean(),
        "median_usable_pct": weekly.usable_pct.median(),
        "std_usable_pct": weekly.usable_pct.std(),
        "pct_weeks_below_50": 100 * (weekly.usable_pct < BLIND_SPOT_THRESHOLD_PCT).mean(),
        "year_range_pt": np.nan,
        "rainfall_pearson_r": np.nan, "rainfall_pearson_p": np.nan,
        "rainfall_spearman_rho": np.nan,
        "n_stress_weeks": pooled["n_stress_weeks"],
        "stress_mean": pooled["stress_mean"], "other_mean": pooled["other_mean"],
        "stress_gap_pt": pooled["stress_gap_pt"],
        "stress_pct_below_50": pooled["stress_pct_below_50"],
        "other_pct_below_50": pooled["other_pct_below_50"],
        "stress_blockperm_p": pooled["stress_blockperm_p"],
    })

    df = pd.DataFrame(recs).set_index("zone")
    df.to_csv(FIG_DIR / "phase2_results_table.csv")
    with pd.option_context("display.width", 200, "display.max_columns", 30):
        print(df.round(3).to_string())
    return df


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--no-pixel", action="store_true",
                        help="Skip fig2 (spatial maps) even if the pixel parquet is present.")
    parser.add_argument("--no-map", action="store_true",
                        help="Skip the study-area locator map (avoids the network fetch).")
    args = parser.parse_args()

    house_style()
    FIG_DIR.mkdir(exist_ok=True)

    weekly = load_weekly()
    mr = load_weekly_with_rain()

    print("Figure: study-area locator map")
    if args.no_map:
        print("  study-area map SKIPPED (--no-map).")
    else:
        fig_study_area_map()

    print("Figure 1: weekly coverage heatmap")
    fig_weekly_heatmap(weekly)

    print("Figure 2: spatial per-pixel coverage maps")
    if args.no_pixel:
        print("  fig2 SKIPPED (--no-pixel).")
    else:
        fig_spatial_maps()

    print("Figure 3: rainfall correlation")
    rain_stats = fig_rainfall_correlation(mr)

    print("Figure 4: crop-stress-window overlay")
    calendar_records = cso.load_calendar_records(cso.CALENDAR_RECORDS)
    overlaid = cso.overlay(cso.load_observations(), calendar_records)
    stress_rows = fig_crop_stress(overlaid)

    print("Figure 5: zonal boxplots")
    fig_zonal_boxplots(weekly)

    print("\n=== Phase 2 consolidated results table (also written to figures/phase2_results_table.csv) ===")
    results_table(weekly, rain_stats, stress_rows)

    print(f"\nWrote figures to {FIG_DIR}/")


if __name__ == "__main__":
    main()


def _fetch_admin1_zone(iso3: str, zone_name: str):
    """Fetch one ADM1 polygon from geoBoundaries (no auth). Inlined for the public
    package so it does not depend on the private acquisition module."""
    import requests
    from shapely.geometry import shape as _shape
    meta = requests.get(
        f"https://www.geoboundaries.org/api/current/gbOpen/{iso3}/ADM1/", timeout=30
    ).json()
    url = meta.get("simplifiedGeometryGeoJSON") or meta["gjDownloadURL"]
    fc = requests.get(url, timeout=60).json()
    target = zone_name.strip().lower()
    for feat in fc["features"]:
        if feat["properties"].get("shapeName", "").strip().lower() == target:
            return _shape(feat["geometry"])
    raise ValueError(f"No ADM1 unit named {zone_name!r} in {iso3}")