Solar as a second writer next to Manual (carmode.SolarPlan, SolarWriter on ManualWriter's one write site, safe phase sequence and other-writer watch): signed spare, Batteries first on the batteries' ratings, the margin, whole amps rounded down, the 30 s / 1 A rule, start and pause dwells, auto phases, a one-phase car. Every way out ends at 0 A, retried by EV-04's rule; at shutdown before the inverters, three tries inside 15 s (D3); start-up and a returning charger or HA write 0 A first (D2); never over another writer's hold. The peak guard treats a Solar car as a Manual car (D1 wording). Solar kWh sensor and card line; select.goodwe_car_sun_first; ev_margin_w, ev_start_min, ev_pause_min with config, validator, translations, DOCS, DECISIONS and CHANGELOG. Checks: test_ev20.py, test_ev20_exits.py, test_ev20_writers.py, test_ev20_guard.py, test_ev20_long.py, test_ev20_long_car.py, test_ev20_fuzz.py (harness tools/ev20_sun.py, ev20_kit.py, ev20_day.py); test_ev03/test_ev04 no longer use Solar as the refused example. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
313 lines
13 KiB
Python
313 lines
13 KiB
Python
"""EV-20: T54, the fuzz. `python3 -B test_ev20_fuzz.py`
|
|
|
|
14 sites of random spare, outages, unplugs, refusals (at the exits too), other
|
|
writers (while stopped and in shadow too), a silent meter, shadow and Stop
|
|
toggles mid-sequence, Solar / Off / Manual changes; half in the production
|
|
cycle order. N1-N3, N5, N9, N10, N12-N14 and N16 on every step (N4 is
|
|
EV-21's; N6-N8, N11 and N15 are rows of test_ev20_*.py).
|
|
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
|
|
"""
|
|
|
|
import asyncio
|
|
import logging
|
|
import os
|
|
import random
|
|
import sys
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
sys.path.insert(0, os.path.join(HERE, "tools"))
|
|
|
|
from app import carmode # noqa: E402
|
|
import ev20_sun as S # noqa: E402
|
|
from chargersim import SimCharger # noqa: E402
|
|
|
|
fails = []
|
|
|
|
|
|
def check(name, cond):
|
|
print(f" {'ok ' if cond else 'FAIL'} {name}")
|
|
if not cond:
|
|
fails.append(name)
|
|
|
|
|
|
class _Log(logging.Handler):
|
|
def __init__(self):
|
|
super().__init__(logging.DEBUG)
|
|
self.tb = []
|
|
|
|
def emit(self, r):
|
|
if r.exc_info:
|
|
self.tb.append(r.getMessage())
|
|
|
|
|
|
LOG = _Log()
|
|
_g = logging.getLogger("goodwe")
|
|
_g.addHandler(LOG)
|
|
_g.setLevel(logging.DEBUG)
|
|
_g.propagate = False
|
|
|
|
|
|
def cur_writes(r):
|
|
return [(x[2], x[1], x[3]) for x in r["c"].car_solar.log
|
|
if x[0] == "current"]
|
|
|
|
|
|
# =========================================================================== #
|
|
print("T54: THE FUZZ")
|
|
# =========================================================================== #
|
|
SITES = 14
|
|
STEPS_PER = int(os.environ.get("EV20_FUZZ_STEPS", "2400"))
|
|
|
|
|
|
class FSim(SimCharger):
|
|
"""The model, knowing who set its current last: the add-on in Solar (or
|
|
on its way out of Solar), Manual, or another writer."""
|
|
ctl = None
|
|
setter = None
|
|
|
|
def _apply(self, what, v):
|
|
if what == "current":
|
|
c = self.ctl
|
|
self.setter = ("manual" if c is not None
|
|
and c.car_mode == "manual" else "solar")
|
|
super()._apply(what, v)
|
|
|
|
def set_current(self, a):
|
|
self.setter = "other"
|
|
super().set_current(a)
|
|
|
|
|
|
def fuzz_site(seed):
|
|
rnd = random.Random(seed)
|
|
sim = FSim(setpoint_a=rnd.choice([0, 6, 10, 16]))
|
|
sim.lag_s = rnd.choice([0.0, 0.0, 3.0, 12.0])
|
|
if seed % 3 == 0:
|
|
sim.ramp_w_s, sim.stop_delay_s = 300.0, 4.0
|
|
state = {"sun": rnd.uniform(3000, 11000),
|
|
"house": rnd.uniform(300, 2000)}
|
|
bad, counts, snap = [], {}, {}
|
|
seen = {"exit_since": None, "avail": None, "back": []}
|
|
|
|
def bump(k):
|
|
counts[k] = counts.get(k, 0) + 1
|
|
|
|
async def ev(p, c):
|
|
sim.ctl = c
|
|
w = c.car_solar
|
|
t = p.t
|
|
# Outages end by themselves.
|
|
for k, off in (("outage", lambda: p.ch.go_unavailable(False)),
|
|
("ha", lambda: setattr(p, "ha_down", False)),
|
|
("meter", lambda: setattr(p, "meter_on", True)),
|
|
("stop", lambda: setattr(c, "auto", True)),
|
|
("shadow", lambda: c.o.__setitem__("shadow_mode",
|
|
"off"))):
|
|
if state.get(k) is not None and t >= state[k]:
|
|
off()
|
|
state[k] = None
|
|
if state.get("mode") is not None and t >= state["mode"]:
|
|
state["mode"] = None
|
|
await c.handle_action("car_mode", value="solar")
|
|
x = rnd.random()
|
|
if x < 0.02:
|
|
state["sun"] = max(0.0, min(12000.0, state["sun"]
|
|
+ rnd.uniform(-4000, 4000)))
|
|
bump("spare")
|
|
elif x < 0.023:
|
|
state["house"] = rnd.uniform(300, 4000)
|
|
elif x < 0.0245 and state.get("outage") is None:
|
|
p.ch.go_unavailable(True)
|
|
state["outage"] = t + rnd.uniform(5, 120)
|
|
bump("outage")
|
|
elif x < 0.0255 and state.get("ha") is None:
|
|
p.ha_down = True
|
|
state["ha"] = t + rnd.uniform(5, 120)
|
|
bump("ha")
|
|
elif x < 0.0265:
|
|
(p.ch.unplug if p.ch.state != "A" else p.ch.plug_in)()
|
|
bump("unplug")
|
|
elif x < 0.0295:
|
|
p.ch.refuse = rnd.choice([None, None, "ignore", "error"])
|
|
bump("refuse" + ("_exit" if not c.car_writing()
|
|
or c.car_mode != "solar" else ""))
|
|
elif x < 0.031:
|
|
p.ch.set_current(rnd.choice([0, 6, 13, 16]))
|
|
bump("other" + ("_out" if not c.car_writing() else ""))
|
|
elif (w.hold or w.gave_up) and x < 0.06:
|
|
bump("press") # the user hands it back to Solar
|
|
await c.handle_action("car_mode", value="solar")
|
|
elif x < 0.032 and state.get("meter") is None:
|
|
p.meter_on = False
|
|
state["meter"] = t + rnd.uniform(5, 360)
|
|
bump("meter")
|
|
elif x < 0.0355 or (w.seq is not None and x < 0.15):
|
|
k = rnd.choice(["stop", "shadow", "mode"])
|
|
bump(k + ("_seq" if w.seq is not None else ""))
|
|
back = t + rnd.uniform(5, 240)
|
|
if k == "stop":
|
|
c.auto = False
|
|
c.o["shadow_mode"] = rnd.choice(["off", "auto"])
|
|
state["stop"] = back
|
|
elif k == "shadow":
|
|
c.o["shadow_mode"] = "on"
|
|
state["shadow"] = back
|
|
else:
|
|
await c.handle_action("car_mode", value=rnd.choice(
|
|
["off", "manual", "solar"]))
|
|
state["mode"] = back
|
|
elif x < 0.0365:
|
|
await c.handle_action("car_sun_first", value=rnd.choice(
|
|
["batteries", "car"]))
|
|
if p.ch.refuse is not None and rnd.random() < 0.02:
|
|
p.ch.refuse = None
|
|
# What the step of this second starts from (it runs after this, in
|
|
# both cycle orders).
|
|
snap[p.t] = dict(mode=c.car_mode, writing=c.car_writing(),
|
|
live=w.live, hold=w.hold, engaged=w.engaged)
|
|
bump("s_" + ("hold" if w.hold else "solar" if c.car_mode == "solar"
|
|
and c.car_writing() else "out"))
|
|
|
|
def on_cycle(p, c, t):
|
|
w, sim = c.car_solar, p.ch
|
|
r = c.car.reading
|
|
avail = bool(r is not None and r.available)
|
|
if avail and seen["avail"] is False:
|
|
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
|
|
seen["back"].append((t, cur))
|
|
seen["avail"] = avail
|
|
# N3: Solar never keeps the car at 6 A or more past the pause after
|
|
# the spare fell under 6 A worth (while it writes and the charger
|
|
# answers: an unreachable charger is held, then set to 0 A on return).
|
|
pause_s = 60.0 * carmode.solar_option(c.o, "ev_pause_min")
|
|
p_ = w.plan
|
|
if c.car_mode == "solar" and c.car_writing() and avail \
|
|
and (w.sent_a or 0.0) >= 6.0 and w.taken \
|
|
and sim.setter == "solar" and sim.setpoint_a >= 6.0 \
|
|
and p_.low_since is not None \
|
|
and t - p_.low_since > pause_s + 2.0:
|
|
bad.append((seed, t, "N3 6 A past the pause"))
|
|
# N9: an exit from Solar leaves no current of its own standing once
|
|
# the charger takes writes again (a minute for the retry).
|
|
out = (c.car_mode == "off" or not c.car_writing()
|
|
or sim.state in ("A", "E", "F") or bool(r and r.error))
|
|
quiet = (avail and not p.ha_down and sim.refuse is None
|
|
and not w.hold and not w.gave_up
|
|
and c.car_mode != "manual")
|
|
if out and quiet:
|
|
seen["exit_since"] = seen["exit_since"] or t
|
|
if t - seen["exit_since"] > carmode.RETRY_S + 15.0 \
|
|
and sim.setter == "solar" and sim.setpoint_a > 0.0 \
|
|
and not sim._pending:
|
|
bad.append((seed, t, "N9 Solar's current stands after the "
|
|
"way out", sim.setpoint_a))
|
|
seen["exit_since"] = t
|
|
else:
|
|
seen["exit_since"] = None
|
|
|
|
race = seed % 2 == 1
|
|
evs = {t: ev for t in range(1, STEPS_PER)}
|
|
r = S.drive(lambda t: state["house"], lambda t: state["sun"],
|
|
dur=STEPS_PER, first=rnd.choice(["batteries", "car", "car"]),
|
|
socs={"a": rnd.uniform(40, 100), "b": rnd.uniform(70, 100)},
|
|
sim=sim, race=race, events=evs, on_cycle=on_cycle,
|
|
phases=rnd.choice([1, 3]),
|
|
opts={"ev_start_min": rnd.choice([1, 1, 2]),
|
|
"ev_pause_min": rnd.choice([1, 2, 5]),
|
|
"ev_phases": rnd.choice(["auto", "auto", "1", "3"])})
|
|
c = r["c"]
|
|
# N1
|
|
if c.charger.clamp_faults:
|
|
bad.append((seed, "N1 clamp fault", c.charger.clamp_faults[:1]))
|
|
for t, what, v, pw, sp in sim.log:
|
|
if what == "current" and v > min(16.0, sim.station_a) + 1e-9:
|
|
bad.append((seed, t, "N1 over the clamp", v))
|
|
# N2
|
|
sel = [x for x in sim.log if x[1] == "phases"]
|
|
for a, b in zip(sel, sel[1:]):
|
|
if b[0] - a[0] < 600.0:
|
|
bad.append((seed, b[0], "N2 two selects inside 600 s"))
|
|
for x in sel:
|
|
if x[4] > 0.0:
|
|
bad.append((seed, x[0], "N2 select with the setpoint up", x))
|
|
log = [x for x in c.car_solar.log if x[0] == "current"]
|
|
for kind, a, t, ok in log:
|
|
s = snap.get(t) or snap.get(t - 1)
|
|
if s is None:
|
|
continue
|
|
# N16: nothing while EV-04's hold stands.
|
|
if s["hold"]:
|
|
bad.append((seed, t, "N16 a write under the hold", a))
|
|
# N10: off Solar or not writing, only the owed 0 A.
|
|
if (s["mode"] != "solar" or not s["writing"]) \
|
|
and (a > 0.0 or not s["live"]):
|
|
bad.append((seed, t, "N10 a write while out", a, s))
|
|
# N12: the first write after the charger (or HA) is back is 0 A, unless
|
|
# the charger came back at 0 A already.
|
|
for tb, cur in seen["back"]:
|
|
nxt = [x for x in log if x[2] >= tb]
|
|
if nxt and nxt[0][1] > 0.0 and (cur is None or cur > 0.5):
|
|
bad.append((seed, tb, "N12 non-zero first after the return",
|
|
nxt[0], cur))
|
|
# N5 / N14 from Solar's own write log: decisions and retries.
|
|
dec = [(t, a, ok) for kind, a, t, ok in log]
|
|
for i, (t, a, ok) in enumerate(dec):
|
|
if i and dec[i - 1][1] == a and not dec[i - 1][2] \
|
|
and t - dec[i - 1][0] < carmode.RETRY_S - 1e-9:
|
|
bad.append((seed, t, "N14 a retry under 60 s", a))
|
|
tries = 0
|
|
for i, (t, a, ok) in enumerate(dec):
|
|
tries = tries + 1 if (i and dec[i - 1][1] == a
|
|
and not dec[i - 1][2]) else 1
|
|
if tries > carmode.MAX_TRIES:
|
|
bad.append((seed, t, "N14 more than 3 tries", a))
|
|
nz = [(t, a) for t, a, ok in dec if a > 0.0]
|
|
for (t0, a0), (t1, a1) in zip(nz, nz[1:]):
|
|
if a1 != a0 and t1 - t0 < carmode.SOLAR_WRITE_S - 1e-9 \
|
|
and not [1 for t, a, ok in dec if t0 < t < t1 and a == 0.0]:
|
|
bad.append((seed, t1, "N5 two changes under 30 s",
|
|
(t0, a0), (t1, a1)))
|
|
for (t0, a0), (t1, a1) in zip(nz, nz[1:]):
|
|
if a1 != a0 and abs(a1 - a0) < carmode.SOLAR_STEP_A:
|
|
bad.append((seed, t1, "N5 a change under 1 A"))
|
|
tally["sel"] += len([x for x in sim.log if x[1] == "phases"])
|
|
tally["zero"] += len([x for x in log if x[1] == 0.0])
|
|
print(f" site {seed:2d} ({'race' if race else 'step'}): "
|
|
f"{len(log)} writes, "
|
|
f"{len([x for x in sim.log if x[1] == 'phases'])} selects, "
|
|
f"{len([x for x in log if x[1] == 0.0])} at 0 A")
|
|
return bad, counts, len(sim.log), r
|
|
|
|
|
|
all_bad, all_counts, n_writes, steps = [], {}, 0, 0
|
|
tally = {"sel": 0, "zero": 0}
|
|
for seed in range(SITES):
|
|
b, cnt, nw, r = fuzz_site(seed)
|
|
all_bad += b
|
|
n_writes += nw
|
|
steps += STEPS_PER
|
|
for k, v in cnt.items():
|
|
all_counts[k] = all_counts.get(k, 0) + v
|
|
n_sel, n_zero = tally["sel"], tally["zero"]
|
|
print(f" {SITES} sites x {STEPS_PER} steps, {n_writes} charger writes; "
|
|
f"disturbances {sorted(all_counts.items())}")
|
|
check(f"T54: N1, N2, N3, N5, N9, N10, N12, N14 and N16 hold on every step "
|
|
f"({all_bad[:3]})", not all_bad)
|
|
need = ("spare", "outage", "ha", "unplug", "refuse", "refuse_exit", "other",
|
|
"other_out", "meter", "stop", "shadow", "mode")
|
|
check(f"T54: each disturbance happened, mid-sequence ones too "
|
|
f"({[k for k in need if not all_counts.get(k)]})",
|
|
all(all_counts.get(k) for k in need)
|
|
and (all_counts.get("stop_seq", 0) + all_counts.get("shadow_seq", 0)
|
|
+ all_counts.get("mode_seq", 0)) > 0)
|
|
check(f"T54: Solar did write, select and pause ({n_writes} writes, "
|
|
f"{n_sel} selects, {n_zero} at 0 A)",
|
|
n_writes >= 5 * SITES and n_sel >= 3 and n_zero >= SITES)
|
|
check(f"T54: at least 1200 steps per site, in both cycle orders ({steps})",
|
|
STEPS_PER >= 1200)
|
|
check("T54/N13: no Traceback", LOG.tb == [])
|
|
|
|
print(f"\n{'all passed' if not fails else f'{len(fails)} FAILED'}")
|
|
for f in fails:
|
|
print(" FAIL:", f)
|
|
sys.exit(1 if fails else 0)
|