FloodGate / core /flood_core /check.py
bpHigh's picture
FloodGate v1: live mode, 3D replay, Beam and Opus runs
79c4cf2 verified
Raw History Blame Contribute Delete
8.53 kB
"""The grader: turn a plan into releases, route them, and price the result. Pure Python, deterministic.
A plan lists release changes, one entry per change:
{"dam": "WC", "from": 3, "cfs": 20} from step 3 (or a time label from the situation) on, release 20 cfs
A dam's release holds until its next entry. Dams and steps not listed keep the release of the step before the window.
Rules (a plan that breaks one is infeasible):
1. min_release <= release <= max_release, every dam, every step
2. |release[t] - release[t-1]| <= ramp (the step before the window counts as release[-1])
3. storage never above the top of the flood pool (the dam would spill uncontrolled)
4. storage never below the top of the inactive pool
Cost, in points:
flooding per 1,000 cfs-days above each NWS category at each gauge, cumulative: action 1, minor +10,
moderate +20, major +40 (so a flow above major stage pays 71 per 1,000 cfs-day above it). Counted
over the window and its tail (the steps water released in the window still takes to arrive).
flood pool per 1,000 acre-feet left in a lake's flood pool at the window's end, by the share of the pool in use:
1 up to a quarter, 2 to half, 4 to three quarters, 8 above
"""
from __future__ import annotations
from dataclasses import dataclass, field
from .basin import AF_PER_CFS_STEP, STEP_H, routing_weights
FLOOD_W = (("action", 1.0), ("minor", 10.0), ("moderate", 20.0), ("major", 40.0))
POOL_TIERS = ((0.25, 1.0), (0.50, 2.0), (0.75, 4.0), (1.00, 8.0))
TOL_CFS = 0.5
TOL_AF = 1.0
DAY_PER_STEP = STEP_H / 24
class PlanError(ValueError):
pass
def _step_of(task: dict, v) -> int:
if isinstance(v, bool):
raise PlanError(f"bad step {v!r}")
if isinstance(v, (int, float)) and float(v).is_integer():
return int(v)
if isinstance(v, str):
s = v.strip()
if s.lstrip("-").isdigit():
return int(s)
for i, lab in enumerate(task["times"][:task["steps"]]):
if s == lab or s == lab.rsplit(" ", 1)[0]:
return i
raise PlanError(f"unknown step {v!r}: use a step number 0-{task['steps'] - 1} or a time label from the situation")
def parse_plan(task: dict, plan) -> tuple[dict[str, list[float]], list[str]]:
"""-> (releases per dam per step, problems with entries that were skipped)."""
import json
if isinstance(plan, str):
try:
plan = json.loads(plan)
except json.JSONDecodeError as e:
raise PlanError(f"plan is not JSON: {e}") from None
if isinstance(plan, dict) and "plan" in plan:
plan = plan["plan"]
if isinstance(plan, dict): # {"WC": [[step, cfs], ...], ...}
plan = [{"dam": d, "from": e[0], "cfs": e[1]} for d, es in plan.items() for e in es]
if not isinstance(plan, list):
raise PlanError("plan must be a list of {dam, from, cfs} entries")
H = task["steps"]
ids = [d["id"] for d in task["dams"]]
changes: dict[str, dict[int, float]] = {k: {} for k in ids}
problems = []
for i, e in enumerate(plan):
if not isinstance(e, dict):
problems.append(f"entry {i}: not an object")
continue
dam = str(e.get("dam", "")).upper()
if dam not in changes:
problems.append(f"entry {i}: unknown dam {e.get('dam')!r} (dams: {', '.join(ids)})")
continue
try:
s = _step_of(task, e.get("from", e.get("step")))
except PlanError as err:
problems.append(f"entry {i}: {err}")
continue
if not 0 <= s < H:
problems.append(f"entry {i}: step {s} outside 0-{H - 1}")
continue
try:
q = float(e.get("cfs", e.get("release")))
except (TypeError, ValueError):
problems.append(f"entry {i}: cfs must be a number")
continue
if s in changes[dam] and changes[dam][s] != q:
problems.append(f"entry {i}: {dam} step {s} set twice; the later entry wins")
changes[dam][s] = q
rel = {}
for d in task["dams"]:
cur, out = d["release_prev_cfs"], []
for t in range(H):
cur = changes[d["id"]].get(t, cur)
out.append(cur)
rel[d["id"]] = out
return rel, problems
@dataclass
class Result:
feasible: bool
cost: float
flood_cost: float
pool_cost: float
violations: list[str] = field(default_factory=list)
clean_fraction: float = 1.0
storage: dict[str, list[float]] = field(default_factory=dict)
flows: dict[str, list[float]] = field(default_factory=dict)
flood_by_point: dict[str, float] = field(default_factory=dict)
pool_by_dam: dict[str, float] = field(default_factory=dict)
def flows(task: dict, rel: dict[str, list[float]]) -> dict[str, list[float]]:
H, T = task["steps"], task["tail_steps"]
out = {}
for p in task["points"]:
q = list(p["base_cfs"][:H + T])
for dam, lags in task["lags_h"].items():
if p["id"] not in lags:
continue
w = routing_weights(lags[p["id"]])
r = rel[dam]
for s in range(H):
for i, wi in enumerate(w):
if s + i < H + T:
q[s + i] += wi * r[s]
out[p["id"]] = q
return out
def flood_cost(point: dict, q: list[float]) -> float:
c = 0.0
for v in q:
for k, w in FLOOD_W:
c += w * max(0.0, v - point["thresholds"][k]) / 1000 * DAY_PER_STEP
return c
def pool_cost(dam: dict, s_end: float) -> float:
bot, top = dam["bottom_of_flood_af"], dam["top_of_flood_af"]
size = top - bot
used = max(0.0, s_end - bot)
c, lo = 0.0, 0.0
for n, (hi, w) in enumerate(POOL_TIERS):
# the top tier runs on above the top of the pool (only live mode, where spill is priced, gets there)
seg = (min(used, hi * size) if n < len(POOL_TIERS) - 1 else used) - lo * size
if seg > 0:
c += w * seg / 1000
lo = hi
return c
def evaluate(task: dict, rel: dict[str, list[float]]) -> Result:
H = task["steps"]
viol, bad = [], 0
storage = {}
pool_by = {}
for d in task["dams"]:
k, r = d["id"], rel[d["id"]]
s = [d["storage0_af"]]
prev = d["release_prev_cfs"]
for t in range(H):
ok = True
if r[t] < d["min_release_cfs"] - TOL_CFS or r[t] > d["max_release_cfs"] + TOL_CFS:
viol.append(f"{k} step {t}: release {r[t]:.0f} cfs outside {d['min_release_cfs']}-"
f"{d['max_release_cfs']}")
ok = False
if abs(r[t] - prev) > d["ramp_cfs_per_step"] + TOL_CFS:
viol.append(f"{k} step {t}: release changes by {r[t] - prev:+.0f} cfs, more than "
f"{d['ramp_cfs_per_step']} in one step")
ok = False
prev = r[t]
s.append(s[-1] + (d["inflow_cfs"][t] - r[t]) * AF_PER_CFS_STEP)
if s[-1] > d["top_of_flood_af"] + TOL_AF:
viol.append(f"{k} end of step {t}: storage {s[-1]:,.0f} af above the top of the flood pool "
f"({d['top_of_flood_af']:,.0f}): the dam spills uncontrolled")
ok = False
if s[-1] < d["top_of_inactive_af"] - TOL_AF:
viol.append(f"{k} end of step {t}: storage {s[-1]:,.0f} af below the top of the inactive pool "
f"({d['top_of_inactive_af']:,.0f})")
ok = False
bad += not ok
storage[k] = s
pool_by[k] = pool_cost(d, s[-1])
q = flows(task, rel)
fl_by = {p["id"]: flood_cost(p, q[p["id"]]) for p in task["points"]}
fc, pc = sum(fl_by.values()), sum(pool_by.values())
return Result(feasible=not viol, cost=fc + pc, flood_cost=fc, pool_cost=pc, violations=viol,
clean_fraction=1 - bad / (H * len(task["dams"])), storage=storage, flows=q,
flood_by_point=fl_by, pool_by_dam=pool_by)
def plan_to_list(task: dict, rel: dict[str, list[float]]) -> list[dict]:
"""The shortest entry list that reproduces `rel` (one entry per change)."""
out = []
for d in task["dams"]:
prev = d["release_prev_cfs"]
for t, v in enumerate(rel[d["id"]]):
if abs(v - prev) > 1e-9:
out.append({"dam": d["id"], "from": t, "cfs": round(v, 1)})
prev = v
return out