helloworld / code /analyze_association.py
eduzrh's picture
Upload code/analyze_association.py with huggingface_hub
27f912d verified
Raw History Blame Contribute Delete
13.4 kB
"""关联关系挖掘:CDHE 面积占比与外部强迫/环流指数的关系。
分析项
A CDHE 与 CO2 年增长率、全球气温距平的年尺度相关
B 一阶差分(去共同趋势)后的相关
C 偏相关(控制全球气温 / 控制 CO2 增长率)
D 超前滞后(0、1、2 年,双向)
E ENSO:CDHE 的面积占比与 Niño3.4 年际分量,厄尔尼诺/拉尼娜年合成
F 复合性:P(热|干)、P(干|热) 的条件概率趋势,判断复合是否比单一致灾更快增长
G 区域贡献:各区域对全球 CDHE 增量按面积加权后的份额
H 季节相位:CDHE 面积占比的月气候态
输出 results/association.json、figures/fig6_association.png
"""
import json
import os
import numpy as np
import netCDF4 as nc
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")
REGIONS = [
("亚马逊", -15, 5, -75, -45), ("欧洲", 35, 70, -10, 40), ("东亚", 20, 50, 100, 145),
("北美", 25, 60, -125, -65), ("澳大利亚", -45, -10, 110, 155), ("非洲南部", -35, 5, 10, 50),
("干旱亚洲", 15, 45, 40, 80), ("南美南部", -40, -20, -75, -45),
]
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 rnd(x, n=3):
return round(float(x), n)
def annual_cdhe():
a = json.load(open(os.path.join(OUT, "annual_series.json")))
return {r["year"]: r["cdhe_frac_mean"] * 100 for r in a}
def annual_co2_growth():
rows = []
for line in open(os.path.join(BASE, "data", "co2_mm_mlo.csv")):
if line.startswith("#") or line.startswith("year"):
continue
p = line.strip().split(",")
if len(p) < 5:
continue
try:
y, m, avg = int(p[0]), int(p[1]), float(p[4])
except ValueError:
continue
rows.append((y, m, avg))
by_year = {}
for y, m, v in rows:
by_year.setdefault(y, {})[m] = v
full = {y: d for y, d in by_year.items() if all(m in d for m in range(1, 13))}
out = {}
for y in sorted(full):
if (y - 1) in full:
out[y] = float(np.mean(list(full[y].values())) - np.mean(list(full[y - 1].values())))
return out
def annual_gmt():
d = nc.Dataset(os.path.join(BASE, "data", "air.mon.mean.nc"))
lat = np.array(d["lat"][:], float)
t = d["time"]
times = nc.num2date(t[:], t.units, only_use_cftime_datetimes=False)
v = np.array(d["air"][:], float)
d.close()
w = np.cos(np.deg2rad(lat))[:, None]
w = np.repeat(w, v.shape[2], axis=1)
gm = np.nansum(v * w, axis=(1, 2)) / np.nansum(w)
by = {}
for i, x in enumerate(times):
by.setdefault(x.year, []).append(gm[i])
s = {y: float(np.mean(m)) for y, m in by.items() if len(m) == 12}
base = np.mean([s[y] for y in range(1991, 2021) if y in s])
return {y: s[y] - base for y in s}
def annual_nino():
"""Niño3.4 异常,按 DJF 定义 El Niño 年(当年 12 月与次年 1—2 月平均)。"""
txt = open(os.path.join(BASE, "data", "nina34.anom.data")).read().splitlines()
data = {}
for line in txt:
p = line.split()
if len(p) == 13 and p[0].isdigit():
y = int(p[0])
data[y] = [float(x) for x in p[1:]]
ann = {y: float(np.mean(v)) for y, v in data.items() if all(x > -99 for x in v)}
return ann
def report(x, y, label):
x, y = np.asarray(x, float), np.asarray(y, float)
r, p = stats.pearsonr(x, y)
rs, ps = stats.spearmanr(x, y)
k, b = np.polyfit(x, y, 1)
return dict(label=label, n=int(len(x)), pearson_r=rnd(r), p=float(f"{p:.3g}"),
spearman=rnd(rs), p_spearman=float(f"{ps:.3g}"), slope=rnd(k, 4))
def partial(x, y, z):
x, y, z = (np.asarray(a, float) for a in (x, y, z))
rxy = stats.pearsonr(x, y)[0]
rxz = stats.pearsonr(x, z)[0]
ryz = stats.pearsonr(y, z)[0]
r = (rxy - rxz * ryz) / np.sqrt((1 - rxz ** 2) * (1 - ryz ** 2))
n = len(x)
df = n - 3
t = r * np.sqrt(df / (1 - r ** 2))
p = 2 * stats.t.sf(abs(t), df)
return rnd(r), float(f"{p:.3g}")
def state_series():
m = json.load(open(os.path.join(OUT, "monthly_series.json")))
yrs = sorted({r["year"] for r in m})
out = {"year": [], "dry_only": [], "hot_only": [], "both": [],
"p_hot_given_dry": [], "p_dry_given_hot": []}
for y in yrs:
rows = [r for r in m if r["year"] == y]
if len(rows) < 12:
continue
d = np.mean([r["dry_frac"] for r in rows]) * 100
h = np.mean([r["hot_frac"] for r in rows]) * 100
c = np.mean([r["cdhe_frac"] for r in rows]) * 100
out["year"].append(y)
out["dry_only"].append(d - c)
out["hot_only"].append(h - c)
out["both"].append(c)
out["p_hot_given_dry"].append(100 * c / d if d > 0 else np.nan)
out["p_dry_given_hot"].append(100 * c / h if h > 0 else np.nan)
return out
def regional_weights():
spi = np.load(os.path.join(OUT, "spi.npy"))
lat = np.linspace(90 - 1.25, -90 + 1.25, spi.shape[1])
lon = np.linspace(-180 + 1.25, 180 - 1.25, spi.shape[2])
land = ~np.isnan(spi[-1])
w = np.cos(np.deg2rad(lat))[:, None] * land
out = {}
for name, la0, la1, lo0, lo1 in REGIONS:
ml = (lat >= la0) & (lat <= la1)
mo = (lon >= lo0) & (lon <= lo1)
out[name] = float(np.nansum(w[np.ix_(ml, mo)]))
return out
def main():
cdhe = annual_cdhe()
co2 = annual_co2_growth()
gmt = annual_gmt()
nino = annual_nino()
yrs = sorted(set(cdhe) & set(co2) & set(gmt))
cd = np.array([cdhe[y] for y in yrs])
cg = np.array([co2[y] for y in yrs])
gt = np.array([gmt[y] for y in yrs])
corr = [
report(cg, cd, "CO2 年增长率 → CDHE(百分点/ppm·yr⁻¹)"),
report(gt, cd, "全球气温距平 → CDHE(百分点/°C)"),
report(gt, cg, "全球气温距平 → CO2 年增长率(ppm·yr⁻¹/°C)"),
]
diff = [
report(np.diff(cg), np.diff(cd), "ΔCO2 增长率 → ΔCDHE"),
report(np.diff(gt), np.diff(cd), "Δ气温距平 → ΔCDHE"),
]
pc_cd_cg = partial(cd, cg, gt)
pc_cd_gt = partial(cd, gt, cg)
pc_diff = partial(np.diff(cd), np.diff(cg), np.diff(gt))
lags = []
for k in (1, 2):
if k < len(yrs):
lags.append(report(cd[:-k], cg[k:], f"CDHE(t) vs CO2增长率(t+{k})"))
lags.append(report(cg[:-k], cd[k:], f"CO2增长率(t) vs CDHE(t+{k})"))
# ENSO:年际分量(去 9 年滑动趋势),避免把升温趋势混进来
nyrs = [y for y in yrs if y in nino]
cm = np.array([cdhe[y] for y in nyrs])
nm = np.array([nino[y] for y in nyrs])
def detr(v, win=9):
s = np.convolve(v, np.ones(win) / win, mode="same")
edge = win // 2
out = v.copy()
out[edge:-edge] = v[edge:-edge] - s[edge:-edge]
return out[edge:-edge]
enso = report(detr(cm), detr(nm), "CDHE 与 Niño3.4(均去 9 年滑动均值)")
el = [cdhe[y] for y in nyrs if nino[y] >= 0.5]
la = [cdhe[y] for y in nyrs if nino[y] <= -0.5]
enso_comp = dict(el_n=len(el), el_mean=rnd(np.mean(el), 2), la_n=len(la),
la_mean=rnd(np.mean(la), 2),
diff=rnd(np.mean(el) - np.mean(la), 2),
welch_p=float(f"{stats.ttest_ind(el, la, equal_var=False).pvalue:.3g}"))
# 复合性
st = state_series()
sy = np.asarray(st["year"], float)
comp = {}
for key, lab in [("dry_only", "仅干"), ("hot_only", "仅热"), ("both", "干热复合")]:
v = np.asarray(st[key], float)
sl, ic, _, _ = stats.theilslopes(v, sy, 0.95)
tau, mk_p = stats.kendalltau(sy, v)
comp[lab] = dict(slope=rnd(sl, 4), mk_p=float(f"{mk_p:.3g}"),
first=rnd(v[:5].mean(), 2), last=rnd(v[-5:].mean(), 2),
ratio_last_first=rnd(v[-5:].mean() / v[:5].mean(), 2))
for key, lab in [("p_hot_given_dry", "P(热|干)"), ("p_dry_given_hot", "P(干|热)")]:
v = np.asarray(st[key], float)
ok = ~np.isnan(v)
sl, _, _, _ = stats.theilslopes(v[ok], sy[ok], 0.95)
tau, mk_p = stats.kendalltau(sy[ok], v[ok])
comp[lab] = dict(slope=rnd(sl * 10, 3), unit="百分点/十年",
mk_p=float(f"{mk_p:.3g}"),
first=rnd(v[ok][:5].mean(), 1), last=rnd(v[ok][-5:].mean(), 1))
# 区域贡献
rw = regional_weights()
rs = json.load(open(os.path.join(OUT, "region_series.json")))
trend = json.load(open(os.path.join(OUT, "trend_stats.json")))["regional_trend"]
tot_w = sum(rw.values())
contrib = {}
for name in rw:
chg = trend[name]["last"] - trend[name]["first"]
contrib[name] = dict(area_share=rnd(100 * rw[name] / tot_w, 1),
change_pp=rnd(chg, 2),
contrib=rnd(100 * rw[name] / tot_w * chg, 2))
csum = sum(v["contrib"] for v in contrib.values())
for name in contrib:
contrib[name]["share_of_rise"] = rnd(100 * contrib[name]["contrib"] / csum, 1)
# 季节相位
ms = json.load(open(os.path.join(OUT, "monthly_series.json")))
seas = {}
for mth in range(1, 13):
v = [r["cdhe_frac"] for r in ms if r["month"] == mth]
seas[mth] = rnd(np.mean(v) * 100, 2)
out = dict(
period=dict(cdhe=[int(yrs[0]), int(yrs[-1])], n_years=len(yrs)),
head=dict(cdhe_first5=rnd(cd[:5].mean(), 2), cdhe_last5=rnd(cd[-5:].mean(), 2),
co2_last=rnd(cg[-1], 2), gmt_last=rnd(gt[-1], 2)),
corr=corr, diff=diff,
partial=dict(cdhe_co2_given_gmt=dict(r=pc_cd_cg[0], p=pc_cd_cg[1]),
cdhe_gmt_given_co2=dict(r=pc_cd_gt[0], p=pc_cd_gt[1]),
diff_cdhe_co2_given_gmt=dict(r=pc_diff[0], p=pc_diff[1])),
lags=lags, enso=dict(test=enso, composite=enso_comp),
compound=comp, contrib=contrib, seasonal=seas)
json.dump(out, open(os.path.join(OUT, "association.json"), "w"), ensure_ascii=False, indent=2)
# ---------------- 图 ----------------
fig = plt.figure(figsize=(11.0, 6.6))
gs = fig.add_gridspec(2, 3, hspace=.42, wspace=.32)
ax = fig.add_subplot(gs[0, 0])
ax.scatter(cg, cd, s=16, color="#c0392b", alpha=.7, edgecolor="none")
k, b = np.polyfit(cg, cd, 1)
xs = np.linspace(cg.min(), cg.max(), 10)
ax.plot(xs, k * xs + b, color="#2c3e50", lw=1.1)
ax.set_xlabel("CO$_2$ 年增长率 (ppm yr$^{-1}$)", fontsize=8)
ax.set_ylabel("CDHE 面积占比 (%)", fontsize=8)
ax.set_title(f"A 与 CO$_2$ 增长 r={corr[0]['pearson_r']:.2f}", loc="left", fontsize=9)
ax = fig.add_subplot(gs[0, 1])
ax.scatter(gt, cd, s=16, color="#c0392b", alpha=.7, edgecolor="none")
k, b = np.polyfit(gt, cd, 1)
xs = np.linspace(gt.min(), gt.max(), 10)
ax.plot(xs, k * xs + b, color="#2c3e50", lw=1.1)
ax.set_xlabel("全球气温距平 (°C,相对 1991—2020)", fontsize=8)
ax.set_ylabel("CDHE 面积占比 (%)", fontsize=8)
ax.set_title(f"B 与全球气温 r={corr[1]['pearson_r']:.2f}", loc="left", fontsize=9)
ax = fig.add_subplot(gs[0, 2])
ax.scatter(detr(cm), detr(nm), s=16, color="#2c7fb8", alpha=.75, edgecolor="none")
k, b = np.polyfit(detr(cm), detr(nm), 1)
xs = np.linspace(min(detr(cm)), max(detr(cm)), 10)
ax.plot(xs, k * xs + b, color="#2c3e50", lw=1.1)
ax.set_xlabel("Niño3.4 年际分量 (°C)", fontsize=8)
ax.set_ylabel("CDHE 年际分量 (百分点)", fontsize=8)
ax.set_title(f"C 与 ENSO r={enso['pearson_r']:.2f}", loc="left", fontsize=9)
ax = fig.add_subplot(gs[1, 0])
ax.plot(sy, st["dry_only"], color="#8c6d1f", lw=1.3, label="仅干")
ax.plot(sy, st["hot_only"], color="#c0392b", lw=1.3, label="仅热")
ax.plot(sy, st["both"], color="#2c3e50", lw=1.8, label="干热复合")
ax.set_ylabel("陆地面积占比 (%)", fontsize=8)
ax.set_title("D 三类状态面积占比", loc="left", fontsize=9)
ax.legend(fontsize=7, frameon=False, ncol=3)
ax.tick_params(labelsize=7)
ax = fig.add_subplot(gs[1, 1])
ax.plot(sy, st["p_hot_given_dry"], color="#c0392b", lw=1.4, label="P(热|干)")
ax.plot(sy, st["p_dry_given_hot"], color="#8c6d1f", lw=1.4, label="P(干|热)")
ax.set_ylabel("条件概率 (%)", fontsize=8)
ax.set_title("E 干与热的共现强度", loc="left", fontsize=9)
ax.legend(fontsize=7, frameon=False)
ax.tick_params(labelsize=7)
ax = fig.add_subplot(gs[1, 2])
names = list(seas)
ax.bar(names, [seas[m] for m in names], color="#4a6fa5", width=.68)
ax.set_xticks(range(1, 13))
ax.set_xticklabels([f"{m}" for m in range(1, 13)], fontsize=7)
ax.set_xlabel("月份", fontsize=8)
ax.set_ylabel("CDHE 面积占比 (%)", fontsize=8)
ax.set_title("F 季节相位(1979—2025 平均)", loc="left", fontsize=9)
ax.tick_params(labelsize=7)
fig.savefig(os.path.join(FIG, "fig6_association.png"), bbox_inches="tight")
print(json.dumps(out, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()