C14 (PM Q2): slowing a battery charge counts as the batteries taking more, so the cut is due whatever the batteries do; their charge counts only as headroom for the 15 s wait. C15 (PM Q1): sent_at is renewed only for a new value, so a retry of a refused cut gets no new 2 s grace. test_ev21_fix1.py: both red on 36e9dd7; C16, C18 and Q1's other writer pinned as the code has them. Test shapes: slow batteries and refusals start after Solar's own start, which C14 would otherwise cut on its start blip; T38 cover off from 300 s; T46 bounds the excess; T39 counts writes after the cut. Co-Authored-By: Claude <noreply@anthropic.com>
299 lines
11 KiB
Python
299 lines
11 KiB
Python
"""EV-21: shared pieces of the peak-cut checks (test_ev21*.py): the shapes of
|
|
reports/EV-21-test-plan.md, the Off twin, a per-cycle recorder and the Never
|
|
checks every run carries.
|
|
|
|
The plant is `ev20_sun` (the real Controller, N batteries, the sun, the house
|
|
and `chargersim.SimCharger` on one meter, a 1 s cycle on a model clock).
|
|
`rig.BASE` is on a quarter boundary, so the second period runs 900-1800 and
|
|
"elapsed 60 s" is t = 960. Units: A = 5000 W, B = 4600 W. Aim = 3500 - 100.
|
|
Each check file imports `check`, `fails` and `LOG` from `ev20_kit`."""
|
|
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import sys
|
|
|
|
_KIT = os.path.dirname(os.path.abspath(__file__))
|
|
sys.path.insert(0, _KIT)
|
|
sys.path.insert(0, os.path.dirname(_KIT))
|
|
|
|
from app import carmode, ctl_car, messages # noqa: E402
|
|
import ev20_sun as S # noqa: E402
|
|
from chargersim import SimCharger # noqa: E402
|
|
from ev20_kit import LOG, check, const, step_fn # noqa: E402,F401
|
|
|
|
AIM = 3400.0
|
|
Q = 900
|
|
ALARMS = S.ALARMS
|
|
CUT_WAIT_S = getattr(ctl_car, "CUT_WAIT_S", 15.0)
|
|
CUT_NEAR_END_S = getattr(ctl_car, "CUT_NEAR_END_S", 120.0)
|
|
|
|
|
|
def _cutamps():
|
|
"""carmode.cut_amps, or a stand-in that says "no cut" on a tree without
|
|
it (c79eb37), so a red row reads as FAIL, never as a crash."""
|
|
return getattr(carmode, "cut_amps", lambda *a, **k: "absent")
|
|
|
|
|
|
def both(*fns):
|
|
async def f(p, c):
|
|
for fn in fns:
|
|
x = fn(p, c)
|
|
if hasattr(x, "__await__"):
|
|
await x
|
|
return f
|
|
|
|
|
|
def merge(events, t, fn):
|
|
ev = dict(events or {})
|
|
ev[t] = both(ev[t], fn) if t in ev else fn
|
|
return ev
|
|
|
|
|
|
def set_resp(s):
|
|
def f(p, c):
|
|
p.response_s = s
|
|
return f
|
|
|
|
|
|
class Rec:
|
|
"""Per cycle: can-cut, the cut state, the guard's floor and want, the
|
|
car's read-back and power. Read after the cycle and its writer step."""
|
|
|
|
def __init__(self):
|
|
self.rows = []
|
|
|
|
def __call__(self, p, c, t):
|
|
st = getattr(c, "_cut", None) or {}
|
|
cc = getattr(c, "car_solar_can_cut", None)
|
|
graded = getattr(c, "_car_can", None)
|
|
g = c.peak_guard
|
|
w = c.car_solar
|
|
self.rows.append(dict(
|
|
t=t, can=graded, can_now=bool(cc()) if cc else None,
|
|
cap=st.get("cap"), wait=st.get("wait"), cuts=st.get("cuts"),
|
|
ex=st.get("ex"), car0=st.get("car0"), under=st.get("under"),
|
|
since=st.get("since"),
|
|
proj=None if c._peak_proj_real is None
|
|
else c._peak_proj_real.projected_w,
|
|
explains=c.car_explains, floor=None if g is None else g.floor_w,
|
|
want=None if g is None else g.wanted_w,
|
|
sat=bool(g is not None and g.saturated),
|
|
flim=bool(g is not None and g.floor_limited),
|
|
writing=c.car_writing(), hold=w.hold, mism=w.mismatch_since,
|
|
fault=w.fault, sent=w.sent_a, rb=p.ch.readback_a,
|
|
car=p.ch.power_w, mode=c.car_mode, plan=w.plan.a))
|
|
|
|
def at(self, t):
|
|
for r in self.rows:
|
|
if r["t"] == t:
|
|
return r
|
|
return None
|
|
|
|
|
|
def drive(house, sun, *, rec=True, **kw):
|
|
"""`ev20_sun.drive` with a recorder (`out["rec"]`)."""
|
|
r_ = Rec() if rec else None
|
|
oc = kw.pop("on_cycle", None)
|
|
|
|
def on_cycle(p, c, t):
|
|
if r_ is not None:
|
|
r_(p, c, t)
|
|
if callable(oc):
|
|
oc(p, c, t)
|
|
kw.setdefault("rows", True)
|
|
out = S.drive(house, sun, on_cycle=on_cycle, **kw)
|
|
out["rec"] = r_
|
|
return out
|
|
|
|
|
|
# --------------------------------------------------------------- the shapes
|
|
def shape(kind, *, step=960, mode="solar", first="car", n=2, cover=True,
|
|
dur=None, events=None, opts=None, socs=None, house_w=None,
|
|
sun_w=None, setpoint=None, **kw):
|
|
"""The test plan's shapes C, W, S, F and M (N=2 unless `n`=1, Car first,
|
|
car 10 A on 3 phases, the step at `step`). The Off twin runs `mode="off"`
|
|
with the charger held at the same current from the start."""
|
|
car_a = 6.0 if kind == "F" else 10.0
|
|
car_w = car_a * 690.0
|
|
soc = {"C": 10.0, "W": 60.0, "S": 60.0, "F": 19.0, "M": 60.0}[kind]
|
|
h_after = house_w if house_w is not None else {
|
|
"C": 3000.0, "W": 3000.0, "S": 16000.0, "F": 9000.0,
|
|
"M": 3000.0}[kind]
|
|
room = 0.0 if first == "car" else 9600.0
|
|
s_before = sun_w if sun_w is not None else 900.0 + car_w + 100.0 + room
|
|
ratings = {"a": 5000.0, "b": 4600.0} if n == 2 else {"a": 5000.0}
|
|
o = dict({"ev_phases": "3", "ev_batt_cover": cover}, **(opts or {}))
|
|
ev = dict(events or {})
|
|
if kind in ("W", "S"):
|
|
# Slow batteries from 60 s before the step: Solar's own start at
|
|
# 120 s runs on quick ones (with slow ones its own start blip lasts
|
|
# past the 15 s wait and is cut, PM Q2 / formal C14).
|
|
ev = merge(ev, max(0, int(step) - 60), set_resp(20.0))
|
|
sp = setpoint if setpoint is not None else (car_a if mode != "solar"
|
|
else 0)
|
|
if kind == "F" and sun_w is None:
|
|
# The start rule needs 7 A worth: start at 7 A, then 6 A from 600 s.
|
|
sun = step_fn((600, s_before), (step, 0.0), base=s_before + 760.0)
|
|
else:
|
|
sun = step_fn((step, 0.0), base=s_before)
|
|
return drive(step_fn((step, h_after), base=900.0), sun,
|
|
dur=dur or (step + 240), first=first, phases=3, mode=mode,
|
|
socs=socs or {u: soc for u in ratings}, ratings=ratings,
|
|
opts=o, events=ev, setpoint=sp, **kw)
|
|
|
|
|
|
def twin(kind, **kw):
|
|
"""Shape `kind` in Off, the charger held at Solar's current."""
|
|
kw = dict(kw)
|
|
kw["mode"] = "off"
|
|
return shape(kind, **kw)
|
|
|
|
|
|
def replay_twin(r, kind, **kw):
|
|
"""Shape `kind` in Off with Solar's own charger writes of run `r` put on
|
|
the charger at the same seconds (as test_ev20_guard's Manual twin), so
|
|
both runs have the same car and only the mode differs."""
|
|
ev = dict(kw.pop("events", None) or {})
|
|
for t_sim, what, v, _pw, _sp in r["sim"].log:
|
|
def put(p, c, what=what, v=v):
|
|
(p.ch.set_current if what == "current" else p.ch.set_phases)(v)
|
|
ev = merge(ev, int(round(t_sim)), put)
|
|
return twin(kind, events=ev, **kw)
|
|
|
|
|
|
def _mode(units, on):
|
|
def f(p, c):
|
|
from app import packmode
|
|
from app.store import unit_key
|
|
for u in units:
|
|
c.store.data[unit_key("inverter-" + u, packmode.USE_KEY)] = on
|
|
return f
|
|
|
|
|
|
class NoGive(S.SunPlant):
|
|
"""Every battery refuses to give: the plant gives min(command, 0)."""
|
|
|
|
def batt_of(self, u, at):
|
|
return min(super().batt_of(u, at), 0.0)
|
|
|
|
|
|
def refuse_n1(p, c):
|
|
"""N=1: the sole battery refuses to give (SAFETY-73's latch, held)."""
|
|
c.batt_refused, c.batt_refused_at = 1, p.t
|
|
|
|
|
|
def near_end(step, *, n=2, house_after=3000.0, sun_back=None, dur=1800,
|
|
house_more=(), **kw):
|
|
"""The period sits near the aim before the step: 900-1500 the house draws
|
|
3350 W and nothing covers it (N=2: both batteries switched off in battery
|
|
modes until 1500; N=1: the battery refuses to give throughout), then the
|
|
sun is back and Solar starts the car at 10 A on 3 phases; at `step` the
|
|
sun goes and the house is `house_after`. The batteries (N=2: 60 %) take
|
|
20 s to respond from 30 s before the step (Solar's own start runs on
|
|
quick ones: PM Q2 / formal C14 would cut its own start blip otherwise).
|
|
`sun_back`: the sun returns then."""
|
|
ev = dict(kw.pop("events", None) or {})
|
|
ev = merge(ev, max(0, int(step) - 30), set_resp(20.0))
|
|
if n == 2:
|
|
ev = merge(merge(ev, 899, _mode("ab", False)), 1500,
|
|
_mode("ab", True))
|
|
ratings = {"a": 5000.0, "b": 4600.0}
|
|
else:
|
|
for t in range(0, int(dur) + 1):
|
|
ev = merge(ev, t, refuse_n1)
|
|
ratings = {"a": 5000.0}
|
|
kw.setdefault("rows", False)
|
|
# The harness plant gives what it is asked; a refusing battery
|
|
# gives nothing (it still takes a charge).
|
|
kw.setdefault("plant_cls", NoGive)
|
|
house = step_fn((900, 3350.0), (1500, 900.0), (step, house_after),
|
|
*house_more, base=900.0)
|
|
pairs = [(900, 0.0), (1500, 7900.0), (step, 0.0)]
|
|
if sun_back is not None:
|
|
pairs.append((sun_back, 9000.0))
|
|
sun = step_fn(*pairs, base=7900.0)
|
|
return drive(house, sun, dur=dur, first="car", phases=3,
|
|
ratings=ratings, socs={u: 60.0 for u in ratings},
|
|
opts={"ev_phases": "3"}, events=ev, **kw)
|
|
|
|
|
|
# ------------------------------------------------------------- reading runs
|
|
def cur_writes(r):
|
|
"""(cycle second, amps, ok) of every current write Solar made."""
|
|
return [(x[2], x[1], x[3]) for x in r["c"].car_solar.log
|
|
if x[0] == "current"]
|
|
|
|
|
|
def after(r, t0):
|
|
return [(t, a, ok) for t, a, ok in cur_writes(r) if t >= t0]
|
|
|
|
|
|
def alarms(r, t0=0):
|
|
return [(t, n) for t, n in r["raised"] if n in ALARMS and t >= t0]
|
|
|
|
|
|
def first_alarm(r, t0=0):
|
|
a = alarms(r, t0)
|
|
return a[0][0] if a else None
|
|
|
|
|
|
def notes(r, *ids):
|
|
return [(t, n) for t, n in r["raised"] if n in ids]
|
|
|
|
|
|
def quarter_avg(r, q0):
|
|
"""The period's real average import, W: the meter of every cycle in it
|
|
(the trace's `grid`; `plant.grid(t)` would use the car's power at the
|
|
end of the run)."""
|
|
g = [x["grid"] for x in r["trace"] if q0 <= x["t"] < q0 + Q]
|
|
return sum(g) / len(g) if g else float("nan")
|
|
|
|
|
|
def peak_key(q0):
|
|
return (S.rig.BASE.replace(microsecond=0)
|
|
+ __import__("datetime").timedelta(seconds=q0)).isoformat()
|
|
|
|
|
|
def digest(obj):
|
|
return hashlib.sha256(json.dumps(obj, default=str, sort_keys=True)
|
|
.encode()).hexdigest()[:16]
|
|
|
|
|
|
def view_writes(r):
|
|
return [(round(t), a) for t, a in S.writes(r)] + [
|
|
("ph", round(t), n) for t, n in S.writes(r, "phases")]
|
|
|
|
|
|
def view_guard(r, t0=0):
|
|
return [(x["t"], round(x["floor"] or 0.0), x["explains"], x["over"],
|
|
tuple(x["red"])) for x in r["trace"] if x["t"] >= t0]
|
|
|
|
|
|
# ------------------------------------------------------------- the Never
|
|
def never(name, r, *, clamp=16.0, solar=True):
|
|
"""N1, N2, N6 (with N3's cut value), N8's grading half (T35) and N11 on
|
|
one run; each a check line. N8's "+2 s" half and N4/N5 are per row."""
|
|
sim = r["sim"]
|
|
tr = r["trace"]
|
|
rec = r.get("rec")
|
|
bad1 = [x for x in sim.log if x[1] == "current" and x[2] > clamp + 1e-9]
|
|
# N2: a select under load (>= 100 W, mode3 C, non-zero setpoint).
|
|
bad2 = [x for x in sim.log if x[1] == "phases" and x[3] >= 100.0
|
|
and x[4] > 0.0]
|
|
check(f"{name}: N1 no write above the clamp ({bad1[:2]}); N2 no phase "
|
|
f"select under load ({bad2[:2]})", not bad1 and not bad2)
|
|
if rec is not None and solar:
|
|
# T35 / N8: graded out in Solar only while Solar can cut.
|
|
bad8 = [x["t"] for x in rec.rows if x["mode"] == "solar"
|
|
and x["explains"] and not x["can"]]
|
|
check(f"{name}: T35 car_explains only while Solar can cut "
|
|
f"({bad8[:3]})", not bad8)
|
|
# N6 / P17: no non-zero write above a standing cut's value.
|
|
caps = {x["t"]: x["cap"] for x in rec.rows}
|
|
bad6 = [(t, a) for t, a, _ok in cur_writes(r) if a > 0.0
|
|
and caps.get(t) is not None and a > caps[t] + 1e-9]
|
|
check(f"{name}: N6 no write above a standing cut ({bad6[:3]})",
|
|
not bad6)
|
|
del tr
|