"""EV-21: Solar's car is cut first for the quarter peak. The amount, when it comes (at once or after the 15 s wait), and what counts as headroom. `python3 -B test_ev21.py` Rows T1-T3, T7-T10, T12-T21, T28 and T35 of reports/EV-21-test-plan.md, on the real Controller (`tools/ev20_sun.py` through `tools/ev21_kit.py`). The second period runs 900-1800; a step at t = 960 is elapsed 60 s. "Within 1 cycle": the writer step that follows the cycle that first sees the cut due, logged at that cycle's second (`race` runs: one second later). Every run also carries the Never checks of `ev21_kit.never` (N1, N2, N6, T35). Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). """ import asyncio import os import sys import types HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(HERE, "tools")) from app import carmode, ctl_car, peakguard # noqa: E402 import ev20_sun as S # noqa: E402 from chargersim import SimCharger # noqa: E402 from ev20_kit import LOG, check, fails, const, step_fn # noqa: E402 from ev21_kit import (AIM, CUT_WAIT_S, after, alarms, first_alarm, # noqa: E402 merge, never, quarter_avg, shape, twin, drive, _cutamps, set_resp, notes, replay_twin, near_end) from app import messages # noqa: E402 n_log0 = LOG.mark() def zero_at(r, t0): """The second of the first 0 A write at or after t0, or None.""" z = [t for t, a, _ in after(r, t0) if a == 0.0] return z[0] if z else None def first_want(r, t0): w = [x["t"] for x in r["rec"].rows if x["t"] >= t0 and (x["want"] or 0) > 0] return w[0] if w else None def banked(r, q0=900): return any(k.startswith(S.rig.BASE.replace(minute=15).isoformat()[:16]) for k in r["c"].car_peak_q) if q0 == 900 else bool( r["c"].car_peak_q) # =========================================================================== # print("\n1. THE CUT AMOUNT (T1)") # =========================================================================== # cut = _cutamps() rows = [((6900, 2700, 3), 6.0), ((6900, 3800, 3), 0.0), ((2300, 800, 1), 6.0), ((2300, 920, 1), 6.0), ((2300, 921, 1), 0.0), ((11040, 2498, 3), 12.0), ((11040, 998, 3), 14.0), ((3680, 1, 1), 15.0)] got = [(a, cut(*a)) for a, _ in rows] check(f"T1: floor((car - excess) / (230 x n)), 0 under 6 A: {got}", all(g == want for (_a, g), (_b, want) in zip(got, rows))) check(f"T1: a car at a 10 A setpoint drawing 2530 W (253 V), excess 100 W, " f"stays at 10 A, never above the setpoint ({cut(2530, 100, 1, 10.0)})", cut(2530, 100, 1, 10.0) == 10.0) check(f"T1: excess <= 0 is no cut ({cut(6900, 0, 3)}, {cut(6900, -50, 3)})", cut(6900, 0, 3) is None and cut(6900, -50, 3) is None) check(f"T1: an unknown car figure cuts to 0 A (OQ2) ({cut(None, 500, 3)})", cut(None, 500, 3) == 0.0) # =========================================================================== # print("\n2. SHAPE C: NOTHING CAN GIVE, THE CUT AT ONCE (T2, T28)") # =========================================================================== # tw_c = twin("C", dur=1800) q_tw = quarter_avg(tw_c, 900) for first in ("car", "batteries"): for race in (False, True): tag = f"{first} first{', race' if race else ''}" r = shape("C", first=first, race=race, dur=1800) w = after(r, 960) z = zero_at(r, 960) q = quarter_avg(r, 900) check(f"T2 [{tag}]: the first write after the step is 0 A within 1 " f"cycle, no 6 A first ({w[:3]})", bool(w) and w[0][1] == 0.0 and w[0][0] <= 960 + int(race)) check(f"T2 [{tag}]: the period lands {q:.0f} W <= {AIM:.0f} W; the " f"Off twin {q_tw:.0f} W > it", q <= AIM and q_tw > AIM) check(f"T2 [{tag}]: nothing banked as the car's " f"({r['c'].car_peak_q})", not r["c"].car_peak_q) if first == "car": # T28 is on the plan's shapes (Car first). Batteries first: see # the dev report's Findings (EV-18's grading in the step's cycle). check(f"T28 [C, {tag}]: no peak alarm or red row while the " f"house alone is under the aim ({alarms(r, 900)}, " f"{[x['t'] for x in r['trace'] if x['red'] and x['t'] >= 900][:3]})", not alarms(r, 900) and not [x for x in r["trace"] if x["red"] and x["t"] >= 900]) never(f"T2 [{tag}]", r) note = notes(r, messages.ID_CAR_CUT) if hasattr(messages, "ID_CAR_CUT") \ else [] check(f"OQ5: one grey note 'Solar lowered the car for the peak.' ({note})", len(note) == 1 and messages.car_cut().body == "Solar lowered the car for the peak.") check("OQ5: no car_over row and no CAR_OVER_PEAK while the cut works", not [x for x in r["trace"] if x["over"]] and not notes(r, messages.ID_CAR_OVER)) # =========================================================================== # print("\n3. THE 30 s GATE AND THE 6 A HOLD NEVER DELAY A CUT (T3, T27)") # =========================================================================== # def stamp(p, c): c.car_solar.nonzero_at = p.t # a non-zero write 2 s before the step for race in (False, True): r = shape("C", step=1200, house_w=800.0, race=race, dur=1500, events={1198: stamp}) w = after(r, 1200) check(f"T3 [{'race' if race else 'step'}]: excess about 2700 W at elapsed " f"300 s, a write 2 s before: the partial cut 6 A goes within 1 " f"cycle, not at the 30 s gate ({w[:3]})", bool(w) and w[0][1] == 6.0 and w[0][0] <= 1200 + int(race)) never(f"T3 [{'race' if race else 'step'}]", r) # T27: Solar holds 6 A since t-100 (a cloud), both at the cut-out, then a # house step heads the period over: 0 A within 1 cycle, not after the hold. sun27 = step_fn((960, 900.0 + 4140.0), (1060, 0.0), base=7900.0) r = drive(step_fn((1060, 3000.0), base=900.0), sun27, dur=1300, first="car", phases=3, socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "3"}) held6 = [x["t"] for x in r["trace"] if 1000 <= x["t"] < 1060 and x["a"] == 6.0] w = after(r, 1060) check(f"T27: Solar held 6 A before the step ({held6[:1]}..{held6[-1:]}); the " f"step writes 0 A within 1 cycle ({w[:2]})", len(held6) > 30 and bool(w) and w[0] == (1060, 0.0, True)) # =========================================================================== # print("\n4. A CAR THAT DRAWS NOTHING, A HOUSE OVERLOAD (T7, T8, T9)") # =========================================================================== # H9 = step_fn((960, 9000.0), base=900.0) # (i) Solar's own pause at 0 A (too little sun ever), (ii) an idle car (B). for name, kw in (("own 0 A pause", {}), ("idle car, state B", {"events": {5: lambda p, c: p.ch.car_full()}})): r = drive(H9, const(900.0), dur=1100, first="car", phases=3, socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "3"}, **kw) o = drive(H9, const(900.0), dur=1100, first="car", phases=3, mode="off", socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "3"}, **kw) a_s, a_o = first_alarm(r, 900), first_alarm(o, 900) check(f"T7 [{name}]: no cut write ({after(r, 960)}), car_explains never " f"True, the alarm at the Off twin's second ({a_s} vs {a_o})", not [x for x in after(r, 960) if x[1] > 0 or x[0] > 961] and not any(x["explains"] for x in r["trace"]) and a_s is not None and a_o is not None and abs(a_s - a_o) <= 2) class Draws50(SimCharger): """EV-10's shape: a car in state C that draws 50 W at any current.""" def target_w(self): return 50.0 if super().target_w() > 0 else 0.0 for name, kw, sim_cls in ( ("T8: a trusted 50 W car in state C", dict(phases=3, opts={"ev_phases": "3"}), Draws50), ("T9: the car on 1 phase, the house alone 9 kW", dict(phases=1, opts={"ev_phases": "1"}), SimCharger)): sun = step_fn((960, 0.0), base=900.0 + 1610.0 + 100.0) \ if sim_cls is SimCharger else step_fn((960, 0.0), base=7900.0) r = drive(H9, sun, dur=1100, first="car", socs={"a": 10.0, "b": 10.0}, sim=sim_cls(setpoint_a=0), **kw) o = drive(H9, sun, dur=1100, first="car", socs={"a": 10.0, "b": 10.0}, mode="off", sim=sim_cls(setpoint_a=7), **kw) w = after(r, 960) a_s, a_o = first_alarm(r, 900), first_alarm(o, 900) check(f"{name}: 0 A within 1 cycle ({w[:2]}); the alarm at the Off " f"twin's second +2 ({a_s} vs {a_o}); car_explains never True", bool(w) and w[0][1] == 0.0 and w[0][0] <= 961 and a_s is not None and a_o is not None and a_s - a_o <= 2 and not any(x["explains"] for x in r["trace"] if x["t"] >= 960)) never(name[:3], r) # =========================================================================== # print("\n5. REAL HEADROOM: THE 15 s WAIT (T10), NONE WITHOUT IT (T12-T15)") # =========================================================================== # for race in (False, True): tag = "race" if race else "step" r = shape("W", race=race, dur=1100) fw = first_want(r, 960) z = zero_at(r, 960) early = [x for x in after(r, 960) if x[1] < 6.0 and x[0] < (fw or 0) + CUT_WAIT_S] check(f"T10 [{tag}]: the guard first wants power at {fw}; the cut (0 A: " f"car 6900 W less an excess over 6900 W) at {z}, 15-16 s later, " f"not before ({after(r, 960)[:3]})", fw is not None and z is not None and fw + CUT_WAIT_S <= z <= fw + CUT_WAIT_S + 1 + int(race) and not early) never(f"T10 [{tag}]", r) check(f"T28 [W, {tag}]: no peak alarm or red row, nothing banked " f"({alarms(r, 900)}, {r['c'].car_peak_q})", not alarms(r, 900) and not r["c"].car_peak_q and not [x for x in r["trace"] if x["red"] and x["t"] >= 900]) r = shape("S", race=race, dur=1100) z = zero_at(r, 960) check(f"T12 [{tag}]: saturated (house 16 kW): the cut at once ({z})", z is not None and z <= 960 + int(race)) r = shape("F", race=race, dur=1100, sun_w=None, events={}) z = zero_at(r, 960) check(f"T13 [{tag}]: floor-limited (19 % against a 20 % reserve): the " f"cut at once ({z}; {after(r, 900)[:3]})", z is not None and z <= 960 + int(race)) never(f"T13 [{tag}]", r) # T12, EV-05 r3: the car at 16 A on 3 phases, sun 13 kW, the house steps to # H at elapsed 5 s; the car-Off twin (no car) lands at or under the aim. for H in (25900.0, 25950.0): kw = dict(dur=1810, first="car", phases=3, socs={"a": 60.0, "b": 60.0}, opts={"ev_phases": "3"}) house = step_fn((905, H), base=900.0) r = drive(house, const(13000.0), **kw) o = drive(house, const(13000.0), plug=False, mode="off", **kw) q, qo = quarter_avg(r, 900), quarter_avg(o, 900) check(f"T12 [H={H:.0f}]: the car-Off twin lands {qo:.0f} W <= aim, the " f"Solar car's period {q:.0f} W too (cut at {zero_at(r, 905)})", qo <= AIM and q <= AIM) class RefusesA(S.SunPlant): """Battery A never gives (the plant gives min(cmd, 0)).""" def batt_of(self, u, at): w = super().batt_of(u, at) return min(w, 0.0) if u == "a" else w def refuse_a(p, c): c.inverters[0].refused = 1 ev14 = {t: refuse_a for t in range(1, 1100)} ev14[0] = lambda p, c: (refuse_a(p, c), set_resp(5.0)(p, c)) r = shape("W", events=ev14, plant_cls=RefusesA, dur=1100, rows=False) z = zero_at(r, 960) check(f"T14: N=2, A refuses to give, B has 4600 W: the excess is beyond " f"what B can add, so the cut at once ({z}), never after the wait", z is not None and z <= 961) def refuse_n1(p, c): c.batt_refused, c.batt_refused_at = 1, p.t r = shape("W", n=1, house_w=900.0, dur=1100, rows=False, events=merge({t: refuse_n1 for t in range(1, 1100)}, 0, lambda p, c: (refuse_n1(p, c), set_resp(20.0)(p, c)))) z = zero_at(r, 960) r0 = shape("W", n=1, house_w=900.0, dur=1100) z0 = zero_at(r0, 960) check(f"T15: N=1, the sole unit refuses to give: the cut at once ({z}); the " f"same unit giving waits ({z0})", z is not None and z <= 961 and z0 is not None and z0 >= 960 + 15) # =========================================================================== # print("\n6. WHAT COUNTS AS HEADROOM (T16, T17, T18)") # =========================================================================== # c = r0["c"] G = peakguard.PeakDecision(engaged=True, floor_w=1.0, ceiling_w=3500.0, ceiling_from="cap", wanted_w=4000.0) fake = types.SimpleNamespace( inverters=[types.SimpleNamespace(name="inverter-a", batt=2500.0, soc=60.0, bms_soc_floor=10.0, refused=0, sign_wd=types.SimpleNamespace( tripped=False), rating_w=lambda: 5000.0), types.SimpleNamespace(name="inverter-b", batt=2500.0, soc=60.0, bms_soc_floor=10.0, refused=0, sign_wd=types.SimpleNamespace( tripped=False), rating_w=lambda: 4600.0)], site_batt_w=5000.0, circ_wd=types.SimpleNamespace(tripped=False), site_sign_wd=types.SimpleNamespace(tripped=False), batt_refused=0, modes_on=False) head = getattr(ctl_car.CarMixin, "_car_cut_headroom", None) h_free = head(fake, G) if head else "absent" h_able = head(fake, __import__("dataclasses").replace(G, able_w=4600.0)) \ if head else "absent" check(f"T16 (a): two units above the cut-out giving 2500 W each: headroom " f"{h_free} W with able_w None, {h_able} W with the guard's able_w 4600 " f"(so the cut comes at once)", h_free == 4600.0 and h_able == 0.0) rep = __import__("dataclasses").replace h_sat = head(fake, rep(G, saturated=True)) if head else "absent" h_flim = head(fake, rep(G, floor_limited=True)) if head else "absent" check(f"T12/T13 (unit): the same batteries with real watts to add count as " f"adding nothing while the guard is saturated ({h_sat}) or " f"floor-limited ({h_flim}): the cut at once", h_sat == 0.0 and h_flim == 0.0) fake.inverters[0].refused = 1 h_ref = head(fake, G) if head else "absent" fake.inverters[0].refused = 0 fake.inverters[0].sign_wd.tripped = True h_sig = head(fake, G) if head else "absent" fake.inverters[0].sign_wd.tripped = False fake.inverters[0].batt = None h_none = head(fake, G) if head else "absent" check(f"T16/T17/T21: a refusing unit adds nothing ({h_ref}), a sign-stopped " f"one nothing ({h_sig}); an unknown battery figure is None, the cut at " f"once ({h_none})", h_ref == 2100.0 and h_sig == 2100.0 and h_none is None) r = shape("W", socs={"a": 19.0, "b": 60.0}, dur=1100, opts={"peak_soc_floor": 20}) z = zero_at(r, 960) rw = r["rec"].at(961) or {} check(f"T16 (b): A at 19 % (held at its reserve), B at 60 %: the cut at " f"once ({z}); floor-limited at the cut: {rw.get('flim')}", z is not None and z <= 961) # T17: a unit's sign stop while a cut is due: Solar cannot write, so it # cannot cut: the alarm and banking as Off. for n in (1, 2): def trip(p, c): c.inverters[0].sign_wd.tripped = True kw = dict(n=n, dur=1100, events={955: trip}) r = shape("C", **kw) o = replay_twin(r, "C", **kw) a_s, a_o = first_alarm(r, 950), first_alarm(o, 950) check(f"T17 [N={n}]: a sign stop: car_explains never True, the alarm at " f"the Off twin's second, the same charger writes replayed " f"({a_s} vs {a_o}; Solar's way-out {after(r, 950)[:1]}), nothing banked " f"({r['c'].car_peak_q})", not any(x["explains"] for x in r["trace"] if x["t"] >= 955) and (a_s == a_o or (a_s is not None and a_o is not None and abs(a_s - a_o) <= 2)) and r["c"].car_peak_q == o["c"].car_peak_q) # T18: battery modes: A switched Off counts for nothing; both Off: at once. def mode_off(*units): def f(p, c): from app import packmode from app.store import unit_key for u in units: c.store.data[unit_key("inverter-" + u, packmode.USE_KEY)] = False return f ra = shape("W", house_w=900.0, dur=1100, events={0: lambda p, c: (set_resp(20.0)(p, c), mode_off("a")(p, c))}) rb = shape("W", house_w=900.0, dur=1100, events={0: lambda p, c: (set_resp(20.0)(p, c), mode_off("a", "b")(p, c))}) za, zb = zero_at(ra, 960), zero_at(rb, 960) check(f"T18: A switched Off counts for nothing (cut at {za}, a partial cut " f"or a wait on B's 4600 W); both Off: at once ({zb}; " f"{after(rb, 960)[:2]})", bool(after(ra, 960)) and bool(after(rb, 960)) and after(rb, 960)[0][0] <= 961) # =========================================================================== # print("\n7. THE PERIOD'S LAST 120 s (T19, T20) AND NO BATTERY FIGURE (T21)") # =========================================================================== # r = near_end(1700) fw = first_want(r, 1700) z = zero_at(r, 1700) check(f"T19: a step 100 s before the end with real headroom: the cut within " f"1 cycle of the first want ({fw} -> {z}; {after(r, 1690)[:2]})", fw is not None and z is not None and z <= fw + 1) never("T19", r) r = near_end(1670) fw = first_want(r, 1670) cuts = [t for t, a, _ in after(r, 1670) if a < 10.0] check(f"T20: first want at {fw} (130 s left): the cut at 1680 (120 s left), " f"not at 1669-1679 and not at 1685 ({cuts[:2]})", fw in (1670, 1671) and bool(cuts) and cuts[0] == 1680 and fw + CUT_WAIT_S > 1681) for name, units in (("(a) A's figure None", {"a"}), ("(b) both None", {"a", "b"})): for past in (False, True): t_nan = 959 if not past else 930 def nan(p, c, units=units): p.batt_nan = set(units) r = shape("W", dur=1100, events={0: set_resp(20.0), t_nan: nan}) z = zero_at(r, 960) check(f"T21 {name}, {'past' if past else 'inside'} the 15 s " f"inputs-missing hold: the cut within 2 s of the excess, never " f"after the wait ({z}; {after(r, 955)[:2]})", z is not None and z <= 962) # =========================================================================== # print("\n8. NO TRACEBACK (N11)") # =========================================================================== # tb = LOG.tracebacks(n_log0) check(f"N11: no traceback in this file's runs ({tb[:1]})", not tb) print(f"\n{'FAILED: ' + str(len(fails)) if fails else 'ALL PASSED'}") sys.exit(1 if fails else 0)