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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Solver-option and execution-integrity gates
|
| 27 |
+
# ---------------------------------------------------------------------------
|
| 28 |
+
|
| 29 |
+
def resolve_legacy_solver_options(options: Mapping[str, Any]) -> dict[str, Any]:
|
| 30 |
+
"""Resolve auditable SWMM legacy-zero sentinels for an execution copy.
|
| 31 |
+
|
| 32 |
+
Older/converted INP files can explicitly serialize zero for dynamic-wave
|
| 33 |
+
options that EPA SWMM displays and executes using unit-aware defaults.
|
| 34 |
+
This function returns substitutions for an immutable derivative; it never
|
| 35 |
+
edits the uploaded source model. Negative and non-numeric values remain
|
| 36 |
+
blocking errors. Omitted values remain omitted for the engine to default.
|
| 37 |
+
"""
|
| 38 |
+
opts = {str(k).upper(): str(v).strip() for k, v in options.items()}
|
| 39 |
+
if opts.get("FLOW_ROUTING", "").upper() != "DYNWAVE":
|
| 40 |
+
return {"effective_options": dict(opts), "substitutions": [], "errors": []}
|
| 41 |
+
flow_units = opts.get("FLOW_UNITS", "").upper()
|
| 42 |
+
si_units = flow_units in {"CMS", "LPS", "MLD"}
|
| 43 |
+
defaults = {
|
| 44 |
+
"MAX_TRIALS": (8.0, "count"),
|
| 45 |
+
"HEAD_TOLERANCE": (0.0015 if si_units else 0.005, "m" if si_units else "ft"),
|
| 46 |
+
"MIN_SURFAREA": (1.167 if si_units else 12.566, "m2" if si_units else "ft2"),
|
| 47 |
+
}
|
| 48 |
+
effective = dict(opts)
|
| 49 |
+
substitutions: list[dict[str, Any]] = []
|
| 50 |
+
errors: list[str] = []
|
| 51 |
+
for name, (default, units) in defaults.items():
|
| 52 |
+
if name not in opts:
|
| 53 |
+
continue # omitted means use the engine default
|
| 54 |
+
try:
|
| 55 |
+
value = float(opts[name])
|
| 56 |
+
except (TypeError, ValueError):
|
| 57 |
+
errors.append(f"{name} must be numeric for dynamic-wave routing.")
|
| 58 |
+
continue
|
| 59 |
+
if value < 0:
|
| 60 |
+
errors.append(
|
| 61 |
+
f"{name} cannot be negative for dynamic-wave routing; "
|
| 62 |
+
f"the uploaded value is {opts[name]!r}."
|
| 63 |
+
)
|
| 64 |
+
elif value == 0:
|
| 65 |
+
effective[name] = format(default, "g")
|
| 66 |
+
substitutions.append({
|
| 67 |
+
"option": name, "original_value": opts[name],
|
| 68 |
+
"effective_value": default, "units": units,
|
| 69 |
+
"reason": "Recognized legacy zero/default sentinel",
|
| 70 |
+
})
|
| 71 |
+
return {"effective_options": effective,
|
| 72 |
+
"substitutions": substitutions, "errors": errors}
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def validate_solver_options(options: Mapping[str, Any]) -> list[str]:
|
| 76 |
+
"""Return only blocking errors after legacy-default resolution."""
|
| 77 |
+
return list(resolve_legacy_solver_options(options)["errors"])
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def execution_integrity_assessment(metadata: Mapping[str, Any]) -> dict[str, Any]:
|
| 81 |
+
"""Classify whether hydraulic results can support screening conclusions."""
|
| 82 |
+
def number(key: str, default: float = 0.0) -> float:
|
| 83 |
+
try:
|
| 84 |
+
return float(metadata.get(key, default))
|
| 85 |
+
except (TypeError, ValueError):
|
| 86 |
+
return default
|
| 87 |
+
|
| 88 |
+
steps = int(number("routing_steps"))
|
| 89 |
+
failed = int(number("not_converged_steps"))
|
| 90 |
+
pct_failed = number("pct_not_converged")
|
| 91 |
+
flow_error = abs(number("flow_error"))
|
| 92 |
+
runoff_error = abs(number("runoff_error"))
|
| 93 |
+
|
| 94 |
+
invalid_reasons: list[str] = []
|
| 95 |
+
if steps > 0 and failed >= steps:
|
| 96 |
+
invalid_reasons.append("every routing step failed to converge")
|
| 97 |
+
elif pct_failed >= 5.0:
|
| 98 |
+
invalid_reasons.append(f"{pct_failed:.3f}% of routing steps failed to converge")
|
| 99 |
+
if flow_error >= 10.0:
|
| 100 |
+
invalid_reasons.append(f"flow-routing continuity error is {flow_error:.3f}%")
|
| 101 |
+
|
| 102 |
+
if invalid_reasons:
|
| 103 |
+
return {
|
| 104 |
+
"status": "invalid",
|
| 105 |
+
"results_usable": False,
|
| 106 |
+
"hydraulic_conclusions_allowed": False,
|
| 107 |
+
"reason": "; ".join(invalid_reasons) + ".",
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
limitations: list[str] = []
|
| 111 |
+
if failed > 0:
|
| 112 |
+
limitations.append(f"{failed} routing step(s) did not converge")
|
| 113 |
+
if flow_error > 1.0:
|
| 114 |
+
limitations.append(f"flow-routing continuity error is {flow_error:.3f}%")
|
| 115 |
+
if runoff_error > 1.0:
|
| 116 |
+
limitations.append(f"runoff continuity error is {runoff_error:.3f}%")
|
| 117 |
+
return {
|
| 118 |
+
"status": "limited" if limitations else "valid",
|
| 119 |
+
"results_usable": True,
|
| 120 |
+
"hydraulic_conclusions_allowed": True,
|
| 121 |
+
"reason": "; ".join(limitations) + ("." if limitations else "Execution-integrity checks passed."),
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# ---------------------------------------------------------------------------
|
| 126 |
+
# Velocity classification and evidence precedence
|
| 127 |
+
# ---------------------------------------------------------------------------
|
| 128 |
+
|
| 129 |
+
def classify_velocity(velocity: float | None, advisory: float = 3.0,
|
| 130 |
+
critical: float = 4.0) -> str:
|
| 131 |
+
"""Deterministic dual-threshold screening classification (not a
|
| 132 |
+
regulatory determination)."""
|
| 133 |
+
if velocity is None:
|
| 134 |
+
return "Not assessed"
|
| 135 |
+
try:
|
| 136 |
+
v = float(velocity)
|
| 137 |
+
except (TypeError, ValueError):
|
| 138 |
+
return "Not assessed"
|
| 139 |
+
if math.isnan(v):
|
| 140 |
+
return "Not assessed"
|
| 141 |
+
if v > critical:
|
| 142 |
+
return f"Critical screening exceedance (> {critical:g} m/s)"
|
| 143 |
+
if v > advisory:
|
| 144 |
+
return f"Advisory screening exceedance (> {advisory:g} m/s)"
|
| 145 |
+
return f"Below advisory threshold ({advisory:g} m/s)"
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def effective_velocity_table(link_df: pd.DataFrame,
|
| 149 |
+
recon_links: pd.DataFrame | None,
|
| 150 |
+
advisory: float = 3.0,
|
| 151 |
+
critical: float = 4.0) -> pd.DataFrame:
|
| 152 |
+
"""Per-conduit screening table applying the reconciliation precedence.
|
| 153 |
+
|
| 154 |
+
Columns: Link ID, Worker Peak Velocity, RPT Peak Velocity,
|
| 155 |
+
Screening Velocity, Evidence Source, Delta (abs), Delta (%),
|
| 156 |
+
Screening Classification, Classification Changed by Reconciliation.
|
| 157 |
+
"""
|
| 158 |
+
if link_df is None or link_df.empty:
|
| 159 |
+
return pd.DataFrame()
|
| 160 |
+
vel_col = next((c for c in link_df.columns if c.startswith("Peak Velocity")), None)
|
| 161 |
+
if vel_col is None:
|
| 162 |
+
return pd.DataFrame()
|
| 163 |
+
recon: dict[str, dict[str, Any]] = {}
|
| 164 |
+
if recon_links is not None and not recon_links.empty:
|
| 165 |
+
for _, r in recon_links.iterrows():
|
| 166 |
+
recon[str(r.get("Link ID"))] = r.to_dict()
|
| 167 |
+
|
| 168 |
+
rows: list[dict[str, Any]] = []
|
| 169 |
+
for _, r in link_df.iterrows():
|
| 170 |
+
link_id = str(r.get("Link ID"))
|
| 171 |
+
worker_v = pd.to_numeric(pd.Series([r.get(vel_col)]), errors="coerce").iloc[0]
|
| 172 |
+
rec = recon.get(link_id, {})
|
| 173 |
+
rpt_v = rec.get("RPT Peak Velocity")
|
| 174 |
+
rpt_v = float(rpt_v) if rpt_v is not None and not (isinstance(rpt_v, float) and math.isnan(rpt_v)) else None
|
| 175 |
+
flagged = str(rec.get("Overall Status", "OK")) not in ("OK", "Unavailable", "nan", "None")
|
| 176 |
+
if flagged and rpt_v is not None:
|
| 177 |
+
eff, source = rpt_v, "engine .rpt (reconciliation-flagged)"
|
| 178 |
+
else:
|
| 179 |
+
eff, source = (float(worker_v) if pd.notna(worker_v) else None), "worker time series"
|
| 180 |
+
worker_class = classify_velocity(float(worker_v) if pd.notna(worker_v) else None, advisory, critical)
|
| 181 |
+
eff_class = classify_velocity(eff, advisory, critical)
|
| 182 |
+
delta_abs = (float(worker_v) - rpt_v) if (pd.notna(worker_v) and rpt_v is not None) else None
|
| 183 |
+
delta_pct = (100.0 * delta_abs / abs(rpt_v)) if (delta_abs is not None and rpt_v not in (None, 0)) else None
|
| 184 |
+
rows.append({
|
| 185 |
+
"Link ID": link_id,
|
| 186 |
+
"Worker Peak Velocity (m/s)": round(float(worker_v), 3) if pd.notna(worker_v) else None,
|
| 187 |
+
"RPT Peak Velocity (m/s)": round(rpt_v, 3) if rpt_v is not None else None,
|
| 188 |
+
"Screening Velocity (m/s)": round(eff, 3) if eff is not None else None,
|
| 189 |
+
"Evidence Source": source,
|
| 190 |
+
"Delta (m/s)": round(delta_abs, 3) if delta_abs is not None else None,
|
| 191 |
+
"Delta (%)": round(delta_pct, 1) if delta_pct is not None else None,
|
| 192 |
+
"Screening Classification": eff_class,
|
| 193 |
+
"Classification Changed by Reconciliation": (
|
| 194 |
+
"Yes" if (flagged and rpt_v is not None and worker_class != eff_class)
|
| 195 |
+
else ("No" if flagged else "n/a - not flagged")),
|
| 196 |
+
})
|
| 197 |
+
return pd.DataFrame(rows)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
# ---------------------------------------------------------------------------
|
| 201 |
+
# Continuity disclosure
|
| 202 |
+
# ---------------------------------------------------------------------------
|
| 203 |
+
|
| 204 |
+
def continuity_disclosure(metadata: Mapping[str, Any], review_pct: float = 0.5,
|
| 205 |
+
warning_pct: float = 1.0,
|
| 206 |
+
has_pollutants: bool = False) -> list[str]:
|
| 207 |
+
"""Sign-preserving continuity lines with symmetric absolute thresholds."""
|
| 208 |
+
lines: list[str] = []
|
| 209 |
+
for label, key in (("Surface-runoff continuity error", "runoff_error"),
|
| 210 |
+
("Flow-routing continuity error", "flow_error")):
|
| 211 |
+
val = metadata.get(key)
|
| 212 |
+
try:
|
| 213 |
+
v = float(val)
|
| 214 |
+
except (TypeError, ValueError):
|
| 215 |
+
lines.append(f"{label}: not reported by the engine.")
|
| 216 |
+
continue
|
| 217 |
+
lines.append(f"{label}: {v:+.3f}% (engine-reported sign preserved).")
|
| 218 |
+
if abs(v) > warning_pct:
|
| 219 |
+
lines.append(f"WARNING: {label} magnitude |{v:.3f}%| exceeds the {warning_pct:g}% absolute warning threshold and must be reviewed before the results are relied upon.")
|
| 220 |
+
elif abs(v) > review_pct:
|
| 221 |
+
lines.append(f"{label} magnitude |{v:.3f}%| exceeds the {review_pct:g}% absolute review threshold.")
|
| 222 |
+
if has_pollutants:
|
| 223 |
+
qv = metadata.get("quality_error")
|
| 224 |
+
try:
|
| 225 |
+
lines.append(f"Water-quality continuity error: {float(qv):+.3f}%.")
|
| 226 |
+
except (TypeError, ValueError):
|
| 227 |
+
lines.append("Water-quality continuity error: pollutants modelled but continuity not reported β review engine output.")
|
| 228 |
+
else:
|
| 229 |
+
lines.append("Water-quality continuity: Not applicable β no pollutants modelled.")
|
| 230 |
+
return lines
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
# ---------------------------------------------------------------------------
|
| 234 |
+
# Missing-information register
|
| 235 |
+
# ---------------------------------------------------------------------------
|
| 236 |
+
|
| 237 |
+
_METADATA_LABELS = {
|
| 238 |
+
"legal_description": "Legal land description",
|
| 239 |
+
"outline_plan_no": "Outline plan number",
|
| 240 |
+
"subdivision_no": "Subdivision number",
|
| 241 |
+
"development_permit_no": "Development permit number",
|
| 242 |
+
"consultant_file_no": "Consultant file number",
|
| 243 |
+
"prepared_by": "Prepared by (responsible person)",
|
| 244 |
+
"checked_by": "Checked by (reviewer)",
|
| 245 |
+
"client": "Client",
|
| 246 |
+
"consultant": "Consultant",
|
| 247 |
+
"construction_drawing_no": "Construction drawing number",
|
| 248 |
+
"development_agreement_no": "Development agreement number",
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def missing_information_register(metadata: Mapping[str, Any],
|
| 253 |
+
criteria_register: pd.DataFrame | None,
|
| 254 |
+
checklist: pd.DataFrame | None) -> pd.DataFrame:
|
| 255 |
+
"""Deterministic register of evidence the report cannot supply.
|
| 256 |
+
|
| 257 |
+
Items listed here block any related Pass classification elsewhere.
|
| 258 |
+
"""
|
| 259 |
+
rows: list[dict[str, str]] = []
|
| 260 |
+
for key, label in _METADATA_LABELS.items():
|
| 261 |
+
value = str(metadata.get(key, "") or "").strip()
|
| 262 |
+
if not value or value.lower() in ("not provided", "none", "-", "β"):
|
| 263 |
+
rows.append({"Item": label, "Category": "Project information",
|
| 264 |
+
"Status": "Not provided",
|
| 265 |
+
"Consequence": "Related administrative checklist items remain incomplete."})
|
| 266 |
+
if criteria_register is not None and not criteria_register.empty:
|
| 267 |
+
status_col = next((c for c in criteria_register.columns if "status" in c.lower()), None)
|
| 268 |
+
name_col = next((c for c in criteria_register.columns
|
| 269 |
+
if c.lower() in ("criterion", "requirement", "item", "name")),
|
| 270 |
+
criteria_register.columns[0])
|
| 271 |
+
if status_col:
|
| 272 |
+
for _, r in criteria_register.iterrows():
|
| 273 |
+
if "not established" in str(r.get(status_col, "")).lower():
|
| 274 |
+
rows.append({"Item": str(r.get(name_col)), "Category": "Governing criteria",
|
| 275 |
+
"Status": "Not established",
|
| 276 |
+
"Consequence": "Related screening cannot be reported as Pass; results remain screening-only."})
|
| 277 |
+
if checklist is not None and not checklist.empty and "Status" in checklist.columns:
|
| 278 |
+
for _, r in checklist.iterrows():
|
| 279 |
+
if str(r.get("Status", "")).strip().lower() == "missing":
|
| 280 |
+
rows.append({"Item": f"{r.get('Item')}: {str(r.get('Requirement'))[:80]}",
|
| 281 |
+
"Category": "SWMR checklist",
|
| 282 |
+
"Status": "Missing",
|
| 283 |
+
"Consequence": "Required for a submission-ready report."})
|
| 284 |
+
if not rows:
|
| 285 |
+
rows.append({"Item": "None identified", "Category": "β", "Status": "β",
|
| 286 |
+
"Consequence": "All tracked evidence items were supplied."})
|
| 287 |
+
return pd.DataFrame(rows)
|