"""Phase 1 descriptive baseline + regional disparity tests for the P3 cloud-cover paper. NOTE (2026-09): the Kruskal-Wallis on 936 zone-weeks that this script prints is pseudoreplication for a *regional* claim (six spatial units, 156 repeated weekly measurements each). The paper does NOT use it as inferential evidence; the independence-aware regional tests (zone level, zone-year level, GEE) are in `analyze_independence.py`. This script is kept for the descriptive summary. Regenerates every number quoted in the spec's Phase 2 "Preliminary result" section from the committed dataset, so those figures are reproducible from the repo rather than existing only as prose in the markdown. They were originally computed ad hoc at a shell prompt; if the dataset is ever rebuilt (a re-run, a fixed bug, an extra zone) this script is what tells you whether the paper's numbers still hold. This is deliberately the *descriptive* half of Phase 2 only -- items 1 and 3 of the spec's Phase 2 list. Rainfall coupling (item 2) is in `analyze_phase2.py`, which joins in the CHIRPS table; the crop-stress-window overlay (item 4, needs FAO calendars for four more countries) is still unwired. Usage: python analyze_phase1.py python analyze_phase1.py --input weekly_usable_observation_frequency_2022_2024.parquet """ from __future__ import annotations import argparse from pathlib import Path import pandas as pd from scipy import stats DEFAULT_INPUT = "weekly_usable_observation_frequency_2022_2024.parquet" # The paper reports the moderate tier as its headline: it is the tier that matches the # production pipeline's own SCL_INVALID_CLASSES, so "usable" here means the same thing it # means to a deployed CropSense field read. strict/lenient exist for the Phase 3 # threshold-sensitivity check, not for the headline number. HEADLINE_TIER = "moderate" # "How often is this zone's cropland effectively unobservable for a whole week?" A mean # hides this: every zone's distribution is left-skewed (most weeks near-fully observable, # a minority collapsing hard), so the share of bad weeks is the more decision-relevant # framing for an agri-monitoring platform than the average is. BLIND_SPOT_THRESHOLD_PCT = 50.0 # The Phase 0 hypothesis is directional -- humid regions worse than arid -- so the two # ends of the climate gradient are the sharpest single contrast the dataset can offer. HUMID_ZONE = "COD/Kasai-Oriental" ARID_ZONE = "EGY/Beheira Governorate" def load(path: Path) -> pd.DataFrame: df = pd.read_parquet(path) expected = {"zone", "region", "iso_year", "iso_week", "tier", "n_items", "usable_pct"} missing = expected - set(df.columns) if missing: raise SystemExit( f"{path} is missing column(s) {sorted(missing)} -- this looks like the superseded " "two-zone table, which predates cropland masking and has no `region` column. " f"Use {DEFAULT_INPUT}." ) return df def integrity(df: pd.DataFrame) -> None: """The same invariants weekly_pipeline.verify() asserts at write time, re-checked at read time. Cheap, and it catches a dataset silently swapped or truncated between the run and the analysis. """ print("=== Integrity ===") m = df[df.tier == HEADLINE_TIER] per_zone_weeks = m.groupby("zone").size() print(f"rows {len(df)} | zones {df.zone.nunique()} | weeks/zone {sorted(per_zone_weeks.unique())} " f"| years {sorted(df.iso_year.unique())}") wide = df.pivot_table(index=["zone", "iso_year", "iso_week"], columns="tier", values="usable_pct") ok = (wide["strict"] <= wide["moderate"] + 1e-9) & (wide["moderate"] <= wide["lenient"] + 1e-9) print(f"tier ordering (strict<=moderate<=lenient): {(~ok).sum()} violation(s)") print(f"nulls: {df.isnull().sum().sum()}") # Zero-item weeks are a real signal, not a defect -- but they are ambiguous, and the # ambiguity has to stay visible until it is resolved. The STAC pre-filter is # eo:cloud_cover < 95, so a week in which every scene was >=95% clouded is # indistinguishable here from a week with no acquisition at all. zero = m[m.n_items == 0] print(f"\nzero-item weeks: {len(zero)} of {len(m)} " f"(all observed_pct==0: {(zero.observed_pct == 0).all()}, " f"all usable_pct==0: {(zero.usable_pct == 0).all()})") if len(zero): print(zero.groupby("zone").size().to_string()) print(" NOTE: ambiguous -- 'no acquisition' vs '>=95% clouded, dropped by the pre-filter'.") print(" Resolve by re-querying these weeks without the cloud filter before publishing them.") def descriptive(df: pd.DataFrame) -> pd.DataFrame: """Spec Phase 2 item 1: usable-observation frequency by zone and by region.""" m = df[df.tier == HEADLINE_TIER].copy() m["blind_spot"] = m.usable_pct < BLIND_SPOT_THRESHOLD_PCT print(f"\n=== Descriptive baseline ({HEADLINE_TIER} tier) ===") by_zone = m.groupby(["region", "zone"]).agg( mean=("usable_pct", "mean"), median=("usable_pct", "median"), std=("usable_pct", "std"), min=("usable_pct", "min"), weeks=("usable_pct", "size"), in_zone_px=("total_in_zone_pixels", "max"), ).round(1) by_zone["pct_weeks_below_50"] = (m.groupby(["region", "zone"]).blind_spot.mean() * 100).round(1) print(by_zone.to_string()) print("\nBy region (the headline ordering -- expect monotonic humid -> arid):") by_region = m.groupby("region").agg( mean=("usable_pct", "mean"), pct_weeks_below_50=("blind_spot", lambda s: 100 * s.mean()), ).round(1).sort_values("mean") print(by_region.to_string()) print("\nPer-year means by zone (Phase 3: does one anomalous year drive the result?):") print(m.pivot_table(index="zone", columns="iso_year", values="usable_pct").round(1).to_string()) return m def disparity_tests(m: pd.DataFrame) -> None: """Spec Phase 2 item 3: is the regional difference real, or noise? Kruskal-Wallis rather than one-way ANOVA: weekly usable_pct is a bounded percentage, strongly left-skewed, and piles up against 100% -- so ANOVA's normality assumption is not met, while a rank-based test needs no distributional assumption. Mann-Whitney is the same argument for the two-sample contrast. """ print("\n=== Regional disparity (Phase 2 item 3) ===") groups = [g.usable_pct.values for _, g in m.groupby("region")] H, p = stats.kruskal(*groups) print(f"Kruskal-Wallis across {len(groups)} regions: H = {H:.1f}, p = {p:.3e}, n = {len(m)} zone-weeks") print(" -> Phase 0's falsifiable null is rejected." if p < 0.05 else " -> NOT significant: the Phase 0 falsifiable null stands; the structural-bias claim does not hold.") print(f"\nSharpest contrast: {HUMID_ZONE} (humid) vs {ARID_ZONE} (arid)") a = m[m.zone == HUMID_ZONE].usable_pct b = m[m.zone == ARID_ZONE].usable_pct U, pu = stats.mannwhitneyu(a, b) print(f" mean {a.mean():.1f}% vs {b.mean():.1f}% ({b.mean() - a.mean():.1f} pt gap), " f"Mann-Whitney U = {U:.0f}, p = {pu:.3e}") # Secondary, finer-grained test the spec keeps from the original West-Africa-only # scope: does bias differ *within* a region, between the Sahel and Guinea savanna? wa = m[m.region == "West Africa"] zones = sorted(wa.zone.unique()) if len(zones) == 2: x = wa[wa.zone == zones[0]].usable_pct y = wa[wa.zone == zones[1]].usable_pct _, pw = stats.mannwhitneyu(x, y) print(f"\nWithin West Africa: {zones[0]} {x.mean():.1f}% vs {zones[1]} {y.mean():.1f}%, p = {pw:.3f}") def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--input", default=DEFAULT_INPUT, help="Weekly parquet to analyze.") args = parser.parse_args() path = Path(__file__).parent.parent / "data" / args.input print(f"Dataset: {path.name}\n") df = load(path) integrity(df) m = descriptive(df) disparity_tests(m) print("\nSee also:") print(" analyze_phase2.py -- item 2, rainfall correlation (CHIRPS now ingested)") print("\nNot yet wired up (blocked on ingestion, see spec Phase 2):") print(" item 4 -- crop-stress-window overlay, needs FAO calendars for GH/EG/CD/ZW") if __name__ == "__main__": main()