"""EV-54: shared pieces of the refused-cut checks (test_ev54*.py): the run with a per-cycle writer recorder, refusal windows, the cut tries per quarter key, the Off twin with Solar's charger replayed, and the Never checks of reports/EV-54-test-plan.md every run carries. The plant is EV-21's (`ev21_kit.drive` on `ev20_sun`): Shape C is N=2, both batteries at 10 %, the car 10 A on 3 phases, the house 3000 W and the sun 0 from 960. Aim 3400 W; the second period runs 900-1800. Every value is read through getattr or `named_absence`, so a tree without EV-54 grades FAIL, never a crash.""" 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 # noqa: E402 from ev20_kit import LOG, check, step_fn # noqa: E402,F401 from ev21_kit import drive, merge, Q, NoGive, refuse_n1 # noqa: E402,F401 from named_absence import first, nth, given, present # noqa: E402,F401 Q3_TEXT = ("The charger did not take the peak cut, so the add-on tries again " "next quarter: CHARGER_REFUSED.") HOLD_TEXT = ("The charger did not take the current, so the add-on stops " "asking until you press Solar: CHARGER_REFUSED.") RETRY_S = carmode.RETRY_S TOL = 0.01 class W54: """Per cycle, after the cycle and its writer step: the cut state, the writer's own state, the read-back and the log mark; and every current write Solar made, with the reason it was sent with.""" def __init__(self): self.rows = [] self.writes = [] # (t, a, ok, why) self.n = 0 self.marks = [] # (t, log index after the cycle) self.mark0 = LOG.mark() def __call__(self, p, c, t): w = c.car_solar st = getattr(c, "_cut", None) or {} for x in w.log[self.n:]: if x[0] == "current": self.writes.append((x[2], x[1], x[3], getattr(w, "sent_why", None))) self.n = len(w.log) cc = getattr(c, "car_solar_can_cut", None) g = c.peak_guard self.rows.append(dict( t=t, key=st.get("key"), cap=st.get("cap"), wait=st.get("wait"), cuts=st.get("cuts"), under=st.get("under"), cut_a=w.cut_a, sent=w.sent_a, taken=w.taken, gave_up=w.gave_up, why=getattr(w, "sent_why", None), fails=w.fails, cut_fails=getattr(w, "cut_fails", None), plan=w.plan.a, plan_why=w.plan.why, ok_since=w.plan.ok_since, set_at=w.plan.set_at, switch=w.plan.switch, seq=w.seq, rb=p.ch.readback_a, sp=p.ch.setpoint_a, car=p.ch.power_w, can=getattr(c, "_car_can", None), can_now=bool(cc()) if cc else None, explains=c.car_explains, floor=None if g is None else g.floor_w, mode=c.car_mode, hold=w.hold, fault=w.fault, stuck=bool(c.car.stuck(t)))) self.marks.append((t, LOG.mark())) def at(self, t): return first(x for x in self.rows if x["t"] == t) def lines(self, text=None, level=None): """(cycle second, level, message) of the log lines of this run.""" out, lo = [], self.mark0 for t, hi in self.marks: for lv, m, _x in LOG.rec[lo:hi]: if (text is None or text in m) and level in (None, lv): out.append((t, lv, m)) lo = hi return out def refuse(kind="ignore"): def f(p, c): p.ch.refuse = kind return f def accept(p, c): p.ch.refuse = None def window(ev, t0, t1, kind="ignore"): """The charger refuses `kind` from t0 to t1 (None: to the end).""" ev = merge(ev, int(t0), refuse(kind)) if t1 is not None: ev = merge(ev, int(t1), accept) return ev def house_c(*more, h=3000.0): """Shape C's house: 900 W, `h` from 960, then the (t, W) pairs.""" return step_fn((960, h), *more, base=900.0) def sun_c(*more, s=0.0): """Shape C's sun: 7900 W (the car's 10 A, the house and 100 W), `s` from 960, then the (t, W) pairs.""" return step_fn((960, s), *more, base=7900.0) def run(house=None, sun=None, *, dur, n=2, socs=None, events=None, opts=None, mode="solar", setpoint=0, phases=3, **kw): """Shape C (N=2 both at 10 %, or N=1 `a` at 10 %) with `house` and `sun`, Car first, the car on 3 phases. `out["w"]` is the W54 recorder. At N=1 without a `plant_cls`, the sole battery refuses to give (EV-21's N=1 rows: `refuse_n1` with the `NoGive` plant), so the cut stays needed.""" if n == 1 and "plant_cls" not in kw: kw["plant_cls"] = NoGive kw.setdefault("rows", False) ev = dict(events or {}) for t in range(int(kw.get("t0", 0.0)), int(kw.get("t0", 0.0) + dur)): ev = merge(ev, t, refuse_n1) events = ev ratings = {"a": 5000.0, "b": 4600.0} if n == 2 else {"a": 5000.0} socs = dict(socs or {u: 10.0 for u in ratings}) rec = W54() oc = kw.pop("on_cycle", None) def on_cycle(p, c, t): rec(p, c, t) if callable(oc): oc(p, c, t) o = dict({"ev_phases": "3"}, **(opts or {})) out = drive(house or house_c(), sun or sun_c(), dur=dur, first="car", phases=phases, mode=mode, socs=socs, ratings=ratings, opts=o, events=events, setpoint=setpoint, on_cycle=on_cycle, **kw) out["w"] = rec out["spec"] = dict(house=house or house_c(), sun=sun or sun_c(), dur=dur, n=n, socs=socs, opts=opts, phases=phases, kw=kw) return out # ------------------------------------------------------------- reading runs def writes(r, t0=0, t1=1e9): """(t, a, ok, why) of every current write Solar made in [t0, t1).""" return [x for x in r["w"].writes if t0 <= x[0] < t1] def row(r, t): return r["w"].at(t) def rows(r, t0=0, t1=1e9): return [x for x in r["w"].rows if t0 <= x["t"] < t1] def cut_writes(r, t0=0, t1=1e9): """The writes made while a cut was due or stood (the cycle's cap or its wait): the cut tries, (t, a, ok, why, key).""" out = [] for t, a, ok, why in writes(r, t0, t1): x = row(r, t) if present(x) and (x["cap"] is not None or x["wait"] is not None): out.append((t, a, ok, why, x["key"])) return out def refused_by_key(r, t0=0, t1=1e9): """{quarter key: [t, ...]} of the refused cut tries.""" out = {} for t, _a, ok, _why, key in cut_writes(r, t0, t1): if not ok: out.setdefault(key, []).append(t) return out def key_change(r, t0, t1): """The first cycle in [t0, t1) whose quarter key differs from the one before it.""" prev = None for x in r["w"].rows: if x["t"] >= t0 and x["t"] < t1 and prev is not None \ and x["key"] is not None and x["key"] != prev: return x["t"] if x["key"] is not None: prev = x["key"] return None def t_lift(r, t0, t1): """The cycle the cap was lifted in [t0, t1): a cap, then none.""" prev = None for x in r["w"].rows: if t0 <= x["t"] < t1 and prev is not None and x["cap"] is None: return x["t"] prev = x["cap"] if t0 <= x["t"] else None return None def dropped(r, t, a, slack=2): """The drop by `t` (+-slack): `sent_a` = `a` (the read-back), taken, the plan's current `a`. Returns the first cycle that shows it, or None.""" for x in rows(r, t - slack, t + slack + 1): if x["sent"] is not None and abs(x["sent"] - a) <= TOL and x["taken"] \ and abs(x["plan"] - a) <= TOL: return x["t"] return None def same_gaps(r, t0=0, t1=1e9): """N2: two tries of the same value less than RETRY_S apart (the list of offending pairs), refused tries and their retries.""" w = [(t, a) for t, a, ok, _why in writes(r, t0, t1)] bad = [] for i, (ta, aa) in enumerate(w): for tb, ab in w[i + 1:]: if abs(aa - ab) <= TOL and tb - ta < RETRY_S - 1e-9: prev_ok = [ok for t, a, ok, _w in writes(r, ta, ta + 1) if abs(a - aa) <= TOL] if prev_ok and not prev_ok[0]: bad.append((ta, tb, aa)) break return bad def never54(name, r, *, clamp=16.0, max_q=3, peak_free=True): """N1 (at most 3 refused cut tries per quarter key), N2 (the same value not twice within RETRY_S after a refusal), N3 (no write between 0 and 6 A), N4 (none above the clamp), N6 (no non-zero write above a standing cap), N12 (`gave_up` never set by a cut try; no "until you press Solar" while a cut is due or stands), N13 (no Traceback), N16 (no "peak cut" write while no cut is due or stands).""" rbk = refused_by_key(r) bad1 = {k: v for k, v in rbk.items() if len(v) > max_q} check(f"{name}: N1 at most {max_q} refused cut tries per quarter key " f"({bad1})", not bad1) bad2 = same_gaps(r) check(f"{name}: N2 no retry of a refused value within {RETRY_S:.0f} s " f"({bad2[:3]})", not bad2) w = writes(r) bad3 = [(t, a) for t, a, _ok, _why in w if 0.0 + TOL < a < 6.0 - TOL] bad4 = [(t, a) for t, a, _ok, _why in w if a > clamp + TOL] check(f"{name}: N3 no write between 0 and 6 A ({bad3[:3]}); N4 none above " f"the clamp ({bad4[:3]})", not bad3 and not bad4) bad6 = [] for t, a, _ok, _why in w: x = row(r, t) if a > TOL and present(x) and x["cap"] is not None \ and a > x["cap"] + TOL: bad6.append((t, a, x["cap"])) check(f"{name}: N6 no non-zero write above a standing cut ({bad6[:3]})", not bad6) hi = r["w"].marks[-1][1] if r["w"].marks else r["w"].mark0 tb = [m for _lv, m, x in LOG.rec[r["w"].mark0:hi] if x] check(f"{name}: N13 no Traceback ({tb[:1]})", not tb) if peak_free: bad16 = [] for t, a, _ok, why in w: x = row(r, t) if why == "peak cut" and present(x) and x["cap"] is None \ and x["wait"] is None: bad16.append((t, a)) for t, _lv, m in r["w"].lines("(peak cut)"): x = row(r, t) if present(x) and x["cap"] is None and x["wait"] is None: bad16.append((t, m)) check(f"{name}: N16 no 'peak cut' write or line while no cut is due " f"or stands ({bad16[:3]})", not bad16) # ------------------------------------------------------------- the Off twin def twin(r, extra_events=None): """The run of `r` in Off: the same house, sun and batteries, and the charger moved at the same seconds as Solar's taken writes moved it, so the car is the same and only the mode differs.""" sp = r["spec"] ev = dict(extra_events or {}) prev = None for x in r["trace"]: if prev is not None and abs(x["sp"] - prev) > TOL: def put(p, c, v=x["sp"]): p.ch.set_current(v) ev = merge(ev, int(x["t"]) + 1, put) prev = x["sp"] kw = dict(sp["kw"]) return run(sp["house"], sp["sun"], dur=sp["dur"], n=sp["n"], socs=sp["socs"], opts=sp["opts"], mode="off", setpoint=0, phases=sp["phases"], events=ev, **kw) def alarms_by_q(r, ids): out = {} for t, n in r["raised"]: if n in ids: q0 = int(t) // Q * Q out.setdefault(q0, t) return out def as_off(name, r, o, ids, *, t0=900, refused=None): """T7 / N5: the run `r` against its Off twin `o`. Before the read-back shows the cut, `car_explains` is never True; the first alarm of every quarter at the twin's second +2; `car_peak_q` as the twin's; the guard's floor within 50 W of the twin's while the cut is refused (`refused`: the (t0, t1) of that); `car_solar_can_cut()` False while the read-back is above `sent_a`.""" # Graded out only in the cut's own cycle (nothing written yet: EV-21 # T30); from the cycle after its write, as Off until the read-back. t_ex = refused[0] if refused is not None else t0 bad_ex = [x["t"] for x in rows(r, t_ex) if x["explains"] and x["sent"] is not None and x["rb"] > x["sent"] + TOL] a_r, a_o = alarms_by_q(r, ids), alarms_by_q(o, ids) qs = sorted(set(a_r) | set(a_o)) bad_a = [(q, a_r.get(q), a_o.get(q)) for q in qs if q >= t0 and ( a_r.get(q) is None or a_o.get(q) is None or abs(a_r[q] - a_o[q]) > 2)] bad_f = [] if refused is not None: fo = {x["t"]: x["floor"] for x in o["w"].rows} for x in rows(r, refused[0], refused[1]): y = fo.get(x["t"]) if abs((x["floor"] or 0.0) - (y or 0.0)) > 50.0: bad_f.append((x["t"], x["floor"], y)) bad_c = [x["t"] for x in rows(r, t0) if x["can_now"] and x["sent"] is not None and x["rb"] > x["sent"] + TOL] check(f"{name}: T7 as Off: car_explains never True before the read-back " f"shows the cut ({bad_ex[:3]}); each quarter's first alarm at the " f"twin's second +2 ({bad_a[:3]}); car_peak_q as the twin's " f"({r['c'].car_peak_q} vs {o['c'].car_peak_q}); floor within 50 W " f"while refused ({bad_f[:3]}); can-cut False while the read-back is " f"above sent_a ({bad_c[:3]})", not bad_ex and not bad_a and not bad_f and not bad_c and r["c"].car_peak_q == o["c"].car_peak_q)