File size: 70,280 Bytes
d79a78d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Data audit of the training tables (everything dated <= 2018).

Run from the repository root (deterministic, offline, about 15 s):

    PYTHONPATH=code .venv/bin/python -m protostar.audit

Writes into reports/audit/ and prints a 30-line summary:

    AUDIT.md                 the summary (at most 120 lines)
    cities.csv               one row per city: location, stations, record span
    coverage.csv             valid-year counts per city x metric (the organizers' 10-day rule)
    unusable.csv             city-metrics without a baseline, or weak, and how they are handled
    units.csv                unit sanity per metric (units_violations.csv: every out-of-range year)
    daily_recompute.csv      annual_indices recomputed from daily, per quantity
                             (daily_recompute_worst.csv: the 20 worst city-years);
                             skipped, and said so, when data/raw/daily.parquet is absent
    outliers.csv             robust-z outliers among valid years 1989-2018
    station_changes.csv      level shift at each documented station change since 1959, per metric
    undocumented_breaks.csv  strongest break 1994-2013 per city x metric
    quirks.csv               what the organizers should hear about, each with an example row

All data comes through protostar.data (sha256 and the no-data-after-2018 guard).

Choices that go beyond the letter of the task (all are stated in AUDIT.md):

* Neighbour-difference series: d[city, year] = value - mean over the city's 8 nearest cities
  (great circle) of their ANOMALY that year, valid years only. A neighbour's anomaly is its value
  minus its own 1989-2018 valid mean. With eight complete neighbours this is "city minus neighbour
  mean" plus a constant; with an incomplete neighbour (a third of the city-years in 1989-2018) it
  keeps the reference from jumping when that neighbour drops out. d needs >= 3 valid neighbours.
  The break scan is repeated with the MEDIAN of the neighbours' anomalies as the reference
  (`t_median_ref`): a break that survives it does not come from one or two neighbours.
* Documented changes: the valid years among the 15 calendar years on each side of the change
  year. A side stops at another documented change of the same city once it holds 3 valid years,
  otherwise it continues beyond it (`crosses_other_change`). A shift needs 3 valid years a side.
* Outliers: only city-metrics with a baseline (>= 10 valid years in 1989-2018) get a robust z;
  `neighbor_mean_z` (mean z of the 8 nearest cities that year) tells weather from a local oddity.
"""

import time
import warnings

import numpy as np
import pandas as pd

from .common import (BASELINE_WINDOW, DATA_RAW, FORECAST_YEARS, MAX_MISSING_DAYS, METRICS,
                     MIN_VALID_YEARS, N_CITIES, REPORTS, ROOT, TRAIN_END, UNITS)
from .data import (cities, load_annual, load_city_info, load_coverage, load_daily, long_table,
                   panels)

OUT = REPORTS / "audit"
WIN = (TRAIN_END - BASELINE_WINDOW + 1, TRAIN_END)   # the organizers' baseline window
LAST10 = (TRAIN_END - 9, TRAIN_END)
LAST5 = (TRAIN_END - 4, TRAIN_END)
assert WIN == (1989, 2018) and LAST10[0] == 2009 and LAST5[0] == 2014   # years are in column names
N_FORECAST_ROWS = N_CITIES * len(METRICS) * len(FORECAST_YEARS)          # 5,880
ORGANIZERS_NO_BASELINE = 9                            # city-metrics the organizers do not score
WEAK_MIN_VALID = 20                                   # "weak" below this many valid years of 30
MISS = {"Miss Tmax": "miss_tmax", "Miss Tmin": "miss_tmin", "Miss Prcp": "miss_prcp"}
SHORT = {"annual_avg_temp": "avg temp", "total_precip_in": "precip", "hottest_day_temp": "hottest day",
         "cdd": "cdd"}
DIGITS = {"annual_avg_temp": 2, "total_precip_in": 2, "hottest_day_temp": 1, "cdd": 0}
US_BOX = {"lat": (24.0, 50.0), "lon": (-125.0, -66.0)}

# Units: plausible range of one valid city-year, and of the median of all valid 1989-2018 values.
RANGE = {"annual_avg_temp": (20.0, 85.0), "total_precip_in": (0.0, 120.0),
         "hottest_day_temp": (70.0, 130.0), "cdd": (0.0, 6000.0)}
MEDIAN_RANGE = {"annual_avg_temp": (45.0, 65.0), "total_precip_in": (20.0, 50.0),
                "hottest_day_temp": (90.0, 105.0), "cdd": (500.0, 2500.0)}
CDD_BASE = 65.0
# Daily recompute tolerances (annual_indices is rounded to 2 decimals); 0 for day counts.
TOL = {"annual_avg_temp": 0.06, "total_precip_in": 0.06, "hottest_day_temp": 0.06, "cdd": 1.0}

Z_LIST, Z_COUNT = 4.0, 5.0        # outliers listed (1989-2018) / counted (whole record)
Z_REGIONAL = 1.0                  # neighbours' mean z beyond this, same sign: a regional event

K_NEIGHBORS = 8
MIN_NEIGHBORS = 3                 # d is missing in a year with fewer valid neighbours
EARTH_KM = 6371.0088
CHANGE_FROM = 1959                # documented station changes are analysed from this year on
SIDE_YEARS = 15                   # calendar years on each side of a documented change
MIN_SIDE_DOC = 3                  # valid years a side needed to estimate a shift
T_FLAG_DOC = 3.0
SCAN_YEARS = range(1994, 2014)    # candidate first years of the later segment
MIN_SIDE_SCAN = 5
T_FLAG_SCAN = 5.0
MD_MAX_LINES = 120


# ----------------------------------------------------------------------------- helpers

def _between(s, span):
    return (s >= span[0]) & (s <= span[1])


def _write(df: pd.DataFrame, name: str) -> None:
    df.to_csv(OUT / name, index=False, lineterminator="\n")


def _metric_sort(df: pd.DataFrame, by: list[str]) -> pd.DataFrame:
    order = {m: i for i, m in enumerate(METRICS)}
    return df.sort_values(by, key=lambda s: s.map(order) if s.name == "metric" else s,
                          kind="stable").reset_index(drop=True)


def _runs(years) -> str:
    """Sorted years as runs: [1989, 1990, 1991, 1996] -> '1989-1991, 1996'."""
    years, out, start = sorted(int(y) for y in years), [], None
    for i, y in enumerate(years):
        start = y if start is None else start
        if i + 1 == len(years) or years[i + 1] != y + 1:
            out.append(str(start) if start == y else f"{start}-{y}")
            start = None
    return ", ".join(out)


def _is_leap(year):
    return (year % 4 == 0) & ((year % 100 != 0) | (year % 400 == 0))


def long_with_missing(annual: pd.DataFrame) -> pd.DataFrame:
    """long_table() plus the city name, the three missing-day counts and `max_miss`
    (max over the missing-day columns the metric uses)."""
    keys = annual.rename(columns={"ID": "city_id", "Year": "year", "Name": "name", **MISS})
    long = long_table(annual).merge(keys[["city_id", "year", "name", *MISS.values()]],
                                    on=["city_id", "year"], how="left", validate="m:1")
    long["max_miss"] = 0
    for metric, (_, cols) in METRICS.items():
        sel = long["metric"] == metric
        long.loc[sel, "max_miss"] = long.loc[sel, [MISS[c] for c in cols]].max(axis=1)
    return long


# ----------------------------------------------------------------------------- 1 cities, tables

def audit_cities(annual: pd.DataFrame, info: pd.DataFrame) -> pd.DataFrame:
    out = cities(annual)
    info = info.sort_values(["ID", "Stn.stDate"], kind="stable")
    current = info.groupby("ID").tail(1).set_index("ID")
    span = annual.groupby("ID")["Year"].agg(["min", "max"])
    out["n_stations"] = out["city_id"].map(info.groupby("ID").size())
    out["current_station"] = out["city_id"].map(current["Stn.Name"])
    out["current_station_start"] = out["city_id"].map(current["Stn.stDate"]).dt.strftime("%Y-%m-%d")
    out["first_year"] = out["city_id"].map(span["min"])
    out["last_year"] = out["city_id"].map(span["max"])
    assert len(out) == N_CITIES and out["city_id"].is_unique and out["name"].is_unique
    assert out.notna().all(axis=None), "a city lacks coordinates or a station record"
    assert out["lat"].between(*US_BOX["lat"]).all() and out["lon"].between(*US_BOX["lon"]).all()
    assert (current["Stn.edDate"].dt.year == TRAIN_END).all() and (out["last_year"] == TRAIN_END).all()
    return out


def station_events(cov: pd.DataFrame, info: pd.DataFrame) -> pd.DataFrame:
    """Every city-year with `Station Changes` > 0, with the stations involved (from city_info)."""
    info = info.sort_values(["ID", "Stn.stDate"], kind="stable").copy()
    info["seq"] = info.groupby("ID").cumcount()
    info["start_year"] = info["Stn.stDate"].dt.year
    info["prev_name"] = info.groupby("ID")["Stn.Name"].shift()
    per_year = info[info["seq"] > 0].groupby(["ID", "start_year"]).agg(
        n_started=("seq", "size"), from_station=("prev_name", "first"), to_station=("Stn.Name", "last"),
        change_date=("Stn.stDate", "first")).reset_index().rename(columns={"start_year": "Year"})
    ev = cov[cov["Station Changes"] > 0].merge(per_year, on=["ID", "Year"], how="left")
    ev["change_date"] = ev["change_date"].dt.strftime("%Y-%m-%d")
    ev = ev.rename(columns={"ID": "city_id", "Name": "name", "Year": "year", "Days Both": "days_both",
                            "Station Segment": "station_segment", "Station Changes": "n_changes"})
    return ev.sort_values(["city_id", "year"], kind="stable").reset_index(drop=True)


def cross_checks(annual: pd.DataFrame, info: pd.DataFrame, cov: pd.DataFrame, events: pd.DataFrame) -> dict:
    """Consistency between the three small tables: counts of disagreeing rows (0 = consistent)."""
    keys = ["ID", "Year"]
    m = annual[keys + ["Name", "Miss Tmax", "Miss Tmin"]].merge(cov, on=keys, how="outer",
                                                               suffixes=("", "_cov"), indicator=True)
    a = annual.groupby("ID").agg(name=("Name", "first"), lat=("Lat", "first"), lon=("Lon", "first"),
                                 first=("Year", "min"), last=("Year", "max"), n=("Year", "size"),
                                 n_coord=("Lat", "nunique"))
    i = info.groupby("ID").agg(name=("Name", "first"), lat=("Lat", "first"), lon=("Lon", "first"),
                               start=("Stn.stDate", "min")).reindex(a.index)
    n_days = 365 + _is_leap(m["Year"])
    both_lo = n_days - m["Miss Tmax"] - m["Miss Tmin"]
    both_hi = n_days - m[["Miss Tmax", "Miss Tmin"]].max(axis=1)
    # Station Segment = number of stations that started on or before 1 Jan (at least the first one).
    on_jan1 = (info["Stn.stDate"].dt.month == 1) & (info["Stn.stDate"].dt.day == 1)
    in_use_from = (info["Stn.stDate"].dt.year + ~on_jan1).groupby(info["ID"]).apply(
        lambda s: np.sort(s.to_numpy())).to_dict()
    seg_bad = 0
    for cid, g in cov.groupby("ID"):
        expected = np.maximum(np.searchsorted(in_use_from[cid], g["Year"].to_numpy(), side="right"), 1)
        seg_bad += int((expected != g["Station Segment"].to_numpy()).sum())
    return {
        "n_city_years": len(annual), "first_year": int(annual["Year"].min()),
        "first_year_latest": int(a["first"].max()), "n_station_records": len(info),
        "max_stations": int(info.groupby("ID").size().max()),
        "n_keys_unmatched": int((m["_merge"] != "both").sum()),
        "n_name_mismatch": int((m["Name"] != m["Name_cov"]).sum() + (a["name"] != i["name"]).sum()),
        "n_coord_mismatch": int(((a["lat"] != i["lat"]) | (a["lon"] != i["lon"]) | (a["n_coord"] != 1)).sum()),
        "n_start_year_mismatch": int((i["start"].dt.year != a["first"]).sum()),
        "n_cities_with_year_gaps": int((a["last"] - a["first"] + 1 != a["n"]).sum()),
        "n_days_both_inconsistent": int(((m["Days Both"] < both_lo) | (m["Days Both"] > both_hi)).sum()),
        "n_station_changes_mismatch": int((events["n_changes"] != events["n_started"]).sum()
                                          + abs(int(events["n_changes"].sum()) - (len(info) - info["ID"].nunique()))),
        "n_station_segment_mismatch": seg_bad,
        "n_changes_all": int(events["n_changes"].sum()),
        "n_changes_since": int(events.loc[events["year"] >= CHANGE_FROM, "n_changes"].sum()),
        "n_changes_win": int(events.loc[_between(events["year"], WIN), "n_changes"].sum()),
    }


# ----------------------------------------------------------------------------- 2-3 coverage

def audit_coverage(long: pd.DataFrame) -> pd.DataFrame:
    w = _between(long["year"], WIN)
    t = long.assign(v_win=long["valid"] & w,
                    v_10=long["valid"] & _between(long["year"], LAST10),
                    v_5=long["valid"] & _between(long["year"], LAST5),
                    inv_win=~long["valid"] & w,
                    valid_year=long["year"].where(long["valid"]),
                    miss_win=long["max_miss"].where(w))
    out = t.groupby(["city_id", "metric"], sort=False).agg(
        name=("name", "first"),
        first_year=("year", "min"), last_year=("year", "max"), n_years=("year", "size"),
        n_valid_all=("valid", "sum"), n_valid_1989_2018=("v_win", "sum"),
        n_valid_2009_2018=("v_10", "sum"), n_valid_2014_2018=("v_5", "sum"),
        first_valid_year=("valid_year", "min"), last_valid_year=("valid_year", "max"),
        n_invalid_1989_2018=("inv_win", "sum"), max_missing_days_1989_2018=("miss_win", "max"),
    ).reset_index()
    for col in ("first_valid_year", "last_valid_year", "max_missing_days_1989_2018"):
        out[col] = out[col].astype("Int64")
    out["has_baseline"] = out["n_valid_1989_2018"] >= MIN_VALID_YEARS
    assert len(out) == N_CITIES * len(METRICS)
    assert (out["n_valid_1989_2018"] + out["n_invalid_1989_2018"] == BASELINE_WINDOW).all()
    return _metric_sort(out, ["city_id", "metric"])


def audit_unusable(cov_tab: pd.DataFrame) -> pd.DataFrame:
    chain = ("`models.fallback`: the mean of the city's last 10 valid years (reaching back over the gap) plus "
             "the change its 8 nearest fitted cities forecast relative to those same years")
    rows = []
    for r in cov_tab.itertuples(index=False):
        last = None if pd.isna(r.last_valid_year) else int(r.last_valid_year)
        why = []
        if not r.has_baseline:
            why.append(f"no baseline: {r.n_valid_1989_2018} valid years in 1989-2018 (< {MIN_VALID_YEARS})")
        elif r.n_valid_1989_2018 < WEAK_MIN_VALID:
            why.append(f"{r.n_valid_1989_2018} valid years in 1989-2018 (< {WEAK_MIN_VALID})")
        if r.n_valid_2014_2018 == 0:
            why.append("no valid year in 2014-2018")
        if last is None:
            why.append("no valid year at all")
        elif last < TRAIN_END:
            why.append(f"last valid year {last} (< {TRAIN_END})")
        if not why:
            continue
        if r.has_baseline:
            handling = ("modeled like every other city-metric, on its valid years (it has a baseline and is "
                        "scored)")
        else:
            handling = (f"not scored by the organizers (no baseline); still forecast because the file needs "
                        f"all {N_FORECAST_ROWS:,} rows, with {chain}")
        rows.append({"city_id": r.city_id, "name": r.name, "metric": r.metric,
                     "category": "weak" if r.has_baseline else "no_baseline",
                     "n_valid_1989_2018": r.n_valid_1989_2018, "n_valid_2009_2018": r.n_valid_2009_2018,
                     "n_valid_2014_2018": r.n_valid_2014_2018, "n_valid_all": r.n_valid_all,
                     "last_valid_year": last, "problem": "; ".join(why), "handling": handling})
    out = pd.DataFrame(rows)
    out["last_valid_year"] = out["last_valid_year"].astype("Int64")
    return out.sort_values(["category", "name"], kind="stable").reset_index(drop=True)


# ----------------------------------------------------------------------------- 4 units

def audit_units(annual: pd.DataFrame, long: pd.DataFrame, city: pd.DataFrame):
    """Per-metric ranges of valid values, the list of out-of-range city-years, and unit checks."""
    stats, viol = [], []
    for metric, (col, _) in METRICS.items():
        lo, hi = RANGE[metric]
        part = long[(long["metric"] == metric) & long["value"].notna()]
        outside = (part["value"] < lo) | (part["value"] > hi)
        in_win = _between(part["year"], WIN)
        x = part.loc[part["valid"] & in_win, "value"]
        bad = part[outside].assign(range_lo=lo, range_hi=hi, in_1989_2018=in_win[outside])
        viol.append(bad[["city_id", "name", "year", "metric", "value", "range_lo", "range_hi", "valid",
                         "in_1989_2018", *MISS.values()]])
        stats.append({
            "metric": metric, "column": col, "unit": UNITS[metric], "n_valid_1989_2018": len(x),
            "min": x.min(), "median": x.median(), "max": x.max(), "range_lo": lo, "range_hi": hi,
            "n_out_of_range_valid_1989_2018": int((outside & part["valid"] & in_win).sum()),
            "n_out_of_range_valid_all_years": int((outside & part["valid"]).sum()),
            "n_out_of_range_invalid_years": int((outside & ~part["valid"]).sum()),
            "median_range_lo": MEDIAN_RANGE[metric][0], "median_range_hi": MEDIAN_RANGE[metric][1]})
    units = pd.DataFrame(stats)
    viol = (pd.concat(viol, ignore_index=True)
            .sort_values(["valid", "metric", "city_id", "year"], ascending=[False, True, True, True],
                         kind="stable").reset_index(drop=True))

    # Avg Temp is the mid-point of mean tmax and mean tmin.
    t3 = annual[["Avg Temp", "Avg Tmax", "Avg Tmin"]].dropna()
    identity = float((t3["Avg Temp"] - (t3["Avg Tmax"] + t3["Avg Tmin"]) / 2).abs().max())
    # Latitude: warmer in the south (city means over valid 1989-2018 years).
    temp = long[(long["metric"] == "annual_avg_temp") & long["valid"] & _between(long["year"], WIN)]
    mean_temp = temp.groupby("city_id")["value"].mean()
    lat = city.set_index("city_id")["lat"].reindex(mean_temp.index)
    lat_r = float(np.corrcoef(lat, mean_temp)[0, 1])
    lat_slope = float(np.polyfit(lat, mean_temp, 1)[0])
    # cdd in degF-days over 65 degF: sum(max(0, T - 65)) >= n_days * (mean T - 65), so in hot valid
    # years cdd / (365 * (Avg Temp - 65)) is about 1 or more; it would be <= 0.8 in degC-days.
    hot = annual[(annual[list(METRICS["cdd"][1])] <= MAX_MISSING_DAYS).all(axis=1)
                 & _between(annual["Year"], WIN) & (annual["Avg Temp"] >= 72)]
    ratio = hot["cdd"] / (365 * (hot["Avg Temp"] - CDD_BASE))
    checks = {"identity_max_abs_diff": identity, "lat_corr": lat_r, "lat_slope": lat_slope,
              "cdd_ratio_min": float(ratio.min()), "cdd_ratio_max": float(ratio.max()),
              "cdd_ratio_n": int(len(ratio))}

    med_ok = units["median"].between(units["median_range_lo"], units["median_range_hi"])
    rng_ok = units["n_out_of_range_valid_1989_2018"] == 0
    extra = {"annual_avg_temp": identity <= 0.011 and lat_r < -0.8, "total_precip_in": True,
             "hottest_day_temp": True, "cdd": checks["cdd_ratio_min"] >= 0.9}
    units["unit_ok"] = med_ok & rng_ok & units["metric"].map(extra).astype(bool)
    med = units.set_index("metric")["median"]
    note = {
        "annual_avg_temp": (f"°F: median {med['annual_avg_temp']:.1f} (in °C the same data would read "
                            f"{(med['annual_avg_temp'] - 32) / 1.8:.1f}); max abs(Avg Temp - (Avg Tmax + Avg Tmin)/2) "
                            f"= {identity:.3f}; corr(city mean, latitude) = {lat_r:.2f} ({lat_slope:.2f} °F per "
                            f"degree north)"),
        "total_precip_in": f"inches: median {med['total_precip_in']:.1f} (in mm it would read "
                           f"{med['total_precip_in'] * 25.4:.0f})",
        "hottest_day_temp": f"°F: median {med['hottest_day_temp']:.0f} (in °C it would read "
                            f"{(med['hottest_day_temp'] - 32) / 1.8:.0f})",
        "cdd": (f"°F-days over 65 °F: in the {len(ratio)} valid city-years with Avg Temp >= 72, "
                f"cdd / (365 x (Avg Temp - 65)) is {ratio.min():.2f} to {ratio.max():.2f} "
                f"(at most 0.8 if cdd were in °C-days)"),
    }
    units["verdict"] = units["metric"].map(note)
    return units, viol, checks


# ----------------------------------------------------------------------------- 5 daily recompute

def prcp_gap_cities(annual: pd.DataFrame) -> pd.Series:
    """Cities with >= 20 years in 1989-2018 in which precipitation is invalid although
    temperature is valid: number of such years by city id."""
    t_ok = (annual[["Miss Tmax", "Miss Tmin"]] <= MAX_MISSING_DAYS).all(axis=1)
    bad = _between(annual["Year"], WIN) & t_ok & (annual["Miss Prcp"] > MAX_MISSING_DAYS)
    n = annual[bad].groupby("ID").size()
    return n[n >= WEAK_MIN_VALID].sort_index()


def audit_daily(annual: pd.DataFrame, cov: pd.DataFrame, prcp_gap_ids=()):
    """Recompute the annual table from daily. None if data/raw/daily.parquet is absent."""
    if not (DATA_RAW / "daily.parquet").exists():
        return None
    daily = load_daily().drop(columns="Name")
    daily["ID"] = daily["ID"].astype("category")
    daily["Year"] = daily["Date"].dt.year.astype("int16")
    notes = {"n_rows": len(daily), "n_duplicate_days": int(daily.duplicated(["ID", "Date"]).sum())}
    # NaN unless tmax and tmin are both present, so the sum runs over the "days with both".
    daily["cdd_day"] = ((daily["tmax"] + daily["tmin"]) / 2 - CDD_BASE).clip(lower=0)
    rec = daily.groupby(["ID", "Year"], observed=True).agg(
        n_days=("Date", "size"), n_tmax=("tmax", "count"), n_tmin=("tmin", "count"),
        n_prcp=("prcp", "count"), mean_tmax=("tmax", "mean"), mean_tmin=("tmin", "mean"),
        sum_prcp=("prcp", "sum"), max_tmax=("tmax", "max"), cdd_sum=("cdd_day", "sum"),
        days_both=("cdd_day", "count")).reset_index()
    rec["ID"] = rec["ID"].astype(str)
    rec["Year"] = rec["Year"].astype("int64")

    # The last year was converted from tenths of °C: one decimal; earlier years are whole °F.
    last = daily["Year"] == TRAIN_END
    any_frac = pd.Series(False, index=daily.index)
    for col in ("tmax", "tmin"):
        present = daily[col].notna()
        frac = present & (daily[col] % 1 != 0)
        any_frac |= frac
        notes[col] = {"nonint_last": int((frac & last).sum()), "obs_last": int((present & last).sum()),
                      "nonint_before": int((frac & ~last).sum()), "obs_before": int((present & ~last).sum())}
    notes["n_cities_nonint_last"] = int(daily.loc[last & any_frac, "ID"].nunique())
    inverted = daily[daily["tmax"] < daily["tmin"]]
    notes["n_tmax_below_tmin"] = len(inverted)
    notes["tmax_below_tmin_example"] = "; ".join(
        f"{r.ID} {r.Date:%Y-%m-%d}: tmax {r.tmax:g}, tmin {r.tmin:g}"
        for r in inverted.sort_values(["Date", "ID"], kind="stable").tail(1).itertuples(index=False))
    notes["n_negative_prcp"] = int((daily["prcp"] < 0).sum())
    # Missing vs zero-precipitation days of the cities whose precipitation is never valid.
    notes["prcp_gap"] = {}
    for cid in prcp_gap_ids:
        p = daily.loc[(daily["ID"] == cid) & (daily["Year"] >= TRAIN_END - 5), ["Year", "prcp"]]
        by = p.assign(missing=p["prcp"].isna(), dry=p["prcp"] == 0).groupby("Year")[["missing", "dry"]].sum()
        notes["prcp_gap"][cid] = {"missing_before": float(by["missing"].iloc[:-1].mean()),
                                  "dry_before": float(by["dry"].iloc[:-1].mean()),
                                  "missing_last": int(by["missing"].iloc[-1]), "dry_last": int(by["dry"].iloc[-1])}
    del daily

    a = annual.merge(cov[["ID", "Year", "Days Both"]], on=["ID", "Year"], validate="1:1")
    m = a.merge(rec, on=["ID", "Year"], how="outer", indicator=True)
    notes["n_city_years"] = len(rec)
    notes["n_unmatched_city_years"] = int((m["_merge"] != "both").sum())
    notes["n_wrong_calendar_length"] = int((m["n_days"] != 365 + _is_leap(m["Year"])).sum())
    m["d_miss_tmax"] = m["n_days"] - m["n_tmax"]
    m["d_miss_tmin"] = m["n_days"] - m["n_tmin"]
    m["d_miss_prcp"] = m["n_days"] - m["n_prcp"]
    m["d_avg_temp"] = (m["mean_tmax"] + m["mean_tmin"]) / 2
    m["d_cdd"] = m["cdd_sum"].where(m["days_both"] > 0)
    pairs = [("Miss Tmax", "Miss Tmax", "d_miss_tmax", 0.0), ("Miss Tmin", "Miss Tmin", "d_miss_tmin", 0.0),
             ("Miss Prcp", "Miss Prcp", "d_miss_prcp", 0.0), ("Days Both", "Days Both", "days_both", 0.0),
             ("annual_avg_temp", "Avg Temp", "d_avg_temp", TOL["annual_avg_temp"]),
             ("total_precip_in", "ToT Prcp", "sum_prcp", TOL["total_precip_in"]),
             ("hottest_day_temp", "Max Tmax", "max_tmax", TOL["hottest_day_temp"]),
             ("cdd", "cdd", "d_cdd", TOL["cdd"])]
    summary, worst = [], []
    for quantity, col, dcol, tol in pairs:
        pub = m[col].astype(float)
        pub = pub.where(np.isfinite(pub))                  # -inf of unobserved years -> missing
        new = m[dcol].astype(float)
        diff = (pub - new).abs()
        one_sided = pub.notna() ^ new.notna()
        summary.append({"quantity": quantity, "published_column": col,
                        "table": "coverage_and_stations" if col == "Days Both" else "annual_indices",
                        "n_city_years_compared": int(diff.notna().sum()),
                        "max_abs_diff": round(float(diff.max()), 6), "tolerance": tol,
                        "n_above_tolerance": int((diff > tol).sum()),
                        "n_published_only": int((pub.notna() & new.isna()).sum()),
                        "n_daily_only": int((pub.isna() & new.notna()).sum())})
        score = (diff / max(tol, 0.5)).where(~one_sided, np.inf)   # a one-sided value is the worst case
        top = score.nlargest(20).index
        worst.append(pd.DataFrame({
            "city_id": m.loc[top, "ID"], "name": m.loc[top, "Name"], "year": m.loc[top, "Year"],
            "quantity": quantity, "published": pub[top].round(6), "from_daily": new[top].round(6),
            "abs_diff": diff[top].round(6), "tolerance": tol,
            "above_tolerance": (diff[top] > tol) | one_sided[top], "score": score[top]}))
    worst = (pd.concat(worst, ignore_index=True)
             .sort_values(["score", "city_id", "year", "quantity"], ascending=[False, True, True, True],
                          kind="stable").head(20).drop(columns="score").reset_index(drop=True))

    # annual Avg Temp is the mean of the already rounded Avg Tmax and Avg Tmin (double rounding).
    notes["n_avg_temp_not_rounded_daily"] = int(((m["Avg Temp"] - m["d_avg_temp"].round(2)).abs() > 1e-6).sum())
    with_max = annual[np.isfinite(annual["Max Tmax"])]
    frac_max = with_max["Max Tmax"] % 1 != 0
    notes["n_max_tmax_nonint_last"] = int((frac_max & (with_max["Year"] == TRAIN_END)).sum())
    notes["n_max_tmax_nonint_before"] = int((frac_max & (with_max["Year"] < TRAIN_END)).sum())
    return {"summary": pd.DataFrame(summary), "worst": worst, "notes": notes}


# ----------------------------------------------------------------------------- 6 outliers

def audit_outliers(long: pd.DataFrame, city: pd.DataFrame, nbr: np.ndarray):
    """Robust z of every valid year against the city-metric's 1989-2018 valid median and MAD."""
    key = ["city_id", "metric"]
    v = long[long["valid"]].copy()
    base = v[_between(v["year"], WIN)].copy()
    base["median"] = base.groupby(key)["value"].transform("median")
    base["absdev"] = (base["value"] - base["median"]).abs()
    ref = base.groupby(key).agg(n_base=("value", "size"), median=("median", "first"),
                                mad=("absdev", "median"), mean_ad=("absdev", "mean")).reset_index()
    # scale: 1.4826 x MAD; if the MAD is 0 (ties), 1.2533 x mean absolute deviation instead.
    ref["scale"] = np.where(ref["mad"] > 0, 1.4826 * ref["mad"], 1.2533 * ref["mean_ad"])
    ref = ref[(ref["n_base"] >= MIN_VALID_YEARS) & (ref["scale"] > 0)]
    v = v.merge(ref, on=key, how="inner")
    v["z"] = (v["value"] - v["median"]) / v["scale"]
    v["abs_z"] = v["z"].abs()
    v["in_win"] = _between(v["year"], WIN)
    v["some_missing_days"] = v["max_miss"] > 0            # valid, but 1-10 days missing

    # Mean z of the 8 nearest cities in the same year: the same sign and size means weather.
    row_of = {cid: i for i, cid in enumerate(city["city_id"])}
    years = np.arange(WIN[0], WIN[1] + 1)
    listed = v[v["in_win"] & (v["abs_z"] >= Z_LIST)].copy()
    nb_mean = pd.Series(np.nan, index=listed.index)
    nb_count = pd.Series(0, index=listed.index)
    for metric in METRICS:
        zp = (v[(v["metric"] == metric) & v["in_win"]].pivot(index="city_id", columns="year", values="z")
              .reindex(index=city["city_id"], columns=years).to_numpy())
        sel = listed[listed["metric"] == metric]
        for i, cid, year in zip(sel.index, sel["city_id"], sel["year"]):
            z_nb = zp[nbr[row_of[cid]], year - WIN[0]]
            nb_count[i] = int(np.isfinite(z_nb).sum())
            nb_mean[i] = np.nanmean(z_nb) if nb_count[i] else np.nan
    listed["neighbor_mean_z"] = nb_mean.round(2)
    listed["n_neighbors"] = nb_count
    listed["regional"] = (np.sign(listed["z"]) * listed["neighbor_mean_z"]) >= Z_REGIONAL
    listed = listed.sort_values(["abs_z", "city_id", "metric", "year"], ascending=[False, True, True, True],
                                kind="stable")
    out = listed[["city_id", "name", "metric", "year", "value", "median", "mad", "z", *MISS.values(),
                  "some_missing_days", "neighbor_mean_z", "n_neighbors", "regional", "n_base"]]
    out = out.rename(columns={"n_base": "n_valid_1989_2018"})
    out = out.assign(median=out["median"].round(3), mad=out["mad"].round(3), z=out["z"].round(2))
    counts = []
    for metric in METRICS:
        p = v[v["metric"] == metric]
        w = p[p["in_win"]]
        clean, gappy = w[~w["some_missing_days"]], w[w["some_missing_days"]]
        counts.append({
            "metric": metric, "n_city_metrics": int(p["city_id"].nunique()),
            "n_valid_win": len(w), "n_list": int((w["abs_z"] >= Z_LIST).sum()),
            "n_valid_all": len(p), "n_count_all": int((p["abs_z"] >= Z_COUNT).sum()),
            "n_count_win": int((w["abs_z"] >= Z_COUNT).sum()),
            "n_mad_zero": int((ref.loc[ref["metric"] == metric, "mad"] == 0).sum()),
            "n_clean": len(clean), "n_gappy": len(gappy),
            "n_list_clean": int((clean["abs_z"] >= Z_LIST).sum()),
            "n_list_gappy": int((gappy["abs_z"] >= Z_LIST).sum()),
            "mean_z_clean": float(clean["z"].mean()), "mean_z_gappy": float(gappy["z"].mean())})
    return out.reset_index(drop=True), pd.DataFrame(counts)


# ----------------------------------------------------------------------------- 7-8 discontinuities

def nearest_neighbors(city: pd.DataFrame, k: int = K_NEIGHBORS):
    """Indices [n_city, k] of each city's k nearest other cities, and their distances in km."""
    lat, lon = np.radians(city["lat"].to_numpy()), np.radians(city["lon"].to_numpy())
    h = (np.sin((lat[:, None] - lat[None, :]) / 2) ** 2
         + np.cos(lat)[:, None] * np.cos(lat)[None, :] * np.sin((lon[:, None] - lon[None, :]) / 2) ** 2)
    dist = 2 * EARTH_KM * np.arcsin(np.sqrt(np.clip(h, 0.0, 1.0)))
    np.fill_diagonal(dist, np.inf)
    idx = np.argsort(dist, axis=1, kind="stable")[:, :k]
    return idx, np.take_along_axis(dist, idx, axis=1)


def neighbor_difference(y: np.ndarray, years: np.ndarray, nbr: np.ndarray, median: bool = False):
    """d[city, year] = y - mean (or median) anomaly of the city's valid neighbours that year
    (module docstring); NaN with fewer than MIN_NEIGHBORS valid neighbours."""
    w = _between(years, WIN)
    n_ref = np.isfinite(y[:, w]).sum(axis=1)
    normal = np.full(len(y), np.nan)
    has = n_ref >= MIN_VALID_YEARS
    normal[has] = np.nansum(y[has][:, w], axis=1) / n_ref[has]
    anom = (y - normal[:, None])[nbr]                      # [city, neighbour, year]
    n_nb = np.isfinite(anom).sum(axis=1)
    if median:
        with warnings.catch_warnings():                    # all-NaN years are expected
            warnings.simplefilter("ignore", RuntimeWarning)
            center = np.nanmedian(anom, axis=1)
    else:
        center = np.nansum(anom, axis=1) / np.maximum(n_nb, 1)
    return y - np.where(n_nb >= MIN_NEIGHBORS, center, np.nan)


def _welch(after: np.ndarray, before: np.ndarray, min_side: int):
    """(shift, Welch t) of mean(after) - mean(before); NaN with fewer than min_side values a side."""
    if after.size < min_side or before.size < min_side:
        return np.nan, np.nan
    shift = float(after.mean() - before.mean())
    se = float(np.sqrt(after.var(ddof=1) / after.size + before.var(ddof=1) / before.size))
    return shift, (shift / se if se > 0 else np.nan)


def _side(d: np.ndarray, first_year: int, change_year: int, step: int, other_changes: set):
    """Valid values of d on one side of a change (step -1: before, +1: after), and whether the
    side continues beyond another documented change of the city."""
    values, beyond, crossed = [], False, False
    for k in range(1, SIDE_YEARS + 1):
        year = change_year + step * k
        i = year - first_year
        if i < 0 or i >= d.size:
            break
        if year in other_changes:
            if len(values) >= MIN_SIDE_DOC:
                break
            beyond = True
            continue
        if np.isfinite(d[i]):
            values.append(d[i])
            crossed |= beyond
    return np.array(values), crossed


def audit_station_changes(events: pd.DataFrame, city: pd.DataFrame, dser: dict, years: np.ndarray):
    """Level shift of d at each documented change since CHANGE_FROM, one row per change x metric."""
    row_of = {cid: i for i, cid in enumerate(city["city_id"])}
    all_years = events.groupby("city_id")["year"].apply(set).to_dict()
    rows = []
    for e in events[events["year"] >= CHANGE_FROM].itertuples(index=False):
        others = all_years[e.city_id] - {e.year}
        for metric in METRICS:
            d = dser[metric][row_of[e.city_id]]
            before, cross_b = _side(d, int(years[0]), e.year, -1, others)
            after, cross_a = _side(d, int(years[0]), e.year, +1, others)
            shift, t = _welch(after, before, MIN_SIDE_DOC)
            rows.append({"city_id": e.city_id, "name": e.name, "year": e.year, "change_date": e.change_date,
                         "from_station": e.from_station, "to_station": e.to_station,
                         "n_changes": e.n_changes, "in_1989_2018": WIN[0] <= e.year <= WIN[1],
                         "metric": metric, "shift": shift, "t": t, "n_before": before.size,
                         "n_after": after.size, "crosses_other_change": cross_b or cross_a,
                         "flag": bool(np.isfinite(t) and abs(t) >= T_FLAG_DOC)})
    out = pd.DataFrame(rows)
    return out.assign(shift=out["shift"].round(3), t=out["t"].round(2))


def _scan(d: np.ndarray) -> dict:
    """Per row of d (years WIN[0]..WIN[1]): the split year in SCAN_YEARS with the largest |Welch t|
    of mean(later) - mean(earlier), with at least MIN_SIDE_SCAN valid years on each side."""
    n = len(d)
    best = {"t": np.full(n, np.nan), "year": np.zeros(n, dtype=int), "shift": np.full(n, np.nan),
            "nb": np.zeros(n, dtype=int), "na": np.zeros(n, dtype=int)}
    for b in SCAN_YEARS:
        k = b - WIN[0]
        bef, aft = d[:, :k], d[:, k:]
        nb, na = np.isfinite(bef).sum(axis=1), np.isfinite(aft).sum(axis=1)
        enough = (nb >= MIN_SIDE_SCAN) & (na >= MIN_SIDE_SCAN)
        with np.errstate(invalid="ignore", divide="ignore"):
            mb, ma = np.nansum(bef, axis=1) / nb, np.nansum(aft, axis=1) / na
            vb = np.nansum((bef - mb[:, None]) ** 2, axis=1) / (nb - 1)
            va = np.nansum((aft - ma[:, None]) ** 2, axis=1) / (na - 1)
            se = np.sqrt(va / na + vb / nb)
            t = np.where(enough & (se > 0), (ma - mb) / se, np.nan)
        better = np.isfinite(t) & (~np.isfinite(best["t"]) | (np.abs(t) > np.abs(best["t"])))
        for name, val in (("t", t), ("year", b), ("shift", ma - mb), ("nb", nb), ("na", na)):
            best[name] = np.where(better, val, best[name])
    return best


def audit_breaks(events: pd.DataFrame, city: pd.DataFrame, dser: dict, dser_median: dict,
                 years: np.ndarray, nbr: np.ndarray):
    """Strongest split of d over 1989-2018 per city x metric: mean(d[b..2018]) - mean(d[1989..b-1])."""
    w = _between(years, WIN)
    documented = events.groupby("city_id")["year"].apply(list).to_dict()
    ids, names = city["city_id"].to_numpy(), city["name"].to_numpy()
    parts = []
    for metric in METRICS:
        d = dser[metric][:, w]
        best, alt = _scan(d), _scan(dser_median[metric][:, w])
        parts.append(pd.DataFrame({
            "city_id": ids, "name": names, "metric": metric, "n_valid_1989_2018": np.isfinite(d).sum(axis=1),
            "break_year": best["year"], "shift": best["shift"], "t": best["t"],
            "n_before": best["nb"], "n_after": best["na"],
            "t_median_ref": alt["t"], "break_year_median_ref": alt["year"], "city_row": np.arange(len(d))}))
    out = pd.concat(parts, ignore_index=True)
    found = out["t"].notna()
    out["abs_t"] = out["t"].abs()
    docs, near, near_nb = [], [], []
    for cid, row, b, ok in zip(out["city_id"], out["city_row"], out["break_year"], found):
        docs.append(" ".join(str(y) for y in documented.get(cid, []) if WIN[0] <= y <= WIN[1]))
        near.append(bool(ok and any(abs(y - b) <= 1 for y in documented.get(cid, []))))
        # a change at a neighbour enters this city's reference with weight 1/8
        near_nb.append(" ".join(f"{names[j]}:{y}" for j in nbr[row] for y in documented.get(ids[j], [])
                                if ok and abs(y - b) <= 1))
    out["documented_changes_1989_2018"] = docs
    out["documented_change_within_1y"] = near
    out["neighbor_changes_within_1y"] = near_nb
    out["suspected"] = out["abs_t"] >= T_FLAG_SCAN
    out["suspected_median_ref"] = (out["suspected"] & (out["t_median_ref"].abs() >= T_FLAG_SCAN)
                                   & (np.sign(out["t_median_ref"]) == np.sign(out["t"])))
    for col in ("break_year", "n_before", "n_after"):
        out[col] = out[col].where(found).astype("Int64")
    out["break_year_median_ref"] = out["break_year_median_ref"].where(out["t_median_ref"].notna()).astype("Int64")
    out = out.assign(shift=out["shift"].where(found).round(3), t=out["t"].round(2),
                     abs_t=out["abs_t"].round(2), t_median_ref=out["t_median_ref"].round(2)).drop(columns="city_row")
    out = _metric_sort(out, ["city_id", "metric"])
    return out.sort_values("abs_t", ascending=False, kind="stable", na_position="last").reset_index(drop=True)


# ----------------------------------------------------------------------------- quirks

def audit_quirks(annual: pd.DataFrame, info: pd.DataFrame, events: pd.DataFrame, n_prcp_gap: pd.Series,
                 daily: dict | None) -> pd.DataFrame:
    """What the organizers should hear about: finding, number of rows, one example. Most important first."""
    w = _between(annual["Year"], WIN)
    rows = []

    def add(table, finding, sel_or_n, example):
        n = int(sel_or_n.sum()) if hasattr(sel_or_n, "sum") else int(sel_or_n)
        rows.append({"table": table, "finding": finding, "n": n, "example": example})

    def latest(sel, cols):
        if not sel.any():
            return "none"
        r = annual[sel].sort_values(["Year", "ID"], kind="stable").iloc[-1]
        return f"{r['Name']} {r['Year']}: " + ", ".join(f"{c}={r[c]}" for c in cols)

    # Precipitation invalid (> 10 missing days) in nearly every year while temperature is complete.
    texts = []
    for cid in n_prcp_gap.index:
        a = annual[(annual["ID"] == cid) & w]
        early, last = a[a["Year"] < TRAIN_END], a[a["Year"] == TRAIN_END].iloc[0]
        text = (f"{last['Name']} ({cid}) {WIN[0]}-{TRAIN_END - 1}: Miss Prcp {early['Miss Prcp'].min()}-"
                f"{early['Miss Prcp'].max()} a year while Miss Tmax is 0-{early['Miss Tmax'].max()}, "
                f"{TRAIN_END}: Miss Prcp {last['Miss Prcp']}").replace("0-0,", "0,")
        if daily is not None:
            g = daily["notes"]["prcp_gap"][cid]
            text += (f" (daily {TRAIN_END - 5}-{TRAIN_END - 1}: {g['missing_before']:.0f} missing + "
                     f"{g['dry_before']:.0f} zero-precipitation days a year; {TRAIN_END}: "
                     f"{g['missing_last']} + {g['dry_last']})")
        texts.append(text)
    if texts:
        add("annual_indices, daily", f"precipitation is missing on more than {MAX_MISSING_DAYS} days in "
            f"nearly every year before {TRAIN_END} although temperature is complete, and on none in "
            f"{TRAIN_END} (it looks like trace amounts stored as missing): {len(texts)} cities lose their "
            "precipitation baseline and are not scored", int(n_prcp_gap.sum()), "; ".join(texts))

    # Runs of years without any observation inside a record.
    dead_all = (annual["Miss Tmax"] >= 365) & (annual["Miss Tmin"] >= 365) & (annual["Miss Prcp"] >= 365)
    runs = []
    for name, g in annual.assign(dead=dead_all).groupby("Name"):
        obs = np.flatnonzero(~g["dead"].to_numpy())
        inner = g.iloc[obs[0]:obs[-1] + 1]
        block = (inner["dead"] != inner["dead"].shift()).cumsum()
        for _, run in inner[inner["dead"]].groupby(block[inner["dead"]]):
            runs.append((len(run), name, int(run["Year"].iloc[0]), int(run["Year"].iloc[-1])))
    long_runs = sorted([r for r in runs if r[0] >= 10], key=lambda r: (-r[0], r[1]))

    def listed(name, first, last):       # the station city_info gives for the middle of the run
        mid = pd.Timestamp((first + last) // 2, 7, 1)
        st = info[(info["Name"] == name) & (info["Stn.stDate"] <= mid) & (info["Stn.edDate"] >= mid)]
        return f"city_info: {st['Stn.Name'].iloc[0]}" if len(st) else "no station in city_info"

    add("annual_indices, city_info", "runs of 10 or more consecutive years without a single observation "
        "inside a city's record; for most of them city_info lists a station",
        len(long_runs), "; ".join(f"{n} {a}-{b} ({k} years, {listed(n, a, b)})" for k, n, a, b in long_runs[:6]))
    dead = annual[w & (annual["Miss Tmax"] >= 365) & (annual["Miss Tmin"] >= 365)]
    by_city = dead.groupby("Name")["Year"].agg(["size", "min", _runs]).sort_values(
        ["size", "min"], ascending=[False, True], kind="stable")
    periods = {cid: list(zip(g["Stn.stDate"], g["Stn.edDate"])) for cid, g in info.groupby("ID")}
    n_listed = sum(any(a <= pd.Timestamp(y, 1, 1) and b >= pd.Timestamp(y, 12, 31) for a, b in periods[cid])
                   for cid, y in zip(dead["ID"], dead["Year"]))
    add("annual_indices, city_info", f"city-years in {WIN[0]}-{WIN[1]} without any temperature observation "
        f"({len(by_city)} cities); {n_listed} of them lie inside a station period of city_info", len(dead),
        "; ".join(f"{n} {r['_runs']} ({r['size']})" for n, r in by_city.iterrows()))

    # Sentinels.
    no_p = annual["Miss Prcp"] >= 365
    zero_p = no_p & (annual["ToT Prcp"] == 0)
    add("annual_indices", "ToT Prcp = 0.0, not missing, in years without any precipitation observation "
        f"({int((zero_p & w).sum())} of them in {WIN[0]}-{WIN[1]}); Max 1-day P is -inf there", zero_p,
        latest(zero_p, ["Miss Prcp", "ToT Prcp", "Max 1-day P"]))
    no_t = np.isneginf(annual["Max Tmax"])
    add("annual_indices", "Max Tmax = -inf and Min Tmax = +inf in years without a tmax observation "
        "(Max Tmin / Min Tmin likewise)", no_t, latest(no_t, ["Miss Tmax", "Max Tmax", "Min Tmax"]))
    partial = annual["Avg Temp"].notna() & (annual[["Miss Tmax", "Miss Tmin"]].max(axis=1) > 300)
    add("annual_indices", "Avg Temp is published for years with more than 300 missing days",
        partial, latest(partial, ["Miss Tmax", "Miss Tmin", "Avg Temp", "Max Tmax"]))
    odd = annual["cdd"].isna() & annual["Avg Temp"].notna()
    add("annual_indices", "cdd is missing although Avg Temp is present (no day has both tmax and tmin)",
        odd, latest(odd, ["Miss Tmax", "Miss Tmin", "Avg Temp", "cdd"]))

    frac_max = np.isfinite(annual["Max Tmax"]) & (annual["Max Tmax"] % 1 != 0)
    text = (f"{latest(frac_max & (annual['Year'] == TRAIN_END), ['Max Tmax'])}; before {TRAIN_END}: "
            f"{int((frac_max & (annual['Year'] < TRAIN_END)).sum())} non-integer Max Tmax")
    if daily is not None:
        nt = daily["notes"]
        text += (f"; daily: {nt['tmax']['nonint_last']:,} of {nt['tmax']['obs_last']:,} tmax and "
                 f"{nt['tmin']['nonint_last']:,} of {nt['tmin']['obs_last']:,} tmin values of {TRAIN_END} are "
                 f"non-integer, {nt['tmax']['nonint_before'] + nt['tmin']['nonint_before']} before")
    add("annual_indices, daily", f"{TRAIN_END} temperatures carry one decimal (converted from tenths of °C), "
        f"every earlier value is a whole °F: cities with a non-integer Max Tmax in {TRAIN_END}",
        frac_max & (annual["Year"] == TRAIN_END), text)

    # city_info: station periods that overlap or leave a gap.
    s = info.sort_values(["ID", "Stn.stDate"], kind="stable").copy()
    s["prev_end"] = s.groupby("ID")["Stn.edDate"].shift()
    s["prev_name"] = s.groupby("ID")["Stn.Name"].shift()
    g = s[s["prev_end"].notna()].copy()
    g["gap_days"] = (g["Stn.stDate"] - g["prev_end"]).dt.days - 1
    g = g[g["gap_days"] != 0].sort_values(["gap_days", "ID"], kind="stable")
    if len(g):
        ex = [f"{r['Name']}: {r['prev_name']} ends {r['prev_end']:%Y-%m-%d}, {r['Stn.Name']} starts "
              f"{r['Stn.stDate']:%Y-%m-%d} ({r['gap_days']:+d} days)" for _, r in g.iloc[[-1, 0]].iterrows()]
        add("city_info", "consecutive station periods of a city that overlap (-) or leave a gap (+)",
            len(g), "; ".join(ex))
    jan1 = events["change_date"].str.endswith("-01-01")
    if jan1.any():
        r = events[jan1].sort_values(["year", "city_id"], kind="stable").iloc[-1]
        add("coverage_and_stations", "a station that starts on 1 Jan is counted in Station Changes of the "
            "year in which Station Segment already shows it; after a mid-year start the segment changes "
            "one year later", jan1, f"{r['name']} {r['year']}: Station Segment={r['station_segment']}, "
            f"Station Changes={r['n_changes']} ({r['to_station']} starts {r['change_date']})")
    if daily is not None:
        add("annual_indices", "Avg Temp is the mean of the already rounded Avg Tmax and Avg Tmin: it is not "
            "the 2-decimal rounding of the daily value (off by 0.01)",
            daily["notes"]["n_avg_temp_not_rounded_daily"],
            "; ".join(f"{r['name']} {r['year']}: published {r['published']}, from daily {r['from_daily']:.4f}"
                      for _, r in daily["worst"][daily["worst"]["quantity"] == "annual_avg_temp"].head(1).iterrows()))
        add("daily", "days with tmax below tmin", daily["notes"]["n_tmax_below_tmin"],
            daily["notes"]["tmax_below_tmin_example"])
    upper = sorted(set(annual.loc[annual["Name"].str.isupper(), "Name"]))
    add("all tables", "city names in upper case (all other names are CamelCase)", len(upper), ", ".join(upper))
    return pd.DataFrame(rows)


# ----------------------------------------------------------------------------- report

def _table(header: list[str], rows: list[list[str]]) -> list[str]:
    return (["| " + " | ".join(header) + " |", "|" + "---|" * len(header)]
            + ["| " + " | ".join(r) + " |" for r in rows])


def _by_city(df: pd.DataFrame) -> str:
    """'Belvidere (avg temp, hottest day, cdd: 4)' per city of an unusable.csv subset."""
    parts = []
    for name, g in df.groupby("name", sort=True):
        metrics = "all four" if len(g) == len(METRICS) else ", ".join(SHORT[m] for m in METRICS if m in set(g["metric"]))
        n = g["n_valid_1989_2018"]
        text = f"{n.min()}" if n.min() == n.max() else f"{n.min()}–{n.max()}"
        if g["last_valid_year"].min() < TRAIN_END:
            text += f", last valid {g['last_valid_year'].min()}"
        parts.append(f"{name} ({metrics}: {text})")
    return "; ".join(parts)


def _shift_cell(r) -> str:
    if not np.isfinite(r.t):
        return "n/a"
    text = f"{r.shift:+.{DIGITS[r.metric]}f} ({r.t:+.1f})"
    return f"**{text}**" if r.flag else text


def build_report(res: dict) -> tuple[list[str], list[str]]:
    """(AUDIT.md lines, 30 console lines) from the audit results."""
    cc, city, cov_tab, unusable = res["cross"], res["city"], res["coverage"], res["unusable"]
    units, viol, daily = res["units"], res["violations"], res["daily"]
    outliers, oc = res["outliers"], res["outlier_counts"].set_index("metric")
    changes, breaks, quirks = res["changes"], res["breaks"], res["quirks"]
    nob, weak = unusable[unusable["category"] == "no_baseline"], unusable[unusable["category"] == "weak"]
    win = f"{WIN[0]}–{WIN[1]}"
    n_valid = cov_tab.groupby("metric", sort=False)["n_valid_1989_2018"].sum()
    least = cov_tab.loc[cov_tab["n_valid_all"].idxmin()]
    files = sorted(p.name for p in OUT.glob("*.csv"))
    md = [f"# Data audit of the training tables (everything dated ≤ {TRAIN_END})", "",
          "Written by `PYTHONPATH=code python -m protostar.audit` (deterministic, offline). A city-year is "
          f"**valid** for a metric if each variable the metric uses misses ≤ {MAX_MISSING_DAYS} days and the "
          f"value is finite. Details: {', '.join(f'`{f}`' for f in files)}."]

    # 1 inventory
    bad_keys = [k for k in cc if k.startswith("n_") and any(s in k for s in ("mismatch", "unmatched",
                                                                               "inconsistent", "gaps"))]
    cross_ok = all(cc[k] == 0 for k in bad_keys)
    md += ["", "## 1. Inventory and cross-table checks",
           f"- {len(city)} cities, {cc['n_city_years']:,} city-years, {cc['first_year']}–{TRAIN_END} (records "
           f"start {cc['first_year']}–{cc['first_year_latest']}, all end {TRAIN_END}, no year is skipped); "
           f"{cc['n_station_records']} station records (1–{cc['max_stations']} per city); every city has "
           "coordinates inside the contiguous-US box.",
           f"- The tables agree with each other ({'all checks pass' if cross_ok else 'SOME CHECKS FAIL'}): "
           f"same city-years in `annual_indices` and `coverage_and_stations` ({cc['n_keys_unmatched']} "
           f"unmatched); names/coordinates vs `city_info` ({cc['n_name_mismatch'] + cc['n_coord_mismatch']} "
           f"differ); `Days Both` vs the missing-day counts ({cc['n_days_both_inconsistent']} impossible); "
           f"`Station Changes` vs stations starting that year in `city_info` ({cc['n_station_changes_mismatch']} "
           f"differ); `Station Segment` vs the station in use on 1 Jan ({cc['n_station_segment_mismatch']} differ).",
           f"- Valid city-years in {win} (of {N_CITIES * BASELINE_WINDOW:,}): "
           + ", ".join(f"{SHORT[m]} {n_valid[m]:,}" for m in METRICS) + ". Documented station changes: "
           f"{cc['n_changes_all']} in all, {cc['n_changes_since']} since {CHANGE_FROM}, {cc['n_changes_win']} in {win}."]

    # 2 unusable / weak
    match = "as the organizers say" if len(nob) == ORGANIZERS_NO_BASELINE else \
        f"THE ORGANIZERS SAY {ORGANIZERS_NO_BASELINE}"
    md += ["", f"## 2. Unusable and weak city–metrics (valid years in {win} in parentheses)",
           f"- **No baseline** (< {MIN_VALID_YEARS} valid years in {win}, not scored): **{len(nob)} "
           f"city–metrics, {match}**: {_by_city(nob)}.",
           f"- **Weak** (< {WEAK_MIN_VALID} valid years in {win}, or no valid year in {LAST5[0]}–{LAST5[1]}, or "
           f"last valid year < {TRAIN_END}): **{len(weak)} city–metrics in {weak['name'].nunique()} cities**: "
           f"{_by_city(weak)}.",
           f"- The other {len(cov_tab) - len(unusable)} city–metrics have ≥ {WEAK_MIN_VALID} valid years in "
           f"{win} and a valid {TRAIN_END}. Every city–metric has a valid year somewhere (fewest: "
           f"{least['name']} {SHORT[least['metric']]}, {least['n_valid_all']}), so the fallback always has a level to start from."]

    # 3 units
    rows = [[f"{SHORT[r.metric]} (`{r.column}`)", f"{r.min:g} / {r.median:g} / {r.max:g}",
             f"{r.range_lo:g}–{r.range_hi:g}",
             f"{r.n_out_of_range_valid_1989_2018} / {r.n_out_of_range_valid_all_years} / "
             f"{r.n_out_of_range_invalid_years}", ("OK, " if r.unit_ok else "**FAIL**, ") + r.verdict]
            for r in units.itertuples(index=False)]
    vv = viol[viol["valid"]]
    excess = float(np.maximum(vv["range_lo"] - vv["value"], vv["value"] - vv["range_hi"]).max()) if len(vv) else 0.0
    vtxt = "; ".join(f"{n} {SHORT[m]} " + (f"{g['value'].min():g}" if g["value"].nunique() == 1 else
                                           f"{g['value'].min():g}–{g['value'].max():g}") + f" in {_runs(g['year'])}"
                     for (n, m), g in vv.groupby(["name", "metric"], sort=True)) or "none"
    md += ["", f"## 3. Units: {'all four metrics pass' if units['unit_ok'].all() else 'CHECK FAILED'}"]
    md += _table(["metric", f"valid {win}: min / median / max", "range checked",
                  f"out of range: valid {win} / valid any year / invalid years", "verdict"], rows)
    md += [f"- Valid years outside the range: {vtxt} (at most {excess:g} outside, none in {win}: climate, not "
           "a unit problem). The invalid ones are partial years; all are listed in `units_violations.csv`."]

    # 4 daily
    md += ["", "## 4. Daily recompute"]
    if daily is None:
        md += ["- `data/raw/daily.parquet` is absent: the daily cross-checks were **skipped** in this run "
               "(fetch the file and re-run; any `daily_recompute*.csv` here is from an earlier run)."]
        day_line = "skipped (data/raw/daily.parquet is absent)"
    else:
        s, nt = daily["summary"].set_index("quantity"), daily["notes"]
        counts = [q for q in s.index if q not in METRICS]
        rows = [[", ".join(f"`{q}`" for q in counts), f"{s.loc[counts, 'n_city_years_compared'].min():,}",
                 f"{s.loc[counts, 'max_abs_diff'].max():g}", "0", f"{s.loc[counts, 'n_above_tolerance'].sum()}"]]
        rows += [[f"{SHORT[q]} (`{s.loc[q, 'published_column']}`)", f"{s.loc[q, 'n_city_years_compared']:,}",
                  f"{s.loc[q, 'max_abs_diff']:.4f}", f"{s.loc[q, 'tolerance']:g}", f"{s.loc[q, 'n_above_tolerance']}"]
                 for q in METRICS]
        md += _table(["quantity", "city-years compared", "max abs diff", "tolerance", "above tolerance"], rows)
        n_bad = int(s["n_above_tolerance"].sum() + s["n_published_only"].sum() + s["n_daily_only"].sum())
        verdict = ("`annual_indices` is exactly what `daily` gives" if n_bad == 0
                   else f"{n_bad} city-years DISAGREE, see `daily_recompute_worst.csv`")
        md += [f"- **Verdict: {verdict}** ({nt['n_rows']:,} daily rows = {nt['n_city_years']:,} complete calendar "
               f"years, {nt['n_duplicate_days']} duplicate days; Avg Temp = (mean tmax + mean tmin)/2, cdd = "
               f"Σ max(0, (tmax+tmin)/2 − 65) over days with both). The {s.loc['annual_avg_temp', 'max_abs_diff']:.4f} "
               f"is double rounding: `Avg Temp` is the mean of the rounded `Avg Tmax` and `Avg Tmin`.",
               f"- {TRAIN_END} is stored with one decimal (converted from tenths of °C): "
               f"{nt['tmax']['nonint_last']:,} of {nt['tmax']['obs_last']:,} tmax and {nt['tmin']['nonint_last']:,} "
               f"of {nt['tmin']['obs_last']:,} tmin values are non-integer in {TRAIN_END}, against "
               f"{nt['tmax']['nonint_before'] + nt['tmin']['nonint_before']} of "
               f"{nt['tmax']['obs_before'] + nt['tmin']['obs_before']:,} before; `Max Tmax` {TRAIN_END} is "
               f"non-integer in {nt['n_max_tmax_nonint_last']} cities (a ±0.1 °F effect)."]
        day_line = (f"{nt['n_city_years']:,} city-years; max abs diff "
                    + ", ".join(f"{SHORT[q]} {s.loc[q, 'max_abs_diff']:.4f}" for q in METRICS)
                    + f"; above tolerance {int(s['n_above_tolerance'].sum())}")

    # 5 outliers
    rows = [[r.name, SHORT[r.metric], str(r.year), f"{r.value:g}", f"{r.median:g}", f"{r.z:+.1f}",
             f"{r.neighbor_mean_z:+.1f}", f"{r.miss_tmax} / {r.miss_tmin} / {r.miss_prcp}"]
            for r in outliers.head(6).itertuples(index=False)]
    local = outliers[~outliers["regional"]]
    md += ["", f"## 5. Outliers among valid years (robust z on the {win} median and 1.4826·MAD)"]
    md += _table(["city", "metric", "year", "value", f"median {win}", "z", "mean z of the 8 nearest cities",
                  "missing days tmax / tmin / prcp"], rows)
    md += [f"- |z| ≥ {Z_LIST:g} in {win}: **{len(outliers)}** of {int(oc['n_valid_win'].sum()):,} valid values ("
           + ", ".join(f"{SHORT[m]} {oc.loc[m, 'n_list']}" for m in METRICS) + f"); {len(outliers) - len(local)} "
           f"are regional (the neighbours' mean z is ≥ {Z_REGIONAL:g} the same way), {len(local)} are local: "
           + "; ".join(f"{r.name} {SHORT[r.metric]} {r.year} ({r.value:g}, z {r.z:+.1f}, neighbours "
                       f"{r.neighbor_mean_z:+.2f})" for r in local.head(5).itertuples(index=False))
           + f"{' …' if len(local) > 5 else ''}. No value is removed. |z| ≥ {Z_COUNT:g} over the whole record: "
           f"{int(oc['n_count_all'].sum())} (" + ", ".join(f"{SHORT[m]} {oc.loc[m, 'n_count_all']}" for m in METRICS)
           + f"), only {int(oc['n_count_win'].sum())} of them in {win}: the early record sits far from today's level.",
           "- Valid years with 1–10 missing days show no bias against complete years (|z| ≥ "
           f"{Z_LIST:g} count of years, mean z): " + "; ".join(
               f"{SHORT[m]} {oc.loc[m, 'n_list_gappy']} of {oc.loc[m, 'n_gappy']:,}, {oc.loc[m, 'mean_z_gappy']:+.2f} "
               f"vs {oc.loc[m, 'n_list_clean']} of {oc.loc[m, 'n_clean']:,}, {oc.loc[m, 'mean_z_clean']:+.2f}"
               for m in METRICS) + "."]

    # 6 documented station changes
    cw = changes[changes["in_1989_2018"]]
    rows = []
    for (name, _), g in cw.groupby(["name", "year"], sort=True):
        g = g.set_index("metric")
        first = g.iloc[0]
        n_txt = f"{g.loc['annual_avg_temp', 'n_before']}/{g.loc['annual_avg_temp', 'n_after']}"
        if (g["n_before"].nunique() > 1) or (g["n_after"].nunique() > 1):
            n_txt += f" (precip {g.loc['total_precip_in', 'n_before']}/{g.loc['total_precip_in', 'n_after']})"
        rows.append([name + ("†" if g["crosses_other_change"].any() else ""), first["change_date"],
                     f"{first['from_station']} → {first['to_station']}", n_txt]
                    + [_shift_cell(r) for r in g.loc[list(METRICS)].reset_index().itertuples(index=False)])
    flags = cw.groupby("metric", sort=False)["flag"].sum()
    estim = cw.groupby("metric", sort=False)["t"].apply(lambda s: int(s.notna().sum()))
    md += ["", f"## 6. Documented station changes {win}: shift (Welch t), bold = |t| ≥ {T_FLAG_DOC:g}"]
    md += _table(["city", "new station from", "from → to", "valid years before/after",
                  "avg temp °F", "precip in", "hottest day °F", "cdd"], rows)
    md += [f"- shift = mean(d after) − mean(d before); d = city value − mean anomaly (vs own {win} mean) of the "
           f"{K_NEIGHBORS} nearest cities with a valid value that year; valid years among the {SIDE_YEARS} "
           f"calendar years on each side, change year excluded, ≥ {MIN_SIDE_DOC} per side (else n/a); a side "
           "stops at another documented change of the city unless too few years remain (†).",
           f"- |t| ≥ {T_FLAG_DOC:g}: " + ", ".join(f"{SHORT[m]} {flags[m]} of {estim[m]} estimable" for m in METRICS)
           + f" (of {cw.groupby(['name', 'year']).ngroups} changes). `station_changes.csv` has all "
           f"{changes.groupby(['name', 'year']).ngroups} changes since {CHANGE_FROM}."]

    # 7 suspected breaks
    sus = breaks[breaks["suspected"]]
    undoc = sus[~sus["documented_change_within_1y"]]
    rows = [[r.name, SHORT[r.metric], str(r.break_year), f"{r.shift:+.{DIGITS[r.metric]}f}", f"{r.t:+.1f}",
             f"{r.t_median_ref:+.1f} ({r.break_year_median_ref})", f"{r.n_before}/{r.n_after}",
             r.documented_changes_1989_2018 or "–", r.neighbor_changes_within_1y or "–"]
            for r in undoc.head(15).itertuples(index=False)]
    doc_txt = ", ".join(f"{r.name} {SHORT[r.metric]} {r.break_year}" for r in
                        sus[sus["documented_change_within_1y"]].itertuples(index=False)) or "none"
    md += ["", f"## 7. Strongest suspected undocumented breaks (scan of d over {win})"]
    md += _table(["city", "metric", "first year of later segment", "shift", "t",
                  "t (year) with the neighbours' median as reference", "valid years before/after",
                  f"documented changes of the city {win}", "neighbour change within ±1 y"], rows)
    md += [f"- For each city–metric the split year b in {SCAN_YEARS[0]}–{SCAN_YEARS[-1]} with the largest "
           f"|Welch t| of mean(d[b..{WIN[1]}]) − mean(d[{WIN[0]}..b−1]), ≥ {MIN_SIDE_SCAN} valid years a side. "
           f"**max |t| ≥ {T_FLAG_SCAN:g}: {len(sus)} of {int(breaks['t'].notna().sum())} city–metrics** ("
           + ", ".join(f"{SHORT[m]} {int((sus['metric'] == m).sum())}" for m in METRICS)
           + f"), {int(sus['suspected_median_ref'].sum())} of them also against the neighbours' median; "
           f"{len(sus) - len(undoc)} have a documented change within ±1 year ({doc_txt}).",
           "- Read with care: the maximum over 20 candidate years inflates t, a slow drift relative to the "
           "neighbours (urban warming) looks like a break, and a neighbour's break enters with weight 1/8."]

    # 8 handling
    md += ["", "## 8. How we handle it",
           "- **Valid-year rule everywhere**: training and backtest scoring use only valid city-years "
           f"(≤ {MAX_MISSING_DAYS} missing days per variable the metric uses), like the organizers.",
           "- **±inf → missing**: non-finite values never count as valid; the 0.0 totals of unobserved years "
           "fall to the missing-day rule.",
           "- **Fallback for city–metrics without a baseline** (`models.fallback`): the mean of the city's last "
           "10 valid years, reaching back over the gap, plus the change its 8 nearest fitted cities forecast "
           "relative to those same years (see `unusable.csv`; checked against NOAA's records in "
           "`reports/ghcnd/GHCND.md`). City–metrics with a baseline are modeled on their valid years.",
           "- **Station shifts are reported, not corrected** (the default): the forecast uses the published "
           "series unless the backtest shows that a correction helps.",
           f"- **No city is dropped**: all {N_FORECAST_ROWS:,} rows ({N_CITIES} cities × {len(METRICS)} metrics × "
           f"{len(FORECAST_YEARS)} years) are predicted, including the {len(nob)} that are not scored."]

    # 9 organizers
    md += ["", "## 9. For the organizers (`quirks.csv`: finding [rows]: example)"]
    room = MD_MAX_LINES - len(md)
    shown = quirks if len(quirks) <= room else quirks.head(room - 1)
    md += [f"- {r.finding} [{r.n:,}]" + (f": {r.example}." if r.example else ".") for r in shown.itertuples(index=False)]
    if len(shown) < len(quirks):
        md += [f"- … and {len(quirks) - len(shown)} smaller ones in `quirks.csv`."]
    assert len(md) <= MD_MAX_LINES, f"AUDIT.md has {len(md)} lines"

    # console: exactly 30 lines
    u = units.set_index("metric")
    big = cw[cw["t"].notna()].assign(a=lambda d: d["t"].abs()).sort_values("a", ascending=False, kind="stable")
    where = OUT.relative_to(ROOT) if OUT.is_relative_to(ROOT) else OUT
    out = [f"protostar audit -> {where} ({len(files) + 1} files, AUDIT.md {len(md)} lines)",
           f" 1 cities {len(city)}, city-years {cc['n_city_years']:,} ({cc['first_year']}-{TRAIN_END}), station "
           f"records {cc['n_station_records']}; coordinates inside the contiguous-US box",
           f" 1 cross-table checks: {'all pass' if cross_ok else 'FAIL'} (keys, names, coordinates, Days Both, "
           "Station Changes, Station Segment)",
           f" 2 valid city-years {WIN[0]}-{WIN[1]} of {N_CITIES * BASELINE_WINDOW:,}: "
           + ", ".join(f"{SHORT[m]} {n_valid[m]:,}" for m in METRICS),
           f" 3 no baseline: {len(nob)} city-metrics (organizers: {ORGANIZERS_NO_BASELINE}): {_by_city(nob)}",
           f" 3 weak: {len(weak)} city-metrics in {weak['name'].nunique()} cities: "
           + ", ".join(sorted(weak["name"].unique())),
           f" 4 units {'OK' if units['unit_ok'].all() else 'FAIL'} (min/median/max valid): "
           + "; ".join(f"{SHORT[m]} {u.loc[m, 'min']:g}/{u.loc[m, 'median']:g}/{u.loc[m, 'max']:g}" for m in METRICS),
           f" 4 checks: max |Avg Temp - (Avg Tmax+Avg Tmin)/2| {res['checks']['identity_max_abs_diff']:.3f}; "
           f"corr(temp, lat) {res['checks']['lat_corr']:.2f}; cdd/(365(T-65)) >= {res['checks']['cdd_ratio_min']:.2f}; "
           f"out of range: {int(u['n_out_of_range_valid_1989_2018'].sum())} valid in window, "
           f"{int(u['n_out_of_range_valid_all_years'].sum())} valid any year",
           f" 5 daily recompute: {day_line}"]
    if daily is None:
        out += [" 5 (no daily file: missing-day counts and the 2018 decimals were not checked)"]
    else:
        nt = daily["notes"]
        out += [f" 5 Miss Tmax/Tmin/Prcp and Days Both identical; {TRAIN_END} non-integer tmax "
                f"{nt['tmax']['nonint_last']:,}/{nt['tmax']['obs_last']:,}, tmin {nt['tmin']['nonint_last']:,}/"
                f"{nt['tmin']['obs_last']:,}; earlier years {nt['tmax']['nonint_before'] + nt['tmin']['nonint_before']}"]
    out += [f" 6 outliers |z|>={Z_LIST:g} in window: {len(outliers)} ("
            + ", ".join(f"{SHORT[m]} {oc.loc[m, 'n_list']}" for m in METRICS)
            + f"), {len(local)} local; |z|>={Z_COUNT:g} whole record: {int(oc['n_count_all'].sum())}",
            " 6 top: " + "; ".join(f"{r.name} {SHORT[r.metric]} {r.year} {r.value:g} (z {r.z:+.1f})"
                                   for r in outliers.head(4).itertuples(index=False)),
            f" 7 documented station changes: {cc['n_changes_since']} since {CHANGE_FROM}, {cc['n_changes_win']} in "
            f"window; |t|>={T_FLAG_DOC:g} in window: "
            + ", ".join(f"{SHORT[m]} {flags[m]}/{estim[m]}" for m in METRICS)]
    out += [f" 7   {r.name} {r.change_date} {SHORT[r.metric]}: {r.shift:+.{DIGITS[r.metric]}f} {UNITS[r.metric]} "
            f"(t {r.t:+.1f}, n {r.n_before}/{r.n_after})" for r in big.head(5).itertuples(index=False)]
    out += [f" 8 suspected breaks (max |t|>={T_FLAG_SCAN:g}): {len(sus)} city-metrics ("
            + ", ".join(f"{SHORT[m]} {int((sus['metric'] == m).sum())}" for m in METRICS)
            + f"), {int(sus['suspected_median_ref'].sum())} also vs the neighbours' median, "
            f"{len(sus) - len(undoc)} at a documented change"]
    out += [f" 8   {r.name} {SHORT[r.metric]} {r.break_year}: {r.shift:+.{DIGITS[r.metric]}f} {UNITS[r.metric]} "
            f"(t {r.t:+.1f})" for r in undoc.head(6).itertuples(index=False)]
    out += [f" 9 quirks for the organizers: {len(quirks)} (quirks.csv), e.g."]
    out += [f" 9   [{r.n:,}] {r.finding[:150]}" for r in quirks.itertuples(index=False)]
    out = out[:29] + [""] * (29 - len(out)) + ["(elapsed)"]   # always 30 lines; main() fills the last
    return md, out


# ----------------------------------------------------------------------------- main

def run() -> dict:
    """Run every check, write the CSV files and return the results."""
    OUT.mkdir(parents=True, exist_ok=True)
    annual, info, cov = load_annual(), load_city_info(), load_coverage()
    long = long_with_missing(annual)
    city = audit_cities(annual, info)
    events = station_events(cov, info)
    res = {"city": city, "cross": cross_checks(annual, info, cov, events)}
    res["coverage"] = audit_coverage(long)
    res["unusable"] = audit_unusable(res["coverage"])
    res["units"], res["violations"], res["checks"] = audit_units(annual, long, city)
    n_prcp_gap = prcp_gap_cities(annual)
    res["daily"] = audit_daily(annual, cov, list(n_prcp_gap.index))

    pans = panels(long)
    years = pans["cdd"].years
    assert all((p.city_ids == city["city_id"].to_numpy()).all() and (p.years == years).all()
               for p in pans.values())
    nbr, _ = nearest_neighbors(city)
    dser = {m: neighbor_difference(p.y, years, nbr) for m, p in pans.items()}
    dser_median = {m: neighbor_difference(p.y, years, nbr, median=True) for m, p in pans.items()}
    res["outliers"], res["outlier_counts"] = audit_outliers(long, city, nbr)
    res["changes"] = audit_station_changes(events, city, dser, years)
    res["breaks"] = audit_breaks(events, city, dser, dser_median, years, nbr)
    res["quirks"] = audit_quirks(annual, info, events, n_prcp_gap, res["daily"])

    _write(city, "cities.csv")
    _write(res["coverage"], "coverage.csv")
    _write(res["unusable"], "unusable.csv")
    _write(res["units"], "units.csv")
    _write(res["violations"], "units_violations.csv")
    if res["daily"] is not None:
        _write(res["daily"]["summary"], "daily_recompute.csv")
        _write(res["daily"]["worst"], "daily_recompute_worst.csv")
    _write(res["outliers"], "outliers.csv")
    _write(res["changes"], "station_changes.csv")
    _write(res["breaks"], "undocumented_breaks.csv")
    _write(res["quirks"], "quirks.csv")
    return res


def main() -> None:
    t0 = time.time()
    res = run()
    md, console = build_report(res)
    (OUT / "AUDIT.md").write_text("\n".join(md) + "\n", encoding="utf-8")
    console[-1] = f"done in {time.time() - t0:.1f} s"
    print("\n".join(console))
    # The reports are written first; a failed unit check still stops the pipeline.
    assert res["units"]["unit_ok"].all(), "unit sanity failed: see reports/audit/units.csv"


if __name__ == "__main__":
    main()