-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathverify_all_sections.py
More file actions
1536 lines (1331 loc) · 51.9 KB
/
Copy pathverify_all_sections.py
File metadata and controls
1536 lines (1331 loc) · 51.9 KB
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
#!/usr/bin/env python3
"""
verify_all_sections.py - Comprehensive data verification for the COEQWAL data explorer.
Computes expected values from CalSim DV and SV reference CSVs, queries the
database for actual ETL output, and produces a JSON verification report with
automated PASS/FAIL per metric.
Usage:
python verify_all_sections.py --scenario s0020
python verify_all_sections.py --scenario s0020 --csv-only
python verify_all_sections.py --all-scenarios --report-dir audits/verification_reports
Requires:
- Reference CSVs: DV (calsim output) and SV (sv input) in etl/reference/ or --ref-dir
- DATABASE_URL env var for DB comparison (skip with --csv-only)
- psycopg2 (pip install psycopg2-binary)
Data sources after ETL refactoring:
- DV: delivery (DN_*, D_*), shortage (SHRTG_*, SHORT_*), AG demand (AW_*),
AG GW pumping (GP_*), reservoir storage (S_*),
env flows (C_*), CWS aggregates (DEL_*, SHORT_*),
Delta outflow (NDO), X2 (X2_PRV_KM), salinity (EM/JP/RS/CO_EC_MONTH, *EC_MAX14DAY)
- SV: urban demand (UD_*)
"""
import argparse
import json
import logging
import os
import sys
from dataclasses import dataclass, field, asdict
from datetime import datetime, timezone
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import numpy as np
import pandas as pd
# Optional: only RealDictCursor is referenced directly. The connection itself
# is opened via etl.common.db.get_db_connection.
try:
from psycopg2.extras import RealDictCursor
except ImportError:
RealDictCursor = None # type: ignore[assignment]
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
log = logging.getLogger(__name__)
# Constants
# Add the repo root to sys.path so `etl.common` is importable when this
# script is run directly. See etl/common/__init__.py for the rationale.
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from units import CFS_TO_TAF_PER_DAY # noqa: E402
from etl.common import get_db_connection # noqa: E402
from etl.common.etl_scenarios import ETL_SCENARIOS as ALL_SCENARIOS # noqa: E402
SHORTAGE_THRESHOLD_TAF = 0.1
ABS_TOL = 0.5
REL_TOL = 0.01
SCENARIO_RUN_IDS = {
"s0020": "s0020_DCRadjBL_2020LU_wTUCP",
"s0028": "s0028_CVgwLimit_SGMALU_wTUCP",
}
# ---------------------------------------------------------------------------
# Roadmap: the per-section variable lists below are hand-curated. The
# long-term goal is to derive them from `domain_family_map` or the seed
# CSVs (`channel_entity.csv`, `du_urban_entity.csv`,
# `du_agriculture_entity.csv`, `du_refuge_entity.csv`) so a new aggregate
# variable added to the ETL is automatically covered here instead of
# silently under-covered. Until then, treat this block as the verifier's
# scope contract: when the ETL adds or removes a variable, update the
# matching list here so the JSON report stays meaningful.
# ---------------------------------------------------------------------------
# Variable lists from COEQWAL_V3/notebooks/variable_groupings.csv
RESERVOIR_VARS = {
"SHSTA": ("S_SHSTA", 4552.0),
"OROVL": ("S_OROVL", 3424.8),
"FOLSM": ("S_FOLSM", 967.0),
"TRNTY": ("S_TRNTY", 2448.0),
"MELON": ("S_MELON", 2420.0),
"MLRTN": ("S_MLRTN", 524.0),
# San Luis CVP/SWP capacities disagree between sources. These match the
# documented federal/state shares (966 + 1062). reservoir_entity, which the
# ETL divides by, instead holds 1062 / 979 (forced to sum to the 2041
# total). Kept at the documented split so this section surfaces the
# mismatch rather than hiding it. Pending modeler confirmation of the
# authoritative per-share capacity.
"SLUIS_CVP": ("S_SLUIS_CVP", 966.0),
"SLUIS_SWP": ("S_SLUIS_SWP", 1062.0),
}
FLOW_VARS = [
"C_SAC041",
"C_SAC085",
"C_FTR003",
"C_SAC257",
"C_KSWCK",
"C_AMR004",
"C_SJR070",
"C_STS017",
"C_TUO003",
"C_SJR115",
"C_MCD005",
]
CWS_AGGREGATE_VARS = [
("DEL_SWP_PMI", "SWP M&I Total"),
("DEL_CVP_PMI_N", "CVP M&I NOD"),
("DEL_CVP_PMI_S", "CVP M&I SOD"),
("DEL_SWP_PMI_S", "SWP M&I SOD"),
]
CWS_SHORTAGE_VARS = [
("SHORT_SWP_TOTA", "SWP Shortage Total"),
("SHORT_CVP_TOT_N", "CVP Shortage NOD"),
("SHORT_CVP_TOT_S", "CVP Shortage SOD"),
]
AG_AGGREGATE_VARS = [
("DEL_SWP_PAG", "SWP AG Total"),
("DEL_SWP_PAG_N", "SWP AG NOD"),
("DEL_SWP_PAG_S", "SWP AG SOD"),
("DEL_CVP_PAG_N", "CVP AG NOD"),
("DEL_CVP_PAG_S", "CVP AG SOD"),
]
AG_AGGREGATE_NEW_VARS = [
("cvp_psc_n", "DEL_CVP_PSC_N", "CVP Settlement NOD"),
("cvp_pex_s", "DEL_CVP_PEX_S", "CVP Exchange SOD"),
]
AG_COMPUTED_AGGREGATES = {
"nod_ag": {
"delivery_components": ["DEL_CVP_PAG_N", "DEL_SWP_PAG_N", "DEL_CVP_PSC_N"],
"shortage_components": [
"SHORT_CVP_PAG_N",
"SHORT_SWP_PAG_N",
"SHORT_CVP_PSC_N",
],
},
"sod_ag": {
"delivery_components": ["DEL_CVP_PAG_S", "DEL_SWP_PAG_S", "DEL_CVP_PEX_S"],
"shortage_components": [
"SHORT_CVP_PAG_S",
"SHORT_SWP_PAG_S",
"SHORT_CVP_PEX_S",
],
},
}
DELTA_OUTFLOW_VARS = [("ndo", "NDO", "CFS")]
DELTA_X2_VARS = [("x2", "X2_PRV_KM", "KM")]
DELTA_SALINITY_VARS = [
("em_ec", "EM_EC_MONTH", "UMHOS/CM"),
("jp_ec", "JP_EC_MONTH", "UMHOS/CM"),
("rs_ec", "RS_EC_MONTH", "UMHOS/CM"),
("co_ec", "CO_EC_MONTH", "UMHOS/CM"),
("banks_ec", "BANKSEC_MAX14DAY", "UMHOS/CM"),
("tracy_ec", "TRACYEC_MAX14DAY", "UMHOS/CM"),
]
SAMPLE_CWS_DUS = ["02_PU", "26S_PU1", "71_PU1", "GDPUD_NU", "MWD", "CCWD"]
SAMPLE_AG_DUS = ["02_PA", "08N_PA", "61_PA1", "71_PA1", "02_NA", "64_PA1"]
# Data Classes───
@dataclass
class Check:
metric: str
section: str
entity: str
expected: Optional[float]
actual: Optional[float] = None
abs_tol: float = ABS_TOL
rel_tol: float = REL_TOL
@property
def status(self) -> str:
if self.expected is None:
return "skip"
if self.actual is None:
return "no_db"
if np.isnan(self.expected) and np.isnan(self.actual):
return "pass"
if np.isnan(self.expected) or np.isnan(self.actual):
return "fail"
if np.isclose(self.expected, self.actual, atol=self.abs_tol, rtol=self.rel_tol):
return "pass"
return "fail"
@dataclass
class Report:
scenario_id: str
timestamp: str = field(
default_factory=lambda: datetime.now(timezone.utc).isoformat()
)
checks: List[Check] = field(default_factory=list)
csv_files_used: Dict[str, str] = field(default_factory=dict)
db_connected: bool = False
@property
def summary(self) -> Dict[str, int]:
statuses = [c.status for c in self.checks]
return {
"total": len(statuses),
"pass": statuses.count("pass"),
"fail": statuses.count("fail"),
"skip": statuses.count("skip"),
"no_db": statuses.count("no_db"),
}
def add(
self,
metric: str,
section: str,
entity: str,
expected: Optional[float],
actual: Optional[float] = None,
abs_tol: float = ABS_TOL,
rel_tol: float = REL_TOL,
):
self.checks.append(
Check(
metric=metric,
section=section,
entity=entity,
expected=expected,
actual=actual,
abs_tol=abs_tol,
rel_tol=rel_tol,
)
)
def to_dict(self) -> dict:
checks = []
for c in self.checks:
d = asdict(c)
d["status"] = c.status
checks.append(d)
return {
"scenario_id": self.scenario_id,
"timestamp": self.timestamp,
"db_connected": self.db_connected,
"csv_files_used": self.csv_files_used,
"summary": self.summary,
"checks": checks,
}
def print_summary(self):
s = self.summary
total = s["total"]
print(f"\n{'=' * 70}")
print(f"VERIFICATION SUMMARY for {self.scenario_id}")
print(f"{'=' * 70}")
print(f" Total checks: {total}")
print(f" PASS: {s['pass']}")
print(f" FAIL: {s['fail']}")
print(f" Skipped: {s['skip']}")
print(f" No DB data: {s['no_db']}")
if total > 0:
pct = s["pass"] / max(total - s["skip"], 1) * 100
print(f" Pass rate: {pct:.1f}%")
failures = [c for c in self.checks if c.status == "fail"]
if failures:
print(f"\nFAILED CHECKS ({len(failures)}):")
for c in failures[:20]:
diff = abs(c.expected - c.actual) if c.actual is not None else None
print(
f" [{c.section}] {c.entity} / {c.metric}: "
f"expected={c.expected:.4f}, actual={c.actual:.4f}, "
f"diff={diff:.4f}"
)
if len(failures) > 20:
print(f" ... and {len(failures) - 20} more")
# CSV parsing
def parse_calsim_csv(file_path: str) -> Tuple[pd.DataFrame, pd.Series]:
"""
Parse a CalSim DSS-export CSV (DV, SV, DELIVERIES, or DEMANDS).
Returns (data_df, units_series).
"""
header_df = pd.read_csv(file_path, header=None, nrows=7, low_memory=False)
var_names = header_df.iloc[1].tolist()
units_row = header_df.iloc[6].tolist() if len(header_df) >= 7 else []
col_names = []
seen: Dict[str, int] = {}
col_units = []
for idx, var in enumerate(var_names):
unit = units_row[idx] if idx < len(units_row) else "UNKNOWN"
if var in seen:
col_names.append(f"{var}_{seen[var]}")
seen[var] += 1
else:
col_names.append(str(var))
seen[var] = 1
col_units.append(str(unit).strip())
data_df = pd.read_csv(file_path, header=None, skiprows=7, low_memory=False)
if len(data_df.columns) > len(col_names):
col_names.extend(
[f"_extra_{i}" for i in range(len(data_df.columns) - len(col_names))]
)
elif len(data_df.columns) < len(col_names):
col_names = col_names[: len(data_df.columns)]
col_units = col_units[: len(data_df.columns)]
data_df.columns = col_names
first_col = col_names[0]
data_df["DateTime"] = pd.to_datetime(data_df[first_col], errors="coerce")
data_df = data_df.dropna(subset=["DateTime"])
period_date = data_df["DateTime"].where(
data_df["DateTime"].dt.day != 1,
data_df["DateTime"] - pd.Timedelta(days=1),
)
data_df["CalendarMonth"] = period_date.dt.month
data_df["CalendarYear"] = period_date.dt.year
data_df["WaterYear"] = data_df["CalendarYear"].where(
data_df["CalendarMonth"] < 10,
data_df["CalendarYear"] + 1,
)
data_df["DaysInMonth"] = period_date.dt.days_in_month
units_series = pd.Series(col_units, index=col_names)
return data_df, units_series
def get_column_taf(
df: pd.DataFrame, units: pd.Series, col_name: str
) -> Optional[pd.Series]:
if col_name not in df.columns:
return None
raw = pd.to_numeric(df[col_name], errors="coerce")
unit = str(units.get(col_name, "UNKNOWN")).upper()
if unit == "TAF":
return raw
elif unit == "CFS":
return raw * df["DaysInMonth"] * CFS_TO_TAF_PER_DAY
return raw
def get_column_cfs(
df: pd.DataFrame, units: pd.Series, col_name: str
) -> Optional[pd.Series]:
if col_name not in df.columns:
return None
return pd.to_numeric(df[col_name], errors="coerce")
def annual_avg_taf(series: pd.Series, water_years: pd.Series) -> Optional[float]:
if series is None or series.dropna().empty:
return None
annual = series.groupby(water_years).sum()
return round(float(annual.mean()), 4)
def monthly_avg(series: pd.Series, months: pd.Series, month: int) -> Optional[float]:
if series is None:
return None
mask = months == month
vals = series[mask].dropna()
if vals.empty:
return None
return round(float(vals.mean()), 4)
# DB Helpers─────
def connect_db() -> Optional[object]:
url = os.environ.get("DATABASE_URL")
if not url:
log.warning("DATABASE_URL not set; skipping DB verification")
return None
try:
conn = get_db_connection(db_url=url)
log.info("Connected to database")
return conn
except Exception as e:
log.error(f"DB connection failed: {e}")
return None
def db_query(conn, sql: str, params: tuple = ()) -> List[dict]:
if conn is None:
return []
with conn.cursor(cursor_factory=RealDictCursor) as cur:
cur.execute(sql, params)
return [dict(row) for row in cur.fetchall()]
# Section: Reservoirs
def verify_reservoirs(
report: Report, dv_df: Optional[pd.DataFrame], dv_units: Optional[pd.Series], conn
) -> None:
section = "reservoirs"
log.info(f"Verifying {section}...")
for short_code, (calsim_var, capacity) in RESERVOIR_VARS.items():
# Expected values from CSV
exp_apr = None
exp_sep = None
exp_ann = None
exp_apr_pct = None
exp_sep_pct = None
if dv_df is not None and calsim_var in dv_df.columns:
raw = pd.to_numeric(dv_df[calsim_var], errors="coerce")
exp_apr = monthly_avg(raw, dv_df["CalendarMonth"], 4)
exp_sep = monthly_avg(raw, dv_df["CalendarMonth"], 9)
exp_ann = round(float(raw.mean()), 4) if not raw.dropna().empty else None
if exp_apr is not None and capacity > 0:
exp_apr_pct = round(exp_apr / capacity * 100, 4)
if exp_sep is not None and capacity > 0:
exp_sep_pct = round(exp_sep / capacity * 100, 4)
# DB actual values
act_apr = None
act_sep = None
act_ann = None
act_apr_pct = None
act_sep_pct = None
if conn:
rows = db_query(
conn,
"""
SELECT rps.april_avg_taf, rps.september_avg_taf,
rps.annual_avg_taf, rps.capacity_taf
FROM reservoir_period_summary rps
JOIN reservoir_entity re ON rps.reservoir_entity_id = re.id
WHERE rps.scenario_short_code = %s AND re.short_code = %s
""",
(report.scenario_id, short_code),
)
if rows:
r = rows[0]
act_apr = _safe_round(r.get("april_avg_taf"))
act_sep = _safe_round(r.get("september_avg_taf"))
act_ann = _safe_round(r.get("annual_avg_taf"))
cap = r.get("capacity_taf")
if act_apr is not None and cap and cap > 0:
act_apr_pct = round(act_apr / float(cap) * 100, 4)
if act_sep is not None and cap and cap > 0:
act_sep_pct = round(act_sep / float(cap) * 100, 4)
report.add("april_avg_taf", section, short_code, exp_apr, act_apr)
report.add("september_avg_taf", section, short_code, exp_sep, act_sep)
report.add("annual_avg_taf", section, short_code, exp_ann, act_ann)
# KNOWN ISSUE: San Luis pct_capacity is skipped. reservoir_entity holds
# CVP/SWP capacities (1062/979) that disagree with the model's
# documented shares (966/1062), so this comparison cannot pass until the
# capacity source is reconciled. The avg_taf checks above still run.
# See README "Known verification discrepancies". The model's Jupyter
# notebooks are the source of truth for the capacity.
if short_code in ("SLUIS_CVP", "SLUIS_SWP"):
log.warning(
f"KNOWN ISSUE: skipping {short_code} pct_capacity. The San Luis "
"CVP/SWP capacity split is unconfirmed. Check with the Water "
"Allocation Modeling Team for the correct split. Then update the "
"SLUIS_CVP and SLUIS_SWP capacity (reservoir_entity seed or "
"CAPACITY_OVERRIDES) and the RESERVOIR_VARS values here to match. "
"Re-run the reservoirs ETL for all scenarios with "
"'python etl/statistics/reservoirs/main.py --all-scenarios'. "
"Remove this skip guard. See the 'Known verification "
"discrepancies' roadmap in etl/statistics/README.md."
)
else:
report.add(
"april_pct_capacity", section, short_code, exp_apr_pct, act_apr_pct
)
report.add(
"september_pct_capacity", section, short_code, exp_sep_pct, act_sep_pct
)
# Spill frequency
if conn:
for short_code, (calsim_var, _cap) in RESERVOIR_VARS.items():
rows = db_query(
conn,
"""
SELECT rps.spill_frequency_pct
FROM reservoir_period_summary rps
JOIN reservoir_entity re ON rps.reservoir_entity_id = re.id
WHERE rps.scenario_short_code = %s AND re.short_code = %s
""",
(report.scenario_id, short_code),
)
act_spill = (
_safe_round(rows[0].get("spill_frequency_pct")) if rows else None
)
report.add("spill_frequency_pct", section, short_code, None, act_spill)
# Section: CWS aggregates
def verify_cws_aggregates(
report: Report, dv_df: Optional[pd.DataFrame], dv_units: Optional[pd.Series], conn
) -> None:
section = "cws_aggregate"
log.info(f"Verifying {section}...")
for var, label in CWS_AGGREGATE_VARS:
exp_ann_taf = None
if dv_df is not None and var in dv_df.columns:
taf_series = get_column_taf(dv_df, dv_units, var)
exp_ann_taf = annual_avg_taf(taf_series, dv_df["WaterYear"])
act_ann_taf = None
act_reliability = None
if conn:
rows = db_query(
conn,
"""
SELECT p.annual_delivery_avg_taf, p.reliability_pct
FROM cws_aggregate_period_summary p
JOIN cws_aggregate_entity e ON p.cws_aggregate_id = e.id
WHERE p.scenario_short_code = %s AND e.short_code = %s
""",
(report.scenario_id, var),
)
if rows:
act_ann_taf = _safe_round(rows[0].get("annual_delivery_avg_taf"))
act_reliability = _safe_round(rows[0].get("reliability_pct"))
report.add("annual_delivery_avg_taf", section, var, exp_ann_taf, act_ann_taf)
if act_reliability is not None:
report.add("reliability_pct", section, var, None, act_reliability)
for var, label in CWS_SHORTAGE_VARS:
exp_short_taf = None
if dv_df is not None and var in dv_df.columns:
taf_series = get_column_taf(dv_df, dv_units, var)
exp_short_taf = annual_avg_taf(taf_series, dv_df["WaterYear"])
report.add("annual_shortage_avg_taf", section, var, exp_short_taf, None)
# Section: M&I contractors
def verify_mi_contractors(report: Report, conn) -> None:
section = "mi_contractors"
log.info(f"Verifying {section}...")
if not conn:
return
rows = db_query(
conn,
"""
SELECT mc.short_code, p.annual_delivery_avg_taf,
p.annual_shortage_avg_taf, p.reliability_pct,
p.avg_pct_demand_met, p.annual_demand_avg_taf
FROM mi_contractor_period_summary p
JOIN mi_contractor mc ON p.mi_contractor_code = mc.short_code
WHERE p.scenario_short_code = %s
ORDER BY mc.short_code
""",
(report.scenario_id,),
)
for r in rows:
code = r["short_code"]
report.add(
"annual_delivery_avg_taf",
section,
code,
None,
_safe_round(r.get("annual_delivery_avg_taf")),
)
report.add(
"annual_shortage_avg_taf",
section,
code,
None,
_safe_round(r.get("annual_shortage_avg_taf")),
)
report.add(
"reliability_pct",
section,
code,
None,
_safe_round(r.get("reliability_pct")),
)
report.add(
"avg_pct_demand_met",
section,
code,
None,
_safe_round(r.get("avg_pct_demand_met")),
)
if not rows:
report.add("data_present", section, "all", 1.0, 0.0)
# Section: CWS demand units
def verify_cws_du(
report: Report,
dv_df: Optional[pd.DataFrame],
dv_units: Optional[pd.Series],
sv_df: Optional[pd.DataFrame],
sv_units: Optional[pd.Series],
conn,
) -> None:
"""Verify CWS DU delivery (DN_* from DV) and demand (UD_* from SV)."""
section = "cws_du"
log.info(f"Verifying {section}...")
for du in SAMPLE_CWS_DUS:
del_col = f"DN_{du}"
dem_col = f"UD_{du}"
exp_del_taf = None
exp_dem_taf = None
if dv_df is not None:
del_taf = get_column_taf(dv_df, dv_units, del_col)
exp_del_taf = annual_avg_taf(del_taf, dv_df["WaterYear"])
if sv_df is not None:
dem_taf = get_column_taf(sv_df, sv_units, dem_col)
exp_dem_taf = annual_avg_taf(dem_taf, sv_df["WaterYear"])
act_del_taf = None
act_dem_taf = None
if conn:
rows = db_query(
conn,
"""
SELECT p.annual_delivery_avg_taf, p.annual_demand_avg_taf
FROM du_period_summary p
WHERE p.scenario_short_code = %s AND p.du_id = %s
""",
(report.scenario_id, du),
)
if rows:
act_del_taf = _safe_round(rows[0].get("annual_delivery_avg_taf"))
act_dem_taf = _safe_round(rows[0].get("annual_demand_avg_taf"))
# KNOWN ISSUE: GDPUD_NU delivery is skipped. This section expects the
# DN_ pathname (the notebooks' SW_DELIVERY-NET), but du_urban_variable
# maps GDPUD_NU to DL_GDPUD_NU. The two diverge only for this DU, so the
# check cannot pass until the correct delivery variable is confirmed
# against the model notebooks. The demand check below still runs.
# See README "Known verification discrepancies".
if du == "GDPUD_NU":
log.warning(
"KNOWN ISSUE: skipping GDPUD_NU delivery. This section expects "
"DN_GDPUD_NU (the notebooks' SW_DELIVERY-NET) but du_urban_variable "
"maps this DU to DL_GDPUD_NU, giving a different value. Check with "
"the Water Allocation Modeling Team for the correct delivery "
"pathname. If DN_ is right, update du_urban_variable.delivery_"
"variable for GDPUD_NU and re-run the du_urban ETL. If DL_ is right, "
"fix the expected variable in this section. Then remove this skip "
"guard. See the 'Known verification discrepancies' roadmap in "
"etl/statistics/README.md."
)
else:
report.add(
"annual_delivery_avg_taf", section, du, exp_del_taf, act_del_taf
)
report.add("annual_demand_avg_taf", section, du, exp_dem_taf, act_dem_taf)
# Section: AG demand units
def verify_ag(
report: Report, dv_df: Optional[pd.DataFrame], dv_units: Optional[pd.Series], conn
) -> None:
"""Verify AG demand (AW_*), delivery (DN_*), GW pumping (GP_*) — all from DV."""
section = "ag"
log.info(f"Verifying {section}...")
for du in SAMPLE_AG_DUS:
del_col = f"DN_{du}"
dem_col = f"AW_{du}"
gp_col = f"GP_{du}"
exp_del_taf = None
exp_dem_taf = None
exp_gp_taf = None
if dv_df is not None:
del_taf = get_column_taf(dv_df, dv_units, del_col)
exp_del_taf = annual_avg_taf(del_taf, dv_df["WaterYear"])
gp_taf = get_column_taf(dv_df, dv_units, gp_col)
exp_gp_taf = annual_avg_taf(gp_taf, dv_df["WaterYear"])
dem_taf = get_column_taf(dv_df, dv_units, dem_col)
exp_dem_taf = annual_avg_taf(dem_taf, dv_df["WaterYear"])
act_del_taf = None
act_gp_taf = None
act_dem_taf = None
act_reliability = None
if conn:
rows = db_query(
conn,
"""
SELECT p.annual_sw_delivery_avg_taf,
p.annual_gw_pumping_avg_taf,
p.annual_demand_avg_taf,
p.reliability_pct
FROM ag_du_period_summary p
WHERE p.scenario_short_code = %s AND p.du_id = %s
""",
(report.scenario_id, du),
)
if rows:
r = rows[0]
act_del_taf = _safe_round(r.get("annual_sw_delivery_avg_taf"))
act_gp_taf = _safe_round(r.get("annual_gw_pumping_avg_taf"))
act_dem_taf = _safe_round(r.get("annual_demand_avg_taf"))
act_reliability = _safe_round(r.get("reliability_pct"))
report.add("annual_sw_delivery_avg_taf", section, du, exp_del_taf, act_del_taf)
report.add("annual_gw_pumping_avg_taf", section, du, exp_gp_taf, act_gp_taf)
report.add("annual_demand_avg_taf", section, du, exp_dem_taf, act_dem_taf)
if act_reliability is not None:
report.add("reliability_pct", section, du, None, act_reliability)
# AG aggregate delivery — expected from DV (original aggregates keyed by DV variable)
for var, label in AG_AGGREGATE_VARS:
exp_ann = None
if dv_df is not None:
taf_series = get_column_taf(dv_df, dv_units, var)
exp_ann = annual_avg_taf(taf_series, dv_df["WaterYear"])
act_ann = None
if conn:
rows = db_query(
conn,
"""
SELECT p.annual_delivery_avg_taf
FROM ag_aggregate_period_summary p
JOIN ag_aggregate_entity e ON p.aggregate_code = e.short_code
WHERE p.scenario_short_code = %s AND e.short_code = %s
""",
(report.scenario_id, var),
)
if rows:
act_ann = _safe_round(rows[0].get("annual_delivery_avg_taf"))
report.add("annual_delivery_avg_taf", "ag_aggregate", var, exp_ann, act_ann)
# New direct AG aggregates (cvp_psc_n, cvp_pex_s)
for short_code, dv_var, label in AG_AGGREGATE_NEW_VARS:
exp_ann = None
if dv_df is not None:
taf_series = get_column_taf(dv_df, dv_units, dv_var)
exp_ann = annual_avg_taf(taf_series, dv_df["WaterYear"])
act_ann = None
if conn:
rows = db_query(
conn,
"""
SELECT p.annual_delivery_avg_taf
FROM ag_aggregate_period_summary p
JOIN ag_aggregate_entity e ON p.aggregate_code = e.short_code
WHERE p.scenario_short_code = %s AND e.short_code = %s
""",
(report.scenario_id, short_code),
)
if rows:
act_ann = _safe_round(rows[0].get("annual_delivery_avg_taf"))
report.add(
"annual_delivery_avg_taf", "ag_aggregate", short_code, exp_ann, act_ann
)
# Computed AG aggregates (nod_ag, sod_ag) — sum of components
for agg_code, components in AG_COMPUTED_AGGREGATES.items():
exp_ann = None
if dv_df is not None:
total_annual = None
for del_var in components["delivery_components"]:
comp_series = get_column_taf(dv_df, dv_units, del_var)
if comp_series is not None:
comp_annual = comp_series.groupby(dv_df["WaterYear"]).sum()
if total_annual is None:
total_annual = comp_annual
else:
total_annual = total_annual + comp_annual
if total_annual is not None:
exp_ann = round(float(total_annual.mean()), 4)
act_ann = None
if conn:
rows = db_query(
conn,
"""
SELECT p.annual_delivery_avg_taf
FROM ag_aggregate_period_summary p
JOIN ag_aggregate_entity e ON p.aggregate_code = e.short_code
WHERE p.scenario_short_code = %s AND e.short_code = %s
""",
(report.scenario_id, agg_code),
)
if rows:
act_ann = _safe_round(rows[0].get("annual_delivery_avg_taf"))
report.add(
"annual_delivery_avg_taf", "ag_aggregate", agg_code, exp_ann, act_ann
)
# Section: Env Flows
def verify_env_flows(
report: Report, dv_df: Optional[pd.DataFrame], dv_units: Optional[pd.Series], conn
) -> None:
section = "env_flows"
log.info(f"Verifying {section}...")
for var in FLOW_VARS:
exp_avg_cfs = None
_exp_ann_taf = None
if dv_df is not None and var in dv_df.columns:
raw = pd.to_numeric(dv_df[var], errors="coerce")
exp_avg_cfs = (
round(float(raw.mean()), 4) if not raw.dropna().empty else None
)
taf_series = get_column_taf(dv_df, dv_units, var)
_exp_ann_taf = annual_avg_taf(taf_series, dv_df["WaterYear"])
act_avg_cfs = None
act_pearson_r = None
act_pct_unimp = None
act_pct_ff = None
# network_arc_id stores the channel code string ("C_SAC041") directly,
# so match the full variable against it. There is no join to network_arc.
if conn:
monthly_rows = db_query(
conn,
"""
SELECT AVG(m.flow_avg_cfs) as overall_avg_cfs
FROM env_flow_channel_monthly m
WHERE m.scenario_short_code = %s AND m.network_arc_id = %s
""",
(report.scenario_id, var),
)
if monthly_rows and monthly_rows[0].get("overall_avg_cfs") is not None:
act_avg_cfs = _safe_round(monthly_rows[0]["overall_avg_cfs"])
period_rows = db_query(
conn,
"""
SELECT p.pearson_r, p.avg_pct_unimpaired, p.avg_pct_ff
FROM env_flow_channel_period_summary p
WHERE p.scenario_short_code = %s AND p.network_arc_id = %s
""",
(report.scenario_id, var),
)
if period_rows:
r = period_rows[0]
act_pearson_r = _safe_round(r.get("pearson_r"))
act_pct_unimp = _safe_round(r.get("avg_pct_unimpaired"))
act_pct_ff = _safe_round(r.get("avg_pct_ff"))
report.add("avg_cfs", section, var, exp_avg_cfs, act_avg_cfs)
if act_pearson_r is not None:
report.add("pearson_r", section, var, None, act_pearson_r)
if act_pct_unimp is not None:
report.add("avg_pct_unimpaired", section, var, None, act_pct_unimp)
if act_pct_ff is not None:
report.add("avg_pct_ff", section, var, None, act_pct_ff)
# Section: Refuge
def verify_refuge(report: Report, conn) -> None:
section = "refuge"
log.info(f"Verifying {section}...")
if not conn:
return
rows = db_query(
conn,
"""
SELECT p.du_id, p.annual_delivery_avg_taf,
p.annual_shortage_avg_taf, p.reliability_pct_95,
p.annual_shortage_pct_avg
FROM refuge_du_period_summary p
WHERE p.scenario_short_code = %s
ORDER BY p.du_id
""",
(report.scenario_id,),
)
for r in rows:
du = r["du_id"]
report.add(
"annual_delivery_avg_taf",
section,
du,
None,
_safe_round(r.get("annual_delivery_avg_taf")),
)
report.add(
"annual_shortage_avg_taf",
section,
du,
None,
_safe_round(r.get("annual_shortage_avg_taf")),
)
report.add(
"reliability_pct_95",
section,
du,
None,
_safe_round(r.get("reliability_pct_95")),
)
if not rows:
report.add("data_present", section, "all", 1.0, 0.0)
# Section: Delta
def verify_delta(
report: Report, dv_df: Optional[pd.DataFrame], dv_units: Optional[pd.Series], conn
) -> None:
"""Verify Delta outflow (NDO), X2 position, and salinity from DV CSV vs DB."""
section = "delta"
log.info(f"Verifying {section}...")
# --- NDO outflow: annual avg TAF ---
for var_code, calsim_var, native_unit in DELTA_OUTFLOW_VARS:
exp_ann_taf = None
if dv_df is not None and calsim_var in dv_df.columns:
taf_series = get_column_taf(dv_df, dv_units, calsim_var)
exp_ann_taf = annual_avg_taf(taf_series, dv_df["WaterYear"])
act_ann_taf = None
act_avg_cfs = None
if conn:
rows = db_query(
conn,
"""
SELECT summary_data
FROM delta_period_summary
WHERE scenario_short_code = %s AND variable_code = %s
""",
(report.scenario_id, var_code),
)
if rows:
sd = rows[0].get("summary_data", {})
act_ann_taf = _safe_round(sd.get("annual_avg_taf"))
act_avg_cfs = _safe_round(sd.get("avg_cfs"))
report.add("annual_avg_taf", section, var_code, exp_ann_taf, act_ann_taf)
if act_avg_cfs is not None:
exp_avg_cfs = None
if dv_df is not None and calsim_var in dv_df.columns:
raw = pd.to_numeric(dv_df[calsim_var], errors="coerce")
exp_avg_cfs = (
round(float(raw.mean()), 4) if not raw.dropna().empty else None
)
report.add("avg_cfs", section, var_code, exp_avg_cfs, act_avg_cfs)
# --- X2: period average in KM ---
for var_code, calsim_var, native_unit in DELTA_X2_VARS:
exp_avg = None
if dv_df is not None and calsim_var in dv_df.columns:
raw = pd.to_numeric(dv_df[calsim_var], errors="coerce")
exp_avg = round(float(raw.mean()), 4) if not raw.dropna().empty else None
act_avg = None
if conn:
rows = db_query(
conn,
"""
SELECT summary_data
FROM delta_period_summary
WHERE scenario_short_code = %s AND variable_code = %s
""",
(report.scenario_id, var_code),
)
if rows: