File size: 53,488 Bytes
26517c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e214285
 
 
 
26517c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7609072
 
 
 
 
 
e214285
7609072
26517c6
 
 
 
 
 
 
 
7609072
 
26517c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7609072
26517c6
 
 
 
 
 
 
 
7609072
26517c6
 
 
 
 
 
 
 
 
 
7609072
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26517c6
 
 
 
 
 
 
7609072
 
26517c6
 
 
 
 
7609072
26517c6
 
7609072
26517c6
 
 
 
 
 
 
 
 
 
 
 
 
e214285
 
 
 
 
 
26517c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e214285
 
26517c6
 
 
7609072
e214285
 
 
26517c6
 
e214285
 
 
26517c6
7609072
26517c6
 
e214285
26517c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7609072
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e214285
7609072
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e214285
7609072
 
 
e214285
 
7609072
 
 
 
 
 
 
e214285
 
 
 
 
 
 
 
 
 
 
 
 
26517c6
 
 
 
 
 
 
 
 
e214285
 
26517c6
 
 
 
 
 
 
 
 
 
 
e214285
26517c6
 
 
 
 
 
 
 
e214285
26517c6
 
 
 
 
 
 
 
7609072
 
 
 
e214285
7609072
 
 
 
 
 
26517c6
 
 
 
 
 
 
 
 
 
e214285
26517c6
 
 
7609072
26517c6
 
 
7609072
 
 
 
 
 
 
 
 
26517c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e214285
 
 
 
26517c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e214285
 
 
 
 
 
 
 
26517c6
 
e214285
26517c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7609072
e214285
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26517c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e214285
 
 
 
26517c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e214285
 
26517c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e214285
26517c6
 
 
 
 
 
 
 
 
 
 
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AfriENSO - data pipeline
========================
Downloads the public datasets used by the AfriENSO dashboard, computes every
statistic shown on the page and writes one file, ``afrienso_data.js``, that the
static page (index.html) reads. Run it on your own computer, then upload
``afrienso_data.js`` to the Hugging Face Space (or run ``publish_hf.py``).

    python update_data.py            # normal run (uses a 12 h download cache)
    python update_data.py --no-c3s   # skip the Copernicus C3S forecasts
    python update_data.py --refresh  # ignore the cache, download everything

Data sources (all public):
  * NOAA CPC  - ONI (ERSSTv5), RONI, weekly OISST v2.1 Nino indices, monthly
                ERSSTv5 Nino indices
  * NOAA PSL  - ERSSTv5 gridded SST, GPCP v2.3 monthly precipitation,
                GHCN_CAMS monthly land air temperature (THREDDS/OPeNDAP)
  * Copernicus Climate Pulse - ERA5 daily global mean 2 m temperature
  * Copernicus C3S (optional, needs a free CDS account + ~/.cdsapirc) -
                multi-system seasonal forecasts of SST and precipitation

October 2026 (v1.1, co-authors' review of the associated paper): adds the West
African land boxes GC, WSHL, CSHL and SHL (units of kind "wa", geo["wa"]) and the
SST indices SENC (Senegal-Mauritania coast), MED (Mediterranean) and AMG (TNA-ATL3).

Author: Dr Ibrahima Diouf - University of Labe / LPAO-SF, ESP, UCAD
"""
import argparse
import datetime as dt
import json
import math
import os
import re
import sys
import time
import traceback
import warnings

import numpy as np
import pandas as pd
import requests

HERE = os.path.dirname(os.path.abspath(__file__))
CACHE = os.path.join(HERE, "_cache")
OUT_JS = os.path.join(HERE, "afrienso_data.js")
GEO_JSON = os.path.join(HERE, "africa_geo.json")

URL = {
    "oni": "https://www.cpc.ncep.noaa.gov/data/indices/oni.ascii.txt",
    "roni": "https://www.cpc.ncep.noaa.gov/data/indices/RONI.ascii.txt",
    "weekly": "https://www.cpc.ncep.noaa.gov/data/indices/wksst9120.for",
    "ersst_nino": "https://www.cpc.ncep.noaa.gov/data/indices/ersst5.nino.mth.91-20.ascii",
    "era5_daily": "https://sites.ecmwf.int/data/climatepulse/data/series/era5_daily_series_2t_global.csv",
    "ersst_dap": "https://psl.noaa.gov/thredds/dodsC/Datasets/noaa.ersst.v5/sst.mnmean.nc",
    "gpcp_dap": "https://psl.noaa.gov/thredds/dodsC/Datasets/gpcp/precip.mon.mean.nc",
    "ghcn_dap": "https://psl.noaa.gov/thredds/dodsC/Datasets/ghcncams/air.mon.mean.nc",
    "ersst_file": "https://downloads.psl.noaa.gov/Datasets/noaa.ersst.v5/sst.mnmean.nc",
    "gpcp_file": "https://downloads.psl.noaa.gov/Datasets/gpcp/precip.mon.mean.nc",
    "ghcn_file": "https://downloads.psl.noaa.gov/Datasets/ghcncams/air.mon.mean.nc",
}

GPCC_DAP = {  # GPCC Full Data (to 2020) + Monitoring (recent months), 1 deg, mm/month
    "full": ["https://psl.noaa.gov/thredds/dodsC/Datasets/gpcc/full_v2022/precip.mon.total.1x1.v2022.nc",
             "https://psl.noaa.gov/thredds/dodsC/Datasets/gpcc/full_v2020/precip.mon.total.1x1.v2020.nc"],
    "monitor": ["https://psl.noaa.gov/thredds/dodsC/Datasets/gpcc/monitor/precip.monitor.mon.total.1x1.v2022.nc",
                "https://psl.noaa.gov/thredds/dodsC/Datasets/gpcc/monitor/precip.monitor.mon.total.1x1.v2020.nc"],
}
DRY_MM = 30.0                        # seasonal (3-month) rainfall below which a season is "dry": not assessed
STRONG_THR = 1.5                     # strong El Nino: NDJ ONI >= 1.5 C
BASE0, BASE1 = 1991, 2020            # WMO climatological reference period
PI_OFFSET_DEFAULT = 0.88             # C3S: 1991-2020 is 0.88 C above 1850-1900
AFRICA_BOX = (-37.0, 39.0, -20.0, 53.0)   # lat0, lat1, lon0, lon1
FDR_Q = 0.10                         # Wilks (2016): alpha_FDR = 2 x alpha_global
SEAS = ["DJF", "JFM", "FMA", "MAM", "AMJ", "MJJ", "JJA", "JAS", "ASO", "SON", "OND", "NDJ"]

# C3S systems tried in order (the most recent first). Edit if C3S upgrades.
C3S_SYSTEMS = {
    "ecmwf": ["51"], "meteo_france": ["9", "8"], "ukmo": ["606", "605", "604", "603", "602"],
    "dwd": ["22", "21"], "cmcc": ["35", "4"], "ncep": ["2"], "jma": ["4", "3", "2"],
    "eccc": ["5", "4"],
}

STATUS = []
warnings.filterwarnings("ignore", category=RuntimeWarning)
warnings.filterwarnings("ignore", category=DeprecationWarning)
ARGS = None


def log(msg):
    print(time.strftime("%H:%M:%S"), msg, flush=True)


def status(key, ok, msg=""):
    STATUS.append({"key": key, "ok": bool(ok), "msg": str(msg)[:300],
                   "time": dt.datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC")})
    log(("OK   " if ok else "FAIL ") + key + (" - " + str(msg)[:200] if msg else ""))


# --------------------------------------------------------------------------
# Download helpers
# --------------------------------------------------------------------------
def http_get(url, name, max_age_h=12, binary=False, timeout=120):
    os.makedirs(CACHE, exist_ok=True)
    path = os.path.join(CACHE, name)
    fresh = os.path.exists(path) and (time.time() - os.path.getmtime(path)) < max_age_h * 3600
    if os.path.exists(path) and (fresh or ARGS.offline) and not ARGS.refresh:
        return path
    if ARGS.offline:
        raise RuntimeError("offline mode and no cached file " + name)
    last = None
    for attempt in range(3):
        try:
            r = requests.get(url, timeout=timeout, stream=True,
                             headers={"User-Agent": "AfriENSO/1.0 (research dashboard)"})
            r.raise_for_status()
            tmp = path + ".part"
            with open(tmp, "wb") as f:
                for chunk in r.iter_content(1 << 20):
                    f.write(chunk)
            os.replace(tmp, path)
            return path
        except Exception as e:  # noqa
            last = e
            time.sleep(3 * (attempt + 1))
    if os.path.exists(path):
        log("  download failed, using older cached copy of " + name)
        return path
    raise RuntimeError("download failed: %s (%s)" % (url, last))


def read_text(path):
    with open(path, "r", encoding="utf-8", errors="replace") as f:
        return f.read()


def r2(x, nd=2):
    if x is None:
        return None
    try:
        xf = float(x)
    except Exception:
        return None
    if not np.isfinite(xf):
        return None
    return round(xf, nd)


def series_out(s, nd=2):
    """Monthly pandas Series (PeriodIndex or DatetimeIndex) -> {start, v}."""
    s = s.copy()
    if not isinstance(s.index, pd.PeriodIndex):
        s.index = pd.PeriodIndex(s.index, freq="M")
    full = pd.period_range(s.index.min(), s.index.max(), freq="M")
    s = s.reindex(full)
    return {"start": str(full[0]), "v": [r2(v, nd) for v in s.values]}


# --------------------------------------------------------------------------
# 1. ENSO indices (NOAA CPC)
# --------------------------------------------------------------------------
def parse_oni(text):
    rows = []
    for line in text.splitlines():
        m = re.match(r"^\s*([A-Z]{3})\s+(\d{4})\s+(.*)$", line)
        if not m or m.group(1) not in SEAS:
            continue
        nums = re.findall(r"-?\d+\.\d+", m.group(3))
        if not nums:
            continue
        val = float(nums[-1])
        if val < -90:
            continue
        rows.append((int(m.group(2)), SEAS.index(m.group(1)) + 1, val))
    idx = pd.PeriodIndex([pd.Period(year=y, month=mo, freq="M") for y, mo, _ in rows], freq="M")
    return pd.Series([v for _, _, v in rows], index=idx).sort_index()


def parse_weekly(text):
    recs = []
    for line in text.splitlines():
        m = re.match(r"^\s*(\d{2}[A-Z]{3}\d{4})(.*)$", line)
        if not m:
            continue
        nums = re.findall(r"-?\d+\.\d", m.group(2))
        if len(nums) < 8:
            continue
        d = dt.datetime.strptime(m.group(1).title(), "%d%b%Y").date()
        v = [float(x) for x in nums[:8]]
        recs.append((d, v[1], v[3], v[5], v[7], v[5 - 1]))
    df = pd.DataFrame(recs, columns=["date", "n12", "n3", "n34", "n4", "sst34"])
    return df


def parse_ersst_nino(text):
    recs = []
    for line in text.splitlines():
        p = line.split()
        if len(p) < 10 or not p[0].isdigit():
            continue
        try:
            y, mo = int(p[0]), int(p[1])
            v = [float(x) for x in p[2:10]]
        except ValueError:
            continue
        recs.append((pd.Period(year=y, month=mo, freq="M"), v[1], v[3], v[5], v[7]))
    df = pd.DataFrame(recs, columns=["per", "n12", "n3", "n4", "n34"]).set_index("per")
    df.index = pd.PeriodIndex(df.index, freq="M")
    return df


def enso_episodes(oni, thr=0.5, nmin=5):
    """CPC definition: >= 5 consecutive overlapping seasons above +0.5 / below -0.5."""
    eps = []
    vals = oni.values
    idx = oni.index
    for sign, kind in ((1, "EN"), (-1, "LN")):
        run = []
        for i, v in enumerate(vals):
            if np.isfinite(v) and sign * v >= thr:
                run.append(i)
            else:
                if len(run) >= nmin:
                    eps.append((kind, run[:]))
                run = []
        if len(run) >= nmin:
            eps.append((kind, run[:], ))
    out = []
    for kind, run in eps:
        seg = vals[run]
        k = int(np.argmax(np.abs(seg)))
        peak = float(seg[k])
        a = abs(peak)
        strength = "weak" if a < 1.0 else "moderate" if a < 1.5 else "strong" if a < 2.0 else "very strong"
        ongoing = run[-1] == len(vals) - 1
        out.append({"type": kind, "start": str(idx[run[0]]), "end": str(idx[run[-1]]),
                    "peak": round(peak, 2), "peak_at": str(idx[run[k]]), "months": len(run),
                    "strength": strength, "ongoing": bool(ongoing)})
    out.sort(key=lambda e: e["start"])
    return out


def phase_series(oni, episodes):
    """Monthly (season-centre) phase: 1 El Nino, -1 La Nina, 0 neutral."""
    ph = pd.Series(0, index=oni.index)
    for e in episodes:
        sl = (ph.index >= pd.Period(e["start"], "M")) & (ph.index <= pd.Period(e["end"], "M"))
        ph[sl] = 1 if e["type"] == "EN" else -1
    return ph


def block_enso():
    out = {}
    oni = parse_oni(read_text(http_get(URL["oni"], "oni.ascii.txt")))
    if len(oni) < 100:
        raise RuntimeError("ONI parse failed")
    eps = enso_episodes(oni)
    out["oni"] = series_out(oni)
    out["episodes"] = eps
    out["phase"] = {"start": str(oni.index[0]), "v": phase_series(oni, eps).astype(int).tolist()}
    status("CPC ONI", True, "%d seasons, last %s = %+.2f" % (len(oni), oni.index[-1], oni.iloc[-1]))
    try:
        roni = parse_oni(read_text(http_get(URL["roni"], "RONI.ascii.txt")))
        out["roni"] = series_out(roni)
        status("CPC RONI", True, "last %s = %+.2f" % (roni.index[-1], roni.iloc[-1]))
    except Exception as e:
        status("CPC RONI", False, e)
    try:
        wk = parse_weekly(read_text(http_get(URL["weekly"], "wksst9120.for")))
        out["weekly"] = {"dates": [d.isoformat() for d in wk["date"]],
                         "n12": wk["n12"].round(2).tolist(), "n3": wk["n3"].round(2).tolist(),
                         "n34": wk["n34"].round(2).tolist(), "n4": wk["n4"].round(2).tolist()}
        status("CPC weekly OISST Nino", True, "last week %s, Nino3.4 %+.1f" % (wk["date"].iloc[-1], wk["n34"].iloc[-1]))
    except Exception as e:
        status("CPC weekly OISST Nino", False, e)
    mon = None
    try:
        mon = parse_ersst_nino(read_text(http_get(URL["ersst_nino"], "ersst5.nino.mth.91-20.ascii")))
        out["monthly"] = {k: series_out(mon[k]) for k in ["n12", "n3", "n34", "n4"]}
        status("CPC monthly ERSSTv5 Nino", True, "last %s" % mon.index[-1])
    except Exception as e:
        status("CPC monthly ERSSTv5 Nino", False, e)
    return out, oni, eps, mon


# --------------------------------------------------------------------------
# 2. Gridded data (NOAA PSL, OPeNDAP with file fallback)
# --------------------------------------------------------------------------
def _runs(idx):
    idx = np.asarray(idx)
    if idx.size == 0:
        return []
    cuts = np.where(np.diff(idx) != 1)[0] + 1
    return [(int(r[0]), int(r[-1]) + 1) for r in np.split(idx, cuts)]


def subset(da, lat0, lat1, lon0, lon1, t0=None):
    """Box subset that works across the Greenwich meridian with 0-360 grids."""
    import xarray as xr
    latn = [n for n in da.dims if n.lower().startswith("lat")][0]
    lonn = [n for n in da.dims if n.lower().startswith("lon")][0]
    if t0 is not None:
        da = da.sel(time=slice(t0, None))
    lat = da[latn].values
    lon = da[lonn].values
    lon180 = ((lon + 180.0) % 360.0) - 180.0
    ilat = np.where((lat >= lat0) & (lat <= lat1))[0]
    ilon = np.where((lon180 >= lon0) & (lon180 <= lon1))[0]
    la = _runs(ilat)
    parts = []
    nt = da.sizes.get("time", 1)
    for a, b in _runs(ilon):
        sub = da.isel({latn: slice(la[0][0], la[-1][1]), lonn: slice(a, b)})
        if "time" in da.dims and nt > 120:  # chunked requests: friendlier to OPeNDAP servers
            chunks = []
            for t0_ in range(0, nt, 120):
                print("    months %d-%d of %d" % (t0_ + 1, min(nt, t0_ + 120), nt), end="\r", flush=True)
                for attempt in range(3):
                    try:
                        chunks.append(sub.isel(time=slice(t0_, t0_ + 120)).load())
                        break
                    except Exception:
                        if attempt == 2:
                            raise
                        time.sleep(5)
            print(" " * 70, end="\r", flush=True)
            blk = xr.concat(chunks, dim="time")
        else:
            blk = sub.load()
        parts.append(blk)
    out = xr.concat(parts, dim=lonn) if len(parts) > 1 else parts[0]
    out = out.assign_coords({lonn: (((out[lonn] + 180.0) % 360.0) - 180.0)})
    out = out.sortby(lonn).sortby(latn)
    return out.rename({latn: "lat", lonn: "lon"})


def open_ds(src):
    """Open a NetCDF/OPeNDAP dataset and decode time by hand: some PSL files use
    units such as 'days since 1800-01-01 00:00:00 0:00' that pandas cannot parse."""
    import xarray as xr
    ds = xr.open_dataset(src, decode_times=False)
    if "time" in ds.variables:
        t = ds["time"]
        units = str(t.attrs.get("units", ""))
        m = re.match(r"\s*(\w+)\s+since\s+(\d{1,4})-(\d{1,2})-(\d{1,2})", units)
        if not m:
            raise RuntimeError("unknown time units: " + units)
        step = {"days": "D", "day": "D", "hours": "h", "hour": "h", "minutes": "min", "seconds": "s"}[m.group(1).lower()]
        base = pd.Timestamp(int(m.group(2)), int(m.group(3)), int(m.group(4)))
        times = base + pd.to_timedelta(np.asarray(t.values, dtype=float), unit=step)
        ds = ds.assign_coords(time=("time", pd.DatetimeIndex(times).values))
    return ds


def open_psl(kind, var):
    """Try OPeNDAP first, then a full-file download (cached)."""
    import xarray as xr
    errs = []
    if not ARGS.offline:
        for attempt in range(2):
            try:
                log("  %s: connecting to NOAA PSL (OPeNDAP)..." % kind)
                ds = open_ds(URL[kind + "_dap"])
                return ds[var], "OPeNDAP"
            except Exception as e:
                errs.append(str(e))
                time.sleep(5)
    try:
        log("  %s: OPeNDAP unavailable, downloading the full file (can take 10-30 min)..." % kind)
        p = http_get(URL[kind + "_file"], kind + "_" + os.path.basename(URL[kind + "_file"]),
                     max_age_h=24 * 7, binary=True, timeout=1800)
        ds = open_ds(p)
        return ds[var], "file"
    except Exception as e:
        errs.append(str(e))
    raise RuntimeError(" | ".join(errs))


def monthly_anom(s):
    """Series with PeriodIndex -> anomaly vs 1991-2020 monthly climatology."""
    base = s[(s.index.year >= BASE0) & (s.index.year <= BASE1)]
    clim = base.groupby(base.index.month).mean()
    return s - clim.reindex(s.index.month).values


def valid(x, lo, hi):
    """Mask fill values and non-physical numbers (e.g. 9.97e36 missing-value codes)."""
    a = np.asarray(x, dtype=float)
    return np.where(np.isfinite(a) & (a >= lo) & (a <= hi), a, np.nan)


def box_mean(da):
    w = np.cos(np.deg2rad(da["lat"]))
    return da.weighted(w.fillna(0)).mean(("lat", "lon"), skipna=True)


def to_period_series(da):
    t = pd.to_datetime(da["time"].values)
    return pd.Series(np.asarray(da.values, dtype=float), index=pd.PeriodIndex(t, freq="M"))


def block_sst_indices():
    sst, how = open_psl("ersst", "sst")
    boxes = {
        "wtio": (-10, 10, 50, 70), "setio": (-10, 0, 90, 110),
        "tna": (5.5, 23.5, -57.5, -15), "atl3": (-3, 3, -20, 0), "n34e": (-5, 5, -170, -120),
        # added October 2026 (co-authors' review): Senegal-Mauritania coast and Mediterranean
        "senc": (10, 20, -24, -16), "med": (32, 44, 0, 30),
    }
    ser = {}
    for k, (a, b, c, d) in boxes.items():
        log("  ERSSTv5: box %s" % k)
        bx = subset(sst, a, b, c, d, t0="1948-01-01")
        bx = bx.copy(data=valid(bx.values, -5, 40))
        ser[k] = to_period_series(box_mean(bx))
    dmi = monthly_anom(ser["wtio"]) - monthly_anom(ser["setio"])
    idx = {"dmi": dmi, "tna": monthly_anom(ser["tna"]), "atl3": monthly_anom(ser["atl3"]),
           "n34e": monthly_anom(ser["n34e"]),
           "senc": monthly_anom(ser["senc"]), "med": monthly_anom(ser["med"])}
    idx["amg"] = idx["tna"] - idx["atl3"]  # Atlantic meridional gradient (TNA - ATL3)
    # latest SST anomaly map, tropics 30S-30N (2 deg), last 3 months
    log("  ERSSTv5: tropical SST map")
    trop = subset(sst, -30, 30, -180, 180, t0="1991-01-01")
    tt = pd.PeriodIndex(pd.to_datetime(trop["time"].values), freq="M")
    arr = valid(trop.values, -5, 40)
    base = (tt.year >= BASE0) & (tt.year <= BASE1)
    maps = []
    for k in range(3):
        i = len(tt) - 1 - k
        clim = np.nanmean(arr[base & (tt.month == tt[i].month)], axis=0)
        an = arr[i] - clim
        maps.append({"month": str(tt[i]), "z": [[r2(v, 2) for v in row] for row in an]})
    sstmap = {"lat": [float(x) for x in trop["lat"].values], "lon": [float(x) for x in trop["lon"].values],
              "maps": maps[::-1]}
    status("PSL ERSSTv5 gridded (%s)" % how, True, "DMI/TNA/ATL3 to %s" % dmi.dropna().index[-1])
    return idx, sstmap


def land_fraction(lat, lon, polys, dlat, dlon, nsub=6):
    """Fraction of each grid cell inside a set of polygons (list of [ext, holes...])."""
    from matplotlib.path import Path
    LA, LO = np.meshgrid(lat, lon, indexing="ij")
    off = (np.arange(nsub) + 0.5) / nsub - 0.5
    oy, ox = np.meshgrid(off * dlat, off * dlon, indexing="ij")
    pts = np.stack([(LO[..., None, None] + ox).ravel(), (LA[..., None, None] + oy).ravel()], axis=1)
    inside = np.zeros(len(pts), dtype=bool)
    for poly in polys:
        ext = np.asarray(poly[0])
        bb = (pts[:, 0] >= ext[:, 0].min()) & (pts[:, 0] <= ext[:, 0].max()) & \
             (pts[:, 1] >= ext[:, 1].min()) & (pts[:, 1] <= ext[:, 1].max())
        if not bb.any():
            continue
        cand = np.where(bb)[0]
        ins = Path(ext).contains_points(pts[cand])
        for hole in poly[1:]:
            ins &= ~Path(np.asarray(hole)).contains_points(pts[cand])
        inside[cand[ins]] = True
    return inside.reshape(len(lat), len(lon), nsub * nsub).mean(axis=2)


def unit_weights(lat, lon, polys, dlat, dlon):
    f = land_fraction(lat, lon, polys, dlat, dlon)
    w = f * np.cos(np.deg2rad(lat))[:, None]
    if w.sum() <= 0:  # very small island: nearest cell to the polygon centroid
        ext = np.asarray(polys[0][0])
        cy, cx = ext[:, 1].mean(), ext[:, 0].mean()
        i = int(np.argmin(np.abs(lat - cy)))
        j = int(np.argmin(np.abs(lon - cx)))
        w = np.zeros_like(w)
        w[i, j] = 1.0
        return w, True
    return w, False


def weighted_series(arr, w):
    """arr (T, ny, nx) with NaN; w (ny, nx) -> (T,) weighted mean over valid cells."""
    m = np.isfinite(arr) & (w[None] > 0)
    num = np.where(m, arr, 0.0) * w[None]
    den = (m * w[None]).sum(axis=(1, 2))
    with np.errstate(invalid="ignore", divide="ignore"):
        out = num.sum(axis=(1, 2)) / den
    # require at least 50 % of the unit weight to be valid
    cover = den / w.sum()
    out[cover < 0.5] = np.nan
    return out


def seasonal_stack(arr, per, how):
    """Monthly (T,...) -> dict centre_month -> (years, (Y,...)) of 3-month sums/means."""
    s = {}
    ym = per.year * 12 + per.month - 1
    pos = {v: i for i, v in enumerate(ym)}
    for c in range(1, 13):
        years, vals = [], []
        for y in range(per.year.min(), per.year.max() + 1):
            k = y * 12 + c - 1
            ii = [pos.get(k - 1), pos.get(k), pos.get(k + 1)]
            if any(i is None for i in ii):
                continue
            blk = arr[ii]
            v = blk.sum(axis=0) if how == "sum" else blk.mean(axis=0)
            if np.ndim(v) == 0 and not np.isfinite(v):
                continue
            years.append(y)
            vals.append(v)
        if years:
            s[c] = (np.array(years), np.array(vals))
    return s


def detrend(y, x):
    ok = np.isfinite(y)
    if ok.sum() < 3:
        return y * np.nan
    p = np.polyfit(x[ok], y[ok], 1)
    return y - np.polyval(p, x)


def detrend_field(Y, x):
    """Y (n, ny, nx) -> residuals from a per-cell linear trend (NaN-safe)."""
    n = Y.shape[0]
    X = np.vstack([np.ones(n), x - x.mean()]).T
    flat = Y.reshape(n, -1)
    out = np.full_like(flat, np.nan)
    ok_cols = np.isfinite(flat).all(axis=0)
    if ok_cols.any():
        beta, *_ = np.linalg.lstsq(X, flat[:, ok_cols], rcond=None)
        out[:, ok_cols] = flat[:, ok_cols] - X @ beta
    return out.reshape(Y.shape)


def corr_field(x, Y):
    """x (n,), Y (n, ny, nx) both detrended -> r, p."""
    from scipy import stats
    n = len(x)
    xa = x - x.mean()
    Ya = Y - Y.mean(axis=0)
    with np.errstate(invalid="ignore", divide="ignore"):
        r = (xa[:, None, None] * Ya).sum(axis=0) / np.sqrt((xa ** 2).sum() * (Ya ** 2).sum(axis=0))
        t = r * np.sqrt((n - 2) / (1 - r ** 2))
    p = 2 * stats.t.sf(np.abs(t), n - 2)
    return r, p


def fdr_mask(p, q=FDR_Q):
    """Benjamini-Hochberg false discovery rate (Wilks 2016)."""
    flat = p[np.isfinite(p)]
    m = np.zeros(p.shape, dtype=bool)
    if flat.size == 0:
        return m
    ps = np.sort(flat)
    k = np.arange(1, ps.size + 1)
    below = ps <= q * k / ps.size
    if not below.any():
        return m
    pthr = ps[np.where(below)[0].max()]
    return np.isfinite(p) & (p <= pthr)


def enc_map(z, scale, landmask):
    out = []
    for row, lrow in zip(z, landmask):
        out.append([None if (not l or not np.isfinite(v)) else int(round(v * scale)) for v, l in zip(row, lrow)])
    return out


def enc_mask(m, landmask):
    return "".join("1" if (a and l) else "0" for a, l in zip(m.ravel(), landmask.ravel()))


def driver_seasonal(driver_monthly, c):
    """3-month mean centred on month c for each year -> dict year->value."""
    s = driver_monthly
    out = {}
    for per in s.index:
        if per.month != c:
            continue
        a, b = per - 1, per + 1
        if a in s.index and b in s.index:
            v = [s[a], s[per], s[b]]
            if all(np.isfinite(v)):
                out[per.year] = float(np.mean(v))
    return out


def strong_events(oni, thr=STRONG_THR):
    """Strong El Nino events: NDJ ONI >= thr (labelled by the developing year)."""
    ev = []
    for p, v in oni.items():
        if p.month == 12 and np.isfinite(v) and v >= thr:
            ev.append({"year": int(p.year), "label": "%d-%s" % (p.year, str(p.year + 1)[2:]), "ndj": round(float(v), 2)})
    return ev


def load_gpcc(lat0, lat1, lon0, lon1):
    import xarray as xr
    parts = {}
    for kind in ("full", "monitor"):
        srcs = list(GPCC_DAP[kind])
        local = os.path.join(CACHE, "gpcc_%s.nc" % kind)
        if os.path.exists(local):
            srcs.insert(0, local)
        if ARGS.offline:
            srcs = [x for x in srcs if os.path.exists(x)]
        for src in srcs:
            try:
                log("  GPCC %s: %s" % (kind, os.path.basename(src)))
                da = subset(open_ds(src)["precip"], lat0, lat1, lon0, lon1, t0="1951-01-01")
                da = da.copy(data=valid(da.values, 0, 3000))
                parts[kind] = da
                break
            except Exception as e:  # noqa
                log("    not available (%s)" % str(e)[:100])
    if "full" not in parts:
        raise RuntimeError("GPCC Full Data not reachable")
    da = parts["full"]
    if "monitor" in parts:
        mon = parts["monitor"]
        mon = mon.sel(time=mon["time"] > da["time"].values[-1])
        if mon.sizes["time"]:
            da = xr.concat([da, mon.interp(lat=da["lat"], lon=da["lon"], method="nearest")], dim="time")
    return da.coarsen(lat=2, lon=2, boundary="trim").mean(skipna=True)


def strong_maps(arr, per, land, events, phase_m, is_pr):
    """Per season: mean anomaly of strong El Nino seasons relative to ENSO-neutral seasons
    (detrended), as % of the 1991-2020 normal (rainfall) or C (temperature), and the number
    of events below the neutral baseline."""
    stack = seasonal_stack(arr, per, "sum" if is_pr else "mean")
    out = []
    for c in range(1, 13):
        if c not in stack:
            out.append(None)
            continue
        years, Y = stack[c]
        resid = detrend_field(Y, years.astype(float))
        phs = {p.year: int(v) for p, v in phase_m.items() if p.month == c}
        neu = np.array([phs.get(int(y)) == 0 for y in years])
        if neu.sum() < 5:
            out.append(None)
            continue
        base = np.nanmean(resid[neu], axis=0)
        bsel = (years >= BASE0) & (years <= BASE1)
        clim = np.nanmean(Y[bsel] if bsel.sum() >= 10 else Y, axis=0)
        an, used = [], []
        for e in events:
            ty = e["year"] if c >= 6 else e["year"] + 1
            k = np.where(years == ty)[0]
            if len(k):
                an.append(resid[k[0]] - base)
                used.append(e["label"])
        if len(an) < 3:
            out.append(None)
            continue
        A = np.array(an)
        if is_pr:
            with np.errstate(invalid="ignore", divide="ignore"):
                P = np.where(clim[None] >= DRY_MM, 100.0 * (clim[None] + A) / clim[None], np.nan)
            mean, scale = np.nanmean(P, axis=0), 1
        else:
            mean, scale = np.nanmean(A, axis=0), 100
        if is_pr:
            A = np.where(clim[None] >= DRY_MM, A, np.nan)
        nneg = np.sum(A < 0, axis=0)
        nval = np.sum(np.isfinite(A), axis=0)
        code = "".join(str(int(min(9, a))) if (l and v > 0) else "." for a, v, l in zip(nneg.ravel(), nval.ravel(), land.ravel()))
        out.append({"events": used, "mean": enc_map(mean, scale, land), "nneg": code})
    return out


def _box_ring(lat0, lat1, lon0, lon1):
    return [[lon0, lat0], [lon1, lat0], [lon1, lat1], [lon0, lat1], [lon0, lat0]]


# West African land boxes (restricted to African land like the AR6 regions); SHL = WSHL + CSHL
WA_BOXES = [
    {"code": "GC", "en": "Guinea Coast", "fr": "Côte guinéenne", "ring": _box_ring(4, 8, -15, 10)},
    {"code": "WSHL", "en": "Western Sahel", "fr": "Sahel occidental", "ring": _box_ring(11, 18, -18, -5)},
    {"code": "CSHL", "en": "Central Sahel", "fr": "Sahel central", "ring": _box_ring(11, 18, -5, 15)},
    {"code": "SHL", "en": "Sahel", "fr": "Sahel", "ring": _box_ring(11, 18, -18, 15)},
]


def block_africa(geo, oni, phase_m, sst_idx):
    """Teleconnection maps + unit (country/AR6/Africa) monthly series."""
    import xarray as xr  # noqa
    lat0, lat1, lon0, lon1 = AFRICA_BOX
    res = {"units": {}, "maps": {}}
    all_polys = [p for c in geo["countries"] for p in c["mask"]]
    units = [("AFR", "Africa (land)", "Afrique (terres)", all_polys, "africa")]
    units += [(r["code"], r["en"], r["fr"], [[r["ring"]]], "ar6") for r in geo["ar6"]]
    units += [(c["iso"], c["en"], c["fr"], c["mask"], "country") for c in geo["countries"]]
    # West African land boxes of the associated paper (Guinea Coast, western and central Sahel, Sahel)
    units += [(b["code"], b["en"], b["fr"], [[b["ring"]]], "wa") for b in WA_BOXES]
    drivers = {"nino34": oni}
    for k in ("dmi", "tna", "atl3"):
        if sst_idx is not None and k in sst_idx:
            drivers[k] = sst_idx[k].dropna()

    grids = {}
    # ---- precipitation: GPCP v2.3 (2.5 deg, mm/day) -> mm/month
    try:
        pr, how = open_psl("gpcp", "precip")
        pr = subset(pr, lat0, lat1, lon0, lon1, t0="1979-01-01")
        per = pd.PeriodIndex(pd.to_datetime(pr["time"].values), freq="M")
        arr = valid(pr.values, 0, 200) * per.days_in_month.values[:, None, None]  # mm/day -> mm/month
        grids["pr"] = (pr["lat"].values, pr["lon"].values, arr, per, 2.5)
        status("PSL GPCP v2.3 (%s)" % how, True, "%s to %s" % (per[0], per[-1]))
    except Exception as e:
        status("PSL GPCP v2.3", False, e)
    # ---- temperature: GHCN_CAMS (0.5 deg) -> 1.5 deg blocks
    try:
        ta, how = open_psl("ghcn", "air")
        ta = subset(ta, lat0, lat1, lon0, lon1, t0="1948-01-01")
        ta = ta.copy(data=valid(ta.values, 150, 350) if float(np.nanmedian(valid(ta.values, -90, 400))) > 150 else valid(ta.values, -80, 70))
        if float(ta.mean(skipna=True)) > 150:
            ta = ta - 273.15
        ta = ta.coarsen(lat=3, lon=3, boundary="trim").mean(skipna=True)
        per = pd.PeriodIndex(pd.to_datetime(ta["time"].values), freq="M")
        grids["tas"] = (ta["lat"].values, ta["lon"].values, np.asarray(ta.values, dtype=float), per, 1.5)
        status("PSL GHCN_CAMS (%s)" % how, True, "%s to %s" % (per[0], per[-1]))
    except Exception as e:
        status("PSL GHCN_CAMS", False, e)
    # ---- long rainfall record for strong El Nino analogs: GPCC (1 deg -> 2 deg), from 1951
    try:
        gp = load_gpcc(lat0, lat1, lon0, lon1)
        per = pd.PeriodIndex(pd.to_datetime(gp["time"].values), freq="M")
        arr = valid(gp.values, 0, 3000)  # mm/month
        grids["prl"] = (gp["lat"].values, gp["lon"].values, arr, per, 2.0)
        status("PSL GPCC (Full + Monitoring)", True, "%s to %s" % (per[0], per[-1]))
    except Exception as e:
        status("PSL GPCC (Full + Monitoring)", False, str(e) + " - strong El Nino rainfall analogs use GPCP (from 1979)")
    events = strong_events(oni)
    res["strong_events"] = events

    for var, (lat, lon, arr, per, dres) in grids.items():
        log("  %s: land fractions and unit weights" % var)
        land = land_fraction(lat, lon, all_polys, dres, dres) >= 0.25
        raw = arr
        arr = np.where(land[None], arr, np.nan)
        # unit series (fraction-weighted on the unmasked grid)
        landfrac = land_fraction(lat, lon, all_polys, dres, dres)
        for code, en, fr, polys, kind in units:
            w, nearest = unit_weights(lat, lon, polys, dres, dres)
            if kind in ("ar6", "wa") and not nearest:
                w = w * landfrac  # AR6 land regions restricted to African land
            s = weighted_series(raw, w)
            u = res["units"].setdefault(code, {"en": en, "fr": fr, "kind": kind})
            nd = 1 if var.startswith("pr") else 2
            u[var] = {"start": str(per[0]), "v": [r2(v, nd) for v in s]}
            if nearest:
                u[var + "_nearest"] = True
        mp = {"lat": [float(x) for x in lat], "lon": [float(x) for x in lon], "res": dres,
              "land": "".join("1" if v else "0" for v in land.ravel()), "corr": {}, "comp": {}}
        do_strong = var in ("tas", "prl") or (var == "pr" and "prl" not in grids)
        if do_strong and events:
            log("  %s: strong El Nino analog maps" % var)
            mp["strong"] = strong_maps(arr, per, land, events, phase_m, var.startswith("pr"))
        if var == "prl":
            res["maps"][var] = mp
            continue
        # maps
        log("  %s: correlation and composite maps" % var)
        how = "sum" if var == "pr" else "mean"
        stack = seasonal_stack(arr, per, how)
        for dname, dser in drivers.items():
            mp["corr"][dname] = []
            for c in range(1, 13):
                if c not in stack:
                    mp["corr"][dname].append(None)
                    continue
                years, Y = stack[c]
                if dname == "nino34":
                    dv = {p.year: float(v) for p, v in dser.items() if p.month == c}
                else:
                    dv = driver_seasonal(dser, c)
                keep = np.array([y in dv for y in years])
                yy = years[keep]
                if len(yy) < 15:
                    mp["corr"][dname].append(None)
                    continue
                x = detrend(np.array([dv[y] for y in yy]), yy.astype(float))
                Yd = detrend_field(Y[keep], yy.astype(float))
                r, p = corr_field(x, Yd)
                if var == "pr":  # dry season: correlation of a few mm is not meaningful
                    wet = np.nanmean(Y[keep], axis=0) >= DRY_MM
                    r = np.where(wet, r, np.nan)
                    p = np.where(wet, p, np.nan)
                r = np.where(land, r, np.nan)
                p = np.where(land, p, np.nan)
                mp["corr"][dname].append({"n": int(len(yy)), "y0": int(yy.min()), "y1": int(yy.max()),
                                          "r": enc_map(r, 100, land), "sig": enc_mask(fdr_mask(p), land)})
        # ENSO composites (El Nino / La Nina seasons, CPC episodes), detrended
        from scipy import stats
        for ph, lab in ((1, "EN"), (-1, "LN")):
            mp["comp"][lab] = []
            for c in range(1, 13):
                if c not in stack:
                    mp["comp"][lab].append(None)
                    continue
                years, Y = stack[c]
                phs = {p.year: int(v) for p, v in phase_m.items() if p.month == c}
                keep = np.array([y in phs for y in years])
                yy, Yk = years[keep], Y[keep]
                sel = np.array([phs[y] == ph for y in yy])
                if sel.sum() < 3:
                    mp["comp"][lab].append(None)
                    continue
                Yd = detrend_field(Yk, yy.astype(float))
                clim = np.nanmean(Yk, axis=0)
                comp = np.nanmean(Yd[sel], axis=0)
                # manual one-sample t-test (scipy nan_policy="omit" returns masked arrays)
                xs = Yd[sel]
                nn = np.sum(np.isfinite(xs), axis=0).astype(float)
                with np.errstate(invalid="ignore", divide="ignore"):
                    sd = np.nanstd(xs, axis=0, ddof=1)
                    tt = comp / (sd / np.sqrt(nn))
                    p = 2.0 * stats.t.sf(np.abs(tt), np.maximum(nn - 1, 1))
                p = np.where(land & (nn >= 3) & np.isfinite(tt), p, np.nan)
                if var == "pr":
                    with np.errstate(invalid="ignore", divide="ignore"):
                        z = np.where(clim >= DRY_MM, 100.0 * comp / clim, np.nan)  # % of normal; dry-season cells masked
                    scale = 1
                else:
                    z = comp
                    scale = 100
                mp["comp"][lab].append({"n": int(sel.sum()), "years": [int(y) for y in yy[sel]],
                                        "z": enc_map(z, scale, land), "sig": enc_mask(fdr_mask(p), land)})
        res["maps"][var] = mp
    return res


# --------------------------------------------------------------------------
# 3. Global temperature: ERA5 daily (Copernicus Climate Pulse)
# --------------------------------------------------------------------------
def parse_era5_daily(path):
    df = pd.read_csv(path, comment="#")
    df.columns = [c.strip().lower() for c in df.columns]
    dcol = [c for c in df.columns if "date" in c][0]
    df[dcol] = pd.to_datetime(df[dcol])
    ano = [c for c in df.columns if c.startswith("ano") and ("91" in c or "1991" in c)]
    pi = [c for c in df.columns if "pi" in c and c.startswith("ano")]
    tcol = [c for c in df.columns if c in ("2t", "t2m", "2m_temperature")]
    s_abs = df[tcol[0]].astype(float) if tcol else None
    if ano:
        s = df[ano[0]].astype(float)
    else:  # compute the 1991-2020 day-of-year climatology ourselves
        x = df.set_index(dcol)[tcol[0]].astype(float)
        doy = x.index.dayofyear.where(~((x.index.month == 2) & (x.index.day == 29)), 59)
        base = (x.index.year >= BASE0) & (x.index.year <= BASE1)
        clim = x[base].groupby(doy[base]).mean().rolling(31, center=True, min_periods=1).mean()
        s = pd.Series(x.values - clim.reindex(doy).values, index=x.index).reset_index(drop=True)
    offset = PI_OFFSET_DEFAULT
    if pi and ano:
        d = (df[pi[0]].astype(float) - df[ano[0]].astype(float)).dropna()
        if len(d) > 100:
            offset = float(d.median())
    out = pd.Series(s.values, index=pd.DatetimeIndex(df[dcol])).dropna()
    absval = pd.Series(s_abs.values, index=pd.DatetimeIndex(df[dcol])).dropna() if s_abs is not None else None
    return out, offset, absval


def ar1_phi(n34m):
    x = n34m.dropna().values
    return float(np.corrcoef(x[:-1], x[1:])[0, 1])


def fit_gmst(mon, n34m, lag, t_start="1995-01"):
    df = pd.DataFrame({"y": mon})
    df["n"] = n34m.reindex(df.index - lag).values if lag else n34m.reindex(df.index).values
    df = df[df.index >= pd.Period(t_start, "M")].dropna()
    t = df.index.year + (df.index.month - 0.5) / 12.0
    X = np.vstack([np.ones(len(df)), t - 2000.0, df["n"].values]).T
    beta, *_ = np.linalg.lstsq(X, df["y"].values, rcond=None)
    res = df["y"].values - X @ beta
    phi = float(np.corrcoef(res[:-1], res[1:])[0, 1])
    sig = float(np.std(res[1:] - phi * res[:-1], ddof=3))
    r2v = 1 - res.var() / df["y"].values.var()
    return beta, res, phi, sig, r2v, df.index


def project_year(mon, n34m, year, k_obs, lag, beta, phi, sig, e_last, n34_fc=None, nsim=4000, seed=1):
    """Monte Carlo projection of the annual mean given k_obs observed months."""
    rng = np.random.default_rng(seed)
    per = pd.period_range("%d-01" % year, "%d-12" % year, freq="M")
    days = per.days_in_month.values.astype(float)
    obs = mon.reindex(per[:k_obs]).values
    phi_n = ar1_phi(n34m)
    last_n = n34m.dropna()
    ln_per, ln_val = last_n.index[-1], float(last_n.iloc[-1])
    sd_n = float(last_n.std())
    sims = np.zeros(nsim)
    for s in range(nsim):
        e = e_last
        tot = np.nansum(obs * days[:k_obs])
        memb = None
        if n34_fc is not None and len(n34_fc["members"]):
            memb = n34_fc["members"][rng.integers(len(n34_fc["members"]))]
        for i in range(k_obs, 12):
            p = per[i]
            src = p - lag
            if src in n34m.index and np.isfinite(n34m[src]):
                nv = float(n34m[src])
            else:
                h = (src - ln_per).n
                nv = None
                if memb is not None:
                    key = str(src)
                    if key in n34_fc["months"]:
                        nv = float(memb[n34_fc["months"].index(key)])
                if nv is None:
                    nv = ln_val * phi_n ** h + rng.normal(0, sd_n * math.sqrt(max(1 - phi_n ** (2 * h), 0)))
            e = phi * e + rng.normal(0, sig)
            t = p.year + (p.month - 0.5) / 12.0
            tot += (beta[0] + beta[1] * (t - 2000.0) + beta[2] * nv + e) * days[i]
        sims[s] = tot / days.sum()
    return sims


def block_globaltemp(n34m, n34_fc):
    p = http_get(URL["era5_daily"], "era5_daily_series_2t_global.csv")
    d, offset, absval = parse_era5_daily(p)
    out = {"daily": {"start": d.index[0].strftime("%Y-%m-%d"), "v": [r2(v, 3) for v in d.values]},
           "pi_offset": round(offset, 3)}
    # monthly means (complete months only for fitting)
    mm = d.groupby(pd.PeriodIndex(d.index, freq="M")).agg(["mean", "count"])
    full = mm["count"] >= mm.index.days_in_month
    mon = mm["mean"][full]
    out["monthly"] = series_out(mm["mean"], 3)
    out["monthly_complete_to"] = str(mon.index[-1])
    # annual means (complete years)
    yr = d.groupby(d.index.year).agg(["mean", "count"])
    yfull = yr[yr["count"] >= 365]["mean"]
    out["annual"] = {"years": [int(y) for y in yfull.index], "v": [r2(v, 3) for v in yfull.values]}
    if n34m is None:
        status("ERA5 daily global (Climate Pulse)", True, "no Nino3.4 -> no projection")
        return out
    # choose lag 0..6 months maximising R2
    best = None
    for lag in range(0, 7):
        beta, res, phi, sig, r2v, idx = fit_gmst(mon, n34m, lag)
        if best is None or r2v > best[4]:
            best = (lag, beta, res, phi, sig, r2v, idx)
    lag, beta, res, phi, sig, r2v, idx = best
    adj = mon - beta[2] * n34m.reindex(mon.index - lag).values
    out["enso_fit"] = {"lag": lag, "trend_per_decade": round(beta[1] * 10, 3), "enso_coef": round(beta[2], 3),
                       "r2": round(r2v, 3), "phi": round(phi, 3), "sigma": round(sig, 3),
                       "period": "%s to %s" % (idx[0], idx[-1])}
    out["enso_adjusted"] = series_out(adj, 3)
    # projection of the current year
    last = mon.index[-1]
    year = last.year if last.month < 12 else last.year + 1
    k_obs = last.month if last.year == year else 0
    e_last = float(res[-1]) if k_obs else 0.0
    sims = project_year(mon, n34m, year, k_obs, lag, beta, phi, sig, e_last, n34_fc)
    prev = yfull[yfull.index < year]
    rec_y, rec_v = int(prev.idxmax()), float(prev.max())
    rank2 = float(prev.sort_values().iloc[-2]) if len(prev) > 1 else None
    hist, edges = np.histogram(sims, bins=40)
    # hindcast (out-of-sample, persistence Nino3.4, same number of observed months)
    errs, cover = [], []
    for y in range(2005, year):
        if y not in yfull.index or k_obs == 0:
            continue
        mon_y = mon[mon.index <= pd.Period("%d-%02d" % (y, k_obs), "M")]
        n34_y = n34m[n34m.index <= pd.Period("%d-%02d" % (y, k_obs), "M")]
        b, rs, ph, sg, _, _ = fit_gmst(mon_y, n34_y, lag)
        sm = project_year(mon_y, n34_y, y, k_obs, lag, b, ph, sg, float(rs[-1]), None, nsim=800, seed=y)
        errs.append(float(np.mean(sm) - yfull[y]))
        lo, hi = np.percentile(sm, [5, 95])
        cover.append(lo <= yfull[y] <= hi)
    out["projection"] = {
        "year": year, "months_observed": k_obs, "mean": r2(np.mean(sims), 3),
        "p05": r2(np.percentile(sims, 5), 3), "p95": r2(np.percentile(sims, 95), 3),
        "p_record": r2(float(np.mean(sims > rec_v)), 3), "record_year": rec_y, "record_value": r2(rec_v, 3),
        "p_top2": r2(float(np.mean(sims > rank2)), 3) if rank2 is not None else None,
        "hist": {"counts": hist.tolist(), "edges": [r2(v, 3) for v in edges]},
        "hindcast": {"n": len(errs), "rmse": r2(np.sqrt(np.mean(np.square(errs))), 3) if errs else None,
                     "bias": r2(np.mean(errs), 3) if errs else None,
                     "coverage90": r2(np.mean(cover), 2) if cover else None,
                     "years": "2005-%d" % (year - 1)},
        "n34_source": "C3S multi-system ensemble" if n34_fc else "damped persistence (AR1)",
    }
    status("ERA5 daily global (Climate Pulse)", True, "to %s, projection %d = %+.2f C (1991-2020)" % (
        d.index[-1].date(), year, np.mean(sims)))
    return out


# --------------------------------------------------------------------------
# 4. Copernicus C3S seasonal forecasts (optional)
# --------------------------------------------------------------------------
def c3s_retrieve(client, centre, systems, year, month, variable, area, target):
    last = None
    for sy in systems:
        try:
            client.retrieve("seasonal-postprocessed-single-levels", {
                "originating_centre": centre, "system": sy, "variable": [variable],
                "product_type": ["monthly_mean"], "year": [str(year)], "month": ["%02d" % month],
                "leadtime_month": ["1", "2", "3", "4", "5", "6"], "area": area, "data_format": "grib",
            }, target)
            return sy
        except Exception as e:  # noqa
            last = e
    raise RuntimeError(str(last)[:200])


def open_grib_members(path):
    import xarray as xr
    ds = xr.open_dataset(path, engine="cfgrib", backend_kwargs={"indexpath": ""})
    v = list(ds.data_vars)[0]
    da = ds[v]
    ren = {}
    for n in da.dims:
        if n.startswith("lat"):
            ren[n] = "lat"
        elif n.startswith("lon"):
            ren[n] = "lon"
        elif n in ("forecastMonth", "step"):
            ren[n] = "lead"
    da = da.rename(ren)
    for n in list(da.dims):
        if n not in ("number", "lead", "lat", "lon") and da.sizes[n] == 1:
            da = da.isel({n: 0})
    if "number" not in da.dims:
        da = da.expand_dims("number")
    extra = [n for n in da.dims if n not in ("number", "lead", "lat", "lon")]
    if extra:
        # lagged ensembles (e.g. NCEP) come as a sparse hypercube (start dates x members, mostly
        # empty). Read one start date at a time and keep only real members (memory safe).
        import itertools
        mems, nmem = [], 0
        for idx in itertools.product(*[range(da.sizes[e]) for e in extra]):
            sub = np.asarray(da.isel(dict(zip(extra, idx))).transpose("number", "lead", "lat", "lon").values,
                             dtype=np.float32)
            ok = ~np.all(np.isnan(sub), axis=(1, 2, 3))
            if ok.any():
                mems.append(sub[ok])
                nmem += int(ok.sum())
            if nmem >= 200:
                break
        if not mems:
            raise RuntimeError("no valid ensemble member in " + os.path.basename(path))
        da = xr.DataArray(np.concatenate(mems, axis=0)[:200], dims=("number", "lead", "lat", "lon"),
                          coords={"lat": da["lat"].values, "lon": da["lon"].values})
    else:
        da = da.dropna("number", how="all")
    return da.transpose("number", "lead", "lat", "lon")


def block_c3s():
    import cdsapi
    client = cdsapi.Client(quiet=True)
    now = dt.date.today()
    inits = [(now.year, now.month)]
    pm = now.replace(day=1) - dt.timedelta(days=1)
    inits.append((pm.year, pm.month))
    os.makedirs(CACHE, exist_ok=True)
    result = None
    for (y, m) in inits:
        systems = {}
        pr_sys = {}
        for centre, sys_list in C3S_SYSTEMS.items():
            f_sst = os.path.join(CACHE, "c3s_sst_%s_%d%02d.grib" % (centre, y, m))
            try:
                if not os.path.exists(f_sst):
                    sy = c3s_retrieve(client, centre, sys_list, y, m, "sea_surface_temperature_anomaly",
                                      [5, -170, -5, -120], f_sst)
                else:
                    sy = "cached"
                da = open_grib_members(f_sst)
                w = np.cos(np.deg2rad(da["lat"]))
                n34 = da.weighted(w).mean(("lat", "lon"), skipna=True).values  # (member, lead)
                if n34.ndim != 2 or n34.shape[1] != 6:
                    # e.g. NCEP/JMA lagged-start GRIBs: leads not mapped to 6 monthly values -> skip system
                    log("  C3S %s skipped: unexpected shape %s (expected members x 6 leads)" % (centre, str(n34.shape)))
                    continue
                systems[centre] = {"system": sy, "members": [[r2(v, 2) for v in row] for row in n34]}
                log("  C3S %s %s: %d members" % (centre, sy, n34.shape[0]))
            except Exception as e:
                log("  C3S %s SST failed: %s" % (centre, str(e)[:120]))
                continue
            f_pr = os.path.join(CACHE, "c3s_pr_%s_%d%02d.grib" % (centre, y, m))
            try:
                if not os.path.exists(f_pr):
                    c3s_retrieve(client, centre, sys_list, y, m,
                                 "total_precipitation_anomalous_rate_of_accumulation",
                                 [39, -20, -37, 53], f_pr)
                da = open_grib_members(f_pr).sortby("lat")
                em = da.mean("number").values * 86400.0 * 1000.0  # m/s -> mm/day
                pr_sys[centre] = (da["lat"].values, da["lon"].values, em)
            except Exception as e:
                log("  C3S %s precip failed: %s" % (centre, str(e)[:120]))
        if len(systems) >= 2:
            months = [str(pd.Period(year=y, month=m, freq="M") + k) for k in range(6)]
            result = {"init": "%d-%02d" % (y, m), "months": months, "systems": systems}
            # probabilities for 3-month windows (equal weight per system)
            probs = []
            for a in range(0, 4):
                pen, pln = [], []
                for s in systems.values():
                    mem = np.array([[np.nan if v is None else v for v in row] for row in s["members"]])
                    sm = np.nanmean(mem[:, a:a + 3], axis=1)
                    pen.append(np.mean(sm >= 0.5))
                    pln.append(np.mean(sm <= -0.5))
                c = pd.Period(months[a + 1], "M")
                probs.append({"season": SEAS[c.month - 1], "centre": str(c), "p_en": r2(np.mean(pen), 3),
                              "p_ln": r2(np.mean(pln), 3), "p_neu": r2(1 - np.mean(pen) - np.mean(pln), 3)})
            result["probs"] = probs
            if pr_sys:
                lat, lon, _ = next(iter(pr_sys.values()))
                wins = []
                for a in range(0, 4):
                    fields = [np.nanmean(em[a:a + 3], axis=0) for (_, _, em) in pr_sys.values()
                              if em.shape[1:] == (len(lat), len(lon))]
                    F = np.array(fields)
                    mme = np.nanmean(F, axis=0)
                    agree = np.mean(np.sign(F) == np.sign(mme)[None], axis=0)
                    c = pd.Period(months[a + 1], "M")
                    wins.append({"season": SEAS[c.month - 1], "centre": str(c),
                                 "z": [[r2(v, 2) for v in row] for row in mme],
                                 "agree": [[r2(v, 2) for v in row] for row in agree]})
                result["precip"] = {"lat": [float(v) for v in lat], "lon": [float(v) for v in lon],
                                    "n_systems": len(pr_sys), "windows": wins}
            break
    if result is None:
        raise RuntimeError("fewer than 2 C3S systems available")
    status("Copernicus C3S seasonal", True, "init %s, %d systems" % (result["init"], len(result["systems"])))
    return result


# --------------------------------------------------------------------------
def main():
    global ARGS
    ap = argparse.ArgumentParser(description="AfriENSO data pipeline")
    ap.add_argument("--no-c3s", action="store_true", help="skip Copernicus C3S seasonal forecasts")
    ap.add_argument("--refresh", action="store_true", help="ignore the download cache")
    ap.add_argument("--offline", action="store_true", help="use cached files only (testing)")
    ARGS = ap.parse_args()
    t0 = time.time()
    geo = json.load(open(GEO_JSON, encoding="utf-8"))
    data = {"meta": {}, "geo": {"countries": [{k: c[k] for k in ("iso", "en", "fr", "draw", "bbox")}
                                              for c in geo["countries"]],
                                "ar6": geo["ar6"], "wa": WA_BOXES,
                                "wsahara": geo["wsahara"], "source": geo["source"]}}
    oni = eps = mon = None
    try:
        data["enso"], oni, eps, mon = block_enso()
    except Exception as e:
        status("CPC ONI", False, e)
        traceback.print_exc()
    sst_idx = None
    try:
        sst_idx, sstmap = block_sst_indices()
        data["sst"] = {k: series_out(v.dropna()) for k, v in sst_idx.items()}
        data["sstmap"] = sstmap
    except Exception as e:
        status("PSL ERSSTv5 gridded", False, e)
        traceback.print_exc()
    c3s = None
    if not ARGS.no_c3s:
        try:
            c3s = block_c3s()
            data["c3s"] = c3s
        except Exception as e:
            status("Copernicus C3S seasonal", False, e)
    n34m = mon["n34"] if mon is not None else None
    n34_fc = None
    if c3s:
        mem = [row for s in c3s["systems"].values() for row in s["members"]]
        n34_fc = {"months": c3s["months"], "members": [[np.nan if v is None else v for v in r] for r in mem]}
    try:
        data["globaltemp"] = block_globaltemp(n34m, n34_fc)
    except Exception as e:
        status("ERA5 daily global (Climate Pulse)", False, e)
        traceback.print_exc()
    if oni is not None:
        try:
            phase_m = phase_series(oni, eps)
            data["africa"] = block_africa(geo, oni, phase_m, sst_idx)
        except Exception as e:
            status("Africa grids", False, e)
            traceback.print_exc()
    data["meta"] = {"generated": dt.datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC"), "status": STATUS,
                    "base": "%d-%d" % (BASE0, BASE1), "fdr_q": FDR_Q, "version": "1.1"}
    js = "window.AFRIENSO = " + json.dumps(data, separators=(",", ":"), ensure_ascii=False, allow_nan=False) + ";\n"
    with open(OUT_JS, "w", encoding="utf-8") as f:
        f.write(js)
    log("wrote %s (%.1f MB) in %.0f s" % (OUT_JS, len(js) / 1e6, time.time() - t0))
    bad = [s["key"] for s in STATUS if not s["ok"]]
    if bad:
        log("Blocks that failed (the page hides them): " + ", ".join(bad))


if __name__ == "__main__":
    main()