File size: 4,987 Bytes
238aecc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""ENSO 的月尺度关联:CDHE 去季节循环后与 Niño3.4 异常的滞后相关。

输出 results/enso_monthly.json、figures/fig7_enso.png
"""
import json
import os
import numpy as np
from scipy import stats
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

BASE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(BASE, "results")
FIG = os.path.join(BASE, "figures")
plt.rcParams.update({
    "font.family": ["Noto Sans CJK SC", "DejaVu Sans"], "axes.unicode_minus": False,
    "figure.facecolor": "white", "axes.grid": True, "grid.color": "#e6e9ee",
    "grid.linewidth": .6, "savefig.dpi": 200,
})


def monthly_cdhe():
    m = json.load(open(os.path.join(OUT, "monthly_series.json")))
    return ([(r["year"], r["month"]) for r in m],
            np.array([r["cdhe_frac"] for r in m]) * 100)


def monthly_nino():
    lines = open(os.path.join(BASE, "data", "nina34.anom.data")).read().splitlines()
    d = {}
    for line in lines:
        p = line.split()
        if len(p) == 13 and p[0].isdigit():
            d[int(p[0])] = [float(x) for x in p[1:]]
    return d


def main():
    keys, cd = monthly_cdhe()
    cd = np.where(np.isnan(cd), np.nanmean(cd), cd)
    # 去季节循环(按日历月去均值),再线性去趋势
    months = np.array([k[1] for k in keys])
    dese = cd.copy()
    for m in range(1, 13):
        sel = months == m
        dese[sel] -= cd[sel].mean()
    t = np.arange(len(dese))
    k, b = np.polyfit(t, dese, 1)
    dese = dese - (k * t + b)

    nino_raw = monthly_nino()
    nino = np.array([nino_raw.get(y, [np.nan] * 12)[m - 1] for y, m in keys])
    bad = nino < -90
    nino[bad] = np.nan
    ok = ~np.isnan(nino)
    # 年际尺度:去季节循环并去 5 年滑动趋势
    nino_c = nino.copy()
    for m in range(1, 13):
        sel = (months == m) & ok
        if sel.sum() > 5:
            nino_c[sel] -= np.nanmean(nino[sel])
    s = np.convolve(np.nan_to_num(nino_c), np.ones(61) / 61, mode="same")
    nino_c = nino_c - s

    lags, rs, ps = [], [], []
    for L in range(-3, 13):
        if L >= 0:
            x = nino_c[:len(nino_c) - L]
            y = dese[L:]
        else:
            x = nino_c[-L:]
            y = dese[:len(dese) + L]
        g = ~np.isnan(x)
        r, p = stats.pearsonr(x[g], y[g])
        lags.append(L)
        rs.append(r)
        ps.append(p)
    best = int(np.argmax(np.abs(rs)))
    best_lag = lags[best]

    # 厄尔尼诺年(DJF 平均 ≥0.5)与非厄尔尼诺年的月份合成
    djf = {}
    for y in sorted(nino_raw):
        v = nino_raw[y]
        prev = nino_raw.get(y - 1, [np.nan] * 12)
        if all(x > -90 for x in v[:2]) and prev[11] > -90:
            djf[y] = float(np.mean([prev[11], v[0], v[1]]))
    el_years = sorted([y for y, v in djf.items() if v >= 0.5])
    la_years = sorted([y for y, v in djf.items() if v <= -0.5])
    cd_by = {}
    for (y, m), v in zip(keys, cd):
        cd_by.setdefault(y, {})[m] = v
    def comp(ys):
        return float(np.nanmean([np.nanmean(list(cd_by[y].values())) for y in ys if y in cd_by]))
    el, la = comp(el_years), comp(la_years)

    out = dict(best_lag_months=best_lag, best_r=round(float(rs[best]), 3),
               best_p=float(f"{ps[best]:.3g}"),
               profile=[dict(lag=L, r=round(float(r), 3), p=float(f"{p:.3g}"))
                        for L, r, p in zip(lags, rs, ps)],
               el_nino_years=el_years, la_nina_years=la_years,
               el_mean=round(el, 2), la_mean=round(la, 2),
               el_minus_la=round(el - la, 2))
    json.dump(out, open(os.path.join(OUT, "enso_monthly.json"), "w"), ensure_ascii=False, indent=2)
    print(json.dumps({k: out[k] for k in ("best_lag_months", "best_r", "best_p",
                                          "el_mean", "la_mean", "el_minus_la")},
                     ensure_ascii=False, indent=1))

    fig, axes = plt.subplots(1, 2, figsize=(8.4, 3.0))
    ax = axes[0]
    cols = ["#2c3e50" if i != best else "#c0392b" for i in range(len(lags))]
    ax.bar(lags, rs, color=cols, width=.72)
    ax.axhline(0, color="#888", lw=.8)
    ax.axhline(1.96 / np.sqrt(np.sum(ok)), color="#888", ls="--", lw=.8)
    ax.axhline(-1.96 / np.sqrt(np.sum(ok)), color="#888", ls="--", lw=.8)
    ax.set_xlabel("Niño3.4 超前 CDHE 的月数", fontsize=8)
    ax.set_ylabel("相关系数", fontsize=8)
    ax.set_title("A  滞后相关", loc="left", fontsize=9)
    ax.tick_params(labelsize=7)

    ax = axes[1]
    ax.bar(["厄尔尼诺年", "拉尼娜年"], [el, la], color=["#c0392b", "#2c7fb8"], width=.5)
    for i, v in enumerate([el, la]):
        ax.text(i, v + .08, f"{v:.2f}", ha="center", fontsize=8)
    ax.set_ylabel("CDHE 面积占比 (%)", fontsize=8)
    ax.set_title("B  合成(DJF 指数 |≥0.5|)", loc="left", fontsize=9)
    ax.tick_params(labelsize=7)
    fig.tight_layout()
    fig.savefig(os.path.join(FIG, "fig7_enso.png"), bbox_inches="tight")


if __name__ == "__main__":
    main()