EV-21: Solar cuts the car first for the quarter peak
infra-pin / fresh (pull_request) Successful in 2s
checks / unit (pull_request) Failing after 1h10m59s

In Solar, when the 15-minute period heads over the aim and the batteries
would have to give more, the car is lowered first: floor((car - excess) /
(230 x phases)) A, 0 under 6 A. At once without real headroom (saturated,
floor-limited, excess beyond what the batteries can add, no battery figure,
cover off, last 120 s), else after at most 15 s. One cut per episode from
its start, deeper only on a growing excess; restart with the start power
under the aim for the start time; none after a 2nd cut in the period.

Grading (formal C2): a Solar car Solar cannot cut is graded, banked and
left in the guard as in Off. A Solar car is never banked. Grey note and Why
"Solar lowered the car for the peak." Manual and Off unchanged.

Tests: test_ev21.py, test_ev21_paths.py, test_ev21_same.py; T49 in
tools/ev20_day.py; T50 in test_ev20_fuzz.py; test_ev20_guard section 8
moved from "as Manual" to "as Off" where Solar cannot cut (T51).

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
ems-agent
2026-11-25 17:01:07 +01:00
co-authored by Claude
parent a8e4ceb859
commit 7bc8988be0
17 changed files with 2175 additions and 85 deletions
+32 -3
View File
@@ -16,7 +16,10 @@ What is checked, per priority and cycle order:
- the car's grid energy outside its holds: SETTLED (not within 20 s of a step
of the sun, the house or the car's own current) at most 10 Wh; the zero-grid
loop's slew after such a step (500 W per cycle) is reported apart;
- house-caused alarms at the same seconds as the car-Off twin, +2 s.
- house-caused alarms at the same seconds as the car-Off twin, +2 s;
- EV-21 (T49): no peak cut on this day (the batteries catch every cloud edge
and house step), no period over the aim that the car's energy alone takes
over (N4), and no period banked as the car's.
"""
import math
@@ -25,6 +28,7 @@ import random
import ev20_sun as S
DAY = 36000 # 08:00 to 18:00, 1 s cycles
AIM = 3400.0 # the harness's cap 3500 less its margin 100
PAUSE_S = 300.0
MARGIN = 100.0
_rnd = random.Random(53)
@@ -113,11 +117,36 @@ def run_day(first, check):
long_c = [(a, b) for a, b in CLOUDS if b - a > PAUSE_S]
short_c = [(a, b) for a, b in CLOUDS if b - a <= PAUSE_S]
print(f" clouds (start, length): {[(a, b - a) for a, b in CLOUDS]}")
cutlog = {"step": [], "race": []}
def cut_rec(tag):
def f(p, c, t):
st = getattr(c, "_cut", None) or {}
if st.get("cap") is not None and st.get("at") == t:
cutlog[tag].append((t, st["cap"]))
return f
runs = {"step": S.drive(house, sun, dur=DAY, first=first, socs=dict(SOCS),
race=False),
race=False, on_cycle=cut_rec("step")),
"race": S.drive(house, sun, dur=RACE[1] - RACE[0], t0=RACE[0],
first=first, socs=dict(SOCS), race=True)}
first=first, socs=dict(SOCS), race=True,
on_cycle=cut_rec("race"))}
for tag, r in runs.items():
# EV-21, T49: N4 per period, and no cut on this day.
per = {}
for x in r["trace"]:
q = int(x["t"]) // 900
per.setdefault(q, [0.0, 0.0, 0])
per[q][0] += x["grid"]
per[q][1] += x["grid"] - x["car"]
per[q][2] += 1
n4 = [(q * 900, round(a / n), round(b / n))
for q, (a, b, n) in per.items() if n == 900
and a / n > AIM and b / n <= AIM]
check(f"T49 (EV-21) [{first} first, {tag}]: no period over the aim "
f"that the car alone takes over (N4: {n4[:3]}), none banked as "
f"the car's ({r['c'].car_peak_q}), no peak cut on this day "
f"({cutlog[tag][:3]})",
not n4 and not r["c"].car_peak_q and not cutlog[tag])
w = cur_writes(r)
# A pause: a 0 A that is not a phase change's (no select within
# 30 s); a start: the first current after a pause or at the start.
+283
View File
@@ -0,0 +1,283 @@
"""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"):
ev = merge(ev, 0, 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
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. `sun_back`: the sun returns then."""
ev = dict(kw.pop("events", None) or {})
ev = merge(ev, 0, 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)
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