"""EV-19: the real Controller, N=2, when the batteries first reach the peak reserve `R` early in a Manual car session (EV-15 F-B). Used by test_ev19.py. python3 tools/ev19_reserve.py # the T1 grid, one row per cell The units stand at 21 % and give `bw` W (`force`) until `R`, where both read 19 %; after `R` they follow the trajectory `traj`. The house is set so that house + car with the batteries at 0 W lands at aim + `over` W (F-B: +520 W, less than the 1 380 W car). Manual is set, then the car plugs in, `rp` s before `R`. The run starts `E` s before a quarter edge (rig.BASE moved back), so `R = E + r_rel`. One dict per cycle, taken after it. Trajectories after R: t1 both 0 W; t2 a 0 W, b follows the house (the loop below the reserve covers house + car, up to b's rating); t3 both ramp to 0 W over 3 cycles; t4 as t1, but every battery reading is 10 s old (the rig reads battery W every 10 fake s, P1 every 5) while P1 is fresh; t4r as t1, but P1 is 5 s late while the battery reading is fresh. """ import hashlib import os import sys from datetime import timedelta HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import ev04_peak as P # noqa: E402 import ev18_peak as H # noqa: E402 import opt11_identity as rig # noqa: E402 import safety81_sim as s81 # noqa: E402 from app import peakguard # noqa: E402 from chargersim import SimCharger # noqa: E402 AIM = H.AIM CAR = 1380.0 FLOOR = H.FLOOR RATE = {"a": 5000.0, "b": 4600.0} OPTS = H.OPTS OPTS1 = {"peak_soc_floor": 20, "inverters": [OPTS["inverters"][0]]} class Meter(SimCharger): """A charger whose energy meter shows no 10 Wh step until `hold_until` (sim seconds; None: always live, float('inf'): never).""" hold_until = None _held = None def _build(self): if self.hold_until is None or self.t >= self.hold_until: self._held = None return super()._build() if self._held is None: self._held = self.kwh keep, self.kwh = self.kwh, self._held try: return super()._build() finally: self.kwh = keep class Draw(Meter): """A charger that draws `real_w` while charging and reports `say_w` (as test_ev18's). `c_at_0`: it stays in mode3 C while drawing 0 W.""" def __init__(self, real_w, say_w, c_at_0=False, **kw): super().__init__(**kw) self.real_w, self.say_w, self.c_at_0 = real_w, say_w, c_at_0 def target_w(self): if super().target_w() <= 0.0: return 0.0 return self.real_w def tick(self, seconds=1.0): super().tick(seconds) if self.c_at_0 and self.state == "B" and not self.full: self.state = "C" def _build(self): keep, self._frozen_w = self._frozen_w, self.say_w try: return super()._build() finally: self._frozen_w = keep class Plant(H.Plant): """`batt_lag`: every battery reading is that many s old. `p1_lag` with `p1_from`: P1 that many s late from that second on.""" batt_lag = 0.0 p1_lag = 0.0 p1_from = 0.0 house = None def batt_of(self, u, at): f = self.force.get(u) if f is not None: return float(f(at, self)) return P.CarPlantN.batt_of(self, u, at) def grid(self, at): if self.p1_lag and at >= self.p1_from: at = at - self.p1_lag return super().grid(at) async def number(self, e, invert=False): for u, secs in self.lost.items(): if e == "sensor.batt_" + u and int(self.t) in secs: return None if self.batt_lag and e.startswith("sensor.batt_") \ and e[-1] in self.socs: return self.batt_of(e[-1], self.t - self.batt_lag) return await P.CarPlantN.number(self, e, invert) def split(bw, units="ab"): """`bw` over the units, each capped at its rating.""" if len(units) == 1: return {units: min(bw, RATE[units])} a = min(RATE["a"], bw / 2.0) b = min(RATE["b"], bw - a) a = min(RATE["a"], bw - b) return {"a": a, "b": b} def traj_fn(u, traj, before, R, house, step=1): """Unit `u`'s W at time `at`: `before` until the first cycle after R (R + `step`), then the trajectory. P1 is sampled 0.3 s before each cycle, so the battery reading shows a change one cycle before the meter does.""" def f(at, plant): if at < R + step: return before if traj in ("t1", "t4", "t4r"): return 0.0 if traj == "t2": if u == "a": return 0.0 return min(RATE["b"], house(at) + plant.ch.power_w) if traj == "t3": k = int((at - R) // step) return before * max(0.0, (3 - k) / 3.0) if traj == "keep": return before raise ValueError(traj) return f def run(*, bw=4250.0, traj="t1", rp=180, r_rel=43, order="manual", energy="ok", x=1, mono_x=None, aim=AIM, over=520.0, house_w=None, house_fn=None, car_a=6, n=2, extra=None, rel=None, lost=None, after=900, soc_after=None, soc0=21.0, mode="manual", sim=None, explain_off=False, latch_off=False, force=None, plug_at=None, man_at=None, opts=None, pre_w=H.PRE_W): """One run; returns (run, trace, meta). `over`: house + car at batteries 0 W lands at aim + `over` W (ignored with `house_w`). `order`: 'manual' (Manual at plug-in - 3 s), 'plug' (plug-in at R-185, Manual at R-180), 'off120' (plug-in and charging in Off from R-180, Manual at R-60). `energy`: 'ok', 'late' (first 10 Wh step at plug-in + 150 s), 'never'. `mode`: 'manual' or 'off' (Off throughout: the base for honest alarms). `house_fn`: fn(t, R) for the house after the step. `extra`: events at run seconds, `rel`: at seconds from R. `lost`: {unit: seconds from R}. `plug_at` / `man_at`: plug-in / Manual at these seconds from R (override `order`). `force`: {unit: fn(at, plant) or None (the unit obeys)}. `opts`: added to the options. `pre_w`: the house before its step.""" units = "ab" if n == 2 else "a" step = int(x) if order == "plug": lead = 185 elif order == "off120": lead = 180 else: lead = rp + 3 if plug_at is not None or man_at is not None: lead = -min(v for v in (plug_at, man_at) if v is not None) E = 150 while E + r_rel - lead - 2 * step < 10: E += 150 E = int(-(-E // step) * step) R = E + r_rel if x != 1: R = int(-(-R // step) * step) hw = (aim + over - CAR) if house_w is None else house_w t_house = min(E - 120, R - lead - step) if x != 1: t_house = int(t_house // step * step) def house(t): if t < t_house: return pre_w if house_fn is not None: return house_fn(t, R) return hw sp = split(bw, units) frc = {u: traj_fn(u, traj, sp[u], R, house, step) for u in units} frc.update(force or {}) soc_after = soc_after or {u: 19.0 for u in units} lagb = 10.0 if traj == "t4" else 0.0 cls = type("Plant", (Plant,), { "force": frc, "batt_lag": lagb, "R": R, "lost": {u: {R + k for k in v} for u, v in (lost or {}).items()}, "p1_lag": 5.0 if traj == "t4r" else 0.0, "p1_from": float(R)}) s = sim or Meter(setpoint_a=car_a) if energy == "never": s.hold_until = float("inf") if x != 1: tick = s.tick s.tick = lambda secs=1.0: tick(secs * x) if order == "plug": t_plug, t_man = R - 185, R - 180 elif order == "off120": t_plug, t_man = R - 180, R - 60 else: t_plug, t_man = R - rp, R - rp - 3 if plug_at is not None: t_plug = R + plug_at if man_at is not None: t_man = R + man_at if x != 1: t_plug = int(t_plug // step * step) t_man = int(t_man // step * step) if t_man == t_plug and order != "plug": t_man -= step tr = [] n_err = [len(H.ERR.rec)] def hook(plant, c): orig = c.car_settle if explain_off: c._car_explains_alarm = lambda *a_, **k_: False if latch_off: c._car_contradicted = lambda *a_, **k_: False if mono_x is not None and mono_x != x: c.car_now = (lambda f=c.car_now: f() * mono_x / x) async def settle(): await orig() g = c.peak_guard red = [r_["id"] for r_ in c.checks() if r_["ok"] is False and not r_["warn"] and r_["id"] == "peak_guard"] errs = [m for m in H.ERR.rec[n_err[0]:] if "may not draw the battery lower" in m] n_err[0] = len(H.ERR.rec) cl = peakguard.claim(g) if g is not None else None mono = c.car_now() tr.append({ "t": plant.t, "explains": c.car_explains, "lim": bool(g is not None and (g.floor_limited or g.saturated)), "floor_lim": bool(g is not None and g.floor_limited), "within_aim": bool(g is not None and g.within_aim), "wants": bool(g is not None and g.engaged and (g.wanted_w or 0.0) > 0.0), "wanted": None if g is None else g.wanted_w, "target": None if g is None else g.target_w, "alarm": c._peak_floor_limited, "red": red, "err": errs, "w": c.car_alarm_w(), "car_raw": c.car.car_w(mono), "batt": c.site_batt_w, "true_batt": plant.batt(plant.t), "need_real": c._car_need_real, "need_excl": c._car_need_excl, "need_house": c._car_need_house, "over_now": c._car_over_now, "contra": c._car_contra_block is not None and ( c._peak_proj_real is not None and c._car_contra_block == c._peak_proj_real.block_start), "idle": c._car_idle(mono), "peak_needed": c._peak_needed, "key": c._carq["key"], "block": (c._peak_proj_real.block_start if c._peak_proj_real is not None else None), "floor_w": g.floor_w if g is not None else None, "lo": getattr(cl, "lo", None), "sp": tuple(i.last_write for i in c.inverters)}) c.car_settle = settle def set_manual(p, c): c._car_action("car_mode", "manual", c.car_now()) def plug(p, c): p.ch.plug_in() if energy == "late": p.ch.hold_until = p.ch.t + 150.0 def reserve(p, c): p.socs.update(soc_after) ev = {} def add(t, fn): t = int(t) old = ev.get(t) ev[t] = fn if old is None else ( lambda p, c, a_=old, b_=fn: (a_(p, c), b_(p, c))) add(0, hook) add(t_plug, plug) if mode == "manual": add(t_man, set_manual) add(R, reserve) for t, fn in (extra or {}).items(): add(t, fn) for t, fn in (rel or {}).items(): add(R + t, fn) base, tick0 = rig.BASE, s81.TICK rig.BASE, s81.TICK = base - timedelta(seconds=E), float(x) o = dict(OPTS if n == 2 else OPTS1, **(opts or {})) try: r = P.drive(house, dur=R + after + step, rating=5000.0, soc={u: soc0 for u in units}, cap=aim + H.MARGIN, phases=1, n=n, plant_cls=cls, opts=o, dev_w=5000.0, setpoint=car_a, user_a=car_a, mode="off", events=ev, sim=s, plug=False) finally: rig.BASE, s81.TICK = base, tick0 meta = {"E": E, "R": R, "t_plug": t_plug, "t_man": t_man, "t_house": t_house, "house_w": hw, "step": step} return r, tr, meta # ---------------------------------------------------------- event helpers # For `rel` (seconds from R) or `extra` (run seconds). def p1_gap(t0, secs): """No P1 sample reaches the add-on for `secs` from `t0` (it is late).""" def off(p, c): c.p1._ev19_submit = c.p1.submit c.p1.submit = lambda *a, **k: None def on(p, c): c.p1.submit = c.p1._ev19_submit return {t0: off, t0 + secs: on} def stale(t0, t1): """The charger's readings stop reaching the car tracker from t0 to t1: its figure ages past `stale_s`.""" def off(p, c): c.car._ev19_observe = c.car.observe c.car.observe = lambda *a, **k: None def on(p, c): c.car.observe = c.car._ev19_observe return {t0: off, t1: on} def unavailable(t0, t1): return {t0: lambda p, c: p.ch.go_unavailable(True), t1: lambda p, c: p.ch.go_unavailable(False)} def restart(t0): return {t0: lambda p, c: H.restart(c)} def phases(t0, n=3): """The user asks for `n` phases (the add-on's own 0 A pause follows).""" return {t0: lambda p, c: c._car_action("car_phases", n, c.car_now())} def socs(t0, **s): return {t0: lambda p, c: p.socs.update(s)} def merge(*evs): out = {} for e in evs: for t, fn in e.items(): old = out.get(t) out[t] = fn if old is None else ( lambda p, c, a_=old, b_=fn: (a_(p, c), b_(p, c))) return out # --------------------------------------------------------------- grading def window(tr, t0, t1): return [x for x in tr if t0 <= x["t"] <= t1] def alarms(r): return H.alarms(r) def edges(tr): return H.edges(tr) def bad(x): """An alarm, red sample or ERROR in this cycle.""" return bool(x["alarm"] or x["red"] or x["err"]) def repro(r, tr, meta, t0=-10, t1=60): """T1's definition: a floor notice, ERROR or red sample in R-10..R+60 in a cycle where the car figure is trusted (the shape lands under the aim without the car, so the car explains). Returns (cycles, C5-only cycles).""" R = meta["R"] w = window(tr, R + t0, R + t1) notes = [t for t in alarms(r) if R + t0 <= t <= R + t1] hit = [x["t"] for x in w if bad(x) and x["w"] is not None and x["w"] > 0.0] c5 = [x["t"] for x in w if bad(x) and not (x["w"] is not None and x["w"] > 0.0)] return hit, c5, notes def quiet(r, tr, t0, t1): return (not [t for t in alarms(r) if t0 <= t <= t1] and not any(bad(x) for x in window(tr, t0, t1))) def commands(r, tr): h = hashlib.sha256() for u in sorted(r["plant"].hists): h.update(repr((u, r["plant"].hists[u])).encode()) h.update(repr(r["sim"].writes()).encode()) h.update(repr([(x["t"], x["floor_w"], x["lo"], x["sp"]) for x in tr]).encode()) return h.hexdigest()[:16] def row(name, r, tr, meta): hit, c5, notes = repro(r, tr, meta) R = meta["R"] first = hit[:1] cause = "" if first: x = next(y for y in tr if y["t"] == first[0]) cause = (f"w={x['w']:.0f} batt={x['batt']} true={x['true_batt']:.0f}" f" real={x['need_real']:d} excl={x['need_excl']:d} " f"house={x['need_house']:d} over={x['over_now']:d} " f"contra={x['contra']:d} pn={x['peak_needed']:d} " f"wa={x['within_aim']:d} wanted={x['wanted']:.0f}") return (f"{name:42s} R={R:5d} notes {[t - R for t in notes]} " f"hit {[t - R for t in hit][:6]}{'...' if len(hit) > 6 else ''}" f" n={len(hit)} c5 {len(c5)} err " f"{len([x for x in window(tr, R - 10, R + 60) if x['err']])} " f"red900 {len([x for x in window(tr, R - 60, R + 900) if x['red']])}" f" {cause}") def t2_shape(**kw): """The reproducing shape (T2): b follows the house from R, 0 W before.""" return dict(dict(bw=0.0, traj="t2"), **kw) def t5_shape(**kw): """The honest shape (T5): the house alone misses the aim by 1 680 W, more than the 1 380 W car; the batteries give 4 250 W until R.""" return dict(dict(bw=4250.0, traj="t1", house_w=AIM + 1680.0), **kw) def flicker_force(bw=2000.0): """T17: each unit gives bw/2 above its reserve and ramps to 0 W over 3 cycles once at it (tau3); back above it, it gives bw/2 again at once.""" def mk(u): st = {"since": None} def f(at, plant): if plant.socs[u] >= 20.0: st["since"] = None return bw / 2.0 if st["since"] is None: st["since"] = at k = int(at - st["since"]) return bw / 2.0 * max(0.0, (3 - k) / 3.0) return f return {"a": mk("a"), "b": mk("b")} def _step_house(k, lo=AIM + 520.0 - CAR, hi=AIM + 1900.0): return lambda t, R: lo if t < R + k else hi def _burst(k, w): """Inverter-b: 2 125 W until R+1, then `w` for 0.5 s before the cycle at R+k (P1, sampled 0.3 s before it, and the reading both show it), else 0 W.""" def f(at, plant): if at < plant.R + 1: return 4250.0 / 2.0 return w if plant.R + k - 0.5 <= at <= plant.R + k else 0.0 return f def _ignoring(): """The charger accepts the 6 A write and ignores it: the car stays at 0 A.""" s = Meter(setpoint_a=0) s.refuse = "ignore" return s def _full_at_plug(p, c): """The car is full (after the plug-in at R-180): mode3 B, 0 W.""" p.ch.car_full() def _no_energy(p, c): """The charger has no energy entity.""" p.ch.no_energy = True def _freeze_stop(p, c): p.ch.freeze() p.ch.car_full() def jobs(): """Every controller run test_ev19.py grades: {name: kwargs}.""" j = {} for name, kw in grid(): j["T1 " + name] = kw # T3: the battery W sweep for tj in ("t1", "t2"): for bw in range(0, 4601, 200): j[f"T3 {tj} bw={bw}"] = dict(bw=float(bw), traj=tj) j[f"T3 {tj} tau5"] = dict(bw=9600.0, traj=tj, aim=6000.0, house_w=5200.0) # T4: the landing without the car at aim + 9 / + 11 W for d in (9, 11): for md in ("manual", "off"): j[f"T4 +{d} {md}"] = t2_shape(house_w=AIM + d, mode=md) # T5: honest at the reserve for tj in ("t1", "t4"): for md in ("manual", "off"): j[f"T5 {tj} {md}"] = t5_shape(traj=tj, mode=md) for md in ("manual", "off"): j[f"T5 tau5 {md}"] = dict(bw=9600.0, traj="t1", aim=6000.0, house_w=7700.0, mode=md) # T6: the honest step in the reserve cycle for k in (0, 1, 5): for md in ("manual", "off"): j[f"T6 step R+{k} {md}"] = dict(bw=4250.0, traj="t1", mode=md, house_fn=_step_house(k)) # T7: unknown values for nm, sh in (("T2", t2_shape), ("T5", t5_shape)): j[f"T7(a) {nm}"] = sh(lost={"a": {0, 1}}) j[f"T7(b) {nm}"] = sh(rel=unavailable(0, 1)) j["T7(a) T5 off"] = t5_shape(lost={"a": {0, 1}}, mode="off") j["T7(b) T5 off"] = t5_shape(rel=unavailable(0, 1), mode="off") # T8: a stale car figure j["T8(a) Off 120 s, Manual R-5"] = t2_shape(plug_at=-125, man_at=-5) j["T8(b) stale R-5..R+20"] = t2_shape(rel=stale(-5, 20)) j["T8(c) frozen, the car stops"] = t5_shape(rel={-30: _freeze_stop}) j["T8(c) off"] = t5_shape(rel={-30: _freeze_stop}, mode="off") # T9: comms for nm, sh in (("T2", t2_shape), ("T5", t5_shape)): j[f"T9(a) {nm} b lost at R"] = sh(lost={"b": {0}}) j[f"T9(a) {nm} b lost at R-1"] = sh(lost={"b": {-1}}) j[f"T9(b) {nm} P1 5 s late at R"] = sh(rel=p1_gap(0, 5)) # T10: a restart for nm, sh in (("T2", t2_shape), ("T5", t5_shape)): j[f"T10 {nm} twin"] = sh() for k in (-2, 2): j[f"T10 {nm} restart R{k:+d}"] = sh(rel=restart(k)) # T11: the quarter edge for rr in (-1, 0, 1, 43): j[f"T11 T2 R=E{rr:+d}"] = t2_shape(r_rel=rr) j[f"T11 T5 R=E{rr:+d}"] = t5_shape(r_rel=rr) j[f"T11 T5 R=E{rr:+d} off"] = t5_shape(r_rel=rr, mode="off") # C4: the old quarter heads over the aim (the house high all along), so the # guard wants power in its last 60 s and SAFETY-126's latch is carried j["T11 C4 T2 R=E+1"] = t2_shape(r_rel=1, house_w=13350.0, pre_w=13350.0) # T12: our own phase change for k in (-15, 5): j[f"T12 T2 1->3 at R{k:+d}"] = t2_shape(rel=phases(k)) j[f"T12 T5 1->3 at R{k:+d}"] = t5_shape(rel=phases(k)) j[f"T12 T5 1->3 at R{k:+d} off"] = t5_shape(rel=phases(k), mode="off") # T13: a wrong charger reply # (a): the house + the 400 W it really draws lands at aim + 520 W, so the # house alone misses by 120 W; (b) and T14(a): the car draws 0 W and the # house alone lands at aim + 520 W. An alarm is due in each. for md in ("manual", "off"): j[f"T13(a) draws 400 W {md}"] = t2_shape( sim=Draw(400.0, CAR, setpoint_a=6), house_w=AIM + 120.0, mode=md) j[f"T13(a) draws 100 W {md}"] = t2_shape( sim=Draw(100.0, CAR, setpoint_a=6), house_w=AIM + 420.0, mode=md) j[f"T13(b) the write ignored, 0 A {md}"] = t2_shape( sim=_ignoring(), house_w=AIM + 520.0, mode=md) # T14: configuration j[f"T14(a) 0 W in C {md}"] = t2_shape( sim=Draw(0.0, 0.0, c_at_0=True, setpoint_a=6), house_w=AIM + 520.0, mode=md) j[f"T14(a) idle B {md}"] = t2_shape( house_w=AIM + 520.0, mode=md, rel={-179: _full_at_plug}) j["T14(b) ev_charger off"] = t2_shape(opts={"ev_charger": "off"}) j["T14(b) off"] = t2_shape(mode="off") for tj in ("t1", "t4"): j[f"T14(c) N=1 anchor {tj}"] = dict(n=1, bw=4250.0, traj=tj) j["T14(c) N=1 T5"] = t5_shape(n=1) j["T14(c) N=1 T5 off"] = t5_shape(n=1, mode="off") # T15: one battery first (SAFETY-87) for nm, hw in (("anchor", AIM + 520.0 - CAR), ("honest", 19000.0)): for md in ("manual", "off"): j[f"T15 {nm} {md}"] = dict( bw=4250.0, traj="t1", house_w=hw, mode=md, force={"b": None}, soc_after={"a": 19.0, "b": 35.0}, rel=socs(360, b=19.0)) # T16: x10 (wall and mono), and mono x1 / wall x10 for xn, xk in (("x10", dict(x=10)), ("mono1", dict(x=10, mono_x=1))): xk = dict(xk, r_rel=40) # x10: b at 1 200 W before R (at 0 W, which the forced unit holds # against the guard's floor, SAFETY-37's gate reads it as frozen) xk2 = dict(xk, bw=1200.0) j[f"T16 {xn} T2"] = t2_shape(**xk2) for tj in ("t1", "t4"): for bw in (0.0, 2000.0, 4250.0): j[f"T16 {xn} T3 {tj} bw={bw:.0f}"] = dict(bw=bw, traj=tj, **xk) for md in ("manual", "off"): j[f"T16 {xn} T5 {md}"] = t5_shape(mode=md, **xk) j[f"T16 {xn} T6 {md}"] = dict(bw=4250.0, traj="t1", mode=md, house_fn=_step_house(0), **xk) j[f"T16 {xn} T7(b) T2"] = t2_shape(rel=unavailable(0, 10), **xk2) for rr in (-10, 0, 10, 40): j[f"T16 {xn} T11 T2 R=E{rr:+d}"] = t2_shape( **dict(xk2, r_rel=rr)) j[f"T16 {xn} T11 T5 R=E{rr:+d}"] = t5_shape(**dict(xk, r_rel=rr)) # T17: no flicker j["T17 flicker"] = dict( force=flicker_force(), after=1200, rel=merge(socs(300, a=21.0, b=21.0), socs(600, a=19.0, b=19.0)), house_fn=lambda t, R: AIM + 10.0 + (40.0 if int(t // 7) % 2 else -40.0)) # N2: figures only `car_w_trusted` keeps out of the alarm path: no energy # entity (never corroborated, never contradicted) and 11 kW reported at # a 6 A read-back (capped at 1 518 W; the house alone misses by 1 680 W) for md in ("manual", "off"): j[f"N2 no energy entity {md}"] = t2_shape(extra={0: _no_energy}, mode=md) j[f"N2 reports 11 kW at 6 A {md}"] = t5_shape( sim=Draw(CAR, 11000.0, setpoint_a=6), mode=md) # Review round 1: an honest house step answered by ONE cycle of inverter-b # power that P1 and the reading both show (the meter in step), after the # T6 shape (4 250 W until R, then 0 W). for k in (5, 30): for hi in (1900, 2500): for burst in (3000.0, 4600.0): for md in ("manual", "off"): j[f"RB step R+{k} aim+{hi} burst {burst:.0f} {md}"] = dict( bw=4250.0, traj="t1", mode=md, house_fn=_step_house(k - 0.5, hi=AIM + hi), force={"b": _burst(k, burst)}) # T10 (mE): restarts at R-1 and R, so the rise cycle has no reading from # two cycles back for nm, sh in (("T2", t2_shape), ("T5", t5_shape)): for k in (-1, 0): j[f"T10 {nm} restart R{k:+d}"] = sh(rel=restart(k)) # T20 / N4: the same runs with the car never explaining j["N4 T2 explain off"] = t2_shape(explain_off=True) j["N4 T5 explain off"] = t5_shape(explain_off=True) return j def grid(): """The T1 cells: (name, kwargs).""" cells = [] for bw in (0.0, 400.0, 800.0, 2000.0, 4250.0, 9600.0): for tj in ("t1", "t2", "t3", "t4", "t4r"): for rp in (30, 100, 110, 180, 600): kw = dict(bw=bw, traj=tj, rp=rp) if bw == 9600.0: kw.update(aim=6000.0, house_w=5200.0) cells.append((f"core bw={bw:.0f} {tj} rp={rp}", kw)) cells.append(("a: plug R-185, Manual R-180", dict(order="plug"))) cells.append(("a: Off 120 s, Manual R-60", dict(order="off120"))) cells.append(("b: energy first step late", dict(energy="late"))) cells.append(("b: energy never steps", dict(energy="never"))) for rr in (-60, 0, 1, 43, 450, 890): cells.append((f"c: R=E{rr:+d}", dict(r_rel=rr))) cells.append(("d: x10 wall+mono", dict(x=10, r_rel=40))) cells.append(("d: x10 wall, mono x1", dict(x=10, mono_x=1, r_rel=40))) for tj, bw in (("t4", 4250.0), ("t2", 4250.0), ("t2", 1200.0)): cells.append((f"d: x10 wall+mono {tj} bw={bw:.0f}", dict(x=10, r_rel=40, traj=tj, bw=bw))) cells.append((f"d: x10 wall, mono x1 {tj} bw={bw:.0f}", dict(x=10, mono_x=1, r_rel=40, traj=tj, bw=bw))) return cells class Res: """What a check needs from one run, picklable: the notices (`raised`, seconds and ids), the trace, the command digest and the run's times.""" def __init__(self, r, tr, meta): self.raised = list(r["raised"]) self.tr, self.meta = tr, meta self.cmd = commands(r, tr) self.R, self.E = meta["R"], meta["E"] def alarms(self): return [t for t, n in self.raised if n == FLOOR] def rel_alarms(self): return [int(t - self.R) for t in self.alarms()] def edges(self): return [int(t - self.R) for t in edges(self.tr)] def errors(self): return [int(x["t"] - self.R) for x in self.tr if x["err"]] def red(self, t0=-60, t1=900): return [int(x["t"] - self.R) for x in window(self.tr, self.R + t0, self.R + t1) if x["red"]] def at(self, k): return next((x for x in self.tr if x["t"] == self.R + k), None) def win(self, t0, t1): return window(self.tr, self.R + t0, self.R + t1) def quiet(self, t0=-60, t1=900): return quiet({"raised": self.raised}, self.tr, self.R + t0, self.R + t1) def edges_per_quarter(self): """False -> True edges of the floor alarm per quarter (N5).""" out = {} for t in edges(self.tr): q = int((t - self.E) // 900) out[q] = out.get(q, 0) + 1 return out def summary(self): return {"alarms": self.rel_alarms(), "edges": self.edges(), "errors": self.errors(), "red": len(self.red()), "cmd": self.cmd} _JOBS = {} def _job(name): import logging logging.disable(logging.WARNING) return name, Res(*run(**_JOBS[name])) def run_many(jobs, procs=None): """{name: kwargs} -> {name: Res}, `procs` runs at a time (fork: the kwargs may hold functions).""" import multiprocessing _JOBS.clear() _JOBS.update(jobs) procs = procs or int(os.environ.get("EV19_JOBS", "0")) \ or min(8, os.cpu_count() or 1) ctx = multiprocessing.get_context("fork") with ctx.Pool(procs) as pool: return dict(pool.imap_unordered(_job, list(jobs), chunksize=1)) def _one(cell): import logging logging.disable(logging.WARNING) name, kw = cell try: r, tr, meta = run(**kw) except Exception as e: # noqa: BLE001 import traceback return name, f"{name:42s} Traceback {e!r}\n{traceback.format_exc()}" return name, row(name, r, tr, meta) if __name__ == "__main__": import multiprocessing cells = grid() if len(sys.argv) > 1: cells = [c for c in cells if any(a in c[0] for a in sys.argv[1:])] with multiprocessing.Pool(int(os.environ.get("EV19_JOBS", "8"))) as pool: for _name, line in pool.imap(_one, cells): print(line, flush=True)