Spaces:
Sleeping
Sleeping
Upload 23 files
Browse files- DEFECT_MATRIX.md +51 -0
- calgary_rules.py +16 -10
- report_engine.py +192 -23
- screening_logic.py +187 -0
- test_regression.py +228 -0
- tools.py +93 -5
DEFECT_MATRIX.md
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Defect Matrix — deterministic report-quality fixes (Rev 23.3)
|
| 2 |
+
|
| 3 |
+
Response to the external review of MCP-generated SWMM Model Review reports.
|
| 4 |
+
Reference model: Kincora Phase 2 (regression pins live in `test_regression.py`
|
| 5 |
+
with documented tolerances; no Kincora values are hard-coded in server code).
|
| 6 |
+
|
| 7 |
+
| # | Defect (as observed) | Authoritative source | Root cause | Module / function | Fix | Regression test |
|
| 8 |
+
|---|---|---|---|---|---|---|
|
| 9 |
+
| 1 | Runoff continuity −1.933% never disclosed as exceeding the 1% absolute warning threshold | Engine `.rpt` continuity block | `_summary_findings` applied thresholds to `flow_error` only | `report_engine._summary_findings` | Replaced with `screening_logic.continuity_disclosure`: runoff and routing checked symmetrically against absolute review/warning thresholds, sign preserved (`-1.933%` printed signed; threshold on \|value\|) | unit: sign + threshold tests; docx: warning line present |
|
| 10 |
+
| 2 | Water-quality continuity reported as a number when no pollutants modelled | INP `[POLLUTANTS]` absent | No applicability gate | same | "Not applicable — no pollutants modelled" when `[POLLUTANTS]` empty; reported numerically only when pollutants exist | unit + docx checks |
|
| 11 |
+
| 3 | Storage facilities labelled **Pass** without facility classification, design HWL, freeboard, or release/spill criteria | None exists (criteria not established) | Permissive default-Pass in `apply_storage_classification` non-trap branch | `calgary_rules.apply_storage_classification` | Three-state screening: "Within modelled depth — compliance **Not assessed** (criteria not established)" / "Near modelled capacity — review" / "Exceeds modelled depth — flag". Trap-lows retain a screening verdict because the 0.5 m Alberta Environment criterion is an established register entry | unit: no bare Pass; docx: storage table scan |
|
| 12 |
+
| 4 | "Remaining Depth Margin" conflatable with regulatory freeboard | — | Terminology | `calgary_rules`, `report_engine` storage table | Renamed **"Modelled Depth Margin"** in both tables; explicitly a model quantity, not a freeboard determination | unit: column name; docx: terminology |
|
| 13 |
+
| 5 | Screening ignored the `.rpt` value for reconciliation-flagged links (e.g. 108(Spill): worker 1.186 vs `.rpt` 2.63 m/s) | Engine `.rpt` Link Flow Summary | Reconciliation produced findings but never fed screening | new `screening_logic.effective_velocity_table` + `report_engine._critical_elements` | Evidence precedence implemented: flagged links screen on the `.rpt` value; both values, Δabs, Δ%, evidence source, and "classification changed Yes/No" recorded; report states deterministically that the 108(Spill) discrepancy does **not** create a 3.0 m/s exceedance; verdict never claims reconciliation fully clean while links remain flagged | unit: precedence + delta tests; integration: 108(Spill); docx: precedence statements |
|
| 14 |
+
| 6 | Single 4.0 m/s velocity threshold; no advisory tier in the report | Criteria register (3.0 advisory / 4.0 critical) | Report used one threshold although the register held two | `report_engine` (`ReportCriteria.velocity_advisory`, `_critical_elements`) | Dual classification: "CRITICAL screening exceedance (>4.0)" for 1000/1001; "Advisory screening exceedance (>3.0)" for 1003/1002/1005; explicitly screening language, not regulatory failure | integration velocity pins; docx language check |
|
| 15 |
+
| 7 | No missing-evidence disclosure section | — | Data existed (readiness, criteria register) but no register | new `screening_logic.missing_information_register` + §4.10 | Deterministic register from unset metadata + "Not established" criteria + "Missing" checklist rows; text states listed items block any related Pass | docx heading + table |
|
| 16 |
+
| 8 | No model identity / provenance (hash, run ID, engine, status) | File bytes + session | Never computed | `tools.run_simulation`, `report_engine` §1.0a | SHA-256 of the uploaded INP + UTC run ID in run output, report Table 0A, and `metadata/model_identity.json` in the audit zip; revision-history Table 0B added | integration SHA check; docx table scan |
|
| 17 |
+
| 9 | No prioritized actions; presentation gaps (page numbers) | Findings register | Rendering only | `report_engine` §5.0a + footer | Severity-sorted (Critical→Low) deterministic action list from the findings register; footer with PAGE field on every page | docx heading check |
|
| 18 |
+
|
| 19 |
+
## Items reviewed and found already correct (no change)
|
| 20 |
+
|
| 21 |
+
- **Full-flow capacity**: already computed only for CIRCULAR conduits with
|
| 22 |
+
explicit slope via Manning; otherwise basis = "Full-flow capacity not
|
| 23 |
+
calculated" and status "Not assessed" — never inferred from velocity/depth.
|
| 24 |
+
- **Complete data coverage**: report tables and appendices are built from the
|
| 25 |
+
complete result DataFrames; the 60-row bounds apply only to MCP tool
|
| 26 |
+
responses (narrative summaries), as the review permits.
|
| 27 |
+
- **CB2A/CB2a case QA**, **advisory/critical thresholds in the screening
|
| 28 |
+
tool**, **continuity percent conversion**, **base-model preservation in
|
| 29 |
+
scenarios**, **velocity extraction** — fixed in Rev 23.2 and retained.
|
| 30 |
+
|
| 31 |
+
## Known remaining limitations (disclosed, not hidden)
|
| 32 |
+
|
| 33 |
+
1. Per-metric provenance is carried at table level (evidence source columns,
|
| 34 |
+
reconciliation records, audit CSVs), not yet as a universal typed record
|
| 35 |
+
for every scalar in the document.
|
| 36 |
+
2. DOCX→PDF rendering checks (blank pages, clipped tables) are approximated
|
| 37 |
+
at the docx-structure level; a LibreOffice render pass is not run in the
|
| 38 |
+
Space image.
|
| 39 |
+
3. The Word TOC relies on heading styles (Word can generate it); an embedded
|
| 40 |
+
auto-updating TOC field is not inserted.
|
| 41 |
+
4. 108(Spill)-class discrepancies on mostly-dry transect channels are
|
| 42 |
+
flagged and precedence-handled, but their physical cause (volume-averaged
|
| 43 |
+
vs midpoint flow area during wave-front filling) is documented rather
|
| 44 |
+
than eliminated.
|
| 45 |
+
|
| 46 |
+
## Reproduce
|
| 47 |
+
|
| 48 |
+
```bash
|
| 49 |
+
SWMM_WORKER_PYTHON=$(which python) python test_regression.py Kincora_Phase_2.inp
|
| 50 |
+
python smoke_test.py http://127.0.0.1:7860 Kincora_Phase_2.inp # against a live server
|
| 51 |
+
```
|
calgary_rules.py
CHANGED
|
@@ -78,9 +78,9 @@ def classify_overland(depth_m: float, velocity_mps: float, curve: tuple[tuple[fl
|
|
| 78 |
d = float(depth_m or 0.0)
|
| 79 |
ratio = d / allowed if allowed > 0 else math.inf
|
| 80 |
if ratio <= 0.90:
|
| 81 |
-
return "
|
| 82 |
if ratio <= 1.00:
|
| 83 |
-
return "
|
| 84 |
return "Exceeds depth-velocity criterion", allowed
|
| 85 |
|
| 86 |
|
|
@@ -208,18 +208,24 @@ def apply_storage_classification(storage_table: pd.DataFrame, criteria: CalgaryC
|
|
| 208 |
margin = maxd - peak if pd.notna(maxd) and pd.notna(peak) else math.nan
|
| 209 |
ratio = peak / maxd if pd.notna(maxd) and maxd > 0 and pd.notna(peak) else math.nan
|
| 210 |
if cls.startswith("Street trap"):
|
| 211 |
-
|
|
|
|
|
|
|
| 212 |
elif peak > criteria.trap_low_max_depth_m: status = "Exceeds trap-low depth criterion"
|
| 213 |
-
elif peak >= 0.95 * criteria.trap_low_max_depth_m: status = "
|
| 214 |
-
else: status = "
|
| 215 |
else:
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
classes.append(cls); statuses.append(status); margins.append(margin)
|
| 221 |
df.insert(1, "Calgary Storage Classification", classes)
|
| 222 |
-
df[f"
|
| 223 |
df["Calgary Status"] = statuses
|
| 224 |
return df
|
| 225 |
|
|
|
|
| 78 |
d = float(depth_m or 0.0)
|
| 79 |
ratio = d / allowed if allowed > 0 else math.inf
|
| 80 |
if ratio <= 0.90:
|
| 81 |
+
return "Screens within depth-velocity criterion", allowed
|
| 82 |
if ratio <= 1.00:
|
| 83 |
+
return "Screens within criterion - near limit", allowed
|
| 84 |
return "Exceeds depth-velocity criterion", allowed
|
| 85 |
|
| 86 |
|
|
|
|
| 208 |
margin = maxd - peak if pd.notna(maxd) and pd.notna(peak) else math.nan
|
| 209 |
ratio = peak / maxd if pd.notna(maxd) and maxd > 0 and pd.notna(peak) else math.nan
|
| 210 |
if cls.startswith("Street trap"):
|
| 211 |
+
# Trap-low criterion (0.5 m ponding, Alberta Environment 1999) is an
|
| 212 |
+
# established register entry, so a screening verdict is supportable.
|
| 213 |
+
if pd.isna(peak): status = "Not assessed - missing peak depth"
|
| 214 |
elif peak > criteria.trap_low_max_depth_m: status = "Exceeds trap-low depth criterion"
|
| 215 |
+
elif peak >= 0.95 * criteria.trap_low_max_depth_m: status = "Screens below trap-low criterion - limited margin"
|
| 216 |
+
else: status = "Screens below trap-low depth criterion"
|
| 217 |
else:
|
| 218 |
+
# No facility classification, design HWL, required freeboard, or
|
| 219 |
+
# release/spill criterion is available from the model alone, so a
|
| 220 |
+
# Pass verdict is unsupportable here (deterministic rule): report
|
| 221 |
+
# the modelled utilisation and return Not assessed for compliance.
|
| 222 |
+
if pd.isna(ratio): status = "Not assessed - unclassified or incomplete"
|
| 223 |
+
elif ratio >= 1.0: status = "Exceeds modelled depth - flag for review"
|
| 224 |
+
elif ratio >= 0.90: status = "Near modelled capacity - review"
|
| 225 |
+
else: status = "Within modelled depth - compliance Not assessed (criteria not established)"
|
| 226 |
classes.append(cls); statuses.append(status); margins.append(margin)
|
| 227 |
df.insert(1, "Calgary Storage Classification", classes)
|
| 228 |
+
df[f"Modelled Depth Margin ({length_unit})"] = margins # model quantity, NOT regulatory freeboard
|
| 229 |
df["Calgary Status"] = statuses
|
| 230 |
return df
|
| 231 |
|
report_engine.py
CHANGED
|
@@ -37,7 +37,8 @@ class ReportCriteria:
|
|
| 37 |
node_depth_ratio: float = 0.80
|
| 38 |
minimum_freeboard: float = 0.50
|
| 39 |
conduit_depth_ratio: float = 0.80
|
| 40 |
-
velocity_threshold: float = 4.00
|
|
|
|
| 41 |
continuity_review: float = 0.50
|
| 42 |
continuity_warning: float = 1.00
|
| 43 |
suppress_empty_sections: bool = True
|
|
@@ -592,7 +593,7 @@ def _area_classification(sub_table: pd.DataFrame, units: UnitContext, overrides:
|
|
| 592 |
return d.groupby("Area Category", as_index=False)[area_col].sum()
|
| 593 |
|
| 594 |
|
| 595 |
-
def _critical_elements(node_df: pd.DataFrame, link_df: pd.DataFrame, units: UnitContext, criteria: ReportCriteria) -> tuple[pd.DataFrame, pd.DataFrame]:
|
| 596 |
node_rows = []
|
| 597 |
if node_df is not None and not node_df.empty:
|
| 598 |
for _, r in node_df.iterrows():
|
|
@@ -623,9 +624,19 @@ def _critical_elements(node_df: pd.DataFrame, link_df: pd.DataFrame, units: Unit
|
|
| 623 |
continue
|
| 624 |
ratio = pd.to_numeric(pd.Series([r.get("Depth Ratio")]), errors="coerce").iloc[0]
|
| 625 |
vel = pd.to_numeric(pd.Series([r.get(vel_col)]), errors="coerce").iloc[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 626 |
issues = []
|
| 627 |
-
|
| 628 |
-
|
|
|
|
|
|
|
|
|
|
| 629 |
if pd.notna(ratio) and ratio >= criteria.conduit_depth_ratio:
|
| 630 |
issues.append(f"depth ratio ≥ {criteria.conduit_depth_ratio:.2f}")
|
| 631 |
if issues:
|
|
@@ -636,16 +647,13 @@ def _critical_elements(node_df: pd.DataFrame, link_df: pd.DataFrame, units: Unit
|
|
| 636 |
|
| 637 |
def _summary_findings(node_df: pd.DataFrame, link_df: pd.DataFrame, sub_df: pd.DataFrame, metadata: dict[str, Any], units: UnitContext, options: dict[str, str], criteria: ReportCriteria) -> list[str]:
|
| 638 |
findings: list[str] = []
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
elif key == "flow_error" and abs(v) > criteria.continuity_review:
|
| 647 |
-
findings.append(f"Flow-routing continuity error exceeds the {criteria.continuity_review:g}% review threshold.")
|
| 648 |
-
except Exception: findings.append(f"{label}: {val}.")
|
| 649 |
if node_df is not None and not node_df.empty:
|
| 650 |
flooded_col = next((c for c in node_df.columns if c.startswith('Peak Flooding (')), None)
|
| 651 |
flooded = int((pd.to_numeric(node_df[flooded_col], errors='coerce').fillna(0) > 0).sum()) if flooded_col else 0
|
|
@@ -929,7 +937,7 @@ def _scenario_detail_tables(record: Mapping[str, Any], units: UnitContext) -> di
|
|
| 929 |
f"Peak Flooding ({units.flow})":_series_peak(vals,"flooding"),
|
| 930 |
"Time of Peak Storage":_peak_time(vals,"volume",times),
|
| 931 |
"Depth Utilization (%)":utilization,
|
| 932 |
-
f"
|
| 933 |
})
|
| 934 |
|
| 935 |
outfall_rows=[]
|
|
@@ -956,6 +964,49 @@ def _compact_scenario_comparison(df: pd.DataFrame) -> pd.DataFrame:
|
|
| 956 |
wanted=["Display Scenario","Source Model","Storm","Storm Status","Simulation Status","Runoff Error (%)","Flow Error (%)","Peak Subcatchment Runoff","Maximum Storage Depth","Maximum Storage Volume","Peak Link Flow","Maximum Node Inflow","Maximum Node Flooding","Hydraulic Difference"]
|
| 957 |
return out[[c for c in wanted if c in out.columns]].copy()
|
| 958 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 959 |
def _embed_attached_figures(doc, figures: list[Mapping[str, Any]] | None) -> None:
|
| 960 |
"""Insert session-attached figures into the built document.
|
| 961 |
|
|
@@ -1023,6 +1074,9 @@ def generate_report_package(
|
|
| 1023 |
scenario_reporting_mode: str = "Base report with scenario comparison",
|
| 1024 |
preliminary_review_artifacts: Mapping[str, Any] | None = None,
|
| 1025 |
attached_figures: list[Mapping[str, Any]] | None = None,
|
|
|
|
|
|
|
|
|
|
| 1026 |
) -> dict[str, bytes | str]:
|
| 1027 |
"""Generate editable Word report and ZIP package entirely in memory."""
|
| 1028 |
criteria = criteria or ReportCriteria()
|
|
@@ -1062,7 +1116,17 @@ def generate_report_package(
|
|
| 1062 |
if outgoing_peak > 0 and (pd.isna(peak_depth) or float(peak_depth) <= 0):
|
| 1063 |
storage_table.at[idx, "Status"] = "Review: control flow occurs but storage depth is zero"
|
| 1064 |
area_table = _area_classification(sub_table, units, criteria.area_classification)
|
| 1065 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1066 |
|
| 1067 |
calgary = CalgaryCriteria(
|
| 1068 |
minor_release_rate_lps_ha=criteria.minor_release_rate_lps_ha,
|
|
@@ -1101,10 +1165,20 @@ def generate_report_package(
|
|
| 1101 |
has_outfalls=bool((node_report.get("Type", pd.Series(dtype=str)).astype(str).str.lower()=="outfall").any()),
|
| 1102 |
has_conduits=bool(_conduit_rows),
|
| 1103 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1104 |
readiness_table = _readiness_scores(checklist_table)
|
| 1105 |
|
| 1106 |
doc = Document()
|
| 1107 |
sec = doc.sections[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1108 |
sec.top_margin = Inches(0.65)
|
| 1109 |
sec.bottom_margin = Inches(0.65)
|
| 1110 |
sec.left_margin = Inches(0.65)
|
|
@@ -1150,6 +1224,21 @@ def generate_report_package(
|
|
| 1150 |
)
|
| 1151 |
|
| 1152 |
doc.add_paragraph("Draft status: suitable for consultant/client discussion and structured engineering review. Human-in-the-loop completion, technical verification, drawing coordination, and professional authentication are required before municipal submission.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1153 |
doc.add_heading("1.1 Calgary SWMR Checklist Summary", level=2)
|
| 1154 |
doc.add_paragraph("The completeness register tracks the principal Calgary SWMR checklist subjects. It is a draft-readiness tool, not a municipal compliance score.")
|
| 1155 |
_add_df_table(doc, "Table 1A - Calgary SWMR Completeness Register", checklist_table, landscape=True, font_size=7.0)
|
|
@@ -1174,13 +1263,18 @@ def generate_report_package(
|
|
| 1174 |
)
|
| 1175 |
_add_df_table(doc, "Table 2A - Model Area Classification", area_table, font_size=8.2)
|
| 1176 |
doc.add_heading("2.1 Design Objectives", level=2)
|
| 1177 |
-
|
| 1178 |
-
|
| 1179 |
-
|
| 1180 |
-
|
| 1181 |
-
|
| 1182 |
-
|
| 1183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1184 |
|
| 1185 |
doc.add_heading("3.0 ANALYSIS METHODOLOGY AND DATA", level=1)
|
| 1186 |
_add_narrative_block(doc, narrative_sections, "methodology")
|
|
@@ -1318,7 +1412,55 @@ def generate_report_package(
|
|
| 1318 |
doc.add_heading("4.9 Model Input/Output Documentation", level=2)
|
| 1319 |
_add_narrative_block(doc, narrative_sections, "model_documentation")
|
| 1320 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1321 |
doc.add_heading("5.0 SUMMARY OF FINDINGS, CONCLUSIONS, AND RECOMMENDATIONS", level=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1322 |
findings = _summary_findings(node_report, link_report, sub_report, simulation_metadata, units, options, criteria)
|
| 1323 |
doc.add_heading("5.1 Executive Summary", level=2)
|
| 1324 |
if not _add_narrative_block(doc, narrative_sections, "executive_summary"):
|
|
@@ -1379,6 +1521,22 @@ def generate_report_package(
|
|
| 1379 |
_add_df_table(doc, "Table B-1 - Subcatchment Model Parameters", sub_model, landscape=True, font_size=7.0)
|
| 1380 |
_add_df_table(doc, "Table B-2 - Subcatchment Simulation Results", sub_results, landscape=True, font_size=7.2)
|
| 1381 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1382 |
llm_context = build_llm_report_context(
|
| 1383 |
metadata=asdict(metadata), criteria=calgary, findings=findings,
|
| 1384 |
tables={
|
|
@@ -1430,6 +1588,17 @@ def generate_report_package(
|
|
| 1430 |
if frame is not None and not frame.empty:
|
| 1431 |
zf.writestr(f"tables/scenarios/{sid}_{key}.csv", frame.to_csv(index=False))
|
| 1432 |
zf.writestr("metadata/llm_report_context.json", json.dumps(llm_context, indent=2, default=str))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1433 |
if attached_figures:
|
| 1434 |
fig_manifest = []
|
| 1435 |
for n, fig in enumerate(attached_figures, start=1):
|
|
|
|
| 37 |
node_depth_ratio: float = 0.80
|
| 38 |
minimum_freeboard: float = 0.50
|
| 39 |
conduit_depth_ratio: float = 0.80
|
| 40 |
+
velocity_threshold: float = 4.00 # critical screening threshold
|
| 41 |
+
velocity_advisory: float = 3.00 # advisory screening threshold
|
| 42 |
continuity_review: float = 0.50
|
| 43 |
continuity_warning: float = 1.00
|
| 44 |
suppress_empty_sections: bool = True
|
|
|
|
| 593 |
return d.groupby("Area Category", as_index=False)[area_col].sum()
|
| 594 |
|
| 595 |
|
| 596 |
+
def _critical_elements(node_df: pd.DataFrame, link_df: pd.DataFrame, units: UnitContext, criteria: ReportCriteria, effective_vel: dict | None = None) -> tuple[pd.DataFrame, pd.DataFrame]:
|
| 597 |
node_rows = []
|
| 598 |
if node_df is not None and not node_df.empty:
|
| 599 |
for _, r in node_df.iterrows():
|
|
|
|
| 624 |
continue
|
| 625 |
ratio = pd.to_numeric(pd.Series([r.get("Depth Ratio")]), errors="coerce").iloc[0]
|
| 626 |
vel = pd.to_numeric(pd.Series([r.get(vel_col)]), errors="coerce").iloc[0]
|
| 627 |
+
source_note = ""
|
| 628 |
+
eff = effective_vel.get(str(r.get("Link ID"))) if effective_vel else None
|
| 629 |
+
if eff is not None:
|
| 630 |
+
if eff.get("Screening Velocity (m/s)") is not None:
|
| 631 |
+
if "rpt" in str(eff.get("Evidence Source", "")):
|
| 632 |
+
vel = eff["Screening Velocity (m/s)"]
|
| 633 |
+
source_note = " [engine .rpt value governs - reconciliation-flagged]"
|
| 634 |
issues = []
|
| 635 |
+
advisory = getattr(criteria, "velocity_advisory", 3.0)
|
| 636 |
+
if pd.notna(vel) and vel > criteria.velocity_threshold:
|
| 637 |
+
issues.append(f"CRITICAL screening exceedance: velocity > {criteria.velocity_threshold:g} {units.velocity}{source_note}")
|
| 638 |
+
elif pd.notna(vel) and vel > advisory:
|
| 639 |
+
issues.append(f"Advisory screening exceedance: velocity > {advisory:g} {units.velocity}{source_note}")
|
| 640 |
if pd.notna(ratio) and ratio >= criteria.conduit_depth_ratio:
|
| 641 |
issues.append(f"depth ratio ≥ {criteria.conduit_depth_ratio:.2f}")
|
| 642 |
if issues:
|
|
|
|
| 647 |
|
| 648 |
def _summary_findings(node_df: pd.DataFrame, link_df: pd.DataFrame, sub_df: pd.DataFrame, metadata: dict[str, Any], units: UnitContext, options: dict[str, str], criteria: ReportCriteria) -> list[str]:
|
| 649 |
findings: list[str] = []
|
| 650 |
+
from screening_logic import continuity_disclosure
|
| 651 |
+
findings.extend(continuity_disclosure(
|
| 652 |
+
metadata, review_pct=criteria.continuity_review,
|
| 653 |
+
warning_pct=criteria.continuity_warning,
|
| 654 |
+
has_pollutants=bool(metadata.get("has_pollutants"))))
|
| 655 |
+
if False: # legacy block replaced by deterministic continuity_disclosure
|
| 656 |
+
pass
|
|
|
|
|
|
|
|
|
|
| 657 |
if node_df is not None and not node_df.empty:
|
| 658 |
flooded_col = next((c for c in node_df.columns if c.startswith('Peak Flooding (')), None)
|
| 659 |
flooded = int((pd.to_numeric(node_df[flooded_col], errors='coerce').fillna(0) > 0).sum()) if flooded_col else 0
|
|
|
|
| 937 |
f"Peak Flooding ({units.flow})":_series_peak(vals,"flooding"),
|
| 938 |
"Time of Peak Storage":_peak_time(vals,"volume",times),
|
| 939 |
"Depth Utilization (%)":utilization,
|
| 940 |
+
f"Modelled Depth Margin ({units.length})":remaining, # model quantity, NOT regulatory freeboard
|
| 941 |
})
|
| 942 |
|
| 943 |
outfall_rows=[]
|
|
|
|
| 964 |
wanted=["Display Scenario","Source Model","Storm","Storm Status","Simulation Status","Runoff Error (%)","Flow Error (%)","Peak Subcatchment Runoff","Maximum Storage Depth","Maximum Storage Volume","Peak Link Flow","Maximum Node Inflow","Maximum Node Flooding","Hydraulic Difference"]
|
| 965 |
return out[[c for c in wanted if c in out.columns]].copy()
|
| 966 |
|
| 967 |
+
_LISTING_MAX_LINES = 8000
|
| 968 |
+
_LISTING_CHUNK = 50
|
| 969 |
+
|
| 970 |
+
|
| 971 |
+
def _add_fixed_width_listing(doc, heading: str, text: str, level: int = 2,
|
| 972 |
+
max_lines: int = _LISTING_MAX_LINES) -> None:
|
| 973 |
+
"""Append a fixed-width (Courier) model-file listing under a heading.
|
| 974 |
+
|
| 975 |
+
Long files are truncated in the MIDDLE (head + tail preserved) with an
|
| 976 |
+
explicit note directing readers to the untruncated copy in the audit
|
| 977 |
+
package. Lines are batched ~50 per paragraph via run breaks to keep the
|
| 978 |
+
document responsive in Word.
|
| 979 |
+
"""
|
| 980 |
+
from docx.shared import Pt
|
| 981 |
+
|
| 982 |
+
doc.add_heading(heading, level=level)
|
| 983 |
+
lines = (text or "").replace("\r\n", "\n").replace("\r", "\n").split("\n")
|
| 984 |
+
total = len(lines)
|
| 985 |
+
if total > max_lines:
|
| 986 |
+
head_n = int(max_lines * 0.7)
|
| 987 |
+
tail_n = max_lines - head_n
|
| 988 |
+
omitted = total - head_n - tail_n
|
| 989 |
+
lines = (lines[:head_n]
|
| 990 |
+
+ [f"... [{omitted} lines omitted for document size - complete file "
|
| 991 |
+
f"is included untruncated in the audit package under model/] ..."]
|
| 992 |
+
+ lines[-tail_n:])
|
| 993 |
+
doc.add_paragraph(
|
| 994 |
+
f"Listing truncated for document size ({total} source lines; {omitted} omitted "
|
| 995 |
+
"mid-file). The complete, untruncated file is archived in the audit package "
|
| 996 |
+
"(model/ directory) and is the authoritative record.")
|
| 997 |
+
for start in range(0, len(lines), _LISTING_CHUNK):
|
| 998 |
+
para = doc.add_paragraph()
|
| 999 |
+
para.paragraph_format.space_after = Pt(0)
|
| 1000 |
+
run = para.add_run()
|
| 1001 |
+
run.font.name = "Courier New"
|
| 1002 |
+
run.font.size = Pt(6.5)
|
| 1003 |
+
chunk = lines[start:start + _LISTING_CHUNK]
|
| 1004 |
+
for j, line in enumerate(chunk):
|
| 1005 |
+
if j:
|
| 1006 |
+
run.add_break()
|
| 1007 |
+
run.add_text(line if line.strip() else " ")
|
| 1008 |
+
|
| 1009 |
+
|
| 1010 |
def _embed_attached_figures(doc, figures: list[Mapping[str, Any]] | None) -> None:
|
| 1011 |
"""Insert session-attached figures into the built document.
|
| 1012 |
|
|
|
|
| 1074 |
scenario_reporting_mode: str = "Base report with scenario comparison",
|
| 1075 |
preliminary_review_artifacts: Mapping[str, Any] | None = None,
|
| 1076 |
attached_figures: list[Mapping[str, Any]] | None = None,
|
| 1077 |
+
model_listings: Mapping[str, str] | None = None,
|
| 1078 |
+
reconciliation: Mapping[str, Any] | None = None,
|
| 1079 |
+
model_identity: Mapping[str, Any] | None = None,
|
| 1080 |
) -> dict[str, bytes | str]:
|
| 1081 |
"""Generate editable Word report and ZIP package entirely in memory."""
|
| 1082 |
criteria = criteria or ReportCriteria()
|
|
|
|
| 1116 |
if outgoing_peak > 0 and (pd.isna(peak_depth) or float(peak_depth) <= 0):
|
| 1117 |
storage_table.at[idx, "Status"] = "Review: control flow occurs but storage depth is zero"
|
| 1118 |
area_table = _area_classification(sub_table, units, criteria.area_classification)
|
| 1119 |
+
from screening_logic import effective_velocity_table, missing_information_register
|
| 1120 |
+
simulation_metadata = dict(simulation_metadata or {})
|
| 1121 |
+
simulation_metadata["has_pollutants"] = bool(inp_sections.get("POLLUTANTS"))
|
| 1122 |
+
recon_links_df = None
|
| 1123 |
+
if reconciliation and reconciliation.get("links") is not None:
|
| 1124 |
+
recon_links_df = pd.DataFrame(reconciliation["links"]) if not isinstance(reconciliation["links"], pd.DataFrame) else reconciliation["links"]
|
| 1125 |
+
effective_table = effective_velocity_table(
|
| 1126 |
+
link_report, recon_links_df,
|
| 1127 |
+
advisory=criteria.velocity_advisory, critical=criteria.velocity_threshold)
|
| 1128 |
+
effective_map = {str(r["Link ID"]): r for r in effective_table.to_dict("records")} if not effective_table.empty else {}
|
| 1129 |
+
critical_nodes, critical_links = _critical_elements(_rename_native_columns(_node_hgl_table(node_report), units), link_report, units, criteria, effective_vel=effective_map)
|
| 1130 |
|
| 1131 |
calgary = CalgaryCriteria(
|
| 1132 |
minor_release_rate_lps_ha=criteria.minor_release_rate_lps_ha,
|
|
|
|
| 1165 |
has_outfalls=bool((node_report.get("Type", pd.Series(dtype=str)).astype(str).str.lower()=="outfall").any()),
|
| 1166 |
has_conduits=bool(_conduit_rows),
|
| 1167 |
)
|
| 1168 |
+
if model_listings and (model_listings.get("inp_text") or model_listings.get("rpt_text")):
|
| 1169 |
+
_m17 = checklist_table["Requirement"].astype(str).str.contains("input/output files", case=False)
|
| 1170 |
+
checklist_table.loc[_m17, "Status"] = "Included (Appendix D listings + digital package)"
|
| 1171 |
+
checklist_table.loc[_m17, "Outstanding Action"] = "Verify appendix listings match the issued digital model package"
|
| 1172 |
readiness_table = _readiness_scores(checklist_table)
|
| 1173 |
|
| 1174 |
doc = Document()
|
| 1175 |
sec = doc.sections[0]
|
| 1176 |
+
_footer_p = sec.footer.paragraphs[0]
|
| 1177 |
+
_footer_p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
| 1178 |
+
_run = _footer_p.add_run(f"{metadata.project_name} — Preliminary Draft — Page ")
|
| 1179 |
+
_run.font.size = Pt(8)
|
| 1180 |
+
_fld = OxmlElement("w:fldSimple"); _fld.set(qn("w:instr"), "PAGE")
|
| 1181 |
+
_footer_p._p.append(_fld)
|
| 1182 |
sec.top_margin = Inches(0.65)
|
| 1183 |
sec.bottom_margin = Inches(0.65)
|
| 1184 |
sec.left_margin = Inches(0.65)
|
|
|
|
| 1224 |
)
|
| 1225 |
|
| 1226 |
doc.add_paragraph("Draft status: suitable for consultant/client discussion and structured engineering review. Human-in-the-loop completion, technical verification, drawing coordination, and professional authentication are required before municipal submission.")
|
| 1227 |
+
if model_identity:
|
| 1228 |
+
doc.add_heading("1.0a Model Identity and Execution Provenance", level=2)
|
| 1229 |
+
_id_tbl = pd.DataFrame([
|
| 1230 |
+
{"Item": "Model file", "Value": str(model_identity.get("inp_name", "—"))},
|
| 1231 |
+
{"Item": "Model SHA-256", "Value": str(model_identity.get("sha256", "—"))},
|
| 1232 |
+
{"Item": "Session / run ID", "Value": f"{model_identity.get('session_id', '—')} / {model_identity.get('run_id', '—')}"},
|
| 1233 |
+
{"Item": "Engine", "Value": str(model_identity.get("engine", "EPA SWMM / OpenSWMM (crash-isolated worker)"))},
|
| 1234 |
+
{"Item": "Execution status", "Value": str(model_identity.get("status", "Completed"))},
|
| 1235 |
+
{"Item": "Generated", "Value": str(model_identity.get("generated", metadata.report_date))},
|
| 1236 |
+
])
|
| 1237 |
+
_add_df_table(doc, "Table 0A - Model Identity", _id_tbl, font_size=8.0)
|
| 1238 |
+
_rev_tbl = pd.DataFrame([{"Rev": "P0", "Date": metadata.report_date,
|
| 1239 |
+
"Description": "Preliminary server-generated draft for engineering review",
|
| 1240 |
+
"Status": metadata.submission_status}])
|
| 1241 |
+
_add_df_table(doc, "Table 0B - Revision History", _rev_tbl, font_size=8.0)
|
| 1242 |
doc.add_heading("1.1 Calgary SWMR Checklist Summary", level=2)
|
| 1243 |
doc.add_paragraph("The completeness register tracks the principal Calgary SWMR checklist subjects. It is a draft-readiness tool, not a municipal compliance score.")
|
| 1244 |
_add_df_table(doc, "Table 1A - Calgary SWMR Completeness Register", checklist_table, landscape=True, font_size=7.0)
|
|
|
|
| 1263 |
)
|
| 1264 |
_add_df_table(doc, "Table 2A - Model Area Classification", area_table, font_size=8.2)
|
| 1265 |
doc.add_heading("2.1 Design Objectives", level=2)
|
| 1266 |
+
custom_objectives = str((narrative_sections or {}).get("design_objectives", "") or "").strip()
|
| 1267 |
+
if custom_objectives:
|
| 1268 |
+
for line in [l.strip().lstrip("-*\u2022 ").strip() for l in custom_objectives.splitlines() if l.strip()]:
|
| 1269 |
+
doc.add_paragraph(line, style="List Bullet")
|
| 1270 |
+
else:
|
| 1271 |
+
for text in [
|
| 1272 |
+
"Confirm minor-system flows remain within selected hydraulic criteria.",
|
| 1273 |
+
"Assess overland conveyance depth and velocity against the applicable municipal criteria.",
|
| 1274 |
+
"Identify surcharge, flooding, instability, and continuity concerns.",
|
| 1275 |
+
"Confirm boundary outflows and runoff volumes for the selected design event.",
|
| 1276 |
+
]:
|
| 1277 |
+
doc.add_paragraph(text, style="List Bullet")
|
| 1278 |
|
| 1279 |
doc.add_heading("3.0 ANALYSIS METHODOLOGY AND DATA", level=1)
|
| 1280 |
_add_narrative_block(doc, narrative_sections, "methodology")
|
|
|
|
| 1412 |
doc.add_heading("4.9 Model Input/Output Documentation", level=2)
|
| 1413 |
_add_narrative_block(doc, narrative_sections, "model_documentation")
|
| 1414 |
|
| 1415 |
+
doc.add_heading("4.9 Continuity and Result Reconciliation", level=2)
|
| 1416 |
+
doc.add_paragraph(
|
| 1417 |
+
"Continuity errors are engine-reported values with sign preserved; thresholds are applied to their "
|
| 1418 |
+
"absolute magnitudes. Reconciliation compares the API-derived result tables against the engine's own "
|
| 1419 |
+
".rpt summaries; for reconciliation-flagged links the .rpt value governs screening.")
|
| 1420 |
+
from screening_logic import continuity_disclosure as _cd
|
| 1421 |
+
for line in _cd(simulation_metadata, review_pct=criteria.continuity_review,
|
| 1422 |
+
warning_pct=criteria.continuity_warning,
|
| 1423 |
+
has_pollutants=bool(simulation_metadata.get("has_pollutants"))):
|
| 1424 |
+
doc.add_paragraph(line, style="List Bullet")
|
| 1425 |
+
if reconciliation and reconciliation.get("summary"):
|
| 1426 |
+
_rs = reconciliation["summary"]
|
| 1427 |
+
doc.add_paragraph(
|
| 1428 |
+
f"Reconciliation verdict: {_rs.get('verdict', 'Not performed')} "
|
| 1429 |
+
f"({_rs.get('ok', 0)} of {_rs.get('links_checked', 0)} links agree; "
|
| 1430 |
+
f"{int(_rs.get('review', 0)) + int(_rs.get('discrepancy', 0)) + int(_rs.get('unmatched', 0))} flagged). "
|
| 1431 |
+
"Reconciliation is not claimed to be fully clean while any link remains flagged.")
|
| 1432 |
+
if not effective_table.empty:
|
| 1433 |
+
_flagged_eff = effective_table[effective_table["Classification Changed by Reconciliation"] != "n/a - not flagged"]
|
| 1434 |
+
if not _flagged_eff.empty:
|
| 1435 |
+
_add_df_table(doc, "Table 13A - Reconciliation-Flagged Links: Evidence Precedence",
|
| 1436 |
+
_flagged_eff, landscape=True, font_size=7.5)
|
| 1437 |
+
for _, _er in _flagged_eff.iterrows():
|
| 1438 |
+
changed = str(_er["Classification Changed by Reconciliation"]) == "Yes"
|
| 1439 |
+
doc.add_paragraph(
|
| 1440 |
+
f"Link {_er['Link ID']}: worker {_er['Worker Peak Velocity (m/s)']} m/s vs engine .rpt "
|
| 1441 |
+
f"{_er['RPT Peak Velocity (m/s)']} m/s; the .rpt value governs screening. The discrepancy "
|
| 1442 |
+
f"{'CHANGES' if changed else 'does not change'} the screening classification "
|
| 1443 |
+
f"({_er['Screening Classification']}).", style="List Bullet")
|
| 1444 |
+
|
| 1445 |
+
doc.add_heading("4.10 Missing-Information Register", level=2)
|
| 1446 |
+
doc.add_paragraph(
|
| 1447 |
+
"Evidence items the model and session cannot supply. Any criterion depending on a listed item is "
|
| 1448 |
+
"reported as Not assessed rather than Pass.")
|
| 1449 |
+
_missing = missing_information_register(asdict(metadata), criteria_table if criteria.calgary_enabled else None, checklist_table)
|
| 1450 |
+
_add_df_table(doc, "Table 14A - Missing-Information Register", _missing, font_size=8.0)
|
| 1451 |
+
|
| 1452 |
doc.add_heading("5.0 SUMMARY OF FINDINGS, CONCLUSIONS, AND RECOMMENDATIONS", level=1)
|
| 1453 |
+
_pda = (preliminary_review_artifacts or {}).get("findings")
|
| 1454 |
+
if _pda is not None:
|
| 1455 |
+
_pda_df = _pda if isinstance(_pda, pd.DataFrame) else pd.DataFrame(list(_pda))
|
| 1456 |
+
if not _pda_df.empty and "severity" in _pda_df.columns:
|
| 1457 |
+
_order = {"critical": 0, "high": 1, "medium": 2, "low": 3}
|
| 1458 |
+
_pda_df = _pda_df.assign(_rank=_pda_df["severity"].astype(str).str.lower().map(_order).fillna(9)).sort_values("_rank")
|
| 1459 |
+
doc.add_heading("5.0a Prioritized Actions", level=2)
|
| 1460 |
+
for _, _f in _pda_df.head(10).iterrows():
|
| 1461 |
+
doc.add_paragraph(
|
| 1462 |
+
f"[{_f.get('severity')}] {_f.get('finding_id')} — {str(_f.get('deterministic_basis', _f.get('finding_type', '')))[:220]} "
|
| 1463 |
+
f"Action: {str(_f.get('recommended_action', 'Review.'))[:180]}", style="List Number")
|
| 1464 |
findings = _summary_findings(node_report, link_report, sub_report, simulation_metadata, units, options, criteria)
|
| 1465 |
doc.add_heading("5.1 Executive Summary", level=2)
|
| 1466 |
if not _add_narrative_block(doc, narrative_sections, "executive_summary"):
|
|
|
|
| 1521 |
_add_df_table(doc, "Table B-1 - Subcatchment Model Parameters", sub_model, landscape=True, font_size=7.0)
|
| 1522 |
_add_df_table(doc, "Table B-2 - Subcatchment Simulation Results", sub_results, landscape=True, font_size=7.2)
|
| 1523 |
|
| 1524 |
+
if model_listings and (model_listings.get("inp_text") or model_listings.get("rpt_text")):
|
| 1525 |
+
doc.add_heading("APPENDIX D - MODEL INPUT AND OUTPUT LISTINGS", level=1)
|
| 1526 |
+
doc.add_paragraph(
|
| 1527 |
+
"Fixed-width listings of the computer model input file and the engine output "
|
| 1528 |
+
"report are reproduced below (Calgary SWMR checklist item: attach computer model "
|
| 1529 |
+
"input and output files). The digital files in the accompanying audit package "
|
| 1530 |
+
"(model/ directory) are the authoritative machine-readable record.")
|
| 1531 |
+
if model_listings.get("inp_text"):
|
| 1532 |
+
_add_fixed_width_listing(
|
| 1533 |
+
doc, f"D.1 Model Input File ({model_listings.get('inp_name', 'model.inp')})",
|
| 1534 |
+
model_listings["inp_text"])
|
| 1535 |
+
if model_listings.get("rpt_text"):
|
| 1536 |
+
_add_fixed_width_listing(
|
| 1537 |
+
doc, f"D.2 Engine Output Report ({model_listings.get('rpt_name', 'model.rpt')})",
|
| 1538 |
+
model_listings["rpt_text"])
|
| 1539 |
+
|
| 1540 |
llm_context = build_llm_report_context(
|
| 1541 |
metadata=asdict(metadata), criteria=calgary, findings=findings,
|
| 1542 |
tables={
|
|
|
|
| 1588 |
if frame is not None and not frame.empty:
|
| 1589 |
zf.writestr(f"tables/scenarios/{sid}_{key}.csv", frame.to_csv(index=False))
|
| 1590 |
zf.writestr("metadata/llm_report_context.json", json.dumps(llm_context, indent=2, default=str))
|
| 1591 |
+
if not effective_table.empty:
|
| 1592 |
+
zf.writestr("tables/velocity_screening_effective.csv", effective_table.to_csv(index=False))
|
| 1593 |
+
if model_identity:
|
| 1594 |
+
zf.writestr("metadata/model_identity.json", json.dumps(dict(model_identity), indent=2, default=str))
|
| 1595 |
+
if model_listings:
|
| 1596 |
+
if model_listings.get("inp_text"):
|
| 1597 |
+
zf.writestr(f"model/{_safe_name(model_listings.get('inp_name', 'model.inp'))}",
|
| 1598 |
+
model_listings["inp_text"])
|
| 1599 |
+
if model_listings.get("rpt_text"):
|
| 1600 |
+
zf.writestr(f"model/{_safe_name(model_listings.get('rpt_name', 'model.rpt'))}",
|
| 1601 |
+
model_listings["rpt_text"])
|
| 1602 |
if attached_figures:
|
| 1603 |
fig_manifest = []
|
| 1604 |
for n, fig in enumerate(attached_figures, start=1):
|
screening_logic.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Deterministic screening logic shared by the report engine and tests.
|
| 2 |
+
|
| 3 |
+
Implements the evidence-precedence, continuity-disclosure, and
|
| 4 |
+
missing-information rules that must never be delegated to an LLM:
|
| 5 |
+
|
| 6 |
+
1. Effective-velocity precedence — for links flagged by the worker-vs-.rpt
|
| 7 |
+
reconciliation, the engine .rpt value governs screening; both values,
|
| 8 |
+
their differences, and whether the discrepancy changes the screening
|
| 9 |
+
classification are recorded. Unflagged links use worker values.
|
| 10 |
+
2. Continuity disclosure — runoff and routing errors are reported separately,
|
| 11 |
+
sign preserved, each checked against ABSOLUTE review/warning thresholds;
|
| 12 |
+
water quality is "Not applicable" when no pollutants are modelled.
|
| 13 |
+
3. Missing-information register — deterministic list of evidence the report
|
| 14 |
+
cannot supply, assembled from metadata, the criteria register, and the
|
| 15 |
+
checklist. Anything listed here can never be a Pass elsewhere.
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import math
|
| 20 |
+
from typing import Any, Mapping
|
| 21 |
+
|
| 22 |
+
import pandas as pd
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# ---------------------------------------------------------------------------
|
| 26 |
+
# Velocity classification and evidence precedence
|
| 27 |
+
# ---------------------------------------------------------------------------
|
| 28 |
+
|
| 29 |
+
def classify_velocity(velocity: float | None, advisory: float = 3.0,
|
| 30 |
+
critical: float = 4.0) -> str:
|
| 31 |
+
"""Deterministic dual-threshold screening classification (not a
|
| 32 |
+
regulatory determination)."""
|
| 33 |
+
if velocity is None:
|
| 34 |
+
return "Not assessed"
|
| 35 |
+
try:
|
| 36 |
+
v = float(velocity)
|
| 37 |
+
except (TypeError, ValueError):
|
| 38 |
+
return "Not assessed"
|
| 39 |
+
if math.isnan(v):
|
| 40 |
+
return "Not assessed"
|
| 41 |
+
if v > critical:
|
| 42 |
+
return f"Critical screening exceedance (> {critical:g} m/s)"
|
| 43 |
+
if v > advisory:
|
| 44 |
+
return f"Advisory screening exceedance (> {advisory:g} m/s)"
|
| 45 |
+
return f"Below advisory threshold ({advisory:g} m/s)"
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def effective_velocity_table(link_df: pd.DataFrame,
|
| 49 |
+
recon_links: pd.DataFrame | None,
|
| 50 |
+
advisory: float = 3.0,
|
| 51 |
+
critical: float = 4.0) -> pd.DataFrame:
|
| 52 |
+
"""Per-conduit screening table applying the reconciliation precedence.
|
| 53 |
+
|
| 54 |
+
Columns: Link ID, Worker Peak Velocity, RPT Peak Velocity,
|
| 55 |
+
Screening Velocity, Evidence Source, Delta (abs), Delta (%),
|
| 56 |
+
Screening Classification, Classification Changed by Reconciliation.
|
| 57 |
+
"""
|
| 58 |
+
if link_df is None or link_df.empty:
|
| 59 |
+
return pd.DataFrame()
|
| 60 |
+
vel_col = next((c for c in link_df.columns if c.startswith("Peak Velocity")), None)
|
| 61 |
+
if vel_col is None:
|
| 62 |
+
return pd.DataFrame()
|
| 63 |
+
recon: dict[str, dict[str, Any]] = {}
|
| 64 |
+
if recon_links is not None and not recon_links.empty:
|
| 65 |
+
for _, r in recon_links.iterrows():
|
| 66 |
+
recon[str(r.get("Link ID"))] = r.to_dict()
|
| 67 |
+
|
| 68 |
+
rows: list[dict[str, Any]] = []
|
| 69 |
+
for _, r in link_df.iterrows():
|
| 70 |
+
link_id = str(r.get("Link ID"))
|
| 71 |
+
worker_v = pd.to_numeric(pd.Series([r.get(vel_col)]), errors="coerce").iloc[0]
|
| 72 |
+
rec = recon.get(link_id, {})
|
| 73 |
+
rpt_v = rec.get("RPT Peak Velocity")
|
| 74 |
+
rpt_v = float(rpt_v) if rpt_v is not None and not (isinstance(rpt_v, float) and math.isnan(rpt_v)) else None
|
| 75 |
+
flagged = str(rec.get("Overall Status", "OK")) not in ("OK", "Unavailable", "nan", "None")
|
| 76 |
+
if flagged and rpt_v is not None:
|
| 77 |
+
eff, source = rpt_v, "engine .rpt (reconciliation-flagged)"
|
| 78 |
+
else:
|
| 79 |
+
eff, source = (float(worker_v) if pd.notna(worker_v) else None), "worker time series"
|
| 80 |
+
worker_class = classify_velocity(float(worker_v) if pd.notna(worker_v) else None, advisory, critical)
|
| 81 |
+
eff_class = classify_velocity(eff, advisory, critical)
|
| 82 |
+
delta_abs = (float(worker_v) - rpt_v) if (pd.notna(worker_v) and rpt_v is not None) else None
|
| 83 |
+
delta_pct = (100.0 * delta_abs / abs(rpt_v)) if (delta_abs is not None and rpt_v not in (None, 0)) else None
|
| 84 |
+
rows.append({
|
| 85 |
+
"Link ID": link_id,
|
| 86 |
+
"Worker Peak Velocity (m/s)": round(float(worker_v), 3) if pd.notna(worker_v) else None,
|
| 87 |
+
"RPT Peak Velocity (m/s)": round(rpt_v, 3) if rpt_v is not None else None,
|
| 88 |
+
"Screening Velocity (m/s)": round(eff, 3) if eff is not None else None,
|
| 89 |
+
"Evidence Source": source,
|
| 90 |
+
"Delta (m/s)": round(delta_abs, 3) if delta_abs is not None else None,
|
| 91 |
+
"Delta (%)": round(delta_pct, 1) if delta_pct is not None else None,
|
| 92 |
+
"Screening Classification": eff_class,
|
| 93 |
+
"Classification Changed by Reconciliation": (
|
| 94 |
+
"Yes" if (flagged and rpt_v is not None and worker_class != eff_class)
|
| 95 |
+
else ("No" if flagged else "n/a - not flagged")),
|
| 96 |
+
})
|
| 97 |
+
return pd.DataFrame(rows)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# ---------------------------------------------------------------------------
|
| 101 |
+
# Continuity disclosure
|
| 102 |
+
# ---------------------------------------------------------------------------
|
| 103 |
+
|
| 104 |
+
def continuity_disclosure(metadata: Mapping[str, Any], review_pct: float = 0.5,
|
| 105 |
+
warning_pct: float = 1.0,
|
| 106 |
+
has_pollutants: bool = False) -> list[str]:
|
| 107 |
+
"""Sign-preserving continuity lines with symmetric absolute thresholds."""
|
| 108 |
+
lines: list[str] = []
|
| 109 |
+
for label, key in (("Surface-runoff continuity error", "runoff_error"),
|
| 110 |
+
("Flow-routing continuity error", "flow_error")):
|
| 111 |
+
val = metadata.get(key)
|
| 112 |
+
try:
|
| 113 |
+
v = float(val)
|
| 114 |
+
except (TypeError, ValueError):
|
| 115 |
+
lines.append(f"{label}: not reported by the engine.")
|
| 116 |
+
continue
|
| 117 |
+
lines.append(f"{label}: {v:+.3f}% (engine-reported sign preserved).")
|
| 118 |
+
if abs(v) > warning_pct:
|
| 119 |
+
lines.append(f"⚠️ {label} magnitude |{v:.3f}%| exceeds the {warning_pct:g}% absolute warning threshold and must be reviewed before the results are relied upon.")
|
| 120 |
+
elif abs(v) > review_pct:
|
| 121 |
+
lines.append(f"{label} magnitude |{v:.3f}%| exceeds the {review_pct:g}% absolute review threshold.")
|
| 122 |
+
if has_pollutants:
|
| 123 |
+
qv = metadata.get("quality_error")
|
| 124 |
+
try:
|
| 125 |
+
lines.append(f"Water-quality continuity error: {float(qv):+.3f}%.")
|
| 126 |
+
except (TypeError, ValueError):
|
| 127 |
+
lines.append("Water-quality continuity error: pollutants modelled but continuity not reported — review engine output.")
|
| 128 |
+
else:
|
| 129 |
+
lines.append("Water-quality continuity: Not applicable — no pollutants modelled.")
|
| 130 |
+
return lines
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
# ---------------------------------------------------------------------------
|
| 134 |
+
# Missing-information register
|
| 135 |
+
# ---------------------------------------------------------------------------
|
| 136 |
+
|
| 137 |
+
_METADATA_LABELS = {
|
| 138 |
+
"legal_description": "Legal land description",
|
| 139 |
+
"outline_plan_no": "Outline plan number",
|
| 140 |
+
"subdivision_no": "Subdivision number",
|
| 141 |
+
"development_permit_no": "Development permit number",
|
| 142 |
+
"consultant_file_no": "Consultant file number",
|
| 143 |
+
"prepared_by": "Prepared by (responsible person)",
|
| 144 |
+
"checked_by": "Checked by (reviewer)",
|
| 145 |
+
"client": "Client",
|
| 146 |
+
"consultant": "Consultant",
|
| 147 |
+
"construction_drawing_no": "Construction drawing number",
|
| 148 |
+
"development_agreement_no": "Development agreement number",
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def missing_information_register(metadata: Mapping[str, Any],
|
| 153 |
+
criteria_register: pd.DataFrame | None,
|
| 154 |
+
checklist: pd.DataFrame | None) -> pd.DataFrame:
|
| 155 |
+
"""Deterministic register of evidence the report cannot supply.
|
| 156 |
+
|
| 157 |
+
Items listed here block any related Pass classification elsewhere.
|
| 158 |
+
"""
|
| 159 |
+
rows: list[dict[str, str]] = []
|
| 160 |
+
for key, label in _METADATA_LABELS.items():
|
| 161 |
+
value = str(metadata.get(key, "") or "").strip()
|
| 162 |
+
if not value or value.lower() in ("not provided", "none", "-", "—"):
|
| 163 |
+
rows.append({"Item": label, "Category": "Project information",
|
| 164 |
+
"Status": "Not provided",
|
| 165 |
+
"Consequence": "Related administrative checklist items remain incomplete."})
|
| 166 |
+
if criteria_register is not None and not criteria_register.empty:
|
| 167 |
+
status_col = next((c for c in criteria_register.columns if "status" in c.lower()), None)
|
| 168 |
+
name_col = next((c for c in criteria_register.columns
|
| 169 |
+
if c.lower() in ("criterion", "requirement", "item", "name")),
|
| 170 |
+
criteria_register.columns[0])
|
| 171 |
+
if status_col:
|
| 172 |
+
for _, r in criteria_register.iterrows():
|
| 173 |
+
if "not established" in str(r.get(status_col, "")).lower():
|
| 174 |
+
rows.append({"Item": str(r.get(name_col)), "Category": "Governing criteria",
|
| 175 |
+
"Status": "Not established",
|
| 176 |
+
"Consequence": "Related screening cannot be reported as Pass; results remain screening-only."})
|
| 177 |
+
if checklist is not None and not checklist.empty and "Status" in checklist.columns:
|
| 178 |
+
for _, r in checklist.iterrows():
|
| 179 |
+
if str(r.get("Status", "")).strip().lower() == "missing":
|
| 180 |
+
rows.append({"Item": f"{r.get('Item')}: {str(r.get('Requirement'))[:80]}",
|
| 181 |
+
"Category": "SWMR checklist",
|
| 182 |
+
"Status": "Missing",
|
| 183 |
+
"Consequence": "Required for a submission-ready report."})
|
| 184 |
+
if not rows:
|
| 185 |
+
rows.append({"Item": "None identified", "Category": "—", "Status": "—",
|
| 186 |
+
"Consequence": "All tracked evidence items were supplied."})
|
| 187 |
+
return pd.DataFrame(rows)
|
test_regression.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Regression test suite for the SWMM Analysis MCP server.
|
| 2 |
+
|
| 3 |
+
Run: SWMM_WORKER_PYTHON=$(which python) python test_regression.py [path/to/Kincora_Phase_2.inp]
|
| 4 |
+
|
| 5 |
+
Levels: (1) unit tests of deterministic screening logic; (2) an integration
|
| 6 |
+
run of the Kincora reference model from upload through report generation;
|
| 7 |
+
(3) DOCX content checks. Kincora expected values live ONLY here (as test
|
| 8 |
+
pins with documented tolerances), never in server code.
|
| 9 |
+
|
| 10 |
+
Tolerances: velocities ±0.05 m/s; depths ±0.005 m; volumes ±2 m³;
|
| 11 |
+
continuity ±0.02 percentage points; times ±120 s.
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import math
|
| 17 |
+
import sys
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
import pandas as pd
|
| 21 |
+
|
| 22 |
+
sys.path.insert(0, str(Path(__file__).parent))
|
| 23 |
+
|
| 24 |
+
PASS = FAIL = 0
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def check(name: str, cond: bool, detail: str = "") -> None:
|
| 28 |
+
global PASS, FAIL
|
| 29 |
+
status = "PASS" if cond else "FAIL"
|
| 30 |
+
if cond:
|
| 31 |
+
PASS += 1
|
| 32 |
+
else:
|
| 33 |
+
FAIL += 1
|
| 34 |
+
print(f" {status}: {name}" + (f" [{detail}]" if detail and not cond else ""))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# ===========================================================================
|
| 38 |
+
# 1. UNIT TESTS
|
| 39 |
+
# ===========================================================================
|
| 40 |
+
|
| 41 |
+
def unit_tests() -> None:
|
| 42 |
+
print("\n== Unit tests: screening_logic ==")
|
| 43 |
+
from screening_logic import (classify_velocity, continuity_disclosure,
|
| 44 |
+
effective_velocity_table,
|
| 45 |
+
missing_information_register)
|
| 46 |
+
|
| 47 |
+
check("advisory classification (3.5)", "Advisory" in classify_velocity(3.5))
|
| 48 |
+
check("critical classification (4.5)", "Critical" in classify_velocity(4.5))
|
| 49 |
+
check("boundary 3.0 is below advisory", "Below" in classify_velocity(3.0))
|
| 50 |
+
check("boundary 4.0 is advisory not critical", "Advisory" in classify_velocity(4.0))
|
| 51 |
+
check("None -> Not assessed", classify_velocity(None) == "Not assessed")
|
| 52 |
+
check("NaN -> Not assessed", classify_velocity(float("nan")) == "Not assessed")
|
| 53 |
+
|
| 54 |
+
md = {"runoff_error": -1.933, "flow_error": 0.022}
|
| 55 |
+
lines = continuity_disclosure(md, 0.5, 1.0, has_pollutants=False)
|
| 56 |
+
joined = " | ".join(lines)
|
| 57 |
+
check("runoff sign preserved", "-1.933%" in joined)
|
| 58 |
+
check("runoff exceeds 1% absolute warning", "⚠️" in joined and "1.933" in joined)
|
| 59 |
+
check("routing reported separately, no warning", "+0.022%" in joined and joined.count("⚠️") == 1)
|
| 60 |
+
check("quality N/A without pollutants", "Not applicable — no pollutants modelled" in joined)
|
| 61 |
+
lines2 = continuity_disclosure({"runoff_error": -1.933, "flow_error": 0.022,
|
| 62 |
+
"quality_error": 0.4}, 0.5, 1.0, has_pollutants=True)
|
| 63 |
+
check("quality reported when pollutants modelled", any("+0.400%" in l for l in lines2))
|
| 64 |
+
check("negative below-threshold not warned", "⚠️" not in " ".join(
|
| 65 |
+
continuity_disclosure({"runoff_error": -0.4, "flow_error": 0.1}, 0.5, 1.0)))
|
| 66 |
+
|
| 67 |
+
link_df = pd.DataFrame([
|
| 68 |
+
{"Link ID": "L1", "Peak Velocity (m/s)": 1.186},
|
| 69 |
+
{"Link ID": "L2", "Peak Velocity (m/s)": 5.6},
|
| 70 |
+
])
|
| 71 |
+
recon = pd.DataFrame([
|
| 72 |
+
{"Link ID": "L1", "RPT Peak Velocity": 2.63, "Overall Status": "Discrepancy"},
|
| 73 |
+
{"Link ID": "L2", "RPT Peak Velocity": 5.61, "Overall Status": "OK"},
|
| 74 |
+
])
|
| 75 |
+
eff = effective_velocity_table(link_df, recon)
|
| 76 |
+
r1 = eff[eff["Link ID"] == "L1"].iloc[0]
|
| 77 |
+
r2 = eff[eff["Link ID"] == "L2"].iloc[0]
|
| 78 |
+
check("flagged link uses .rpt value", abs(r1["Screening Velocity (m/s)"] - 2.63) < 1e-6)
|
| 79 |
+
check("flagged link source is .rpt", ".rpt" in r1["Evidence Source"])
|
| 80 |
+
check("both values shown", r1["Worker Peak Velocity (m/s)"] == 1.186 and r1["RPT Peak Velocity (m/s)"] == 2.63)
|
| 81 |
+
check("deltas computed", abs(r1["Delta (m/s)"] - (1.186 - 2.63)) < 1e-6 and r1["Delta (%)"] is not None)
|
| 82 |
+
check("discrepancy does not create 3.0 exceedance", "Below advisory" in r1["Screening Classification"])
|
| 83 |
+
check("classification-changed = No for L1", r1["Classification Changed by Reconciliation"] == "No")
|
| 84 |
+
check("unflagged link uses worker value", abs(r2["Screening Velocity (m/s)"] - 5.6) < 1e-6
|
| 85 |
+
and "worker" in r2["Evidence Source"])
|
| 86 |
+
|
| 87 |
+
print("\n== Unit tests: storage & criteria gating ==")
|
| 88 |
+
from calgary_rules import CalgaryCriteria, apply_storage_classification, classify_overland
|
| 89 |
+
crit = CalgaryCriteria()
|
| 90 |
+
stor = pd.DataFrame([
|
| 91 |
+
{"Node ID": "Storage8a", "Type": "storage", "Time-Series Peak Depth (m)": 0.491, "Maximum Depth (m)": 0.5},
|
| 92 |
+
{"Node ID": "SUB1", "Type": "storage", "Time-Series Peak Depth (m)": 0.349, "Maximum Depth (m)": 2.0},
|
| 93 |
+
])
|
| 94 |
+
sc = apply_storage_classification(stor, crit, "m")
|
| 95 |
+
joined = sc.to_string()
|
| 96 |
+
check("no bare Pass in non-trap storage", not any(
|
| 97 |
+
str(s).strip() == "Pass" for s in sc["Calgary Status"]))
|
| 98 |
+
check("Not assessed language present for unclassified compliance",
|
| 99 |
+
"Not assessed" in joined)
|
| 100 |
+
margin_col = next(c for c in sc.columns if "Margin" in c)
|
| 101 |
+
check("margin column renamed to Modelled", margin_col.startswith("Modelled Depth Margin"))
|
| 102 |
+
m8a = float(sc[sc["Node ID"] == "Storage8a"][margin_col].iloc[0])
|
| 103 |
+
check("Storage8a modelled margin ~= 0.009 m", abs(m8a - 0.009) < 0.005, f"got {m8a}")
|
| 104 |
+
status, allowed = classify_overland(0.05, 1.0, crit.depth_velocity_curve)
|
| 105 |
+
check("overland verdict uses screening wording", "Screens" in status)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# ===========================================================================
|
| 109 |
+
# 2. INTEGRATION TESTS (Kincora reference model)
|
| 110 |
+
# ===========================================================================
|
| 111 |
+
|
| 112 |
+
def integration_tests(inp_path: str) -> tuple[str, dict]:
|
| 113 |
+
print("\n== Integration: Kincora pipeline ==")
|
| 114 |
+
import tools
|
| 115 |
+
inp_text = Path(inp_path).read_text(encoding="utf-8", errors="replace")
|
| 116 |
+
up = tools.upload_model(inp_text, Path(inp_path).name)
|
| 117 |
+
sid = up["session_id"]
|
| 118 |
+
check("inventory: 16 conduits / 11 subs / 11 storage",
|
| 119 |
+
up["element_counts"].get("CONDUITS") == 16
|
| 120 |
+
and up["element_counts"].get("SUBCATCHMENTS") == 11
|
| 121 |
+
and up["element_counts"].get("STORAGE") == 11, str(up["element_counts"]))
|
| 122 |
+
|
| 123 |
+
run = tools.run_simulation(sid)
|
| 124 |
+
check("simulation completed", run["simulation"] == "completed")
|
| 125 |
+
check("model SHA-256 present", len(run.get("model_sha256", "")) == 64)
|
| 126 |
+
check("runoff continuity ~ -1.933%", abs(run["runoff_continuity_error_pct"] - (-1.933)) <= 0.02)
|
| 127 |
+
check("routing continuity ~ 0.022%", abs(run["flow_continuity_error_pct"] - 0.022) <= 0.02)
|
| 128 |
+
check("reconciliation not claimed clean",
|
| 129 |
+
"Review" in run["rpt_reconciliation"].get("verdict", ""))
|
| 130 |
+
|
| 131 |
+
# High-velocity conduits (worker values ~= .rpt after Rev 23.2 velocity fix)
|
| 132 |
+
links = {r["Link ID"]: r for r in tools.get_link_results(sid, limit=30)["rows"]}
|
| 133 |
+
expected = {"1000": 5.606, "1001": 5.373, "1003": 3.864, "1002": 3.456, "1005": 3.251}
|
| 134 |
+
for lid, ev in expected.items():
|
| 135 |
+
got = links[lid]["Peak Velocity (m/s)"]
|
| 136 |
+
check(f"velocity {lid} ~= {ev}", abs(got - ev) <= 0.05, f"got {got}")
|
| 137 |
+
|
| 138 |
+
# Storage8a pins
|
| 139 |
+
stor = {r["Node ID"]: r for r in tools.get_node_results(sid, node_type="storage", limit=30)["rows"]}
|
| 140 |
+
s8 = stor["Storage8a"]
|
| 141 |
+
check("Storage8a peak depth ~= 0.491 m", abs(s8["Peak Depth (m)"] - 0.491) <= 0.005)
|
| 142 |
+
check("Storage8a utilization ~= 98.2%", abs(s8["Depth Ratio"] - 0.982) <= 0.01)
|
| 143 |
+
ts = tools.get_timeseries(sid, "node", "Storage8a", "volume")
|
| 144 |
+
check("Storage8a peak volume ~= 179.8 m3", abs(ts["peak"] - 179.8) <= 2.0, f"got {ts['peak']}")
|
| 145 |
+
check("Storage8a peak time ~ 00:26:30",
|
| 146 |
+
"00:26" in str(ts["time_of_peak"]) or "00:27" in str(ts["time_of_peak"]),
|
| 147 |
+
str(ts["time_of_peak"]))
|
| 148 |
+
|
| 149 |
+
# CB2A/CB2a case QA + 108(Spill) reconciliation
|
| 150 |
+
review = tools.preliminary_design_review(sid)
|
| 151 |
+
basis = " | ".join(str(r.get("deterministic_basis")) for r in review["findings"]["rows"])
|
| 152 |
+
check("CB2A/CB2a case finding present", "CB2A" in basis and "CB2a" in basis and "case" in basis.lower())
|
| 153 |
+
recon = tools.get_reconciliation(sid)
|
| 154 |
+
fl = {r["Link ID"]: r for r in recon["flagged_links"]["rows"]}
|
| 155 |
+
check("108(Spill) flagged", "108(Spill)" in fl)
|
| 156 |
+
if "108(Spill)" in fl:
|
| 157 |
+
r = fl["108(Spill)"]
|
| 158 |
+
check("108(Spill) worker ~1.186 vs rpt ~2.63",
|
| 159 |
+
abs(r["Worker Peak Velocity"] - 1.186) <= 0.05 and abs(r["RPT Peak Velocity"] - 2.63) <= 0.05,
|
| 160 |
+
f"{r['Worker Peak Velocity']} / {r['RPT Peak Velocity']}")
|
| 161 |
+
|
| 162 |
+
rep = tools.generate_report(sid, "Kincora Regression", client="Test")
|
| 163 |
+
from sessions import STORE
|
| 164 |
+
docx_path = STORE.get(sid).workdir / "outputs" / "Kincora_Regression_SWMR_Draft.docx"
|
| 165 |
+
return str(docx_path), {"session": sid}
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
# ===========================================================================
|
| 169 |
+
# 3. DOCX CONTENT TESTS
|
| 170 |
+
# ===========================================================================
|
| 171 |
+
|
| 172 |
+
def docx_tests(docx_path: str) -> None:
|
| 173 |
+
print("\n== DOCX content checks ==")
|
| 174 |
+
from docx import Document
|
| 175 |
+
doc = Document(docx_path)
|
| 176 |
+
texts = [p.text for p in doc.paragraphs]
|
| 177 |
+
joined = "\n".join(texts)
|
| 178 |
+
heads = [t for t in texts if t and doc.paragraphs[texts.index(t)].style.name.startswith("Heading")]
|
| 179 |
+
|
| 180 |
+
for h in ["1.0 INTRODUCTION", "4.9 Continuity and Result Reconciliation",
|
| 181 |
+
"4.10 Missing-Information Register", "5.0 SUMMARY OF FINDINGS",
|
| 182 |
+
"APPENDIX D - MODEL INPUT AND OUTPUT LISTINGS", "5.0a Prioritized Actions",
|
| 183 |
+
"1.0a Model Identity and Execution Provenance"]:
|
| 184 |
+
check(f"heading present: {h[:45]}", any(t.startswith(h) for t in texts))
|
| 185 |
+
|
| 186 |
+
check("runoff warning disclosed with sign", "-1.933%" in joined and "⚠️" in joined)
|
| 187 |
+
check("routing reported separately", "+0.022%" in joined)
|
| 188 |
+
check("quality N/A disclosed", "Not applicable — no pollutants modelled" in joined)
|
| 189 |
+
check("reconciliation not claimed clean", "not claimed to be fully clean" in joined)
|
| 190 |
+
check("108(Spill) precedence statement present",
|
| 191 |
+
"108(Spill)" in joined and ".rpt value governs" in joined)
|
| 192 |
+
check("108(Spill) discrepancy does not change classification",
|
| 193 |
+
"does not change the screening classification" in joined)
|
| 194 |
+
all_cells = " | ".join(c.text for t in doc.tables for r in t.rows for c in r.cells)
|
| 195 |
+
everything = joined + " | " + all_cells
|
| 196 |
+
check("critical vs advisory language present",
|
| 197 |
+
"CRITICAL screening exceedance" in everything and "Advisory screening exceedance" in everything)
|
| 198 |
+
check("preliminary disclaimer present", "professional authentication are required" in joined)
|
| 199 |
+
check("no calibration/validation claims",
|
| 200 |
+
"calibrated" not in joined.lower() and "validated model" not in joined.lower())
|
| 201 |
+
|
| 202 |
+
# No unsupported storage Pass: scan tables for a bare "Pass" in Calgary Status
|
| 203 |
+
bare_pass = False
|
| 204 |
+
for tbl in doc.tables:
|
| 205 |
+
headers = [c.text for c in tbl.rows[0].cells]
|
| 206 |
+
if any("Calgary Status" in h for h in headers):
|
| 207 |
+
idx = next(i for i, h in enumerate(headers) if "Calgary Status" in h)
|
| 208 |
+
for row in tbl.rows[1:]:
|
| 209 |
+
if row.cells[idx].text.strip() == "Pass":
|
| 210 |
+
bare_pass = True
|
| 211 |
+
check("no bare 'Pass' in storage status table", not bare_pass)
|
| 212 |
+
check("modelled-margin terminology used", "Modelled Depth Margin" in
|
| 213 |
+
" ".join(c.text for t in doc.tables for r in t.rows for c in r.cells))
|
| 214 |
+
check("SHA-256 in identity table", any(len(c.text.strip()) == 64 and all(
|
| 215 |
+
ch in "0123456789abcdef" for ch in c.text.strip())
|
| 216 |
+
for t in doc.tables[:6] for r in t.rows for c in r.cells))
|
| 217 |
+
n_blank_runs = sum(1 for i in range(len(texts) - 3)
|
| 218 |
+
if all(not texts[i + j].strip() for j in range(4)))
|
| 219 |
+
check("no 4+ consecutive blank paragraphs", n_blank_runs == 0, f"{n_blank_runs} runs")
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
if __name__ == "__main__":
|
| 223 |
+
inp = sys.argv[1] if len(sys.argv) > 1 else "Kincora_Phase_2.inp"
|
| 224 |
+
unit_tests()
|
| 225 |
+
docx_path, _ = integration_tests(inp)
|
| 226 |
+
docx_tests(docx_path)
|
| 227 |
+
print(f"\n{'=' * 50}\nTOTAL: {PASS} passed, {FAIL} failed")
|
| 228 |
+
sys.exit(1 if FAIL else 0)
|
tools.py
CHANGED
|
@@ -104,6 +104,11 @@ def run_simulation(session_id: str) -> dict:
|
|
| 104 |
raise ValueError("Session has no uploaded model.")
|
| 105 |
results = run_swmm(inp_path)
|
| 106 |
md = results["metadata"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
sections = session.data["sections"]
|
| 108 |
node_df = mp.build_node_summary(results["node_ts"], mp.parse_node_types(sections), 0.001, 0.9)
|
| 109 |
link_df = mp.build_link_summary(results["link_ts"], mp.parse_link_topology(sections),
|
|
@@ -132,6 +137,8 @@ def run_simulation(session_id: str) -> dict:
|
|
| 132 |
return {
|
| 133 |
"session_id": session.id,
|
| 134 |
"simulation": "completed",
|
|
|
|
|
|
|
| 135 |
"flow_units": md.get("flow_units"),
|
| 136 |
"runoff_continuity_error_pct": round(float(md.get("runoff_error", 0.0)), 3),
|
| 137 |
"flow_continuity_error_pct": round(float(md.get("flow_error", 0.0)), 3),
|
|
@@ -394,19 +401,90 @@ def attach_figure(session_id: str, image_base64: str, caption: str,
|
|
| 394 |
"next_step": "Call generate_report; the figure will be embedded with a labelled caption."}
|
| 395 |
|
| 396 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 397 |
def generate_report(session_id: str, project_name: str, client: str = "",
|
| 398 |
consultant: str = "", prepared_by: str = "",
|
| 399 |
-
outline_plan_no: str = ""
|
|
|
|
| 400 |
"""Generate the Calgary-style SWMR draft package (docx + audit zip).
|
| 401 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 402 |
Returns download paths served by this Space at /files/{session_id}/{name}.
|
| 403 |
The draft-readiness score honestly reflects missing project information.
|
| 404 |
"""
|
| 405 |
from report_engine import ReportMetadata, generate_report_package
|
| 406 |
session = STORE.get(session_id)
|
| 407 |
_require_results(session)
|
| 408 |
-
|
| 409 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 410 |
findings = session.data.get("findings") or []
|
| 411 |
pkg = generate_report_package(
|
| 412 |
metadata=meta, inp_sections=session.data["sections"],
|
|
@@ -418,7 +496,17 @@ def generate_report(session_id: str, project_name: str, client: str = "",
|
|
| 418 |
"findings": findings, "status": "Preliminary",
|
| 419 |
"manifest": {"rpt_reconciliation": session.data.get("recon_summary", {})},
|
| 420 |
} if findings else None,
|
| 421 |
-
attached_figures=session.data.get("figures") or None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 422 |
outputs = session.workdir / "outputs"
|
| 423 |
outputs.mkdir(exist_ok=True)
|
| 424 |
files = {}
|
|
@@ -445,6 +533,6 @@ TOOL_REGISTRY: dict[str, Callable[..., dict]] = {
|
|
| 445 |
get_node_results, get_link_results, get_subcatchment_results,
|
| 446 |
get_timeseries, query_results, get_table_catalog,
|
| 447 |
calgary_screening, preliminary_design_review, get_reconciliation,
|
| 448 |
-
run_scenario, attach_figure, generate_report,
|
| 449 |
]
|
| 450 |
}
|
|
|
|
| 104 |
raise ValueError("Session has no uploaded model.")
|
| 105 |
results = run_swmm(inp_path)
|
| 106 |
md = results["metadata"]
|
| 107 |
+
import hashlib, datetime
|
| 108 |
+
sha256 = hashlib.sha256(Path(inp_path).read_bytes()).hexdigest()
|
| 109 |
+
run_id = datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")
|
| 110 |
+
md["model_sha256"] = sha256
|
| 111 |
+
md["run_id"] = run_id
|
| 112 |
sections = session.data["sections"]
|
| 113 |
node_df = mp.build_node_summary(results["node_ts"], mp.parse_node_types(sections), 0.001, 0.9)
|
| 114 |
link_df = mp.build_link_summary(results["link_ts"], mp.parse_link_topology(sections),
|
|
|
|
| 137 |
return {
|
| 138 |
"session_id": session.id,
|
| 139 |
"simulation": "completed",
|
| 140 |
+
"model_sha256": sha256,
|
| 141 |
+
"run_id": run_id,
|
| 142 |
"flow_units": md.get("flow_units"),
|
| 143 |
"runoff_continuity_error_pct": round(float(md.get("runoff_error", 0.0)), 3),
|
| 144 |
"flow_continuity_error_pct": round(float(md.get("flow_error", 0.0)), 3),
|
|
|
|
| 401 |
"next_step": "Call generate_report; the figure will be embedded with a labelled caption."}
|
| 402 |
|
| 403 |
|
| 404 |
+
_METADATA_FIELDS = {
|
| 405 |
+
"client", "consultant", "consultant_file_no", "subdivision_no", "outline_plan_no",
|
| 406 |
+
"development_permit_no", "design_storm", "prepared_by", "checked_by", "municipality",
|
| 407 |
+
"contact_name", "contact_email", "legal_description", "construction_drawing_no",
|
| 408 |
+
"development_agreement_no",
|
| 409 |
+
}
|
| 410 |
+
_NARRATIVE_FIELDS = {
|
| 411 |
+
"introduction", "site_description", "design_objectives", "methodology",
|
| 412 |
+
"applicable_criteria",
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def set_report_details(session_id: str, details: dict | str) -> dict:
|
| 417 |
+
"""Store site-specific narrative and project metadata for generate_report.
|
| 418 |
+
|
| 419 |
+
details keys — NARRATIVE (multi-line text; design_objectives lines become
|
| 420 |
+
bullets): introduction, site_description, design_objectives, methodology,
|
| 421 |
+
applicable_criteria. METADATA (single values): client, consultant,
|
| 422 |
+
consultant_file_no, subdivision_no, outline_plan_no,
|
| 423 |
+
development_permit_no, design_storm, prepared_by, checked_by,
|
| 424 |
+
municipality, contact_name, contact_email, legal_description,
|
| 425 |
+
construction_drawing_no, development_agreement_no.
|
| 426 |
+
|
| 427 |
+
Repeated calls merge (later values win); pass an empty string to clear a
|
| 428 |
+
key. Attribute provenance inside the text itself (model-derived vs
|
| 429 |
+
user-supplied vs inferred) — the server stores it verbatim. For a site
|
| 430 |
+
aerial/location image use attach_figure with section="site".
|
| 431 |
+
"""
|
| 432 |
+
session = STORE.get(session_id)
|
| 433 |
+
if isinstance(details, str):
|
| 434 |
+
details = json.loads(details)
|
| 435 |
+
if not isinstance(details, dict):
|
| 436 |
+
raise ValueError("details must be a JSON object of field -> text.")
|
| 437 |
+
unknown = sorted(set(details) - _METADATA_FIELDS - _NARRATIVE_FIELDS)
|
| 438 |
+
if unknown:
|
| 439 |
+
raise ValueError(f"Unknown field(s) {unknown}. Narrative: {sorted(_NARRATIVE_FIELDS)}; "
|
| 440 |
+
f"metadata: {sorted(_METADATA_FIELDS)}.")
|
| 441 |
+
store = session.data.setdefault("report_details", {})
|
| 442 |
+
for key, value in details.items():
|
| 443 |
+
text = str(value).strip()
|
| 444 |
+
if text:
|
| 445 |
+
store[key] = text
|
| 446 |
+
else:
|
| 447 |
+
store.pop(key, None)
|
| 448 |
+
return {"session_id": session.id,
|
| 449 |
+
"stored_narrative": sorted(k for k in store if k in _NARRATIVE_FIELDS),
|
| 450 |
+
"stored_metadata": sorted(k for k in store if k in _METADATA_FIELDS),
|
| 451 |
+
"next_step": "generate_report will include these details; readiness scoring reflects them."}
|
| 452 |
+
|
| 453 |
+
|
| 454 |
def generate_report(session_id: str, project_name: str, client: str = "",
|
| 455 |
consultant: str = "", prepared_by: str = "",
|
| 456 |
+
outline_plan_no: str = "",
|
| 457 |
+
include_model_appendix: bool = True) -> dict:
|
| 458 |
"""Generate the Calgary-style SWMR draft package (docx + audit zip).
|
| 459 |
|
| 460 |
+
include_model_appendix (default True) reproduces the model input (.inp)
|
| 461 |
+
and engine output (.rpt) as fixed-width listings in APPENDIX D, per the
|
| 462 |
+
Calgary SWMR checklist; very long files are middle-truncated in the docx
|
| 463 |
+
with the untruncated copies archived in the audit zip under model/.
|
| 464 |
Returns download paths served by this Space at /files/{session_id}/{name}.
|
| 465 |
The draft-readiness score honestly reflects missing project information.
|
| 466 |
"""
|
| 467 |
from report_engine import ReportMetadata, generate_report_package
|
| 468 |
session = STORE.get(session_id)
|
| 469 |
_require_results(session)
|
| 470 |
+
stored = dict(session.data.get("report_details", {}))
|
| 471 |
+
meta_kwargs = {k: v for k, v in stored.items() if k in _METADATA_FIELDS}
|
| 472 |
+
# Explicit arguments override stored details when provided.
|
| 473 |
+
for key, value in (("client", client), ("consultant", consultant),
|
| 474 |
+
("prepared_by", prepared_by), ("outline_plan_no", outline_plan_no)):
|
| 475 |
+
if value:
|
| 476 |
+
meta_kwargs[key] = value
|
| 477 |
+
narrative = {k: v for k, v in stored.items() if k in _NARRATIVE_FIELDS}
|
| 478 |
+
meta = ReportMetadata(project_name=project_name, **meta_kwargs)
|
| 479 |
+
model_listings = None
|
| 480 |
+
if include_model_appendix:
|
| 481 |
+
inp_p = Path(session.data["inp_path"])
|
| 482 |
+
model_listings = {"inp_name": inp_p.name,
|
| 483 |
+
"inp_text": inp_p.read_text(encoding="utf-8", errors="replace")}
|
| 484 |
+
rpt_p = (session.data["results"].get("metadata", {}) or {}).get("report_path")
|
| 485 |
+
if rpt_p and Path(str(rpt_p)).exists():
|
| 486 |
+
model_listings["rpt_name"] = Path(str(rpt_p)).name
|
| 487 |
+
model_listings["rpt_text"] = Path(str(rpt_p)).read_text(encoding="utf-8", errors="replace")
|
| 488 |
findings = session.data.get("findings") or []
|
| 489 |
pkg = generate_report_package(
|
| 490 |
metadata=meta, inp_sections=session.data["sections"],
|
|
|
|
| 496 |
"findings": findings, "status": "Preliminary",
|
| 497 |
"manifest": {"rpt_reconciliation": session.data.get("recon_summary", {})},
|
| 498 |
} if findings else None,
|
| 499 |
+
attached_figures=session.data.get("figures") or None,
|
| 500 |
+
narrative_sections=narrative or None,
|
| 501 |
+
model_listings=model_listings,
|
| 502 |
+
reconciliation={"links": session.data.get("recon_links"),
|
| 503 |
+
"summary": session.data.get("recon_summary", {})},
|
| 504 |
+
model_identity={"inp_name": Path(session.data["inp_path"]).name,
|
| 505 |
+
"sha256": session.data["results"]["metadata"].get("model_sha256", "—"),
|
| 506 |
+
"session_id": session.id,
|
| 507 |
+
"run_id": session.data["results"]["metadata"].get("run_id", "—"),
|
| 508 |
+
"engine": "EPA SWMM / OpenSWMM 6 (crash-isolated worker, engine Rev 23.2)",
|
| 509 |
+
"status": "Completed"})
|
| 510 |
outputs = session.workdir / "outputs"
|
| 511 |
outputs.mkdir(exist_ok=True)
|
| 512 |
files = {}
|
|
|
|
| 533 |
get_node_results, get_link_results, get_subcatchment_results,
|
| 534 |
get_timeseries, query_results, get_table_catalog,
|
| 535 |
calgary_screening, preliminary_design_review, get_reconciliation,
|
| 536 |
+
run_scenario, attach_figure, set_report_details, generate_report,
|
| 537 |
]
|
| 538 |
}
|