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>
307 lines
13 KiB
Python
307 lines
13 KiB
Python
"""EV-21: what must NOT change (Manual, Off, no excess, cloud edges the
|
|
batteries catch), the cut amount over a table of sites, the write seam, and
|
|
the docs and strings.
|
|
`python3 -B test_ev21_same.py`
|
|
|
|
Rows T4-T6, T11, T36 (the guard's floor), T37, T38, T47, T52, T53 of
|
|
reports/EV-21-test-plan.md. "Identical to c79eb37": each run's writes,
|
|
notices with their second, and per-second guard view (floor, car_explains,
|
|
car_over, red rows) are hashed (`ev21_kit.digest`); GOLDEN holds the hashes
|
|
the same runs give on c79eb37 (release/1.0 before EV-21), taken with
|
|
`EV21_GOLDEN=1 python3 -B test_ev21_same.py` on that tree. A hash that
|
|
differs fails, and the line prints what this tree gives.
|
|
|
|
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
|
|
"""
|
|
|
|
import ast
|
|
import io
|
|
import os
|
|
import sys
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
sys.path.insert(0, os.path.join(HERE, "tools"))
|
|
|
|
import opt11_identity as rig # noqa: E402
|
|
from ev20_kit import LOG, check, fails, const, step_fn # noqa: E402
|
|
from ev21_kit import (AIM, after, digest, drive, shape, view_guard, # noqa: E402
|
|
view_writes, _cutamps, refuse_n1, merge)
|
|
|
|
n_log0 = LOG.mark()
|
|
TAKE = os.environ.get("EV21_GOLDEN") == "1"
|
|
GOLDEN = {
|
|
'T4 [Manual, cover on]': {
|
|
'writes': 'f391f105a59891b9',
|
|
'notes': '2e109ddce05805c1',
|
|
'guard': 'e9f0a5079393d301',
|
|
'floor': 'ee3dd0b6ddcda88a',
|
|
'batt': '0f657edaab7156ef'},
|
|
'T4 [Manual, cover off]': {
|
|
'writes': 'f391f105a59891b9',
|
|
'notes': '2e109ddce05805c1',
|
|
'guard': '461119b75fbb738a',
|
|
'floor': 'ee3dd0b6ddcda88a',
|
|
'batt': '0f657edaab7156ef'},
|
|
'T5 [Off]': {
|
|
'writes': '4f53cda18c2baa0c',
|
|
'notes': '346a74064b62c0f5',
|
|
'guard': '165d51d07b84c233',
|
|
'floor': 'ee3dd0b6ddcda88a',
|
|
'batt': 'a91930f22238e925'},
|
|
'T6 [Shape M: the batteries cover house and car]': {
|
|
'writes': '385ae1fbf07b25d6',
|
|
'notes': '4f53cda18c2baa0c',
|
|
'guard': 'a52b1c929747cd07',
|
|
'floor': 'f62cb235198fa562',
|
|
'batt': '26965ed24b700eae'},
|
|
'T11 (a) [the batteries catch it in a few seconds]': {
|
|
'writes': '2feff2d70bc160e2',
|
|
'notes': '4f53cda18c2baa0c',
|
|
'guard': '58bb40545886af53',
|
|
'floor': '547335adccb04a76',
|
|
'batt': '0954ff4dd06faae5'},
|
|
'T11 (b) [EV-05 T21b cloud edge, 16 A on 3 phases]': {
|
|
'writes': '65a8a3fa50b4d81c',
|
|
'notes': 'c70d97f8902a82a0',
|
|
'guard': '269d88368a15b2d9',
|
|
'floor': '309fe221f371aa6f',
|
|
'batt': '4719e28af092fdbe'},
|
|
'T38 [cover on]': {
|
|
'writes': '324aac021ce35055',
|
|
'notes': '4f53cda18c2baa0c',
|
|
'guard': '86809c51ba676e49',
|
|
'floor': 'f0e12bc7f14924dc',
|
|
'batt': '3ce6bd3c1711cc3b'},
|
|
'T38 [cover off]': {
|
|
'writes': '324aac021ce35055',
|
|
'notes': '4f53cda18c2baa0c',
|
|
'guard': '86809c51ba676e49',
|
|
'floor': 'f0e12bc7f14924dc',
|
|
'batt': '3ce6bd3c1711cc3b'},
|
|
'T36 [Shape M, cover off]': {
|
|
'writes': '385ae1fbf07b25d6',
|
|
'notes': '4f53cda18c2baa0c',
|
|
'guard': '912e434b12e20f7e',
|
|
'floor': 'bbb7dc2b3e81dba8',
|
|
'batt': 'c262ee254e496a16'},
|
|
}
|
|
got = {}
|
|
|
|
|
|
def same(name, r, t0=0, parts=("writes", "notes", "guard", "batt"),
|
|
t1=1e9):
|
|
"""The run against c79eb37, part by part: its charger writes, the
|
|
notices with their second, the per-second guard view (floor,
|
|
car_explains, car_over, red rows) and the battery commands."""
|
|
d = {"writes": digest(view_writes(r)), "notes": digest(r["raised"]),
|
|
"guard": digest(view_guard(r, t0)),
|
|
"floor": digest([(x["t"], round(x["floor"] or 0.0))
|
|
for x in r["trace"] if t0 <= x["t"] < t1]),
|
|
"batt": digest([(round(t), e, v) for t, e, v in r["plant"].sets
|
|
if e.startswith("number.sp_")])}
|
|
got[name] = d
|
|
if TAKE:
|
|
print(f"GOLDEN {name!r}: {d!r},")
|
|
return
|
|
want = GOLDEN.get(name) or {}
|
|
diff = [k for k in parts if want.get(k) != d[k]]
|
|
check(f"{name}: identical to c79eb37 in {', '.join(parts)} (differs in: "
|
|
f"{diff})", bool(want) and not diff)
|
|
|
|
|
|
def manual_store(a=10.0, n=3):
|
|
st = rig._Store()
|
|
st.data["car_current"], st.data["car_phases"] = a, n
|
|
return st
|
|
|
|
|
|
# =========================================================================== #
|
|
print("\n1. MANUAL AND OFF DO NOT CHANGE (T4, T5, T37)")
|
|
# =========================================================================== #
|
|
for cover in (True, False):
|
|
r = shape("C", mode="manual", cover=cover, dur=1300, store=manual_store(),
|
|
setpoint=0)
|
|
same(f"T4 [Manual, cover {'on' if cover else 'off'}]", r)
|
|
r = shape("C", mode="off", dur=1300)
|
|
check(f"T5 [Off]: zero charger writes ({r['sim'].log[:2]})", not r["sim"].log)
|
|
same("T5 [Off]", r)
|
|
|
|
# =========================================================================== #
|
|
print("\n2. NO CUT WHERE NONE IS DUE (T6, T11, T38)")
|
|
# =========================================================================== #
|
|
r = shape("M", dur=1300)
|
|
same("T6 [Shape M: the batteries cover house and car]", r)
|
|
check(f"T6: no cut state in Shape M "
|
|
f"({[x['t'] for x in r['rec'].rows if x['cap'] is not None][:2]})",
|
|
not [x for x in r["rec"].rows if x["cap"] is not None])
|
|
# (a) A house step of 5 kW the batteries (60 %, 1 s to respond) take over
|
|
# within a few seconds: the guard wants power briefly, no cut.
|
|
r = drive(step_fn((960, 5900.0), base=900.0), const(7900.0), dur=1300,
|
|
first="car", phases=3, socs={"a": 60.0, "b": 60.0},
|
|
opts={"ev_phases": "3"},
|
|
events={1: lambda p, c: setattr(p, "response_s", 1.0)})
|
|
wants = [x["t"] for x in r["rec"].rows if (x["want"] or 0) > 0]
|
|
check(f"T11 (a): the guard wants power {len(wants)} s ({wants[:1]}..."
|
|
f"{wants[-1:]}), no cut state "
|
|
f"({[x['t'] for x in r['rec'].rows if x['cap'] is not None][:2]})",
|
|
0 < len(wants) <= 8
|
|
and not [x for x in r["rec"].rows if x["cap"] is not None])
|
|
same("T11 (a) [the batteries catch it in a few seconds]", r)
|
|
r = drive(const(900.0), step_fn((910, 3000.0), (1030, 13000.0),
|
|
base=13000.0),
|
|
dur=1300, first="car", phases=3, socs={"a": 60.0, "b": 60.0},
|
|
opts={"ev_phases": "3"})
|
|
same("T11 (b) [EV-05 T21b cloud edge, 16 A on 3 phases]", r)
|
|
check(f"T11 (b): no cut state ({[x['t'] for x in r['rec'].rows if x['cap'] is not None][:2]})",
|
|
not [x for x in r["rec"].rows if x["cap"] is not None])
|
|
|
|
|
|
def house_trace(t):
|
|
"""A 1 h house trace, 600 to 1500 W, deterministic."""
|
|
k = int(t) // 37
|
|
return 600.0 + (k * 7919 % 900)
|
|
|
|
|
|
for cover in (True, False):
|
|
r = drive(house_trace, lambda t: house_trace(t) + 7000.0, dur=3600,
|
|
first="car", phases=3, socs={"a": 60.0, "b": 60.0},
|
|
opts={"ev_phases": "3", "ev_batt_cover": cover})
|
|
caps = [x["t"] for x in r["rec"].rows if x["cap"] is not None]
|
|
check(f"T38 [cover {'on' if cover else 'off'}]: no cut in an hour with no "
|
|
f"excess ({caps[:2]})", not caps)
|
|
same(f"T38 [cover {'on' if cover else 'off'}]", r)
|
|
|
|
# =========================================================================== #
|
|
print("\n3. THE COVER OFF: THE GUARD'S FLOOR (T36)")
|
|
# =========================================================================== #
|
|
r = shape("M", cover=False, dur=1300)
|
|
# Up to the cut. From it the car is lowered, so the plant differs from
|
|
# c79eb37's (there the car runs on); the cut itself is T36 in
|
|
# test_ev21_paths.py.
|
|
same("T36 [Shape M, cover off]", r, parts=("floor",), t1=960)
|
|
|
|
# =========================================================================== #
|
|
print("\n4. THE CUT AMOUNT OVER A TABLE OF SITES (T47)")
|
|
# =========================================================================== #
|
|
cut = _cutamps()
|
|
rows47 = []
|
|
|
|
|
|
def stamp(p, c):
|
|
c.car_solar.nonzero_at = p.t # Solar's own 30 s gate is closed
|
|
|
|
|
|
for n in (2, 1):
|
|
for cover in (True, False):
|
|
for ph, car_ph in (("3", 3), ("1", 3), ("auto", 3), ("3", 1)):
|
|
for first in (("car", "batteries") if ph == "3" and car_ph == 3
|
|
else ("car",)):
|
|
ratings = {"a": 5000.0, "b": 4600.0} if n == 2 \
|
|
else {"a": 5000.0}
|
|
room = 0.0 if first == "car" else 9600.0
|
|
if ph == "3" and car_ph == 3:
|
|
car_w, n_draw = 6900.0, 3 # 10 A on 3 phases
|
|
elif ph == "3":
|
|
car_w, n_draw = 3680.0, 1 # a 1-phase car, 16 A
|
|
else:
|
|
car_w, n_draw = 2300.0 if ph == "1" else 3680.0, 1
|
|
sun0 = 900.0 + max(car_w, 4830.0 + 500.0 if car_ph == 1
|
|
else car_w) + 100.0 + room
|
|
# The house steps so about 6.4 A is left after the cut.
|
|
d = 3400.0 + car_w - 6.4 * 230.0 * n_draw + 150.0 + room
|
|
ev = {t: refuse_n1 for t in range(0, 1001)} if n == 1 else {}
|
|
ev = merge(ev, 958, stamp)
|
|
r = drive(step_fn((960, 900.0 + d), base=900.0),
|
|
const(sun0), dur=1000,
|
|
first=first, phases=1 if ph == "1" else 3,
|
|
car_phases=car_ph, ratings=ratings,
|
|
socs={u: 10.0 for u in ratings}, events=ev,
|
|
rows=False,
|
|
opts={"ev_phases": ph, "ev_batt_cover": cover})
|
|
w = after(r, 958)
|
|
ep = [x for x in r["rec"].rows if x["t"] >= 958
|
|
and x["cap"] is not None]
|
|
want = cut(ep[0]["car0"], ep[0]["ex"], n_draw) if ep \
|
|
else "none"
|
|
ok = bool(w) and w[0][0] <= 961 and bool(ep) \
|
|
and ep[0]["cap"] == want and w[0][1] == want
|
|
rows47.append(((n, cover, ph, car_ph, first), w[:1],
|
|
ep[0]["cap"] if ep else None, want, ok))
|
|
bad47 = [x for x in rows47 if not x[-1]]
|
|
check(f"T47: over N=1/2, cover on/off, ev_phases 1/3/auto, a 1-phase car on "
|
|
f"3, Car/Batteries first ({len(rows47)} sites): the cut within 1 cycle "
|
|
f"and floor((car0 - excess) / (230 x the phases the car draws on)) "
|
|
f"({bad47[:3]})", rows47 and not bad47)
|
|
|
|
# =========================================================================== #
|
|
print("\n5. THE WRITE SEAM (T52) AND THE DOCS AND STRINGS (T53)")
|
|
# =========================================================================== #
|
|
|
|
|
|
def seam_callers():
|
|
out = []
|
|
for f in sorted(os.listdir(os.path.join(HERE, "app"))):
|
|
if not f.endswith(".py") or f == "chargers.py":
|
|
continue
|
|
tree = ast.parse(io.open(os.path.join(HERE, "app", f),
|
|
encoding="utf-8").read())
|
|
for n in ast.walk(tree):
|
|
if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) \
|
|
and n.func.attr in ("write_current", "write_phases"):
|
|
out.append((f, n.func.attr))
|
|
return sorted(out)
|
|
|
|
|
|
def calls_in(path, fn_names):
|
|
tree = ast.parse(io.open(os.path.join(HERE, "app", path),
|
|
encoding="utf-8").read())
|
|
out = []
|
|
for n in ast.walk(tree):
|
|
if isinstance(n, ast.FunctionDef) and n.name in fn_names:
|
|
for m in ast.walk(n):
|
|
if isinstance(m, ast.Call) and isinstance(m.func,
|
|
ast.Attribute):
|
|
out.append(m.func.attr)
|
|
return out
|
|
|
|
|
|
cut_calls = calls_in("ctl_car.py", {"_car_cut_tick", "_car_cut_hold",
|
|
"_car_cut_headroom"}) \
|
|
+ calls_in("carmode.py", {"_cut"})
|
|
check(f"T52: the write seam is still carmode.py's write_current and "
|
|
f"write_phases ({seam_callers()}); the cut's own code writes nothing and "
|
|
f"selects no phases ({sorted(set(cut_calls))})",
|
|
seam_callers() == [("carmode.py", "write_current"),
|
|
("carmode.py", "write_phases")]
|
|
and bool(cut_calls)
|
|
and not {"write_current", "write_phases", "_write", "_begin",
|
|
"_begin_solar", "_put"} & set(cut_calls))
|
|
|
|
|
|
def read(*p):
|
|
path = os.path.join(HERE, *p)
|
|
return io.open(path, encoding="utf-8").read() if os.path.exists(path) \
|
|
else ""
|
|
|
|
|
|
dec = " ".join(read("DECISIONS", "EV-21-car-cut-first.md").split())
|
|
docs = " ".join(read("DOCS.md").split())
|
|
chlog = read("CHANGELOG.md")
|
|
need = ["cut first", "15 s", "120 s", "Once per episode", "start power",
|
|
"can really cut"]
|
|
check(f"T53: DECISIONS/EV-21-car-cut-first.md states the rule in plain words "
|
|
f"({[w for w in need if w.lower() not in dec.lower()]} missing)",
|
|
bool(dec) and all(w.lower() in dec.lower() for w in need))
|
|
check("T53: DOCS 'Car charger' Solar section says the car is cut first, and "
|
|
"documents the grey note; the CHANGELOG has an EV-21 line",
|
|
"the car is cut first" in docs and "### Car lowered for the peak"
|
|
in docs and "`goodwe_car_cut`" in docs and "[[EV-21]]" in chlog)
|
|
|
|
tb = LOG.tracebacks(n_log0)
|
|
check(f"N11: no traceback in this file's runs ({tb[:1]})", not tb)
|
|
if TAKE:
|
|
print("(golden taken; no checks graded)")
|
|
sys.exit(0)
|
|
print(f"\n{'FAILED: ' + str(len(fails)) if fails else 'ALL PASSED'}")
|
|
sys.exit(1 if fails else 0)
|