File size: 8,924 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
"""Phase 2 item 2 (rainfall correlation) + item 5 (Kasai-Oriental year trend) for the
P3 cloud-cover-bias paper.

Joins the CHIRPS weekly rainfall table (chirps_ingest.py) against the usable-observation
-frequency table (weekly_pipeline.py) on (zone, iso_year, iso_week) -- the two are built
to share that key exactly, see chirps_ingest.py's module docstring. This is the piece
analyze_phase1.py deferred: "item 2 -- rainfall correlation, needs CHIRPS".

Usage:
    python analyze_phase2.py
"""

from __future__ import annotations

import argparse
from pathlib import Path

import pandas as pd
from scipy import stats

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

# Same headline tier as analyze_phase1.py -- matches production's SCL_INVALID_CLASSES.
HEADLINE_TIER = "moderate"

# Cloud persistence after a rain event is the spec's stated reason to check beyond
# same-week correlation: a rainy week can leave cloud cover behind into the following
# week even after the rain itself has stopped.
LAGS = [1, 2]

HUMID_ZONE = "COD/Kasai-Oriental"


def load_merged() -> pd.DataFrame:
    obs = pd.read_parquet(Path(__file__).parent.parent / "data" / OBS_INPUT)
    obs = obs[obs.tier == HEADLINE_TIER].copy()
    rain = pd.read_parquet(Path(__file__).parent.parent / "data" / CHIRPS_INPUT)

    merged = obs.merge(
        rain[["zone", "iso_year", "iso_week", "n_days", "rainfall_mm_sum", "rainfall_mm_mean"]],
        on=["zone", "iso_year", "iso_week"],
        how="inner",
    )
    if len(merged) != len(obs):
        raise SystemExit(
            f"Join dropped rows: {len(obs)} usable-observation weeks ({HEADLINE_TIER} tier) "
            f"vs {len(merged)} after joining CHIRPS -- the two tables' zone/week keys should "
            "match exactly (see chirps_ingest.py's module docstring). Investigate before trusting "
            "any correlation below."
        )
    return merged.sort_values(["zone", "iso_year", "iso_week"]).reset_index(drop=True)


def same_week_correlation(m: pd.DataFrame) -> None:
    """Spec Phase 2 item 2: Pearson/Spearman, rainfall vs usable_pct, per zone then pooled
    by region. A negative correlation is the expected sign: more rain -> more cloud ->
    lower usable_pct.
    """
    print("=== Same-week correlation (rainfall_mm_sum vs usable_pct) ===")
    rows = []
    for zone, g in m.groupby("zone"):
        r, rp = stats.pearsonr(g.rainfall_mm_sum, g.usable_pct)
        rho, rhop = stats.spearmanr(g.rainfall_mm_sum, g.usable_pct)
        rows.append({"zone": zone, "region": g.region.iloc[0], "n": len(g),
                      "pearson_r": r, "pearson_p": rp, "spearman_rho": rho, "spearman_p": rhop})
    out = pd.DataFrame(rows).set_index("zone").round(3)
    print(out.to_string())

    print("\nPooled by region:")
    rows = []
    for region, g in m.groupby("region"):
        r, rp = stats.pearsonr(g.rainfall_mm_sum, g.usable_pct)
        rho, rhop = stats.spearmanr(g.rainfall_mm_sum, g.usable_pct)
        rows.append({"region": region, "n": len(g), "pearson_r": r, "pearson_p": rp,
                      "spearman_rho": rho, "spearman_p": rhop})
    print(pd.DataFrame(rows).set_index("region").round(3).to_string())


def lagged_correlation(m: pd.DataFrame) -> None:
    """Does rainfall in week (t - lag) predict low usable_pct in week t? Weeks are
    ordered by week_start (not iso_week alone, which resets every year) so the shift is
    continuous across year boundaries within a zone; a lag that straddles a checkpoint
    gap or the very start of a zone's series becomes NaN and is dropped by pearsonr/
    spearmanr's paired handling.
    """
    print(f"\n=== Lagged correlation (rainfall at t-lag vs usable_pct at t), lags={LAGS} ===")
    m = m.sort_values(["zone", "week_start"])
    rows = []
    for lag in LAGS:
        for zone, g in m.groupby("zone"):
            g = g.copy()
            g["rainfall_lag"] = g["rainfall_mm_sum"].shift(lag)
            g = g.dropna(subset=["rainfall_lag"])
            r, rp = stats.pearsonr(g.rainfall_lag, g.usable_pct)
            rho, rhop = stats.spearmanr(g.rainfall_lag, g.usable_pct)
            rows.append({"lag_weeks": lag, "zone": zone, "n": len(g),
                         "pearson_r": r, "pearson_p": rp, "spearman_rho": rho, "spearman_p": rhop})
    out = pd.DataFrame(rows).set_index(["lag_weeks", "zone"]).round(3)
    print(out.to_string())
    print("\n  Compare each zone's lag-1/lag-2 |r| against its same-week |r| above -- a lagged "
          "correlation stronger than same-week would support the cloud-persistence-after-rain "
          "hypothesis from the spec; a weaker one means same-week cloud is the dominant effect.")


def kasai_year_trend(m: pd.DataFrame) -> None:
    """Spec Phase 2 item 5/6: does CHIRPS explain Kasai-Oriental's 48% -> 53% -> 65%
    usable_pct climb across 2022-2024? The three candidate explanations in the spec are
    (a) genuine climate variability, (b) a change in acquisition density, (c) an artifact
    of the 2.3%-cropland denominator. This function rules on (a) and (b); (c) needs the
    unmasked-pixel run and is a Phase 3 item.
    """
    print(f"\n=== Kasai-Oriental year trend (spec item 5/6) ===")
    z = m[m.zone == HUMID_ZONE]
    by_year = z.groupby("iso_year").agg(
        usable_pct_mean=("usable_pct", "mean"),
        observed_pct_mean=("observed_pct", "mean"),
        n_items_mean=("n_items", "mean"),
        zero_item_weeks=("n_items", lambda s: int((s == 0).sum())),
        rainfall_mm_sum_mean=("rainfall_mm_sum", "mean"),
        rainfall_mm_sum_total=("rainfall_mm_sum", "sum"),
    ).round(2)
    print(by_year.to_string())

    # Candidate (b): acquisition density. If usable_pct climbed because the catalog simply
    # has more scenes per week in 2024 than 2022, n_items_mean would rise sharply and the
    # trend would be an artifact. If n_items is roughly flat while observed_pct and the
    # zero-item-week count move with usable_pct, the driver is cloud, not acquisition --
    # and per the spec's zero-item-week investigation those zero weeks are total-cloud, so
    # they are themselves a cloud signal.
    n0, n2 = by_year["n_items_mean"].iloc[0], by_year["n_items_mean"].iloc[-1]
    zshift = by_year["zero_item_weeks"].iloc[0] - by_year["zero_item_weeks"].iloc[-1]
    print(f"\nAcquisition density: mean n_items/week {n0:.2f} (2022) -> {n2:.2f} "
          f"({by_year.index[-1]}), {100 * (n2 - n0) / n0:+.0f}%. "
          f"Zero-item (total-cloud) weeks: {by_year['zero_item_weeks'].iloc[0]} -> "
          f"{by_year['zero_item_weeks'].iloc[-1]} ({zshift:+d}).")
    if abs((n2 - n0) / n0) < 0.20:
        print("  -> acquisition density is essentially flat; the climb is not a catalog artifact. "
              "The falling zero-item-week count is a cloud signal (those weeks are total-cloud, "
              "per the zero-item-week investigation), consistent with the climate explanation.")
    else:
        print("  -> acquisition density moved materially -- acquisition change cannot be ruled "
              "out as a contributor to the usable_pct trend.")

    r, rp = stats.pearsonr(z.rainfall_mm_sum, z.usable_pct)
    rho, rhop = stats.spearmanr(z.rainfall_mm_sum, z.usable_pct)
    print(f"\nWithin-zone same-week correlation: pearson r = {r:.3f} (p = {rp:.3e}), "
          f"spearman rho = {rho:.3f} (p = {rhop:.3e})")

    delta_rain = by_year["rainfall_mm_sum_mean"].iloc[0] - by_year["rainfall_mm_sum_mean"].iloc[-1]
    delta_usable = by_year["usable_pct_mean"].iloc[-1] - by_year["usable_pct_mean"].iloc[0]
    print(f"\n2022 vs {by_year.index[-1]}: mean weekly rainfall {'higher' if delta_rain > 0 else 'lower'} "
          f"by {abs(delta_rain):.1f} mm in 2022, usable_pct climbed {delta_usable:.1f} pt over the same span.")
    if r < 0 and delta_rain > 0:
        print("  -> Consistent with the climate explanation: 2022 was both wetter and less "
              "observable in this zone, and the correlation sign matches the pooled/regional result.")
    else:
        print("  -> NOT a clean climate story: either the correlation sign is wrong for this zone "
              "or the year-over-year rainfall trend doesn't match the usable_pct trend -- the "
              "48->53->65% climb needs a different explanation (acquisition density, denominator "
              "artifact -- see spec Phase 2 caveats) before publishing this as a climate finding.")


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.parse_args()

    print(f"Joining {OBS_INPUT} ({HEADLINE_TIER} tier) with {CHIRPS_INPUT}\n")
    m = load_merged()
    print(f"Joined: {len(m)} zone-weeks, {m.zone.nunique()} zones, years {sorted(m.iso_year.unique())}\n")

    same_week_correlation(m)
    lagged_correlation(m)
    kasai_year_trend(m)


if __name__ == "__main__":
    main()