File size: 3,641 Bytes
b0ac7d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""事件案例图:两个代表性月份的状态对比。"""
import json
import os
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch, Patch

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,
    "axes.edgecolor": "#3a3f4b",
    "text.color": "#22262e",
    "xtick.color": "#4a505c",
    "ytick.color": "#4a505c",
    "figure.facecolor": "white",
})

CMAP = ["#eef1f4", "#4a90c2", "#d98324", "#c0392b"]


def load_land():
    gj = json.load(open(os.path.join(BASE, "data", "land110.geojson")))
    paths = []
    for f in gj["features"]:
        g = f["geometry"]
        polys = g["coordinates"] if g["type"] == "MultiPolygon" else [g["coordinates"]]
        for poly in polys:
            for ring in poly:
                arr = np.array(ring)
                if len(arr) >= 4:
                    paths.append(Path(arr, closed=True))
    return paths


LAND = load_land()


def panel(ax, lat, lon, spi, sti, title, sub):
    lo_s = ((lon + 180) % 360) - 180
    order = np.argsort(lo_s)
    val = np.where((spi <= -1) & (sti >= 1), 3, np.where(spi <= -1, 1, np.where(sti >= 1, 2, 0))).astype(float)
    nan = np.isnan(spi) | np.isnan(sti)
    val[nan] = np.nan
    ax.set_facecolor("#f4f6f8")
    ax.pcolormesh(lo_s[order], lat, val[:, order], cmap=plt.matplotlib.colors.ListedColormap(CMAP),
                  vmin=0, vmax=3, shading="nearest")
    for p in LAND:
        ax.add_patch(PathPatch(p, facecolor="none", edgecolor="#7b8390", lw=0.35, zorder=3))
    ax.set_xlim(-180, 180); ax.set_ylim(-60, 85)
    ax.set_xticks([-150, -100, -50, 0, 50, 100, 150])
    ax.set_yticks([-40, -20, 0, 20, 40, 60, 80])
    ax.grid(False)
    ax.set_title(f"{title}   {sub}", loc="left", fontsize=9.2, color="#12161d")


def main():
    import netCDF4 as nc
    d = nc.Dataset(os.path.join(BASE, "data", "precip.mon.mean.nc"))
    lat = np.array(d["lat"][:], float); lon = np.array(d["lon"][:], float)
    d.close()
    spi = np.load(os.path.join(OUT, "spi.npy"))
    sti = np.load(os.path.join(OUT, "sti.npy"))
    monthly = json.load(open(os.path.join(OUT, "monthly_series.json")))

    def pick(y, m):
        return next(i for i, r in enumerate(monthly) if r["year"] == y and r["month"] == m)

    a = max([r for r in monthly if r["year"] == 2023], key=lambda r: r["cdhe_frac"])
    b = max([r for r in monthly if r["year"] == 2024], key=lambda r: r["cdhe_frac"])
    cases = [(a, f"{a['year']}-{a['month']:02d}"), (b, f"{b['year']}-{b['month']:02d}")]

    fig, axes = plt.subplots(2, 1, figsize=(7.6, 6.4), dpi=200)
    for ax, (r, lab) in zip(axes, cases):
        k = pick(r["year"], r["month"])
        panel(ax, lat, lon, spi[k], sti[k], f"{lab}",
              f"CDHE {r['cdhe_frac']*100:.1f}% · 干 {r['dry_frac']*100:.1f}% · 热 {r['hot_frac']*100:.1f}%")
    fig.legend(handles=[Patch(color=CMAP[1], label="仅干 (SPI≤-1)"),
                        Patch(color=CMAP[2], label="仅热 (STI≥1)"),
                        Patch(color=CMAP[3], label="复合(干且热)")],
               loc="lower center", ncol=3, frameon=False, fontsize=7.5, bbox_to_anchor=(0.5, -0.01))
    fig.tight_layout(rect=(0, 0.03, 1, 1))
    fig.savefig(os.path.join(FIG, "fig5_cases.png"), bbox_inches="tight")
    plt.close(fig)
    print("ok", [(c[1], round(c[0]["cdhe_frac"] * 100, 1)) for c in cases])


if __name__ == "__main__":
    main()