Files
goodwe-addon/goodwe_controller/test_ev21_fix1.py
T
ems-agentandClaude 5759e9dc9f
checks / unit (pull_request) Successful in 46m9s
infra-pin / fresh (pull_request) Successful in 1s
EV-21 fix round 1 (formal round 4): C14 cut due while batteries charge; C15 grace once per value
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>
2026-11-27 01:33:41 +01:00

183 lines
8.5 KiB
Python

"""EV-21 fix round 1 (formal round 4): C14 and C15, and pins of the code's
current answer to three questions the owner has not ruled (C16, C18, Q1's
other writer). `python3 -B test_ev21_fix1.py`
- C14 (PM Q2): slowing a battery charge counts as the batteries taking more,
so a cut is due while the batteries charge at least the excess: after
CUT_WAIT_S with real headroom, at once with the cover off.
- C15 (PM Q1): the 2 s grace of a lowering on its way is once per value; a
retry of a refused cut gets none.
- C16, C18, Q1-other-writer: what the code does today, pinned so a ruling
that changes it shows here. These are not rulings.
The real Controller on `tools/ev20_sun.py` through `tools/ev21_kit.py`.
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import dataclasses
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
from app import ctl_car # noqa: E402
import ev20_sun as S # noqa: E402
from ev20_kit import LOG, check, fails, const, step_fn # noqa: E402
from ev21_kit import (AIM, after, drive, shape, _mode, set_resp, # noqa: E402
merge, never)
n_log0 = LOG.mark()
CUT_WAIT_S = getattr(ctl_car, "CUT_WAIT_S", 15.0)
def tick_case(cover, elapsed):
"""`_car_cut_tick` itself, on a real Controller: Shape W just before its
step (Solar runs the car at 10 A on 3 phases, both batteries at 60 %),
then the batteries set to CHARGE 3 kW and a projection with the car
whose excess is 1 kW at `elapsed` s; the guard does not engage
(battery + excess = -2 kW). Returns (cap, wait) after the first tick
and the cap after a second tick CUT_WAIT_S later."""
# The run itself with the cover on: with it off, Solar's own start at
# 120 s already meets C14's rule (see the dev report's Findings).
r = shape("W", dur=959)
c = r["c"]
c.o["ev_batt_cover"] = cover
t = c.car_now()
for inv in c.inverters:
inv.batt = -1500.0 # 3 kW of charge, site sum
c._car_cut_meter_fresh = lambda: True # the meter is fresh (N9 aside)
left = 900.0 - elapsed
proj = dataclasses.replace(
c._peak_proj_real, elapsed_s=elapsed,
projected_w=AIM + 1000.0 * left / 900.0)
guard = dataclasses.replace(
c.peak_guard, engaged=False, floor_w=None, saturated=False,
floor_limited=False, blind=None, wanted_w=-2000.0, able_w=None,
held=())
c._cut = c._cut_fresh(None)
c.car_now = lambda: t
c._car_cut_tick(proj, guard, AIM, t)
first = (c._cut["cap"], c._cut["wait"], c._cut["since"])
c.car_now = lambda: t + CUT_WAIT_S
c._car_cut_tick(proj, guard, AIM, t + CUT_WAIT_S)
return first, c._cut["cap"], c.site_batt_w
# =========================================================================== #
print("\n1. C14: A CUT IS DUE WHILE THE BATTERIES CHARGE (PM Q2)")
# =========================================================================== #
for name, cover, el, at_once in (
("cover on, real headroom", True, 300.0, False),
("cover off (OQ3)", False, 300.0, True),
("the last 120 s", True, 800.0, True)):
first, later, batt = tick_case(cover, el)
cap0, wait0, since0 = first
if at_once:
ok = cap0 is not None
how = "at once"
else:
ok = cap0 is None and since0 is not None and later is not None
how = f"after the {CUT_WAIT_S:.0f} s wait"
check(f"C14 [{name}]: the batteries charge {-(batt or 0):.0f} W against "
f"an excess of 1000 W; the cut is due all the same, {how} (first "
f"tick cap {cap0}, wait {wait0}, episode since {since0}; "
f"{CUT_WAIT_S:.0f} s later cap {later})", ok)
# =========================================================================== #
print("\n2. C15: THE 2 s GRACE IS ONCE PER VALUE (PM Q1)")
# =========================================================================== #
def ignore(p, c):
p.ch.refuse = "ignore"
r = shape("C", dur=1120, beside=True, events={959: ignore})
sends = [(t, v) for t, e, v in r["plant"].sets if e == S.SET and t >= 959]
rec = r["rec"].rows
t_first = sends[0][0] if sends else None
late = [x["t"] for x in rec if t_first is not None
and x["t"] > t_first + 2.0 and x["can"] and x["rb"] > 0.0]
check(f"C15: the cut 0 A is ignored and tried again ({sends}); while the "
f"read-back still shows the old current, Solar counts as able to cut "
f"for the first 2 s of the first send only, never on a retry "
f"({late[:4]})", len(sends) >= 2 and not late)
# =========================================================================== #
print("\n3. OPEN QUESTIONS, PINNED AS THE CODE HAS THEM (C16, C18, Q1)")
# =========================================================================== #
# C16: after a partial cut, the restart adds only max(0, start power - the
# car's power now) to the projection. A car still at 6 A adds nothing, so
# the car may come back while the period with a FULL 6 A on top would not
# be under the aim.
sun16 = step_fn((1200, 0.0), (1260, 5000.0), base=7900.0)
r = drive(step_fn((1200, 800.0), base=900.0), sun16, dur=1700, first="car",
phases=3, socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "3"},
events={1198: lambda p, c: setattr(c.car_solar, "nonzero_at",
p.t)})
rows = r["rec"].rows
part = [x for x in rows if x["t"] >= 1200 and x["cap"] is not None]
und = [x for x in rows if x["t"] > 1200 and x["under"] is not None]
u = und[0] if und else {}
left = 900.0 - (u.get("t", 0) - 900.0)
full = (u.get("proj") or 0) + 4140.0 * left / 900.0
check(f"C16 (pinned, not a ruling): a partial cut to "
f"{part[0]['cap'] if part else None} A; the restart clock starts at "
f"{u.get('t')} with the projection {u.get('proj') or 0:.0f} W under "
f"the aim while the car still draws {u.get('car')} W; with a full 6 A "
f"on top it would be {full:.0f} W",
bool(part) and 0 < part[0]["cap"] < 10 and bool(und)
and (u.get("car") or 0) >= 4000.0 and (u.get("proj") or 0) < AIM
and full >= AIM)
# C18: Solar's own 1 -> 3 change under way when a cut becomes due WITH
# headroom (the 15 s wait). Pinned: the change may close during the wait, at
# no more than the current the wait holds, on the phases it selected.
kw = dict(dur=700, first="car", phases=1, socs={"a": 60.0, "b": 60.0},
opts={"ev_phases": "auto"})
r0 = drive(const(900.0), const(9280.0), **kw)
log0 = r0["c"].car_solar.log
sel_t = [t for k, a, t, ok in log0 if k == "phases"]
zero_b = [t for k, a, t, ok in log0 if k == "current" and a == 0.0
and sel_t and t <= sel_t[0]]
tb = int(zero_b[-1]) if zero_b else 400
kw["dur"] = tb + 60
r = drive(step_fn((tb + 1, 9280.0 + 3400.0 + 1500.0), base=900.0),
const(9280.0), **dict(kw, events={0: set_resp(20.0)}))
rows = r["rec"].rows
wait = [x for x in rows if x["t"] >= tb + 1 and x["wait"] is not None]
close = [(t, a) for t, a, _ in after(r, tb + 1) if a > 0.0]
sel = [(x[0], x[2]) for x in r["sim"].log if x[1] == "phases"
and x[0] >= tb]
caps = [x["t"] for x in rows if x["t"] >= tb + 1 and x["cap"] is not None]
check(f"C18 (pinned, not a ruling): Solar's change began at {tb}; the cut "
f"due at {wait[0]['t'] if wait else None} waits (cap "
f"{wait[0]['wait'] if wait else None} A); during the wait the change "
f"selects {sel} and closes at {close[:1]}; the cut at {caps[:1]}",
bool(wait) and bool(close) and close[0][1] <= wait[0]["wait"]
and (not caps or close[0][0] <= caps[0]))
# Q1 (other writer): another writer raises the current inside the 2 s grace
# of Solar's lowering. Pinned: until the next writer step marks the
# difference (`mismatch_since`), car_solar_can_cut() stays True.
r = shape("C", dur=950)
c = r["c"]
w = c.car_solar
rd = c.car.reading
w.sent_a, w.sent_at, w.fail_at, w.mismatch_since = 0.0, c.car_now(), None, \
None
c.car.reading = dataclasses.replace(rd, allowed_a=16.0, setpoint_a=16.0)
in_grace = c.car_solar_can_cut()
w.mismatch_since = c.car_now()
marked = c.car_solar_can_cut()
check(f"Q1 other writer (pinned, not a ruling): Solar sent 0 A, another "
f"writer shows 16 A inside the 2 s grace: can-cut {in_grace} until the "
f"difference is marked, then {marked}", in_grace is True
and marked is False)
tb_ = LOG.tracebacks(n_log0)
check(f"N11: no traceback in this file's runs ({tb_[:1]})", not tb_)
print(f"\n{'FAILED: ' + str(len(fails)) if fails else 'ALL PASSED'}")
sys.exit(1 if fails else 0)