Compare commits

...
2 Commits
Author SHA1 Message Date
review-agentandClaude Opus 5.5 ff2eebe28b EV-10b review: pin the done-part clip and the car's power now in test_ev10b
infra-pin / fresh (pull_request) Waiting to run
checks / unit (pull_request) In progress
Two checks a mutant survived: crediting the car-made export in the done part,
and taking off the car's quarter average instead of its power now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 23:58:13 +01:00
glenn schrooyenandClaude b12776c705 EV-10b: grade the alarm on the house alone without the 0 W clip
checks / unit (pull_request) Successful in 22m5s
infra-pin / fresh (pull_request) Successful in 2s
The period without the car was clipped at 0 W, so batteries covering the car
were charged to the house and the floor alarm fired (rig F-1). New
car_exclude_alarm keeps the sign of the rest of the period; car_exclude (the
cover-off guard input) is unchanged.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-16 22:16:29 +01:00
4 changed files with 254 additions and 8 deletions
@@ -89,7 +89,7 @@ up to 1.8 kW; the 40 Wh floor fixes that.)
- **The car is the cause when the alarm's own test says so, on the same
landing** (EV-10). `car_cycle` (`_car_explains_alarm`) runs the alarm's test on
the period as it is and on the period without the car's fresh, corroborated
average (`car_exclude`): the car explains the alarm only if it is true with the
average (`car_exclude_alarm`, EV-10b below): the car explains the alarm only if it is true with the
car and false without it. A saturated guard, and a floor with other batteries
left, use `load_too_high` on the landing (the batteries give only what they
still can). A floor that leaves nothing uses SAFETY-126's `misses_aim` (the
@@ -101,6 +101,18 @@ up to 1.8 kW; the 40 Wh floor fixes that.)
same, so it explains nothing; a stale, stuck or uncorroborated figure is `None`,
sets the latch without the car, and the normal alarms stand. There is no minimum
car power: the comparison itself is what separates car from house.
- **The period without the car is not clipped at 0 W** (EV-10b). The rig showed
EV-10 failing: house 3 kW, car 11 kW, batteries 8.1 kW, aim 6 kW. The batteries
give more than the house uses, so the house alone is an export; `car_exclude`
clipped it at 0 W, `misses_aim` added the batteries' full 8.1 kW back, the
"house needs the batteries" latch set early in the quarter, and the floor alarm
could never be explained. `car_exclude_alarm` (alarm grading only) builds the
house alone as: rest of the period `held - car_w`, keeping its sign, so
`misses_aim` adds the batteries back to `held - car_w + batt` = the house; done
part `max(0, done - car so far)` in Ws (no export is credited that only the
car caused); landing `(done + max(held, 0) * left) / 900`. Without a fresh
car reading it is the period as it is. `car_exclude` (the projection the guard
sees with the cover off) is unchanged, with its clip.
- **Steady row, no hold on the alarm** (EV-11). Cause: after the car's own quarter
became the month peak, the aim sat on the grid it made (14.04 kW +-40 W), so
the test crossed the aim every few seconds. `car_over` (row, card, notice) now
+24 -2
View File
@@ -253,6 +253,28 @@ class CarMixin:
proj, projected_w=max(0.0, float(proj.projected_w) - avg),
held_w=max(0.0, float(proj.held_w) - float(w)))
def car_exclude_alarm(self, proj, w):
"""EV-10b: the period as it would be without the car, for grading the
alarm. The house alone, the batteries giving only what the house
would draw from them: the car's share of their power is not charged to
the house. The rest of the period keeps its sign (`held - car`, an
export while the batteries give more than the house uses), so
`misses_aim` adds the batteries back to exactly the house. What is
already done is clipped at 0 Ws: no export is credited for power only
the car asked for. Unchanged without a fresh car reading."""
if proj is None or w is None or proj.block_start is None:
return proj
avg = self.car_avg_w(proj, w)
left = max(0.0, QUARTER_S - float(proj.elapsed_s))
held = float(proj.held_w)
done_ws = QUARTER_S * float(proj.projected_w) - max(held, 0.0) * left
car_ws = avg * QUARTER_S - float(w) * left # the car so far
held_x = held - float(w)
return dataclasses.replace(
proj, held_w=held_x,
projected_w=(max(0.0, done_ws - car_ws)
+ max(held_x, 0.0) * left) / QUARTER_S)
def car_cycle(self, real_proj, guard, target_w, now_utc) -> None:
"""After the guard has decided: does the car alone explain the excess?
`real_proj` is the projection WITH the car, whatever the guard saw."""
@@ -289,7 +311,7 @@ class CarMixin:
def _car_explains_alarm(self, real_proj, guard, target_w, w) -> bool:
"""EV-10: is the alarm's own test true with the car and false without
its fresh, corroborated share (`car_exclude`), on the same landing? The
its fresh, corroborated share (`car_exclude_alarm`), on the same landing? The
tests are the alarms': a saturated guard and a floor with other
batteries left are graded by `load_too_high` on where the period lands
(SAFETY-81 / 87); a floor that leaves nothing is graded by SAFETY-126's
@@ -313,7 +335,7 @@ class CarMixin:
self._car_need_real = self._car_need_excl = False
if batt is not None and prev is not None:
batt = min(float(batt), float(prev))
excl = self.car_exclude(real_proj, w)
excl = self.car_exclude_alarm(real_proj, w)
if wants:
if batt is None:
self._car_need_real = self._car_need_excl = True
+176
View File
@@ -0,0 +1,176 @@
"""EV-10b: the period without the car is not clipped at 0 W (rig F-1 again).
`python3 -B test_ev10b.py`
The rig shape: house 3 kW, car 11 kW, batteries 8.1 kW, aim 6 kW. The batteries
give more than the house uses, so the house alone is an export; clipping it at
0 W charged the car's battery share to the house, latched "the house needs the
batteries" for the quarter, and the floor alarm fired once both batteries
reached the reserve. Mutating a module this file grades? Read MUTATION.md first.
"""
import asyncio
import dataclasses
import os
import sys
from datetime import datetime, timedelta, timezone
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
from app import ctl_car, peakguard, tariff # noqa: E402
import ev04_peak as P # noqa: E402
import safety81_sim as s81 # noqa: E402
fails = []
def check(name, cond):
print(f" {'ok ' if cond else 'FAIL'} {name}")
if not cond:
fails.append(name)
CAP = 6050.0 # aim 6000 W
OPTS = {"inverters": [
{"name": f"inverter-{u}", "setpoint_entity": f"number.sp_{u}",
"soc_entity": f"sensor.soc_{u}", "batt_entity": f"sensor.batt_{u}",
"max_w": 4050, "bms_soc_floor": 10} for u in "ab"]}
def rig_run(house_w, soc_events, dur=895):
"""A whole quarter from its start, N=2 (4.05 kW each = 8.1 kW), the car at
11 kW; `soc_events` is {second: {"a": soc, "b": soc}}."""
def setter(socs):
return lambda plant, c: plant.socs.update(socs)
return P.drive(s81.constant(house_w), dur=dur, rating=4050.0,
soc={"a": 60.0, "b": 60.0}, cap=CAP, phases=3, n=2,
plant_cls=P.CarPlantN, opts=OPTS, dev_w=4050.0,
events={t: setter(s) for t, s in soc_events.items()})
def summary(r):
rows = r["c"].checks()
red = [x["id"] for x in rows if x["ok"] is False and not x["warn"]]
return (P.ids(r, *P.ALARMS), red, P.ids(r, P.OVER),
max(abs(r["plant"].batt(t)) for t in range(0, 30)) if r else 0)
print("1. THE RIG SHAPE, A WHOLE QUARTER (house 3 kW, car 11 kW, batteries 8.1 kW)")
r = rig_run(3000.0, {30: {"a": 19.0, "b": 19.0}})
al, red, over, _ = summary(r)
peak_batt = max(r["plant"].batt(t) for t in range(5, 30))
check("PRECONDITION: the batteries gave more than the house uses (8.1 kW "
"against 3 kW) before the reserve", peak_batt > 7500.0)
check("both batteries reach the reserve early in the quarter: no 'Battery "
"stopped limiting the peak', no 'Load too high'", al == [])
check("...no red row, and no goodwe_peak_soc_floor", red == [])
check("...one car-over notice", len(over) == 1)
check("...the car-over row is on at the end", any(
x["id"] == "car_over" and x["ok"] is True for x in r["c"].checks()))
r2 = rig_run(3000.0, {30: {"a": 19.0}, 200: {"b": 19.0}})
al2, red2, over2, _ = summary(r2)
check("N=2, one battery reaches the reserve first, the other later: no "
"alarm, no red row, one car-over notice",
al2 == [] and red2 == [] and len(over2) == 1)
print("\n2. BATTERIES ABOVE THE HOUSE AND THE HOUSE ALONE OVER THE AIM")
r3 = rig_run(7000.0, {30: {"a": 19.0, "b": 19.0}})
check("house 7 kW, car 11 kW, aim 6 kW, batteries to the reserve: the alarm "
"fires (the house alone misses the aim)", summary(r3)[0] != []
and not r3["c"].car_explains)
print("\n3. THE COUNTERFACTUAL ITSELF")
BS = datetime(2026, 11, 16, 20, 0, tzinfo=timezone.utc)
class _Car(ctl_car.CarMixin):
def __init__(self, cover=True):
self.o = {"ev_batt_cover": cover}
self._carq = {"key": BS, "ws": 0.0, "mono": 0.0}
def proj(grid, elapsed, held=None):
return tariff.Projection(
projected_w=grid, elapsed_w=grid, elapsed_s=elapsed,
covered_frac=1.0, complete=False, block_start=BS,
held_w=grid if held is None else held)
def lands(p, batt, aim=5950.0):
return peakguard.misses_aim(p, batt_w=batt, target_w=aim)
c = _Car()
for el in (10.0, 30.0, 120.0, 300.0, 600.0):
c._carq["ws"] = 11040.0 * el
p = proj(3000 + 11040 - 8100, el)
x = c.car_exclude_alarm(p, 11040.0)
check(f"rig numbers at {el:.0f} s: the house alone does not miss the aim "
"(no 0 W clip)", not lands(x, 8100.0))
check(f"...and the guard-side `car_exclude` is unchanged (still clipped)",
c.car_exclude(p, 11040.0).held_w == 0.0)
c._carq["ws"] = 11040.0 * 30
x = c.car_exclude_alarm(proj(5940.0, 30.0), 11040.0)
check("the rest of the period keeps its sign: held = grid - car = -5100 W",
abs(x.held_w - (5940.0 - 11040.0)) < 1e-6)
check("a fresh car reading is needed: None gives the period back as it is",
c.car_exclude_alarm(proj(5940.0, 30.0), None).held_w == 5940.0)
# the house alone over the aim still misses
c._carq["ws"] = 11040.0 * 30
check("house 7 kW alone (batteries 8.1 kW, car 11 kW): the house misses the aim",
lands(c.car_exclude_alarm(proj(7000 + 11040 - 8100, 30.0), 11040.0),
8100.0))
# review: the done part is clipped at 0 Ws. Rig shape for 400 s (grid 5940 W),
# then the batteries at the reserve and the house at 12 kW: the house alone
# lands 6667 W. Crediting the car-made export (-5100 W x 400 s) would hide it.
c._carq["ws"] = 11040.0 * 400
held = 12000.0 + 11040.0
check("the car's battery share earlier is not credited against a later house "
"overload (done part clipped at 0 Ws)",
lands(c.car_exclude_alarm(
proj((5940.0 * 400 + held * 500) / 900, 400.0, held), 11040.0), 0.0))
# review: the rest of the period takes off the car's power NOW, not its
# quarter average. Car 11 kW for 500 s, then 1.4 kW; house 7 kW, no batteries.
c._carq["ws"] = 11040.0 * 500 + 1380.0 * 100
held = 7000.0 + 1380.0
check("a car turned down mid-quarter: the rest takes off its power now, so "
"the house alone (7 kW) still misses the aim",
lands(c.car_exclude_alarm(
proj(((7000 + 11040) * 500 + held * 100 + held * 300) / 900, 600.0,
held), 1380.0), 0.0))
# with the batteries giving less than the house the two agree where the old
# clip did not bite
p = proj(3000 + 3700 - 300, 300.0)
c._carq["ws"] = 3700.0 * 300.0
old, new = c.car_exclude(p, 3700.0), c.car_exclude_alarm(p, 3700.0)
check("batteries under the house: the same landing as before (no clip bit)",
abs(old.projected_w - new.projected_w) < 1e-6
and abs(old.held_w - new.held_w) < 1e-6)
# cover OFF: the projection the guard sees is `car_exclude`, bit for bit what
# b86c015 built (a frozen copy of its formula), over a grid of periods
def frozen(c, p, w):
avg = c.car_avg_w(p, w)
return (max(0.0, float(p.projected_w) - avg),
max(0.0, float(p.held_w) - float(w)))
same = True
for grid in (-3000.0, 0.0, 800.0, 5900.0, 14000.0):
for held in (-4000.0, 0.0, 6000.0, 15000.0):
for el in (0.0, 30.0, 450.0, 899.0):
for w in (1380.0, 3700.0, 11040.0):
c._carq["ws"] = w * el * 0.9
p = proj(grid, el, held)
x = c.car_exclude(p, w)
same = same and (x.projected_w, x.held_w) == frozen(c, p, w)
check("cover off: the projection the guard sees (`car_exclude`) is bit for "
"bit the old formula over 240 periods", same)
check("...and `car_exclude` still hands back the period when the car figure "
"is None", c.car_exclude(proj(5000.0, 30.0), None).projected_w == 5000.0)
print()
print("FAIL: " + ", ".join(fails) if fails else "PASS: every check passed")
sys.exit(1 if fails else 0)
+41 -5
View File
@@ -61,33 +61,69 @@ class CarPlant(s81._Plant):
return await super().call(domain, service, data)
class CarPlantN(CarPlant):
"""EV-10b: N batteries, each its own setpoint, power and SoC (`soc` is a
dict {"a": %, "b": %}); `rating` is per battery. The grid sees them all."""
def __init__(self, house, rating, soc, charger):
super().__init__(house, rating, 0.0, charger)
self.socs = dict(soc)
self.hists = {u: [(-1e9, 0.0)] for u in self.socs}
def batt_of(self, u, at):
w = 0.0
for when, v in self.hists[u]:
if when <= at:
w = v
return max(-self.rating, min(self.rating, float(round(w))))
def batt(self, at):
return sum(self.batt_of(u, at) for u in self.socs)
async def number(self, e, invert=False):
for u in self.socs:
if e == "sensor.soc_" + u:
return self.socs[u]
if e == "sensor.batt_" + u:
return self.batt_of(u, self.t)
return await super().number(e, invert)
async def set_number(self, e, v):
if e.startswith("number.sp_"):
self.hists[e[-1]].append((self.t + s81.RESPONSE_S, float(v)))
return True
return await super().set_number(e, v)
def drive(house, *, dur=300.0, rating=2000.0, soc=60.0, cap=3500.0, margin=50,
opts=None, plug=True, setpoint=16, phases=3, mode="manual",
user_a=16, events=None, sim=None, store=None):
user_a=16, events=None, sim=None, store=None, n=1, plant_cls=None,
dev_w=5000.0):
"""Run it. Returns a namespace-like dict: plant, controller, charger, the
notification ids raised with their second, and the controller's rows."""
sim = sim or SimCharger(setpoint_a=setpoint)
if plug:
sim.plug_in()
sim.phases_allowed = phases
o = rig._options(1, dict({
o = rig._options(n, dict({
"meter_source": "ha_signed", "p1_net_entity": "sensor.net",
"meter_phases": 1, "peak_cap_w": cap, "peak_margin_w": margin,
"battery_modes_enabled": True, "max_w": rating,
"ev_charger": "alfen_ha", "ev_max_a": 16, "ev_phases": "auto",
"ev_current_entity": SET}, **(opts or {})))
store = store or rig._Store()
store.data[unit_key("inverter-a", packmode.USE_KEY)] = False
for u in "ab"[:n]:
store.data[unit_key("inverter-" + u, packmode.USE_KEY)] = False
store.data[packmode.USE_KEY] = False
db = os.path.join(tempfile.mkdtemp(prefix="ev4-"), "tariff.db")
out = {}
async def go():
plant = CarPlant(house, rating, soc, sim)
plant = (plant_cls or CarPlant)(house, rating, soc, sim)
c = Controller(o, plant, store, rig._Pub(), stop=asyncio.Event(),
peak_db_path=db)
for i in c.inverters:
i.dev_min, i.dev_max = -5000.0, 5000.0
i.dev_min, i.dev_max = -dev_w, dev_w
c.auto = True
clock = [0.0]
c.car_now = lambda: clock[0]