Files
goodwe-addon/goodwe_controller/tools/ev20_day.py
T
ems-agentandClaude 7bc8988be0
infra-pin / fresh (pull_request) Successful in 2s
checks / unit (pull_request) Failing after 1h10m59s
EV-21: Solar cuts the car first for the quarter peak
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>
2026-11-25 17:01:07 +01:00

210 lines
8.7 KiB
Python

"""EV-20, T53: the acceptance sim day, shared by test_ev20_long.py (Batteries
first) and test_ev20_long_car.py (Car first).
The real Controller, N=2 (A 40 % and may charge, B full), 08:00-18:00 of sun
(9 kW at noon) with 12 clouds of 1 to 8 minutes, a house of 0.4 to 2.5 kW with
three +3 kW steps of a little under 5 minutes. The cycle order of `step` over
the whole day, of `step_race` over the cloudiest three hours, and a car-Off
twin over the quarters around the house steps for the alarms.
What is checked, per priority and cycle order:
- starts: at most one per stretch in which the car's target stayed under
6 A worth longer than `ev_pause_min` (the morning counts as one), so no cloud
or house step shorter than that starts or pauses the car;
- no start and no pause inside a cloud of 300 s or less;
- selects at least 600 s apart;
- 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;
- 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
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)
CLOUDS = []
_t = 1800
for _k in range(12):
_t += _rnd.randint(1200, 2400)
CLOUDS.append((_t, _t + _rnd.randint(60, 480)))
STEPS = [(9000, 9290), (19000, 19290), (27000, 27290)]
SOCS = {"a": 40.0, "b": 100.0}
RACE = (7200, 7200 + 10800) # the cloudiest three hours
def sun(t):
base = 9000.0 * max(0.0, math.sin(math.pi * t / DAY))
for a, b in CLOUDS:
if a <= t < b:
return 0.15 * base
return base
def house(t):
w = 400.0 + 2100.0 * (0.5 + 0.5 * math.sin(t / 1700.0))
for a, b in STEPS:
if a <= t < b:
w += 3000.0
return w
def cur_writes(r):
return [(x[2], x[1], x[3]) for x in r["c"].car_solar.log
if x[0] == "current"]
def low_stretches(r, first, longer=PAUSE_S):
"""Stretches in which the car's target was under 6 A worth on 1 phase for
longer than `longer`: (start, end); the last may run to the day's end."""
out, since = [], None
for x in r["trace"]:
sp = x["spare"]
room = x.get("room") or 0.0
tgt = None if sp is None else sp - (room if first == "batteries"
else 0.0) - MARGIN
low = tgt is None or tgt < 6.0 * 230.0
if low and since is None:
since = x["t"]
if not low and since is not None:
if x["t"] - since > longer:
out.append((since, x["t"]))
since = None
if since is not None and r["trace"] \
and r["trace"][-1]["t"] - since > longer:
out.append((since, r["trace"][-1]["t"]))
return out
def grid_split(r):
"""The car's grid energy outside its holds (W s): settled, and within 20 s
of a step of the sun, the house or the car's own current."""
tr = r["trace"]
marks = []
for i in range(1, len(tr)):
a, b = tr[i - 1], tr[i]
if abs(b["sun"] - a["sun"]) > 200.0 or abs(b["house"] - a["house"]) \
> 200.0 or b["sp"] != a["sp"] or b["ph"] != a["ph"]:
marks.append(b["t"])
settled = slew = 0.0
j = 0
for x in tr:
imp = max(0.0, min(x["car"], x["grid"])) \
if x["why"] != "hold" and x["sp"] > 0 else 0.0
if imp <= 0.0:
continue
while j < len(marks) and marks[j] < x["t"] - 20.0:
j += 1
near = j < len(marks) and marks[j] <= x["t"]
if near:
slew += imp
else:
settled += imp
return settled, slew
def run_day(first, check):
"""Run the day for one priority and grade it through `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, 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,
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.
log = r["c"].car_solar.log
sel_t = [t for k, a, t, ok in log if k == "phases"]
starts, pauses, paused = [], [], True
for kind, a, t, ok in log:
if kind != "current":
continue
if a == 0.0:
if not [1 for t2 in sel_t if t <= t2 <= t + 30.0]:
pauses.append(t)
paused = True
elif paused:
starts.append(t)
paused = False
lows = low_stretches(r, first)
check(f"T53 [{first} first, {tag}]: {len(starts)} starts, at most one "
f"per stretch under 6 A worth longer than the pause "
f"({len(lows)}: {lows[:6]})", len(starts) <= len(lows) + 1)
# A pause or start inside a short cloud is the cloud's only when the
# low stretch it ends began with that cloud.
every = low_stretches(r, first, longer=-1.0)
bad = []
for t in pauses + starts:
for a, b in short_c:
if a <= t <= b + 1:
began = [s0 for s0, e0 in every if s0 <= t <= e0 + 1]
if not began or began[-1] >= a - 1:
bad.append((t, a, b))
check(f"T53 [{first} first, {tag}]: no start and no pause from a "
f"cloud of 300 s or less ({bad[:2]}; {len(long_c)} clouds are "
f"longer)", not bad)
sel = [x[0] for x in r["sim"].log if x[1] == "phases"]
check(f"T53 [{first} first, {tag}]: selects at least 600 s apart "
f"({sel})", all(b - a >= 600.0 for a, b in zip(sel, sel[1:])))
settled, slew = grid_split(r)
print(f" [{first} first, {tag}] writes {len(w)}; car grid energy "
f"outside holds: settled {settled / 3600.0:.1f} Wh, loop slew "
f"after a step {slew / 3600.0:.1f} Wh; sun "
f"{r['c'].car_sun_kwh()} of {r['c'].car.today_kwh} kWh")
check(f"T53 [{first} first, {tag}]: the car's settled grid energy "
f"outside its holds is at most 10 Wh ({settled / 3600.0:.1f} Wh)",
settled <= 10.0 * 3600.0)
r = runs["step"]
for a, _b in STEPS:
t0 = float(a - a % 900 - 900)
off = S.drive(house, sun, dur=2700, t0=t0, first=first, mode="off",
plug=False, socs=dict(SOCS))
win = (t0 + 900.0, t0 + 2700.0) # the first quarter warms up
al = [t for t, n in r["raised"] if n in S.ALARMS
and win[0] <= t < win[1]]
ao = [t for t, n in off["raised"] if n in S.ALARMS
and win[0] <= t < win[1]]
check(f"T53 [{first} first]: house-caused alarms around the +3 kW "
f"step at {a} s at the same seconds as the car-Off twin, +2 s "
f"({al[:3]} vs {ao[:3]})",
len(al) == len(ao) and all(abs(x - y) <= 2
for x, y in zip(al, ao)))
return runs