Compare commits

..
37 Commits
Author SHA1 Message Date
Claude 0eb332d93f EV-71: Solar and Manual keep their own untaken non-zero write as their own
checks / unit (pull_request) Successful in 58m47s
infra-pin / fresh (pull_request) Successful in 2s
A press that lifts nothing no longer clears attempted_a, prior_a, the EV-69
carry or the new kept value; a held read no longer adopts (no taken, carry
untouched, the owed 0 A is written); a refused 0 A no longer loses the
untaken non-zero value. The kept value ends at a fresh own take, a different
non-zero write, a lifting press, a hold or Solar's charger return.

Existing tests edited only as the brief allows: test_ev69.py T12 (press
alone) and T24 setup, test_ev69_fuzz.py N4, N1b user cause, I1, I2.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-05 00:22:01 +01:00
ems-agent 278041b25c Merge pull request 'EV-69: an ended phase change's close values stay own (no false CHARGER_OTHER)' (#285) from EV-69 into release/1.0
infra-pin / fresh (push) Successful in 2s
2026-12-04 09:45:54 +01:00
Claude fe5e3ee477 EV-69 round 4: mixed fuzz pass back to 9b09158's event model with its fixed floors; plan floors in a directed pass of their own
infra-pin / fresh (pull_request) Successful in 2s
checks / unit (pull_request) Successful in 56m14s
Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-04 07:20:05 +01:00
Claude 8a40343a84 EV-69 router r2: fuzz keeps full interference in a mixed pass; calm Solar pass in addition; floors per pass
checks / unit (pull_request) Successful in 54m32s
infra-pin / fresh (pull_request) Successful in 2s
Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-04 04:51:33 +01:00
Claude 0f3d5d75e5 EV-69 review r1: Manual T10, cap-end T17 (i), 0 A guard row, fuzz floors per writer and bound end
checks / unit (pull_request) Successful in 54m11s
infra-pin / fresh (pull_request) Successful in 1s
Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-04 02:29:30 +01:00
Claude 9b09158ef8 EV-69: T12 row for a press alone ending the carry
checks / unit (pull_request) Successful in 52m56s
infra-pin / fresh (pull_request) Successful in 2s
Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 23:58:09 +01:00
Claude 7d1ed1bbcf EV-69: an ended phase change's close values stay own (no false CHARGER_OTHER)
A phase change that ends on MAX_TRIES (both writers) or on Solar's EV-60 cap
end now carries every value it tried, its 0 A too, until the first of: an own
take, any own current write, a user change, a hold, Solar's charger return.
A carried take resets fails/gave_up only (GUR). Tests: test_ev69.py (T1-T20,
T23-T25), test_ev69_fuzz.py (T21), tools/ev69_kit.py.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 23:53:54 +01:00
ems-agent de733f44bf Merge pull request 'EV-22: Solar and Manual never write over another writer; one rule of control' (#284) from EV-22 into release/1.0
infra-pin / fresh (push) Successful in 1s
2026-12-03 16:05:56 +01:00
Claude 7710d45393 EV-22 review r2: Solar row where R1 is seen (clamp falls between close tries); note on the masked Solar row
checks / unit (pull_request) Successful in 52m35s
infra-pin / fresh (pull_request) Successful in 1s
Test only, no implementation change. Green on e0e51da, red under R1 (seq own dropped).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 15:12:19 +01:00
Claude e0e51dac12 EV-22 review round 1: press covers one reading, unknown read keeps the count, window ends on the close's clock
checks / unit (pull_request) Successful in 53m40s
infra-pin / fresh (pull_request) Successful in 2s
Major 1: the `pressed` mark of a sequence is consumed by the first `_advance`
(the first reading judged after the press); a later raise in the same zero
stage gets the raise-check hold again (Solar and Manual).
Major 2: with `cur` None `_watch` does not judge the current: the count
neither starts nor clears (phases are still judged).
Finding 4 (PM): the DA3 window uses the close's own clock and comparison
(`now - t1 < SETTLE_S`) and the one step that closes at its end is still
inside it, so a `last_done` a fraction of a second after the step's now no
longer pushes the close step outside the window.
Tests: rows A-D, R1 (Manual red under the mutant), the two fraction rows,
all red on b7c91ff. test_ev60: comment exactly as ruled, unused imports gone.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 12:30:17 +01:00
Claude b7c91ff746 EV-22: retire the ManualWriter source pin in test_ev60 N7 (PM ruling)
infra-pin / fresh (pull_request) Successful in 2s
checks / unit (pull_request) Successful in 53m19s
The SHA-256 of ManualWriter's source was an EV-60 review-time pin. EV-22
changes ManualWriter by design (C7, DA1), so the pin is removed; the
behavioural Manual rows of test_ev56, test_ev59 and test_ev60 are unchanged
and green.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 05:32:46 +01:00
Claude c7b1b7dbd1 EV-22: Solar and Manual never write over another writer; one rule of control
checks / unit (pull_request) Failing after 57m18s
infra-pin / fresh (pull_request) Successful in 3s
C7: the other-writer watch now runs in every step of a phase change (zero,
select, settle) in both writers, with the change's own 0 A and every closing
current it tried counted as own. While a difference or a hold stands, nothing
non-zero is written over it: no settle close, no EV-28 restore, no select, no
Manual undo or abandon. The 6 A raise check stays and runs first.

D4 (Solar): the read-back phases are judged like the current, against the
phases Solar itself chose (start state = first known read-back outside an own
select window, or an own select seen taken), never the plan's adopted n.
Same mismatch_since, hold and CHARGER_OTHER; lift only when current and
phases both match, or a press. The window of an own select is SETTLE_S from
the try's return; a take seen after it is another writer's.

DA1: a press that lifts a difference inside a phase change ends the change
at its 0 A (both writers); the raise check never holds over a value the
press took. DA2: the not-writing path does not judge the current with the
reading from before its own 0 A.

test_ev22.py (T1-T49, review row T48 (stale)), test_ev22_fuzz.py (T38,
N1-N10). test_ev20_writers T46 (a)(b)(c) edited as ruled (PM, v3).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 04:21:38 +01:00
ems-agent 19c5d5a61e Merge pull request 'EV-60: Solar never passes the cut cap per quarter; press during close retries gets 3 tries' (#283) from EV-60 into release/1.0
infra-pin / fresh (push) Successful in 2s
2026-12-02 13:47:26 +01:00
Claude bba10f44c3 EV-60 review: test_ev60 row T4-owed (the gate is for cut tries only)
checks / unit (pull_request) Successful in 50m22s
infra-pin / fresh (pull_request) Successful in 1s
A pending change whose 0 A already stands begins with no write under a
cap with cut_fails 3, as base. Kills the review mutant that gates
_begin_solar also when nothing is owed (it survived every other row).
Test-only.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-02 12:26:12 +01:00
Claude 392f9c2b57 EV-60: test_ev60 T22 check without raising reads (test_named_absence)
checks / unit (pull_request) Successful in 50m49s
infra-pin / fresh (pull_request) Successful in 1s
Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-02 09:49:13 +01:00
Claude 5ddabfbd93 EV-60: gate the "car kept drawing" close, reset _cap_end at _advance entry, more checks
- SolarWriter._advance gates the close where the value is asked for
  (wrapped want_a raising a private _CloseHeld), so the shared zero -> settle
  fall-through write of "the car kept drawing" passes the same cut gate, the
  Q5/Q6 wait and the end at 0 A. ManualWriter is unchanged (N7 sha pin).
- _cap_end is reset at each Solar _advance entry (no stale flag).
- test_ev60: rows S-a, S-b, T12, T15, T22, T25-flag, N4, N6, N11, N12, N13;
  docstring states the coverage; dead pre_roll line removed; T17 text/asserts.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-02 09:09:50 +01:00
Claude 1c387441c7 EV-60: test row T5b (route (b) world, next key, cap lifted, change runs)
checks / unit (pull_request) Successful in 56m6s
infra-pin / fresh (pull_request) Successful in 2s
Test only; carmode.py is unchanged from 5bd2b1e.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-02 06:48:49 +01:00
Claude 5bd2b1ec97 EV-60: Solar never passes the cut cap of 3 refused tries per quarter key
checks / unit (pull_request) Successful in 57m13s
infra-pin / fresh (pull_request) Successful in 2s
Solar's phase change 0 A and its capped close are cut tries. They now pass
the same gates as `_put`: none at cut_fails >= MAX_TRIES, none within RETRY_S
of the last refused cut try (the sequence's first cut close waits at 0 A, the
rest keep the 5 s spacing). A gated 0 A waits for the next quarter key and
never gives up; a capped close with no tries left ends the change at 0 A
(end_switch(False), reapply, no write). Solar's close end adds no extra
_failed (EV-56 F1 on the cut path, EV-59 finding 2 on the non-cut path), so
a press during the close retries gives the value MAX_TRIES tries.

Solar only (override in SolarWriter); Manual is byte for byte as before.
Edited tests as ruled (Q3, Q4): test_ev59 T25/T14, T25 press, T14c and the
N11 digest list; test_ev56 T19b [a]/[b], T12 and golden "T20 T12 [R]".

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-02 05:48:20 +01:00
ems-agent 2e09622fe1 Merge pull request 'EV-59: Manual gives one value at most MAX_TRIES tries per user change' (#282) from EV-59 into release/1.0
infra-pin / fresh (push) Successful in 2s
2026-12-01 10:10:11 +01:00
Claude 7628cacdb7 EV-59 review: CHANGELOG line; T21 power-unknown check exact
checks / unit (pull_request) Successful in 50m12s
infra-pin / fresh (pull_request) Successful in 1s
Reviewer fixes, Minor only, no implementation change:
- CHANGELOG.md: the user-visible change under "Not in a release yet".
- test_ev59 T21 (power unknown): assert the 3 restore tries at 20, 25, 30,
  the give-up and one REF, instead of "at most 3" (which passed with 0).
  Red on 1b909fb (20, 25, 30, 90, 150).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-01 09:19:38 +01:00
Claude e522e6ffbb EV-59: test_ev59 gains T14c, T17, T18, T11c, N3, N7, N11, N12; docstring
infra-pin / fresh (pull_request) Successful in 2s
checks / unit (pull_request) Successful in 51m36s
T14c drives SolarWriter._advance with a moving close value (pinned to the
base result). T17, T18, T11c and N11 are source checks on the edited test
files. N3 is asserted in every run, N7 with an answering charger, N12 on the
tracker notes. The docstring now says which row is here, which is carried by
another suite, and which existing tests are edited.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-01 05:32:29 +01:00
Claude e83b2e315b EV-59: test_ev13 T26 goldens, N4/N8/N10 tests, stronger T12b/T11a
infra-pin / fresh (pull_request) Successful in 2s
checks / unit (pull_request) Failing after 1h13m10s
PM ruling: drop the 4th and 5th tries (1095, 1155) from the test_ev13 T26
goldens T20-beside and T20-inside. test_ev59 gains T13e (a give-up never
blocks _undo, abandon or _begin), N8 and N10, and the fails-at-select and
fails-at-timeout asserts that kill mutant M12.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-01 02:50:45 +01:00
Claude 009393a5ee EV-59: Manual gives one value at most MAX_TRIES tries per user change
A refused phase-change close ended its sequence with one `_failed`, so the
same value got 5 tries (3 closes, then 2 on the normal path). Manual now
counts the not-taken closes of the value owed since the last user change
(`_close_k`); at the capped close end `fails` = that count, so `gave_up` and
CHARGER_REFUSED come at the 3rd refused close, and a value changed during the
retries still gets 3 tries. SolarWriter overrides the end hook and is
unchanged (EV-60).

Tests: new test_ev59.py; test_ev56 T5, T5b and the T20 T5 [R] golden,
test_ev28 T15 and the test_ev13 T13 text per the brief rulings.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-01 02:40:49 +01:00
ems-agent 1b909fb7bd Merge pull request 'EV-56: a charger write that raises counts as a not-taken try' (#281) from EV-56 into release/1.0
infra-pin / fresh (push) Successful in 1s
2026-11-30 20:00:48 +01:00
ems-agentandClaude 3682b0754b EV-56: a charger write that raises counts as a not-taken try
checks / unit (pull_request) Successful in 57m33s
infra-pin / fresh (pull_request) Successful in 2s
ManualWriter._write catches an Exception from drv.write_current (not CancelledError) and returns False, so every caller in Manual and Solar counts it as a refused try: RETRY_S spacing, MAX_TRIES, CHARGER_REFUSED. The tracker is not told (Q2). One ERROR record per raised value, armed again by another value, a taken write, a user change or the charger's return (Q1, G2). Shutdown writes (abandon, release) pass strict and keep base's behaviour (F3, H1, G3); the peak cut path keeps EV-54's (G1). test_ev13 T13: fails is 1 now (Q2). New test_ev56.py.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-30 18:52:11 +01:00
ems-agent 344c974f90 Merge pull request 'EV-54: a refused peak cut no longer stops Solar; tried again next quarter' (#280) from EV-54 into release/1.0
infra-pin / fresh (push) Successful in 2s
2026-11-30 09:14:11 +01:00
ems-agentandClaude 7613468cf9 EV-54 review r2: fails counts only refusals of the value now owed
checks / unit (pull_request) Successful in 45m48s
infra-pin / fresh (pull_request) Successful in 2s
Where a refused cut value stops being owed without a drop (the charger's return, another value written in its place), fails goes to 0; cut_fails is untouched. After a return under a capped quarter, Solar's own write gets its own 3 tries again instead of giving up after 1. New rows T40 (refused to 1430), T41 (to 1600, against the run without the away), T42 (replaced value).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-30 06:37:40 +01:00
ems-agentandClaude 095f773921 EV-54 review r1: no stale fails block after the charger returns; peak cut reason
checks / unit (pull_request) Successful in 45m27s
infra-pin / fresh (pull_request) Successful in 2s
The fails >= MAX_TRIES block on non-cut writes applies only while the refused cut value is still owed, so Solar resumes after the charger came back under a capped quarter (it froze before). The quarter's cut count is untouched and D2's 0 A stays held while capped. A new cut value under the read-back above a refused one logs 'peak cut'. New rows T36 (away while capped, 0 A and 6 A), T37 (F6), T38 (Off after 3 tries), T39 (reason replay).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-30 04:51:54 +01:00
ems-agentandClaude cf07f6f99b EV-54 tests: T26 asserts the first write after the lift is the step-up; T8 checks named T8
checks / unit (pull_request) Successful in 50m12s
infra-pin / fresh (pull_request) Successful in 1s
Mutant M18 (the drop leaves taken False) re-sent the standing read-back at the lift and T26 missed it; the T8 checks were filed under T2/T5 by name. Test-only.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-30 01:47:38 +01:00
ems-agentandClaude a698211318 EV-54: a refused peak cut no longer stops Solar; tried again next quarter
checks / unit (pull_request) Successful in 52m35s
infra-pin / fresh (pull_request) Successful in 1s
Refused cut tries are capped at 3 per quarter key and never set the session-wide gave_up. The next quarter tries again while a cut is needed. Once no cut stands, a refused cut value is dropped (sent_a and the plan current = the read-back, taken), never re-sent; the drop waits for a good, known read-back. A cut write that raises counts as a refused try. New notice text (Q3); the hold path's text is unchanged. Tests: test_ev54.py, test_ev54_drop.py (T1-T35); test_ev52 N8 knows the new text.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-30 00:24:58 +01:00
ems-agent bdfd3e6848 Merge pull request 'EV-52: log one plain line for a new car current and a car mode change' (#279) from EV-52 into release/1.0
infra-pin / fresh (push) Successful in 2s
2026-11-29 14:54:38 +01:00
ems-agent 64991d7cde EV-52 review round 2: test row for Solar's late try cleared on leave
checks / unit (pull_request) Successful in 45m23s
infra-pin / fresh (pull_request) Successful in 1s
Test only. Kills a mutant that drops the _late clear in SolarWriter._leave(), which no row covered.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-29 14:08:48 +01:00
ems-agent 2931e6e852 EV-52 round 2: a refused Manual try is not logged later by another source's value
checks / unit (pull_request) Successful in 44m13s
infra-pin / fresh (pull_request) Successful in 2s
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-29 11:55:51 +01:00
ems-agent fd1cb423b1 EV-52 round 1: Manual late-accept line (Q2), N5, N8, T44 rows
checks / unit (pull_request) Successful in 44m57s
infra-pin / fresh (pull_request) Successful in 1s
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-29 09:49:52 +01:00
ems-agent ca06456ffa EV-52: charger-less stubs, CHANGELOG, EV-28/EV-51 log rows set the two new lines aside
checks / unit (pull_request) Successful in 47m21s
infra-pin / fresh (pull_request) Successful in 1s
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-29 07:47:17 +01:00
ems-agent c1536b0e93 EV-52: log one plain line for a new car current and for a car mode change
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-29 06:48:52 +01:00
ems-agent 02166e28eb Merge pull request 'EV-21: Solar cuts the car first for the quarter peak' (#278) from EV-21 into release/1.0
infra-pin / fresh (push) Successful in 2s
2026-11-29 03:24:38 +01:00
25 changed files with 10517 additions and 88 deletions
+5
View File
@@ -2,6 +2,11 @@
### Not in a release yet
- **Solar no longer writes over another writer's car current or phases.** If something else changes the car's current or its phases, also in the middle of a phase change, the add-on writes nothing over it. After 30 seconds it stops writing until you press Solar, and warns CHARGER_OTHER once. Manual does the same for a current changed during its own phase change ([[EV-22]]).
- **A car phase change whose current the charger refuses no longer sends that current five times.** After three refused tries the add-on stops at once and warns CHARGER_REFUSED; the car stays at 0 A until you change something. A value you change meanwhile gets its own three tries ([[EV-59]]).
- **A car current the add-on cannot send because of an error is no longer sent again every second.** It counts as a write the charger did not take: 3 tries a minute apart, then the add-on stops and warns CHARGER_REFUSED. The error is logged once per current ([[EV-56]]).
- **A peak cut the charger does not take no longer stops Solar.** After three refused tries in a 15-minute period, Solar goes on controlling the car and tries the cut again at the start of the next period while it is still needed. The warning now says "The charger did not take the peak cut, so the add-on tries again next quarter: CHARGER_REFUSED." ([[EV-54]]).
- **The add-on log now says when the add-on sets a new car current or the car mode changes.** One line each, for example "Car: set from 10 A to 6 A on 1 phase (Manual)." and "Car mode is now Manual." It names the reason: Manual, Solar, peak cut, start-up or shutdown. A refused write adds no such line, and nothing is written or timed differently ([[EV-52]]).
- **Solar now lowers the car first for the peak limit.** When the 15-minute period heads over the limit, Solar lowers the car before the batteries give more, and brings it back when the period allows. One grey note says "Solar lowered the car for the peak." A Solar car the add-on cannot lower (another writer, shadow mode, a stop) no longer hides a peak alarm. Manual and Off do not change. See "Car charger" in DOCS ([[EV-21]]).
## 0.25.0
@@ -0,0 +1,64 @@
# EV-54 — Solar: a refused peak cut is tried again next quarter
EV-21 sent its cut tries through Solar's normal retry, whose third refusal set
the session-wide `gave_up`. A cut is held at 0 A (or a partial value) under a
standing cap, so neither way out of `gave_up` could come: after three refused
tries Solar never wrote again, also once the charger took writes again (EV-21
rig, finding 1). The rules below are the PM rulings Q1-Q9, G1-G6, QA, QB and
QC (brief v6); the formal check is reports/EV-54-formal-report.md.
## The rule, in plain words
- **A cut try** is a Solar write while a cut is due or stands, at or under its
cap (the cut, its retry, a 0 A of a phase change or a way out): `_cut_try`.
- **At most 3 refused cut tries per quarter key** (the projection's
`block_start`), across cut values and episodes. A deeper cut does not give
new tries; a press of Solar, or Off then Solar, does not either. The count
is in memory only: a restart starts afresh (`cut_quarter`, `cut_fails`).
- **A refused cut try never sets `gave_up`.** Solar's normal writes go on. The
third refusal of a quarter logs one warning per episode: "The charger did not
take the peak cut, so the add-on tries again next quarter: CHARGER_REFUSED."
(DEBUG after; a taken cut or a mode change re-arms it). The amber row and
the card's Why show it while the tries are used up and the charger shows
more than the cut (`cut_refused`). The hold path's text is unchanged.
- **The next quarter tries again** while a cut is still needed, as EV-21's cut:
at once without headroom, else after the 15 s wait; a same-value retry no
sooner than 60 s after the last refusal.
- **The drop.** Once no cut stands (the cap lifted, or a new quarter's cut
waits) a refused cut value is never sent again. Solar takes the read-back
as its own: `sent_a` = read-back, taken, `gave_up` cleared, and the plan's
current = read-back, timed as a new decision (`_drop`). The retry clock
stays, so nothing non-zero reaches the charger within 60 s of its refusal.
The drop waits while the reading is stuck (QA) or the read-back is unknown
(QB); meanwhile Solar sends nothing but a way out's 0 A.
- **A stuck reading after the lift** keeps base's fault path: its 0 A goes
out three times 60 s apart with reason Solar, then `gave_up` with the hold
path's text; the first good reading drops it and clears `gave_up` (QC).
- **A cut write that raises** counts as a refused cut try (no Traceback, no
try per cycle). The same gap outside the cut is EV-56.
## Choices the rulings left open
- Refused cut tries still count in `fails` (without `gave_up`), and outside the
cut `fails >= MAX_TRIES` stops a write as `gave_up` did, but only while the
refused value is still owed. So Off's way-out 0 A after refused cut tries is
written exactly as before (N10). Once that value is gone (the charger came
back, another value was written), nothing blocks Solar's normal writes
(review round 1: a gate on `fails` alone froze Solar after the charger came
back under a capped quarter). The gate is scoped rather than `fails` reset,
so one rule covers every way the value goes, and the quarter's cut count
(`cut_fails`) is never touched by it. When the cut
stops standing in Solar and the value cannot be dropped yet (stuck), that
value becomes Solar's own: reason Solar, a fresh `fails` count (QC).
- `fails` counts only refusals of the value now owed (PM, review round 2).
Where a refused cut value stops being owed without a drop (the charger's
return, another value written in its place), `fails` goes to 0
(`_forget_refused`); `cut_fails` stays. Elsewhere `fails` is already
right: a drop, a taken write or an adopt clear it; a Solar press or a
change into Solar clear it; Off and the quarter roll keep the owed value,
so its count stays (Off's way-out as before).
- At a new quarter's wait the cut tick holds the read-back the writer is about
to take, not the refused value, so the wait never re-sends it (G1).
- No drop over another writer's value (a hold or a difference being watched).
- A new cut value under the read-back is logged "peak cut", also when it lies
above a refused value.
@@ -0,0 +1,37 @@
# EV-56 — a charger write that raises is a not-taken try
`drv.write_current` raising (an HA call error, a binding or setup error, a bug)
left `ManualWriter._write` before any bookkeeping, so no caller counted it and
Manual and Solar sent the same write every cycle. The rules below are the PM
rulings Q1-Q4, F1, F3, G1-G3, H1, H3 and H4 (brief v6); the formal check is
reports/EV-56-formal-report.md.
## The rule, in plain words
- **A raise is a try the charger did not take**, on every path that writes a
current (the normal write, a phase change's 0 A and closing current, the
Off or shadow undo): the same RETRY_S spacing, MAX_TRIES cap, give-up and
CHARGER_REFUSED as a refusal, and the same writer state (`log` row,
`attempted_a`, a late accept). `ManualWriter._write` catches it and returns
False; the callers count it as before. Solar counts it in its own `_write`.
- **The tracker is not told** (Q2): no `note_write`, so no refusal window and
no stuck arming. The write's `end_write` (the mute) still runs.
- **One ERROR record per raised value** (Q1): "The car charger step failed",
with the traceback, at the first raise of a value; DEBUG on its retries. It
is armed again by another value written, a taken write, a user change and
the charger's return (G2), in `_rec_a`.
- **A peak cut try that raises** keeps EV-54's path: one DEBUG line, no record
(G1).
- **Shutdown is as before** (F3, H1, G3): `abandon` and `release` pass
`strict`, so a raise still leaves the write. Manual's give-back keeps its
CHARGER_RESTORE; Solar's release stops after 1 try with no cut standing and
keeps the cut path's 3 tries with one. No record at shutdown.
- **Cancel is not a raise**: only `Exception` is caught, never
`CancelledError`.
## Left as they were
The phase select (`write_phases`, Q4, EV-58), Solar's 4 fails for a refused
close (F1), Manual's up to 5 tries of a close value (H3, EV-59) and the cut
tries through a phase change (H4, EV-60). test_ev56.py T5b and T19b pin the
last two at base.
+9 -4
View File
@@ -3370,10 +3370,11 @@ changes at most once per 30 seconds and only by 1 A or more.
be charging* follows.
- **Shadow mode** writes nothing but that one 0 A; a start in shadow mode writes
nothing at all. The card says what Solar would set.
- **Another writer.** If the charger shows a current Solar did not set for 30
seconds, Solar writes nothing over it (also no 0 A), shows an amber row and
logs one warning, until you press Solar again or the charger shows Solar's
value.
- **Another writer.** If the charger shows a current or a number of phases
that Solar did not set, Solar writes nothing over it from the first moment,
also in the middle of a phase change. After 30 seconds it writes nothing more
(also no 0 A), shows an amber row and logs one warning, until you press Solar
again or the charger shows Solar's own current and phases.
- **The peak limit: the car is cut first.** When the 15-minute period heads
over the peak limit, Solar lowers the car first, also while the batteries
could instead charge less: by the excess, to 0 A when less than 6 A would be left.
@@ -3389,6 +3390,10 @@ changes at most once per 30 seconds and only by 1 A or more.
fault, or a lower current the charger has not shown yet), the peak alarms
treat the car as in Off. A Solar charge is never counted as setting the
month's peak.
- **A cut the charger does not take** is tried again after a minute, at most
three times per 15-minute period; then one warning and an amber row say so.
Solar's normal control goes on, and the cut is tried again at the start of
the next period while it is still needed.
- **Energy.** The card says "{kWh} charged today, {kWh} from the sun", and the
sensor `goodwe_car_today_solar_kwh` has the sun's part. Only Solar's own
share of spare sun counts, not the hold's battery or grid power.
File diff suppressed because it is too large Load Diff
+20 -5
View File
@@ -88,6 +88,10 @@ class CarMixin:
ok = carmode.allowed_phases(opts)
self.car_n = n if n in ok else ok[0]
self.car_rev = 0
ch = getattr(self, "charger", None)
if ch is not None and ch.configured(): # EV-52: the mode at the start
_LOG.info("Car mode is now %s.",
carmode.MODE_LABELS[self.car_mode])
self.car_writer = carmode.ManualWriter()
self.car_solar = carmode.SolarWriter() # EV-20
self.car_solar.on_owed = self._car_owed
@@ -290,7 +294,7 @@ class CarMixin:
w = self.car_solar
if not self.car_solar_mode():
self._cut = self._cut_fresh(None)
w.cut_a = None
w.cut_a, w.cut_on, w.cut_blind = None, False, False
return
key = None if real_proj is None else real_proj.block_start
st = self._cut
@@ -302,7 +306,10 @@ class CarMixin:
# N9: nothing sized from a stale projection; what stands stays.
w.cut_a = st["cap"] if st["cap"] is not None \
else self._car_wait_a(st)
w.cut_on, w.cut_blind = st["cap"] is not None, True
return
w.cut_blind = False
w.cut_quarter(key) # EV-54: the quarter's refused cut tries
ex = peakguard.excess_w(real_proj, target_w)
left = QUARTER_S - float(real_proj.elapsed_s)
r = self.car.reading
@@ -351,10 +358,11 @@ class CarMixin:
st = self._cut = self._cut_fresh(key)
st["cuts"] = cuts
w.cut_a = st["cap"]
w.cut_on = st["cap"] is not None
return
if not due:
st["since"], st["wait"] = None, None # the batteries caught it
w.cut_a = None
w.cut_a, w.cut_on = None, False
return
if st["since"] is None:
st["since"], st["car0"], st["ex"] = mono, car_w, ex
@@ -369,13 +377,18 @@ class CarMixin:
st["cap"] = 0.0 if a is None else a
st["cuts"] += 1
st["wait"], st["at"] = None, mono
w.cut_a = st["cap"]
w.cut_a, w.cut_on = st["cap"], True
return
# C4: due and waiting: no raise meanwhile. PM R1: held in watts (the
# plan's current on its phases), turned into amps with the phases at
# the write.
# the write. EV-54 (G1): a refused cut value is dropped in the wait,
# so the hold is the read-back the writer takes, not that value.
w.cut_on = False
p = w.plan
now_w = float(p.a) * carmode.VOLTS * (p.n if p.n in (1, 3) else n)
a_now = float(p.a)
if w.drop_ready(cur, self.car.stuck(mono)):
a_now = float(cur)
now_w = a_now * carmode.VOLTS * (p.n if p.n in (1, 3) else n)
st["wait"] = now_w if st["wait"] is None else min(st["wait"], now_w)
w.cut_a = self._car_wait_a(st)
@@ -476,6 +489,8 @@ class CarMixin:
# A Manual phase change in the middle is not restored: Solar
# starts from the 0 A it stands at.
self.car_writer.seq = None
if value != self.car_mode: # EV-52: one plain line
_LOG.info("Car mode is now %s.", carmode.MODE_LABELS[value])
self.car_mode = value
self.store.set(carmode.KEY_MODE, value)
elif what == "car_sun_first":
+1 -1
View File
@@ -211,7 +211,7 @@ class StatusMixin:
if sw.other and self.car_mode == "solar":
out.append({"ok": False, "warn": True, "id": "charger_other",
"text": messages.row_charger_other_solar()})
if sw.gave_up:
if sw.gave_up or getattr(sw, "cut_refused", False): # EV-54
out.append({"ok": False, "warn": True, "id": "charger_refused",
"text": messages.row_charger_refused()})
if sw.phases_gave_up and self.car_mode == "solar":
+3 -2
View File
@@ -1386,11 +1386,12 @@ def _car_solar_why(c, key):
return _t("car.why.solar_peak")
if w.hold:
return _t("car.why.solar_other")
refused = w.gave_up or getattr(w, "cut_refused", False) # EV-54
if w.zero_owed:
# The way-out 0 A is not taken yet: never "paused".
return _t("car.why.solar_zero_failed" if w.gave_up
return _t("car.why.solar_zero_failed" if refused
else "car.why.solar_zeroing")
if w.gave_up:
if refused:
return _t("car.why.solar_refused")
if c.shadow:
a, n = w.would if w.would is not None else (0.0, p.n)
+4 -4
View File
@@ -799,10 +799,10 @@ for exc in (RuntimeError("the link broke"), hass.ReadOnly("read only")):
errs = [m for lv, m in LOG.rec[n0:]
if lv == "ERROR" and "car charger step failed" in m]
check(f"T13 write_current raises {type(exc).__name__}: as on the base: "
"never armed, no window left, no refusal counted, the mute set, "
"never armed, no window left, one refusal counted, the mute set, "
f"the step error logged once ({len(errs)})",
never_stuck(tr) and pend(w.c.car) is None
and w.c.car_writer.fails == 0 and w.c.car.mute_until > 0
and w.c.car_writer.fails == 1 and w.c.car.mute_until > 0
and len(errs) == 1)
@@ -1027,8 +1027,8 @@ BASE_SENDS = { # recorded on 76f4de2 (release/1.0 before EV-13)
'T19-inside': ([(1011, 0.0, False), (1071, 0.0, False), (1131, 0.0, False)], [(11, 'current', 0.0), (71, 'current', 0.0), (131, 'current', 0.0)]),
'T2-error-beside': ([(1011, 10.0, False), (1071, 10.0, False), (1131, 10.0, False)], []),
'T2-error-inside': ([(1011, 10.0, False), (1071, 10.0, False), (1131, 10.0, False)], []),
'T20-beside': ([(1011, 0.0, True), (1025, 16.0, False), (1030, 16.0, False), (1035, 16.0, False), (1095, 16.0, False), (1155, 16.0, False)], [(11, 'current', 0.0), (15, 'phases', 1)]),
'T20-inside': ([(1011, 0.0, True), (1025, 16.0, False), (1030, 16.0, False), (1035, 16.0, False), (1095, 16.0, False), (1155, 16.0, False)], [(11, 'current', 0.0), (15, 'phases', 1)]),
'T20-beside': ([(1011, 0.0, True), (1025, 16.0, False), (1030, 16.0, False), (1035, 16.0, False)], [(11, 'current', 0.0), (15, 'phases', 1)]),
'T20-inside': ([(1011, 0.0, True), (1025, 16.0, False), (1030, 16.0, False), (1035, 16.0, False)], [(11, 'current', 0.0), (15, 'phases', 1)]),
'T21-beside': ([(1011, 12.0, False)], [(11, 'current', 12.0)]),
'T21-inside': ([(1011, 12.0, False)], [(11, 'current', 12.0)]),
}
+27 -17
View File
@@ -217,23 +217,33 @@ check(f"T46: Solar starts on 1 phase (select at the start), then another "
f"phase, Expected 5) ({[(x[0], x[2]) for x in s46]})",
s46[:1] and s46[0][2] == 1
and not [x for x in s46 if 140 < x[0] < 700])
low = [x for x in w46 if 140 < x[0] < 700]
# EV-21: with both batteries at the cut-out, the other writer's 3 phases
# take the period over the aim, so Solar's peak cut lowers the car first,
# within 1 cycle and at 690 W/A (EV-21 T34 (ii)); the 6 A hold and the pause
# follow. Every write in the stretch lowers; none waits for PHASE_GAP_S.
six = [x for x in low if x[1] == 6.0]
check(f"T46 (a)(b): the arithmetic uses the 3 phases the car draws on, and a "
f"lower current (EV-21's cut, the 6 A hold, the pause) is written "
f"within the 30 s rule, never blocked by PHASE_GAP_S ({w46})",
low and six and six[0][0] <= 171 and low[0][0] <= 171
and all(b[1] < a[1] for a, b in zip(low, low[1:]))
and [a for _, a, _ in low][-1:] == [0.0])
imp46 = sum(max(0.0, x["grid"]) for x in r46["trace"]
if x["t"] > 140 and x["sp"] > 0)
check(f"T46 (c): the car's grid import only within the hold rule "
f"(<= 300 s of 6 A on 3 phases) ({imp46 / 3600:.0f} Wh)",
imp46 <= 4140.0 * 302.0)
# EV-22 (PM ruling v3, D4): another writer's phase switch is a mismatch from
# its first cycle, like a foreign current. Solar writes nothing after it (no
# cut, no 6 A hold, no pause: it does not cut a car it does not control) and
# holds after WRITER_S with one CHARGER_OTHER; the guard's alarm path is the
# one it has with the car in Off (`car_solar_can_cut` False), which is the
# alarm. Before (EV-21 T34 (ii) via EV-05): the cut, the 6 A hold and the
# pause were written within the 30 s rule, a 4140 W x 302 s import.
n46 = r46["_log"]
hold46 = next((x["t"] for x in r46["trace"] if x["hold"]), None)
other46 = [m for m in LOG.since(n46, "WARNING") if "CHARGER_OTHER" in m]
check(f"T46 (a)(b): no Solar write after another writer's 3 phases at 140 "
f"({[x for x in w46 if x[0] > 140]}), the hold at {hold46} (170), "
f"CHARGER_OTHER once ({len(other46)})",
not [x for x in w46 if x[0] > 140]
and hold46 is not None and 170 <= hold46 <= 171 and len(other46) == 1)
off46 = run("T46 Off", S.drive, step_fn((300, 700.0), (600, 900.0), base=500.0),
const(3500.0), dur=900, first="car", phases=1, mode="off",
sim=SimCharger(setpoint_a=12), socs={"a": 10.0, "b": 10.0},
rows=True, events={140: lambda p, c: p.ch.set_phases(3)})
al_s = [t for t, _n in S.ids(r46, *S.ALARMS)][:1]
al_o = [t for t, _n in S.ids(off46, *S.ALARMS)][:1]
ex_s = [(x["explains"], x["red"]) for x in r46["trace"] if x["t"] >= 142]
ex_o = [(x["explains"], x["red"]) for x in off46["trace"] if x["t"] >= 142]
check(f"T46 (c): the alarm path is the one with the car in Off: the alarm "
f"within 2 s of the Off twin's ({al_s} / {al_o}), car_explains and the "
f"red rows equal in every cycle from 142 s",
al_s and al_o and abs(al_s[0] - al_o[0]) <= 2.0 and ex_s == ex_o)
r46h = std(900, sun=const(3500.0), phases=3,
events={200: lambda p, c: p.ch.set_current(16),
300: lambda p, c: p.ch.set_phases(3)})
File diff suppressed because it is too large Load Diff
+467
View File
@@ -0,0 +1,467 @@
"""EV-22 T38: the Solar fuzz for the one rule of control (N1-N10 of
reports/EV-22-test-plan.md), 14 seeds of 3600 s, both cycle orders.
`python3 -B test_ev22_fuzz.py`
A model charger that knows who set its current and its phases last (the
add-on, or another writer); random foreign currents and phase switches at any
stage (zero, select, settle), unknown phases, read gaps, refused selects and
writes, late takes of a refused select inside and after the window, Stop, Off,
shadow, latch, a press (also inside a change), and a silent meter. Every cycle
checks: N1/N2 (no non-zero write, no select over a foreign value or phase that
has stood WRITER_S, unless a press took it), N3 (no mismatch, hold or
CHARGER_OTHER without a foreign event shortly before), N4 (the N3 reading, 6 A
never past the pause), N5 (the cut cap), N6 (the select rules), N7 (no select
under a mismatch or hold), N8 (can_cut False under one), N9 (one
CHARGER_OTHER per hold), N10 (Manual never judges phases; the raise check
never holds over the value a press took). The branches are counted and a
floor is asserted, so a fuzz that never reaches them fails.
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
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
from ev20_kit import LOG, check, fails, nevers, report # noqa: E402
SITES = 14
STEPS_PER = int(os.environ.get("EV22_FUZZ_STEPS", "3600"))
ONLY = [int(x) for x in os.environ.get("EV22_FUZZ_ONLY", "").split(",") if x]
DEBUG = bool(os.environ.get("EV22_FUZZ_DEBUG"))
WRITER_S = carmode.WRITER_S
# The fuzz shortens Solar's dwells and the phase gap so that a 1 h run holds
# many phase changes (it is the changes that carry C7); nothing else moves.
if not os.environ.get("EV22_FUZZ_SLOW"):
carmode.UP_S, carmode.DOWN_S, carmode.PHASE_GAP_S = 20.0, 30.0, 60.0
class FSim(SimCharger):
"""Who set the current and the phases last, and when."""
ctl = None
def __init__(self, *a, **kw):
super().__init__(*a, **kw)
self.setter = None
self.cur_other_at = None # a foreign current stands since
self.ph_other_at = None # foreign phases stand since
self.own_ph = None # set at the first event (the start)
self.unknown = False
self.sel_log = [] # (sim t, n, taken?) of own selects
self.late = None # (n, t_sent) a refused select to take
def _apply(self, what, v):
if what == "current":
self.setter = "solar"
self.cur_other_at = None
else:
self.own_ph = 3 if v == 3 else 1
self.ph_other_at = None
super()._apply(what, v)
now_t = 0.0 # the plant's clock (not this model's)
refuse_ph = False # only the phase selects are ignored
last_sel = None # (n, plant second) of the latest select
def request_phases(self, n):
self.last_sel = (n, self.now_t)
self.sel_log.append((self.now_t, n, self.refuse_ph, self.refuse,
self.phases_allowed, self.own_ph))
keep = self.refuse
if self.refuse_ph:
self.refuse = "ignore"
try:
ok = super().request_phases(n)
finally:
self.refuse = keep
if ok and (self.refuse_ph or keep == "ignore"):
self.late = (n, self.now_t)
return ok
def set_current(self, a):
if abs(float(a) - self.setpoint_a) > 0.5:
self.setter = "other"
self.cur_other_at = self.now_t
super().set_current(a)
def set_phases(self, n):
super().set_phases(n)
if self.own_ph is None:
return # Solar has no phases of its own yet
if self.phases_allowed != self.own_ph:
self.ph_other_at = self.now_t
else:
self.ph_other_at = None
def _build(self):
out = super()._build()
if self.unknown:
for k in list(out):
if "phases" in k and ("select." in k or "max_allowed" in k):
out[k] = dict(out[k], state="unknown")
return out
COUNT = {}
EVLOG = []
NOW = [0.0]
def bump(k, n=1):
COUNT[k] = COUNT.get(k, 0) + n
EVLOG.append((NOW[0], k))
HIST = {}
def fuzz_site(seed):
rnd = random.Random(seed)
HIST.clear()
del EVLOG[:]
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, mem = [], dict(last_foreign=-1e9, press_at=-1e9, hold=False,
rises=0, n_sel=0, n_cur=0, seq=None, zero_cnt=0,
was_ms=False)
pend = {} # name -> end second of an outage
async def ev(p, c):
sim.ctl = c
w = c.car_solar
t = p.t
NOW[0] = sim.now_t = t
def takes_charger():
"""The user's press (or Solar entered, or the charger back with
no hold) takes the charger as it is: nothing on it is foreign,
and Solar's phases are the first known read after it (OQ2), which
`on_cycle` copies from Solar's start state."""
sim.own_ph, sim.ph_other_at = None, None
sim.cur_other_at = None
if pend.get("outage") is not None and t >= pend["outage"] \
and not w.hold:
takes_charger()
for k, off in (("outage", lambda: p.ch.go_unavailable(False)),
("meter", lambda: setattr(p, "meter_on", True)),
("stop", lambda: setattr(c, "auto", True)),
("unknown", lambda: setattr(sim, "unknown", False)),
("shadow", lambda: c.o.__setitem__("shadow_mode",
"off"))):
if pend.get(k) is not None and t >= pend[k]:
off()
pend[k] = None
if pend.get("mode") is not None and t >= pend["mode"]:
pend["mode"] = None
mem["press_at"] = t
takes_charger()
await c.handle_action("car_mode", value="solar")
if sim.refuse is not None and rnd.random() < 0.03:
sim.refuse = None
# a late take of a refused select: inside (<= 12 s after it went) or
# after (>= 25 s) the window
if sim.late is not None:
n_, t_ = sim.late
age = t - t_
if 3 <= age <= 12 and rnd.random() < 0.005:
sim.set_phases(n_)
sim.own_ph = sim.phases_allowed
sim.ph_other_at = None
sim.late = None
bump("late_in")
elif age >= 25 and rnd.random() < 0.2:
sim.set_phases(n_)
mem["last_foreign"] = t
sim.late = None
bump("late_after")
elif age > 400:
sim.late = None
if pend.get("latch") is not None and t >= pend["latch"]:
c.circ_wd.tripped = False
pend["latch"] = None
seqnow = w.seq is not None
s = "_seq" if seqnow else ""
# independent draws; a change in progress draws far more events
if rnd.random() < 0.02:
state["sun"] = max(0.0, min(12000.0, state["sun"]
+ rnd.uniform(-8000, 8000)))
if rnd.random() < 0.002:
state["house"] = rnd.uniform(300, 4000)
if rnd.random() < 0.0004 and pend.get("outage") is None:
p.ch.go_unavailable(True)
pend["outage"] = t + rnd.uniform(1, 40)
bump("outage")
if rnd.random() < 0.0003:
(p.ch.unplug if p.ch.state != "A" else p.ch.plug_in)()
if rnd.random() < 0.002:
sim.refuse = rnd.choice([None, "ignore", "ignore", "error"])
bump("refuse")
if rnd.random() < (0.12 if seqnow else 0.0015):
sim.set_current(rnd.choice([0, 5, 6, 13, 16]))
mem["last_foreign"] = t
bump("f_cur" + s)
if rnd.random() < (0.12 if seqnow else 0.003):
x = rnd.choice([1, 3])
ls = sim.last_sel
if ls is not None and t - ls[1] <= 25:
# inside Solar's own select window nothing is judged (DA3,
# Finding 4): a foreign switch there can hide behind the take
# and is not drawn; T47 and T48 cover its edges
bump("f_ph_skipped_in_window")
else:
sim.set_phases(x)
if sim.ph_other_at is not None:
mem["last_foreign"] = t
bump("f_ph" + s)
ls = sim.last_sel
in_sel = ls is not None and t - ls[1] <= 40
if in_sel and sim.unknown:
# a take that nobody could read inside the window is judged when
# seen (DA3, Finding 3): no unknown phases around an own select
sim.unknown, pend["unknown"] = False, None
if rnd.random() < 0.001 and pend.get("unknown") is None \
and not in_sel:
sim.unknown = True
pend["unknown"] = t + rnd.uniform(3, 30)
bump("unknown")
if (w.hold or w.mismatch_since is not None) and rnd.random() < 0.012:
# the other writer puts its change back: the read-back is ours
if w.last_a is not None:
sim.set_current(w.last_a)
if sim.own_ph is not None:
sim.set_phases(sim.own_ph)
sim.setter = "solar"
sim.cur_other_at = sim.ph_other_at = None
bump("put_back")
if (w.hold or w.gave_up) and rnd.random() < 0.025:
mem["press_at"] = t
takes_charger()
bump("press_hold")
await c.handle_action("car_mode", value="solar")
elif seqnow and rnd.random() < (0.3 if w.mismatch_since is not None
else 0.03):
if w.hold or w.mismatch_since is not None:
bump("lift_press_seq")
mem["press_at"] = t
takes_charger()
bump("press_seq")
await c.handle_action("car_mode", value="solar")
if seqnow and not sim.refuse_ph and rnd.random() < 0.2:
sim.refuse_ph = True # a select the charger ignores
bump("refuse_seq")
elif sim.refuse_ph and rnd.random() < 0.02:
sim.refuse_ph = False
if rnd.random() < 0.0004 and pend.get("meter") is None:
p.meter_on = False
pend["meter"] = t + rnd.uniform(5, 60)
bump("meter")
counting = w.mismatch_since is not None and not w.hold
if rnd.random() < (0.05 if seqnow else 0.05 if counting else 0.0006):
k = rnd.choice(["stop", "shadow", "mode", "latch"])
bump(k + s)
back = t + rnd.uniform(5, 60)
if k == "stop" and pend.get("stop") is None:
c.auto = False
c.o["shadow_mode"] = rnd.choice(["off", "auto"])
pend["stop"] = back
elif k == "shadow" and pend.get("shadow") is None:
c.o["shadow_mode"] = "on"
pend["shadow"] = back
elif k == "latch" and pend.get("latch") is None:
c.circ_wd.tripped = True
pend["latch"] = back
elif k == "mode" and pend.get("mode") is None:
await c.handle_action("car_mode", value="off")
pend["mode"] = back
if rnd.random() < 0.0005:
await c.handle_action("car_sun_first", value=rnd.choice(
["batteries", "car"]))
def on_cycle(p, c, t):
w, m = c.car_solar, c.car_writer
t = float(t)
if sim.own_ph is None and getattr(w, "_own_n", None) is not None:
sim.own_ph = w._own_n
HIST[t] = (w.mismatch_since, w.hold, getattr(w, "_own_n", None),
getattr(w, "_win_t1", None),
None if w.seq is None else w.seq["stage"],
p.ch.phases_allowed, p.ch.own_ph, p.ch.ph_other_at,
w.sent_a, p.ch.setpoint_a)
held = w.hold
was_hold = mem["hold"]
ms = w.mismatch_since is not None
# N8
if (held or ms) and c.car_solar_can_cut():
bad.append((seed, t, "N8 can_cut under a mismatch or hold"))
# N10: Manual never judges phases
if getattr(m, "_ph_diff", False):
bad.append((seed, t, "N10 Manual judges phases"))
# N3: a mismatch or hold needs a foreign event shortly before
# (judged where it starts: a foreign value that stands unseen while
# Solar does not watch, no car or a fault, is seen when it does)
explained = (sim.ph_other_at is not None
or sim.cur_other_at is not None
or t - mem["last_foreign"] <= 400
or t - mem["press_at"] <= 400)
if ((ms and not mem["was_ms"]) or (held and not mem["hold"])) \
and not explained:
bad.append((seed, t, "N3 mismatch or hold with no foreign event",
w.mismatch_since, held))
if ms and not mem["was_ms"]:
bump("mismatch")
if mem["seq"] is not None:
bump("mismatch_seq")
mem["was_ms"] = ms
mem["seq"] = w.seq
if held and not mem["hold"]:
mem["rises"] += 1
bump("hold")
if getattr(w, "_ph_diff", False):
bump("hold_ph")
if mem["hold"] and not held:
if t - mem["press_at"] <= 2:
bump("lift_press")
else:
bump("lift_match")
mem["hold"] = held
# N10: no hold over the value a press took, in the 3 cycles after it
if held and 0 <= t - mem["press_at"] <= 3 \
and t - mem["last_foreign"] > 3:
bad.append((seed, t, "N10 hold right after a press"))
# N9: one CHARGER_OTHER per hold
others = len([1 for m_ in LOG.since(mem.get("mark", 0), "WARNING")
if "CHARGER_OTHER" in m_])
if others > mem["rises"]:
bad.append((seed, t, "N9 more CHARGER_OTHER than holds", others,
mem["rises"]))
# N5: the cut cap
if w.cut_fails > carmode.MAX_TRIES:
bad.append((seed, t, "N5 cut tries over the cap", w.cut_fails))
# N1 / N2 / N7 on the writes of this cycle
for e in p.wlog[mem["n_wlog"]:]:
# a write waits for its read-back, so its own stamp runs ahead of
# the cycle that sent it: judge by the cycle's second
tt, what, v = t, e[1], e[2]
if what == "current" and v > 0:
bump("nz_write")
for lab, since in (("N1 current", sim.cur_other_at),
("N2 phases", sim.ph_other_at)):
if since is not None and sim.setter in ("other", "solar") \
and tt - since >= WRITER_S + 2 \
and mem["press_at"] < since:
bad.append((seed, tt, lab, "write over a foreign "
"value that stood", v, since))
if what == "phases":
bump("select")
if sim.ph_other_at is not None \
and tt - sim.ph_other_at >= WRITER_S + 2 \
and mem["press_at"] < sim.ph_other_at:
bad.append((seed, tt, "N2 select over foreign phases",
sim.ph_other_at, mem["press_at"],
sim.own_ph, sim.phases_allowed))
if ms or held:
bad.append((seed, tt, "N7 select under a mismatch/hold"))
if what == "current" and v == 0.0 and ms and not held:
bump("zero_in_count")
# (the way-out 0 A of the step in which the count runs out is
# written before the watch holds: OQ1)
if what == "current" and v == 0.0 and held and was_hold:
bad.append((seed, tt, "N2 0 A written under a hold"))
mem["n_wlog"] = len(p.wlog)
if held and (c.car_mode != "solar" or not c.car_writing()):
bump("stop_under_hold")
# N4: 6 A never past the pause
pause_s = 60.0 * carmode.solar_option(c.o, "ev_pause_min")
rd = c.car.reading
avail = bool(rd is not None and rd.available)
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 w.plan.low_since is not None \
and t - w.plan.low_since > pause_s + 2.0 and not ms and not held:
bad.append((seed, t, "N4 6 A past the pause"))
race = seed % 2 == 1
evs = {t: ev for t in range(30, STEPS_PER)}
mark = LOG.mark()
mem["mark"] = mark
mem["n_wlog"] = 0
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"] * 5 + ["1", "3"])})
r["_log"] = mark
nv = nevers(r, f"N6/N13 seed {seed}", gap=carmode.PHASE_GAP_S)
if DEBUG and bad:
t0 = float(os.environ.get("EV22_FUZZ_T0") or bad[0][1])
print(" DEBUG first bad", bad[0])
print(" writes", [(x[0], x[1], x[2]) for x in r["plant"].wlog
if t0 - 90 <= x[0] <= t0 + 5])
print(" events", sorted(x for x in EVLOG if t0 - 120 <= x[0] <= t0 + 5))
print(" lag", sim.lag_s, "seed", seed)
print(" selects (plant s, n, refuse_ph, refuse, phases, own)",
[x for x in sim.sel_log if t0 - 200 <= x[0] <= t0 + 5])
print(" hist (t, ms, hold, own_n, win_end, seq, phases, model own,"
" model foreign since)")
for tk in sorted(HIST):
if t0 - 40 <= tk <= t0 + 2:
print(" ", tk, HIST[tk])
return bad, nv
print("T38: THE FUZZ")
allbad, allnv = [], []
for seed in (ONLY or range(SITES)):
bad, nv = fuzz_site(seed)
allbad += bad
allnv += nv
if bad:
print(" seed", seed, bad[:2])
check(f"T38: N1-N5, N7-N10 hold in every cycle of {SITES} seeds x "
f"{STEPS_PER} s ({allbad[:3]})", not allbad)
WHAT = {
"N1": "no non-zero current write over a foreign current that stood "
"WRITER_S (the close, the EV-28 restore, an undo included)",
"N2": "no non-zero write and no select over foreign phases that stood "
"WRITER_S; a 0 A is never written under a hold",
"N3": "no mismatch, hold or CHARGER_OTHER without a foreign event shortly "
"before (own writes, own selects, own sequence values, a reading "
"from before the step's own 0 A, unknown, stale or failed reads)",
"N4": "the N3 reading: never 6 A past pause_s",
"N5": "at most MAX_TRIES cut tries per quarter key",
"N7": "no phase select under a mismatch or a hold",
"N8": "car_solar_can_cut is never True under a mismatch or a hold",
"N9": "at most one CHARGER_OTHER per hold",
"N10": "Manual never judges phases; no hold right after a press",
}
for k, txt in WHAT.items():
check(f"{k}: {txt} (every cycle of {SITES} seeds)",
not [b for b in allbad if b[2].split()[0] == k])
check(f"N6: no write above the clamp, a select only at 0 A under 100 W, one "
f"per 600 s, no Traceback (nevers of every seed) ({allnv[:2]})",
not allnv)
print(" counts", dict(sorted(COUNT.items())), "UP_S", carmode.UP_S,
"PHASE_GAP_S", carmode.PHASE_GAP_S)
floor = {"mismatch_seq": 20, "hold_ph": 10, "lift_match": 10, "lift_press": 10,
"lift_press_seq": 5, "zero_in_count": 5, "stop_under_hold": 5,
"late_after": 5}
if STEPS_PER >= 3600:
check(f"T38: the fuzz reaches its branches ({ {k: COUNT.get(k, 0) for k in floor} }, "
f"floor {floor})", all(COUNT.get(k, 0) >= v for k, v in floor.items()))
report()
+14 -6
View File
@@ -57,8 +57,12 @@ class _Cap(logging.Handler):
self.rec.append((r.levelno, r.getMessage()))
def loud(self, since=0):
"""INFO and above from `since` on."""
return [m for lv, m in self.rec[since:] if lv >= logging.INFO]
"""INFO and above from `since` on, but for EV-52's two plain lines
("Car: set ..." for a taken write, "Car mode is now ..."): they are
asserted in test_ev52.py (T11, T13); this file's rows are about every
OTHER line a phase change may log."""
return [m for lv, m in self.rec[since:] if lv >= logging.INFO
and not m.startswith(("Car: set", "Car mode is now"))]
CAP = _Cap()
@@ -700,7 +704,8 @@ async def t15():
await w.step(19)
w.sim.refuse = "error"
await w.step(40)
mid = (list(calls), w.wr.seq is None and w.wr.fails == 1,
mid = (list(calls), w.wr.seq is None and w.wr.fails == MAX_TRIES
and w.wr.gave_up,
bool(w.writes("phases")))
w.sim.refuse = None
await w.step(int(carmode.RETRY_S) + 10)
@@ -711,11 +716,14 @@ w, (calls, over, anyph) = run(t15())
tries = [c for c in calls if c[1] == 16.0]
gaps = [round(b[0] - a[0]) for a, b in zip(tries, tries[1:])]
check(f"T15: the restore is refused: tried {len(tries)} times ~5 s apart "
f"({gaps}), no select, sequence ends, one failed write counted",
f"({gaps}), no select, sequence ends, the 3 closes counted: given up "
"(EV-59)",
len(tries) == MAX_TRIES and all(4 <= g <= 6 for g in gaps) and over
and not anyph and not w.writes("phases"))
check("T15: after the refusal ends the current is back at 16 A, never a "
"select", w.sim.readback_a == 16 and not w.writes("phases"))
check("T15: EV-59: given up after the 3 closes: no 4th try, the current stays "
"at 0 A until a user change, never a select",
w.sim.readback_a == 0 and len(tries) == MAX_TRIES
and not w.writes("phases"))
# --- T14: the controller level (the EV-15 harness) ------------------------- #
+5 -1
View File
@@ -624,7 +624,11 @@ GOOGLE.setLevel(logging.INFO)
try:
n = LOG.mark()
r, st = run_log(go, dur=760, cyc=5, phase=0, race=True)
info = [(lv, m) for lv, m, _x in LOG.rec[n:]]
# EV-52 adds two plain INFO lines ("Car: set ...", "Car mode is now ...");
# test_ev52.py asserts them. This row is about EV-51's own line, so they
# are set aside here and every other record must still be base's.
info = [(lv, m) for lv, m, _x in LOG.rec[n:]
if not m.startswith(("Car: set", "Car mode is now"))]
finally:
GOOGLE.setLevel(logging.DEBUG)
# Measured on 5bff894 (same run, INFO), pinned:
+942
View File
@@ -0,0 +1,942 @@
"""EV-52: one plain info line when the add-on writes a new car current, and one
when the car mode changes. `python3 -B test_ev52.py`
Logging only: no write, no time and no notification changes (T43-T45 pin that
against golden lists taken on the base build 02166e2). The real Controller on
`tools/ev20_sun.py` (a model clock, the charger model, one 1 s cycle), as
test_ev20.py and test_ev21_paths.py use it; a few rows call the writer's own
`_write` from the run's finale or on a stub driver. Time is the model clock
throughout, never x10 and never wall time.
Rows T1-T45 and N1-N11 of reports/EV-52-test-plan.md, with T23 as PM ruling Q2
changed it: a write the charger took late logs its line ONCE, at the accept.
A "line" is an INFO record that starts `Car: set`; a "mode line" one that
starts `Car mode is now`; each is placed on the cycle second it was logged in
(None: before the first cycle or in the finale).
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import asyncio
import os
import re
import sys
from types import SimpleNamespace
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
from app import carmode, chargers as CH, ctl_car # noqa: E402
import ev20_sun as S # noqa: E402
import ev21_kit as K # noqa: E402
from chargersim import SimCharger # noqa: E402
from ev20_kit import (LOG, check, fails, const, step_fn, act, # noqa: E402
report)
SET = S.SET
SETP = "Car: set"
MODEP = "Car mode is now"
MOPT = {"ev_phases": "1"} # a one-phase installation
ALL = [] # every run of this file, for N2 / N10
# The reason a caller names; the base build (no line) takes no such argument,
# so its rows read red there instead of crashing.
WHY = {"why": "Manual"} if hasattr(carmode.ManualWriter, "_log_set") else {}
# ------------------------------------------------------------------ helpers
def _stamp():
n0, stamps = LOG.mark(), {}
def oc(p, c, t):
stamps[t] = LOG.mark()
return n0, stamps, oc
def _tag(r, n0, stamps):
ts = sorted(stamps)
out = []
for i in range(n0, len(LOG.rec)):
lv, m, _x = LOG.rec[i]
out.append((next((t for t in ts if stamps[t] > i), None), lv, m))
r["lines"], r["n0"], r["end"] = out, n0, len(LOG.rec)
ALL.append(r)
return r
def run(mode, dur, house=900.0, sun=0.0, events=None, **kw):
n0, stamps, oc = _stamp()
r = S.drive(house if callable(house) else const(house),
sun if callable(sun) else const(sun), dur=dur, mode=mode,
events=events, on_cycle=oc, **kw)
return _tag(r, n0, stamps)
def kdrive(house, sun, **kw):
n0, stamps, oc = _stamp()
r = K.drive(house, sun, on_cycle=oc, **kw)
return _tag(r, n0, stamps)
def kshape(kind, **kw):
n0, stamps, oc = _stamp()
r = K.shape(kind, on_cycle=oc, **kw)
return _tag(r, n0, stamps)
def sets(r, lo=None, hi=None):
return [(t, m) for t, lv, m in r["lines"]
if m.startswith(SETP)
and (lo is None or (t if t is not None else 1e12) >= lo)
and (hi is None or (t if t is not None else 1e12) < hi)]
def texts(r, **kw):
return [m for _t, m in sets(r, **kw)]
def modes(r):
return [(t, m) for t, lv, m in r["lines"] if m.startswith(MODEP)]
def taken(r):
"""Every current write the charger took, Manual's and Solar's."""
return [x for w in (r["c"].car_writer, r["c"].car_solar) for x in w.log
if x[0] == "current" and x[3]]
def warns(r, text):
return [m for _t, lv, m in r["lines"] if lv == "WARNING" and text in m]
def wlist(r):
return [(round(t), v) for t, v in S.writes(r)]
def amps_in(m):
return float(re.search(r" to (\d+) A", m).group(1))
MANUAL = {10: act("car_phases", 1), 15: act("car_current", 6),
20: act("car_mode", "manual")}
def manual(dur, events=None, **kw):
ev = dict(MANUAL)
ev.update(events or {})
kw.setdefault("setpoint", 10)
kw.setdefault("phases", 1)
kw.setdefault("car_phases", 1)
kw.setdefault("opts", MOPT)
return run("off", dur, events=ev, **kw)
def solar(dur, house=900.0, sun=7900.0, **kw):
kw.setdefault("first", "car")
kw.setdefault("phases", 1)
kw.setdefault("car_phases", 1)
kw.setdefault("opts", MOPT)
return run("solar", dur, house=house, sun=sun, **kw)
def both(*fns):
async def f(p, c):
for fn in fns:
x = fn(p, c)
if asyncio.iscoroutine(x):
await x
return f
async def _shutdown(p, c):
await c.shutdown()
def refuse(kind):
def f(p, c):
p.ch.refuse = kind
return f
def lift(p, c):
p.ch.refuse = None
# =========================================================================== #
print("1. MANUAL: A NEW CURRENT LOGS ONE LINE (T1-T3)")
# =========================================================================== #
r1 = manual(500, events={200: act("car_current", 8),
300: act("car_current", 8)})
s1 = sets(r1)
check(f"T1: Manual 10 -> 6 A (user set 6 A, then Manual), 180 cycles: exactly "
f"1 line, old 10 A, 1 phase, Manual ({texts(r1, hi=200)})",
texts(r1, hi=200) == ["Car: set from 10 A to 6 A on 1 phase (Manual)."])
check(f"T1: logged in the writer's own step at the action's cycle "
f"({s1[:1]}) at INFO, and it equals what was sent "
f"({r1['c'].charger.sent[:1]})",
[t for t, _m in s1[:1]] == [20] and r1["c"].charger.sent[0] == 6.0
and all(lv == "INFO" for _t, lv, m in r1["lines"]
if m.startswith(SETP)))
check(f"T2: the user sets 8 A: exactly 1 more line, 6 -> 8, Manual "
f"({texts(r1, lo=200)})",
texts(r1, lo=200) == ["Car: set from 6 A to 8 A on 1 phase (Manual)."])
check(f"T3: the same 8 A again and 200 more cycles: 0 new lines and 0 new "
f"writes ({len(s1)} lines, {len(wlist(r1))} writes)",
len(sets(r1, lo=300)) == 0 and len(wlist(r1)) == 2)
check("T3/N4: one line per taken write, none per cycle",
len(s1) == len(taken(r1)) == 2)
check("T1: the mode line comes with the action",
[m for t, m in modes(r1) if t == 20] == ["Car mode is now Manual."])
# T24 / T25: the old value, or the phases, unknown. The writer's own `_write`
# from the finale: no old value, then no reading at all.
async def _unknown(p, c):
w = c.car_writer
await w._write(c.charger, 7.0, None, 400.0, c.car, **WHY)
w._r = None
await w._write(c.charger, 9.0, None, 401.0, c.car, **WHY)
r24 = manual(150, finale=_unknown)
check(f"T24/T25: the old value unknown: 'set to 7 A on 1 phase'; no reading, "
f"so no phase count either: 'set to 9 A (Manual)'; no exception "
f"({[m for t, m in sets(r24) if t is None]})",
[m for t, m in sets(r24) if t is None] == [
"Car: set to 7 A on 1 phase (Manual).",
"Car: set to 9 A (Manual)."])
def _odd():
w = carmode.ManualWriter()
n0 = LOG.mark()
for a, was, n in ((float("nan"), 6.0, 1), (None, 6.0, 1),
("x", None, 3), (6.0, float("inf"), "1"),
(6.0, 6.0, 1)):
if hasattr(w, "_log_set"): # the base build has none: red, not a crash
w._log_set(a, was, "Manual", n)
return [m for _lv, m, _x in LOG.rec[n0:] if m.startswith(SETP)]
check(f"N9: a NaN, None, text or infinite figure never raises and logs "
f"nothing wrong; an unchanged value logs nothing ({_odd()})",
_odd() == ["Car: set to 6 A (Manual)."])
# =========================================================================== #
print("\n2. THE MODE (T4-T6, T31)")
# =========================================================================== #
r4 = manual(200, events={100: act("car_mode", "manual"),
110: act("car_current", 9),
120: act("car_phases", 1),
130: act("car_sun_first", "car"),
140: act("car_mode", "bogus"),
150: act("car_current", 9)})
check(f"T4: Off -> Manual: exactly 1 mode line at the action ({modes(r4)})",
[m for t, m in modes(r4) if t == 20] == ["Car mode is now Manual."])
check(f"T4: the add-on's start logs the mode it started in, once "
f"({modes(r4)[:1]})", modes(r4)[:1] == [(0.0, "Car mode is now Off.")])
check(f"T5: Manual picked again, a value, the phases, Sun first and a bad "
f"mode: no mode line ({modes(r4)})", len(modes(r4)) == 2)
r6 = run("off", 300, events={20: act("car_mode", "manual"),
40: act("car_current", 9)},
opts={"ev_charger": "off"})
check(f"T6/N6: no charger: no car line, no mode line, not at start-up "
f"either ({[m for _t, _l, m in r6['lines'] if m.startswith(('Car:', MODEP))]})",
not [m for _t, _l, m in r6["lines"]
if m.startswith(("Car:", MODEP))] and not wlist(r6))
r31 = run("solar", 60, opts=dict(MOPT, ev_mode_start="off"), first="car",
phases=1, car_phases=1)
check(f"T31: ev_mode_start off with Solar stored: one mode line, Off "
f"({modes(r31)})",
[m for _t, m in modes(r31)] == ["Car mode is now Off."])
# =========================================================================== #
print("\n3. SOLAR (T7-T10, T14, T26)")
# =========================================================================== #
r7 = solar(700)
t7 = sets(r7)[0][0] if sets(r7) else -10 ** 6
check(f"T7: Solar, Car first, spare sun, charger at 0 A: exactly 1 line for "
f"the start current ({texts(r7)})",
texts(r7) == ["Car: set from 0 A to 16 A on 1 phase (Solar)."])
check(f"T7: the line is in the step of the write ({t7}; write {wlist(r7)})",
wlist(r7) == [(t7 + 1, 16)])
check("T9: Solar steady, 580 cycles after the start: 0 new lines",
len(sets(r7, lo=t7 + 1)) == 0)
check("T7: the mode line once, at start-up",
[m for _t, m in modes(r7)] == ["Car mode is now Solar."])
def cloud_house(t):
return 900.0 + 800.0 if 300 <= t < 720 else 900.0
r8 = solar(900, house=cloud_house, sun=3400.0)
check(f"T8: Solar steady, a cloud (the house imports 800 W for 420 s): one "
f"line per taken write, each Solar ({texts(r8)}, taken "
f"{len(taken(r8))})",
len(sets(r8)) == len(taken(r8)) and len(sets(r8)) >= 2
and all(m.endswith("(Solar).") for m in texts(r8)))
def dither(t):
return 900.0 + 2300.0 + 100.0 + (0.0 if int(t // 7) % 2 else -10.0)
r10 = solar(900, sun=dither)
ln = [t for t, _m in sets(r10)]
gaps = [b - a for a, b in zip(ln, ln[1:])]
check(f"T10: spare dithering on an amp boundary: lines == taken writes "
f"({len(ln)}), at most one per SOLAR_WRITE_S ({gaps}); it fired "
f"{len(ln)} times in 900 s",
len(ln) == len(taken(r10)) and all(g >= carmode.SOLAR_WRITE_S - 1
for g in gaps))
r14 = run("solar", 900, sun=9600.0, first="car", phases=1, car_phases=3)
t14 = texts(r14)
z14 = [m for m in t14 if " to 0 A on 1 phase (Solar)" in m]
c14 = [m for m in t14 if "on 3 phases (Solar)" in m]
check(f"T14: Solar auto 1 -> 3 phases: one 0 A line on 1 phase, one close on "
f"3 phases, nothing else ({t14}; selects {S.writes(r14, 'phases')})",
len(S.writes(r14, "phases")) == 1 and len(z14) == 1 and len(c14) == 1
and len(t14) == 3 and t14.index(z14[0]) < t14.index(c14[0]))
check("T12: the select itself logs nothing: one line per taken current write",
len(sets(r14)) == len(taken(r14)))
r26 = solar(300, sun=0.0, setpoint=0)
check(f"T26: Solar, the charger already shows the 0 A Solar wants: no write, "
f"0 lines ({texts(r26)}, writes {wlist(r26)})",
not texts(r26) and not wlist(r26))
# =========================================================================== #
print("\n4. MANUAL PHASE CHANGE (T11-T13, T42)")
# =========================================================================== #
r11 = manual(300, events={200: act("car_phases", 3)}, car_phases=3, opts={})
t11 = texts(r11, lo=200)
s11 = [t for t, _m in sets(r11, lo=200)]
check(f"T11: Manual 6 A on 1 phase, the user picks 3 phases, the car stops: "
f"exactly 2 lines, the 0 A on 1 phase and the 6 A on 3 ({t11})",
t11 == ["Car: set from 6 A to 0 A on 1 phase (Manual).",
"Car: set from 0 A to 6 A on 3 phases (Manual)."])
check(f"T11/T12: the 0 A logs as a write; the close comes after the select "
f"and the 10 s settle, the select itself logs nothing ({s11}; selects "
f"{S.writes(r11, 'phases')})",
len(s11) == 2 and s11[1] - s11[0] >= carmode.SETTLE_S
and len(S.writes(r11, "phases")) == 1)
def drawing(p, c):
p.ch.ramp_w_s = 0.0001 # the car does not let go
r13 = manual(400, events={200: both(drawing, act("car_phases", 3))},
car_phases=3, opts={})
t13 = texts(r13, lo=200)
check(f"T13: the car keeps drawing: the 0 A line, the existing warning once, "
f"the restore line on 1 phase ({t13})",
t13 == ["Car: set from 6 A to 0 A on 1 phase (Manual).",
"Car: set from 0 A to 6 A on 1 phase (Manual)."]
and len(warns(r13, "The car kept drawing, so the phases were not "
"changed.")) == 1)
def shadow_on(p, c):
c.o["shadow_mode"] = "on"
r42 = manual(260, events={200: act("car_phases", 3), 201: shadow_on},
car_phases=3, opts={})
t42 = texts(r42, lo=200)
check(f"T42: shadow mode in the middle of a phase change: the 0 A and the one "
f"write shadow allows, Manual's undo: 2 lines, then none ({t42})",
t42 == ["Car: set from 6 A to 0 A on 1 phase (Manual).",
"Car: set from 0 A to 6 A on 1 phase (Manual)."]
and not S.writes(r42, "phases"))
# =========================================================================== #
print("\n5. THE PEAK CUT (T15-T17, T41)")
# =========================================================================== #
r15 = kdrive(step_fn((960, 900.0 + 5700.0), (966, 900.0 + 9000.0), base=900.0),
const(13000.0), dur=1100, first="car", phases=3,
socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "3"},
events={958: lambda p, c: setattr(c.car_solar, "nonzero_at",
p.t)})
cuts = sets(r15, lo=958)
wcut = [v for t, v in S.writes(r15) if t >= 958]
check(f"T15: the EV-21 cut (two cuts as the excess grows): one line per cut, "
f"each 'peak cut' with the value written ({[m for _t, m in cuts]}; "
f"writes {wcut})",
len(cuts) == len(wcut) >= 1
and all(m.endswith("(peak cut).") for _t, m in cuts)
and [amps_in(m) for _t, m in cuts] == wcut)
cut_note = [m for _t, lv, m in r15["lines"]
if m == "Solar lowered the car for the peak: CAR_CUT."]
check(f"T15: the existing CAR_CUT info line and notice once per session, "
f"unchanged ({len(cut_note)}, notices "
f"{[n for _t, n in r15['raised'] if 'cut' in n]})", len(cut_note) == 1)
check("T15: the 16 A before the cut was Solar's own line, not a cut",
texts(r15, hi=958)[-1].endswith("(Solar).") if texts(r15, hi=958)
else False)
r16 = kshape("C", dur=1300)
c16 = texts(r16, lo=950)
check(f"T16: a cut deeper than the car can follow (to 0 A): the line says "
f"'to 0 A' and 'peak cut' ({c16})",
c16 == ["Car: set from 10 A to 0 A on 3 phases (peak cut)."])
r18 = kshape("C", dur=1300,
events={959: lambda p, c: setattr(p.ch, "refuse", "ignore")})
check(f"T18: the cut refused (3 tries 60 s apart): the existing CHARGER_REFUSED "
f"once, 0 lines for the cut ({texts(r18, lo=950)}, "
f"{len(warns(r18, 'CHARGER_REFUSED'))}, tries "
f"{[round(t) for t, v in S.writes(r18) if t >= 959]})",
not texts(r18, lo=950) and len(warns(r18, "CHARGER_REFUSED")) == 1
and len([1 for t, v in S.writes(r18) if t >= 959]) == 3)
class Drv:
"""A driver that takes, or not, what it is given, for the writer's own
steps. `write_current` notes how many log records existed when it
returned (N3: the line follows the write)."""
def __init__(self, ok=True):
self.ok, self.sent, self.marks = ok, [], []
async def write_current(self, a, **kw):
self.sent.append(a)
self.marks.append(LOG.mark())
return self.ok
async def write_phases(self, n):
return True
def reading(**kw):
base = dict(available=True, state="C", power_w=0.0, phases_allowed=3,
allowed_a=0.0, setpoint_a=0.0)
base.update(kw)
return CH.ChargerReading(**base)
def tracker():
return CH.CarTracker()
def go(coro):
return asyncio.run(coro)
# T17: the cut's cap lowers the closing current of a phase change.
async def t17():
w = carmode.SolarWriter()
drv, tr = Drv(), tracker()
w.plan.a, w.plan.target_w, w.plan.n = 16.0, 16.0 * 230.0 * 3, 3
w.cut_a = 8.0
w.seq = {"stage": "settle", "t0": 0.0, "t1": 0.0, "n": 3, "tries": 0,
"prev": None, "sel_ok": True}
n0 = LOG.mark()
await w._advance(drv, reading(), 0.0, 20.0, tr, w._seq_want(16.0, 3),
16.0, None)
return drv, [m for _lv, m, _x in LOG.rec[n0:] if m.startswith(SETP)]
d17, l17 = go(t17())
check(f"T17: a cut due while Solar's phase change is under way: the close "
f"carries 'peak cut' and the capped value, no extra line ({l17}, sent "
f"{d17.sent})",
l17 == ["Car: set from 0 A to 8 A on 3 phases (peak cut)."]
and d17.sent == [8.0])
async def t17b():
w = carmode.SolarWriter()
drv, tr = Drv(), tracker()
w.plan.a, w.plan.target_w, w.plan.n = 10.0, 10.0 * 230.0 * 3, 3
w.seq = {"stage": "settle", "t0": 0.0, "t1": 0.0, "n": 3, "tries": 0,
"prev": None, "sel_ok": True}
n0 = LOG.mark()
await w._advance(drv, reading(), 0.0, 20.0, tr, w._seq_want(16.0, 3),
16.0, None)
return [m for _lv, m, _x in LOG.rec[n0:] if m.startswith(SETP)]
check(f"T17: the same close with no cut: 'Solar', the plan's value "
f"({go(t17b())})",
go(t17b()) == ["Car: set from 0 A to 10 A on 3 phases (Solar)."])
# T41: a write either side of the quarter boundary (900): one line each.
sun41 = step_fn((899, 4760.0), (931, 4100.0), base=4300.0)
r41 = solar(1000, sun=sun41)
l41 = sets(r41, lo=890, hi=960)
check(f"T41: Solar writes at 899 and 931 across the quarter boundary: one "
f"line each, no duplicate ({l41}, writes "
f"{[x for x in wlist(r41) if x[0] > 890]})",
len(l41) == 2 and len({m for _t, m in l41}) == 2
and len(l41) == len([1 for t, v in S.writes(r41) if t > 890]))
# =========================================================================== #
print("\n6. FAILED OR LATE WRITES (T19-T23, T33, T37, T39, N2, N3)")
# =========================================================================== #
REF = "The charger did not take the current, so the add-on stops asking"
for kind in ("ignore", "error"):
r19 = manual(400, events={19: refuse(kind)})
check(f"T19 [{kind}]: Manual write refused, 3 tries 60 s apart: 0 lines, "
f"CHARGER_REFUSED once, text unchanged ({texts(r19)}, "
f"{len(warns(r19, REF))})",
not texts(r19) and len(warns(r19, REF)) == 1)
r20 = manual(300, events={19: refuse("ignore"), 40: lift})
t20 = sets(r20)
check(f"T20: refused once, the charger takes it at the retry: exactly 1 line, "
f"at the retry, 60 s or more after the fail ({t20})",
len(t20) == 1 and t20[0][0] >= 20 + 60
and t20[0][1] == "Car: set from 10 A to 6 A on 1 phase (Manual).")
async def _clamp(p, c):
p.clamp_ok = await c.car_writer._write(c.charger, 30.0, 10.0, 400.0, c.car)
r21 = manual(120, finale=_clamp)
fin = [(lv, m) for t, lv, m in r21["lines"] if t is None]
check(f"T21: a write above the clamp: CHARGER_CLAMP error unchanged, nothing "
f"sent, no line ({[(lv, m[:30]) for lv, m in fin]})",
any(lv == "ERROR" and m.endswith("CHARGER_CLAMP.") for lv, m in fin)
and not [m for lv, m in fin if m.startswith(SETP)]
and r21["plant"].clamp_ok is False)
class RaisingPlant(S.SunPlant):
"""Home Assistant whose call on the current entity raises, from 19 s."""
async def set_number(self, e, v):
if e == SET and self.t >= 19.0:
raise RuntimeError("HA call error")
return await super().set_number(e, v)
r22 = manual(200, plant_cls=RaisingPlant)
check(f"T22: the driver raises in write_current: 0 lines, the existing 'step "
f"failed' error once, no new exception from the log path "
f"({texts(r22)})",
not texts(r22) and len([1 for _t, lv, m in r22["lines"]
if lv == "ERROR"
and m == "The car charger step failed"]) == 1)
def slow(p, c):
p.ch.lag_s = 12.0 # over TOOK_S (10 s)
r23 = solar(400, events={100: slow})
w23 = [(round(t), v) for t, v in S.writes(r23)]
check(f"T23 (Q2): a late read-back (12 s, over TOOK_S): the write is not "
f"taken at once, then adopted; exactly 1 'set' line, at the accept "
f"({sets(r23)}, write {w23})",
texts(r23) == ["Car: set from 0 A to 16 A on 1 phase (Solar)."]
and sets(r23)[0][0] >= 120 + 10
and len(taken(r23)) == 0)
check("T23 (Q2): no line at the write itself, none for the failed try",
not sets(r23, hi=130))
async def t23b():
"""The accept after the warning: three refused tries, then the charger
shows the value (late): the warning is the existing one, then one line."""
w = carmode.SolarWriter()
drv, tr = Drv(ok=False), tracker()
w.engaged = True
n0 = LOG.mark()
for k in range(3):
await w._write(drv, 16.0, 0.0, 100.0 + 70 * k, tr)
mid = [m for _lv, m, _x in LOG.rec[n0:]]
w._adopt(16.0)
w._adopt(16.0) # a second read-back: nothing again
end = [m for _lv, m, _x in LOG.rec[n0:]]
return mid, end
mid, end = go(t23b())
check(f"T23 (Q2): three tries not taken give the existing CHARGER_REFUSED "
f"warning and no line; the accept then gives exactly one line "
f"({mid} -> {end})",
len(mid) == 1 and mid[0].endswith("CHARGER_REFUSED.")
and end[1:] == ["Car: set from 0 A to 16 A (Solar)."])
async def t23c():
w = carmode.SolarWriter()
drv, tr = Drv(ok=False), tracker()
n0 = LOG.mark()
await w._write(drv, 16.0, 0.0, 100.0, tr)
w._adopt(10.0) # shows something else: not our write
return [m for _lv, m, _x in LOG.rec[n0:] if m.startswith(SETP)]
check("T23/M4: a read-back that shows another value is not an accept: 0 lines",
go(t23c()) == [])
# Q2 for Manual: a write taken late logs its line once, at the accept.
r23m = manual(200, events={10: slow})
w23m = [(round(t), v) for t, v in S.writes(r23m)]
check(f"T23 Manual (Q2): a late read-back (12 s): no line at the write, "
f"exactly 1 line at the accept, a few seconds later ({sets(r23m)}, "
f"write {w23m})",
texts(r23m) == ["Car: set from 10 A to 6 A on 1 phase (Manual)."]
and sets(r23m)[0][0] >= 20 + 10 and len(taken(r23m)) == 0)
async def t23m():
"""Three tries not taken: the existing CHARGER_REFUSED warning, no line;
the charger then shows the value: exactly one line, once."""
w = carmode.ManualWriter()
w.boot = False
drv, tr = Drv(ok=False), tracker()
async def step(a, now):
await w.step(drv, reading(state="C", allowed_a=a, setpoint_a=a,
phases_allowed=1), mode=carmode.MANUAL,
want_a=6.0, want_phases=1, rev=1, clamp=16.0, now=now,
tracker=tr, writing=True, status="charging")
n0 = LOG.mark()
for k in range(3):
await step(10.0, 100.0 + 70 * k)
mid = [m for lv, m, _x in LOG.rec[n0:] if lv != "DEBUG"]
await step(6.0, 300.0)
await step(6.0, 310.0) # the next read-back: nothing again
return mid, [m for lv, m, _x in LOG.rec[n0:] if lv != "DEBUG"]
mid, end = go(t23m())
check(f"T23 Manual (Q2): three tries not taken give the existing Manual "
f"CHARGER_REFUSED warning and no line; the accept then gives exactly "
f"one line ({mid} -> {end})",
len(mid) == 1 and mid[0].endswith("CHARGER_REFUSED.")
and end[1:] == ["Car: set from 10 A to 6 A on 1 phase (Manual)."])
async def stale(shape):
"""Review round 2: a refused Manual try is not a request any more once
the user changed something or another mode ran. Another source then
shows the same value; Manual's adopt must log nothing."""
w = carmode.ManualWriter()
w.boot = False
drv, tr = Drv(ok=False), tracker()
async def step(a, now, mode=carmode.MANUAL, rev=1):
await w.step(drv, reading(state="C", allowed_a=a, setpoint_a=a,
phases_allowed=1), mode=mode,
want_a=6.0, want_phases=1, rev=rev, clamp=16.0, now=now,
tracker=tr, writing=True, status="charging")
n0 = LOG.mark()
await step(10.0, 100.0) # refused
if shape == "solar": # the user picks Solar, then Manual
w.user_changed()
await step(10.0, 200.0, mode=carmode.SOLAR, rev=2)
await step(6.0, 300.0, mode=carmode.SOLAR, rev=2) # Solar's own 6 A
w.user_changed()
await step(6.0, 500.0, rev=3)
elif shape == "off": # Off, the wallbox app sets 6 A
await step(10.0, 150.0, mode=carmode.OFF)
await step(6.0, 400.0, mode=carmode.OFF)
await step(6.0, 500.0)
else: # the user changed the value
w.user_changed()
await step(6.0, 500.0, rev=2)
return [m for lv, m, _x in LOG.rec[n0:]
if lv != "DEBUG" and m.startswith(SETP)]
for shape in ("solar", "off", "user"):
check(f"T23 Manual (review round 2, N2) [{shape}]: a refused try is not "
f"logged later when the same value comes from another source",
go(stale(shape)) == [])
async def t23l():
"""Review round 2: Solar's refused try is history once Solar is left;
a later read-back of that value logs nothing."""
w = carmode.SolarWriter()
drv, tr = Drv(ok=False), tracker()
w.engaged = True
n0 = LOG.mark()
await w._write(drv, 16.0, 0.0, 100.0, tr)
w._leave()
w._adopt(16.0)
return [m for _lv, m, _x in LOG.rec[n0:] if m.startswith(SETP)]
check("T23 (review round 2, N2) [solar leave]: a refused Solar try is not "
"logged after Solar is left: 0 lines", go(t23l()) == [])
# T33: shutdown, the charger refuses all 3 release tries.
async def _refuse_shutdown(p, c):
p.ch.refuse = "ignore"
await c.shutdown()
r33 = solar(300, finale=_refuse_shutdown)
check(f"T33: Solar shutdown, the charger refuses all 3 release tries: "
f"CHARGER_RELEASE unchanged once, 0 shutdown lines "
f"({texts(r33, lo=121)}, {len(warns(r33, 'CHARGER_RELEASE'))})",
len(warns(r33, "CHARGER_RELEASE")) == 1 and not texts(r33, lo=121)
and not [m for t, m in sets(r33) if "(shutdown)" in m])
# T37: stale charger reads with no write due.
r37 = solar(500, events={300: lambda p, c: p.ch.freeze(),
308: lambda p, c: p.ch.freeze(False)})
check(f"T37: a frozen charger reading for 8 s with no write due: 0 lines "
f"({texts(r37, lo=125)}, writes {wlist(r37)})",
not texts(r37, lo=125) and len(wlist(r37)) == 1)
# T39: a stuck (frozen) charger, Solar's starts are not taken.
r39 = solar(1300, events={100: lambda p, c: p.ch.freeze()})
check(f"T39: a stuck charger reading, the 3 starts not taken: 0 lines, the "
f"stuck CHARGER_REFUSED once, unchanged "
f"({texts(r39)}, {len(warns(r39, 'CHARGER_REFUSED'))}, "
f"{len([1 for t, v in S.writes(r39) if v > 0])} starts)",
not texts(r39) and len(warns(r39, "CHARGER_REFUSED")) == 1)
# N3: the line follows the write: nothing is logged before it returns.
async def n3():
w = carmode.ManualWriter()
drv, tr = Drv(), tracker()
n0 = LOG.mark()
await w._write(drv, 7.0, 10.0, 50.0, tr, **WHY)
rec = LOG.rec[n0:]
first = next((i for i, x in enumerate(rec) if x[1].startswith(SETP)),
10 ** 9)
return n0 + first, drv.marks[0]
at, ret = go(n3())
check(f"N3: the line is logged after write_current returned (record {at} vs "
f"the driver's return at {ret})", ret <= at < 10 ** 8)
# =========================================================================== #
print("\n7. START-UP, SHUTDOWN, WAYS OUT (T27-T30, T32, T34-T36, T38, T40)")
# =========================================================================== #
st27 = S.rig._Store()
st27.data["car_current"] = 6.0
r27 = run("manual", 120, store=st27, setpoint=10, phases=1, car_phases=1,
opts=MOPT)
check(f"T27: restart in Manual, stored 6 A, the charger shows 10 A: 1 mode "
f"line at start-up, exactly 1 line, 'start-up' "
f"({modes(r27)}, {texts(r27)})",
[m for _t, m in modes(r27)] == ["Car mode is now Manual."]
and texts(r27) == ["Car: set from 10 A to 6 A on 1 phase (start-up)."])
r28 = solar(400, setpoint=10)
check(f"T28: restart in Solar, the charger shows its own 10 A (D2): the mode "
f"line, the 0 A as 'start-up', the start current as 'Solar' "
f"({texts(r28)})",
[m for _t, m in modes(r28)] == ["Car mode is now Solar."]
and texts(r28) == ["Car: set from 10 A to 0 A on 1 phase (start-up).",
"Car: set from 0 A to 16 A on 1 phase (Solar)."])
st29 = S.rig._Store()
st29.data[ctl_car.CAR_EXIT_KEY] = True
r29 = run("off", 120, store=st29, setpoint=10, phases=1, car_phases=1,
opts=MOPT)
check(f"T29: restart in Off with the exit 0 A owed (C1), charger 10 A: the "
f"mode line Off and 1 line 'to 0 A (start-up)' "
f"({modes(r29)}, {texts(r29)})",
[m for _t, m in modes(r29)] == ["Car mode is now Off."]
and texts(r29) == ["Car: set from 10 A to 0 A on 1 phase (start-up)."])
r30 = run("off", 2000, events={1800: act("car_mode", "manual")}, setpoint=10,
phases=1, car_phases=1, opts=MOPT)
check(f"T30: restart in Off, nothing owed; 30 min later the user picks "
f"Manual: the start mode line once, the later write is 'Manual', not "
f"'start-up' ({modes(r30)}, {texts(r30)})",
[m for _t, m in modes(r30)] == ["Car mode is now Off.",
"Car mode is now Manual."]
and texts(r30) == ["Car: set from 10 A to 6 A on 1 phase (Manual)."])
check("T30: the Manual line is not 'start-up' even for the first write of "
"the process (M9)", bool(texts(r30))
and "start-up" not in " ".join(texts(r30)))
r32 = solar(300, finale=_shutdown)
check(f"T32: Solar shutdown, 0 A taken: 1 line 'to 0 A ... (shutdown)' "
f"({texts(r32, lo=121)}, {[t for t, m in sets(r32)]})",
[m for t, m in sets(r32) if t is None] == [
"Car: set from 16 A to 0 A on 1 phase (shutdown)."])
r34 = manual(205, events={200: act("car_phases", 3)}, car_phases=3, opts={},
finale=_shutdown)
check(f"T34: Manual shutdown in the middle of a phase change (abandon), the "
f"give-back taken: 1 line, 'shutdown' ({texts(r34, lo=200)})",
[m for t, m in sets(r34) if t is None] == [
"Car: set from 0 A to 6 A on 3 phases (shutdown)."])
r35 = solar(400, events={300: act("car_mode", "off")})
check(f"T35: Solar -> Off while Solar's 16 A stands: 1 mode line Off, 1 line "
f"'to 0 A (Solar)' (Q3), then nothing ({modes(r35)[-1:]}, "
f"{texts(r35, lo=300)})",
[m for _t, m in modes(r35)[-1:]] == ["Car mode is now Off."]
and texts(r35, lo=300) == [
"Car: set from 16 A to 0 A on 1 phase (Solar)."])
r36 = solar(400, events={300: act("car_mode", "manual")})
check(f"T36: Solar -> Manual (user 6 A, charger 16 A): 1 mode line and 1 line "
f"for Manual's 6 A, reason Manual ({modes(r36)[-1:]}, "
f"{texts(r36, lo=300)})",
[m for _t, m in modes(r36)[-1:]] == ["Car mode is now Manual."]
and texts(r36, lo=300) == [
"Car: set from 16 A to 6 A on 1 phase (Manual)."])
r38 = kshape("C", dur=1400, events={940: lambda p, c: setattr(p, "meter_on",
False)})
check(f"T38: the meter silent past meter_max_age_s: Solar's pause, exactly 1 "
f"line 'to 0 A (Solar)' ({texts(r38, lo=940)})",
texts(r38, lo=940) == [
"Car: set from 10 A to 0 A on 3 phases (Solar)."])
class Liar(SimCharger):
"""The read-back shows what was asked; the car draws a third more."""
def target_w(self):
w = super().target_w()
return w * 8.0 / 6.0 if self.setpoint_a == 6.0 else w
r40 = manual(120, sim=Liar(setpoint_a=10))
check(f"T40: the read-back shows 6 A but the car draws 8 A (1840 W): the line "
f"says 6 A, what was written ({texts(r40)}, car "
f"{round(r40['trace'][-1]['car'])} W)",
texts(r40) == ["Car: set from 10 A to 6 A on 1 phase (Manual)."]
and round(r40["trace"][-1]["car"]) == 1840)
# =========================================================================== #
print("\n8. NOTHING ELSE MOVES (T43-T45, N1, N2, N7, N8, N10, N11)")
# =========================================================================== #
# N5: a mode line only for a mode change (and the one at start-up).
chg4 = 1 + 1 # r4: the start, then Off -> Manual
check(f"N5: no mode line without a change: {len(modes(r4))} in r4 (start + "
f"the one change, six more same-mode or refused actions), "
f"{len(modes(r7))} in a 700 s Solar run with no action, "
f"{len(modes(r1))} in r1 (start + Manual, two same-value actions)",
len(modes(r4)) == chg4 and len(modes(r7)) == 1 and len(modes(r1)) == 2
and len(modes(r30)) == 2)
# N8: the existing warning and info texts are the base's, word for word.
# EV-54 (Q3) adds the refused peak cut's own text; the others are unchanged.
EXACT = {
"The charger did not take the current, so the add-on stops asking until "
"you change it: CHARGER_REFUSED.",
"The charger did not take the current, so the add-on stops asking until "
"you press Solar: CHARGER_REFUSED.",
"The charger did not take the peak cut, so the add-on tries again next "
"quarter: CHARGER_REFUSED.",
"The charger did not take the current, so the add-on tries again in 15 "
"min, then every 30 min: CHARGER_REFUSED.",
"The charger did not take 0 A before the add-on stopped, so the car may "
"still be charging: CHARGER_RELEASE.",
"Software fault: the add-on was about to ask the charger for more than "
"its limit, so nothing was sent: CHARGER_CLAMP.",
"Solar lowered the car for the peak: CAR_CUT.",
"The car kept drawing, so the phases were not changed."}
seen8 = {m for r in ALL for _t, lv, m in r["lines"] if lv != "DEBUG"
and ("CHARGER_" in m or "CAR_CUT" in m or "kept drawing" in m)}
check(f"N8: every CHARGER_* / CAR_CUT / kept-drawing line seen in any run is "
f"one of base's texts or EV-54's, and each of the eight was seen "
f"({sorted(seen8 - EXACT)[:2]}, missing {sorted(EXACT - seen8)[:2]})",
seen8 == EXACT)
# T44: the existing suites run unedited in CI (checks / unit) and were run
# here (the report lists them). What a unit row can pin: the two existing
# files this ticket had to touch still hold their own assertions and set
# aside ONLY the two new prefixes.
_here = os.path.dirname(os.path.abspath(__file__))
_t28 = open(os.path.join(_here, "test_ev28.py")).read()
_t51 = open(os.path.join(_here, "test_ev51.py")).read()
check("T44: test_ev28 and test_ev51 keep their pinned rows and filter only "
"'Car: set' and 'Car mode is now'",
'check(f"T13: a clean change logs nothing at INFO or above' in _t28
and "CAP.loud(MARK[0]) == []" in _t28
and "info == BASE_INFO" in _t51
and _t28.count('("Car: set", "Car mode is now")') == 1
and _t51.count('("Car: set", "Car mode is now")') == 1)
# Taken on the base build 02166e2 with EV52_GOLDEN=1 (the same scenarios).
_CAR1 = ["car current set to 8 by operator", "car current set to 8 by operator",
"car mode set to manual by operator", "car current set to 6 by operator",
"car phases set to 1 by operator"]
GOLDEN = {
"T1": {"cur": [(21, 6.0), (201, 8.0)], "events": _CAR1,
"keys": "bb1fe135bd15690c", "notes": [], "ph": [],
"sent": [6.0, 8.0]},
"T11": {"cur": [(21, 6.0), (201, 0.0), (212, 6.0)],
"events": ["car phases set to 3 by operator",
"car mode set to manual by operator",
"car current set to 6 by operator",
"car phases set to 1 by operator"],
"keys": "bb1fe135bd15690c", "notes": [], "ph": [(202, 3)],
"sent": [6.0, 0.0, 6.0]},
"T15": {"cur": [(121, 16.0), (961, 13.0), (967, 12.0), (997, 6.0)],
"events": [], "keys": "00425fef63358fa7",
"notes": [(13, "goodwe_integrator_bound"), (961, "goodwe_car_cut")],
"ph": [], "sent": [16.0, 13.0, 12.0, 6.0]},
"T28": {"cur": [(1, 0.0), (121, 16.0)], "events": [],
"keys": "642fc116d64d9487", "notes": [], "ph": [],
"sent": [0.0, 16.0]},
"T32": {"cur": [(121, 16.0), (300, 0.0)], "events": [],
"keys": "642fc116d64d9487", "notes": [], "ph": [],
"sent": [16.0, 0.0]},
"T7": {"cur": [(121, 16.0)], "events": [], "keys": "00425fef63358fa7",
"notes": [], "ph": [], "sent": [16.0]},
}
def view(r):
return {"cur": wlist(r), "ph": [(round(t), n) for t, n in
S.writes(r, "phases")],
"sent": list(r["c"].charger.sent),
"notes": [(round(t), n) for t, n in r["raised"]],
"events": [e[9:] for e in r["c"].events if e[9:].startswith("car ")],
"keys": K.digest(sorted(r["store"].data))}
SCEN = {"T1": r1, "T7": r7, "T11": r11, "T15": r15, "T28": r28, "T32": r32}
if os.environ.get("EV52_GOLDEN"):
import json
print("GOLDEN", json.dumps({k: view(v) for k, v in SCEN.items()},
sort_keys=True))
for k, r in SCEN.items():
check(f"T43/T45 {k}: the writes (value, second, phases), the notices, the "
f"action log and the store keys are those of the base build",
view(r) == GOLDEN.get(k))
check("N7: no new store key, notification or option (the key lists above are "
"base's)", all(view(r)["keys"] == GOLDEN.get(k, {}).get("keys")
for k, r in SCEN.items()))
bad = [m for r in ALL for _t, lv, m in r["lines"]
if m.startswith((SETP, MODEP)) and (
lv != "INFO" or re.search(r"number\.|select\.|sensor\.|http|token",
m))]
check(f"N10: every new line is INFO, with no entity id or secret ({bad[:2]})",
not bad)
n2 = []
for r in ALL:
sent = {v for _t, v in S.writes(r)} | set(
getattr(r["c"].charger, "sent", ()))
n2 += [m for _t, m in sets(r) if amps_in(m) not in sent]
check(f"N2: every line's value is a value the add-on sent ({n2[:2]})", not n2)
n11 = []
for r in ALL:
if r.get("sim") is None:
continue
n11 += [x for x in r["sim"].log if x[1] == "current" and x[2] > 16.0]
n11 += [x for x in r["sim"].log if x[1] == "phases" and x[3] >= 100.0
and x[4] > 0.0]
check(f"N1/N11: no write above the clamp and no select under load in any "
f"run ({n11[:2]})", not n11)
tb = [i for r in ALL if r is not r22
for _lv, _m, x in LOG.rec[r["n0"]:r["end"]] if x]
check(f"N9: no exception from the log path in any run but T22's own "
f"({len(tb)})", not tb)
report()
+577
View File
@@ -0,0 +1,577 @@
"""EV-54: after the quarter's refused cut tries, Solar's normal control goes
on, and the cut is tried again at the next quarter start while one is needed.
`python3 -B test_ev54.py`
Rows T1-T13 and T15-T23 of reports/EV-54-test-plan.md (T14 and T25-T35, the
drop rule, are in test_ev54_drop.py; T24 is the run of the existing files).
The real Controller on `tools/ev20_sun.py` through `tools/ev54_kit.py`;
Shape C is N=2, both batteries at 10 %, the car at 10 A on 3 phases, the
house 3000 W and the sun 0 from 960; the second period runs 900-1800.
"Refusal" is the charger ignoring a write ("ignore") or Home Assistant
refusing it ("error"). Golden values marked bdfd3e6 were taken on that tree
with `EV54_GOLDEN=1 python3 -B test_ev54.py`.
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
from app import carmode, messages # noqa: E402
from ev20_kit import LOG, check, fails, act, step_fn, const # noqa: E402
from ev21_kit import (ALARMS, digest, merge, shape, view_guard, # noqa: E402
view_writes, refuse_n1, set_resp)
from ev54_kit import (HOLD_TEXT, Q3_TEXT, W54, as_off, cut_writes, # noqa: E402
house_c, key_change, never54, refused_by_key, row,
rows, run, sun_c, t_lift, twin, window, writes,
dropped, first, nth, present)
n_log0 = LOG.mark()
TAKE = os.environ.get("EV54_GOLDEN") == "1"
CUT = messages.ID_CAR_CUT
GOLDEN = {
'T10 [C]': ('938225cc1dd6d8f8', 'ba8e36dfa3011013'),
'T10 [W]': ('dfb6d075dd1f2330', 'eec4c29653ce1e3e'),
'T10 [M]': ('385ae1fbf07b25d6', 'a52b1c929747cd07'),
'T11 [Manual]': ([(1601.0, 8.0), (1671.0, 8.0), (1741.0, 8.0)],
['WARNING']),
'T11 [Off]': [(1080.0, 0.0, False)],
}
got = {}
def golden(name, value):
got[name] = value
if TAKE:
print(f"GOLDEN {name!r}: {value!r},")
return GOLDEN.get(name)
def refused(r, t0=0, t1=1e9):
"""(t, a) of the refused cut tries in [t0, t1)."""
return [(t, a) for t, a, ok, _why, _k in cut_writes(r, t0, t1) if not ok]
def gaps(ts):
return [b - a for a, b in zip(ts, ts[1:])]
def near(t, want, lo, hi):
return t is not None and want - lo <= t <= want + hi
def amber(r, t0, t1, rid="charger_refused"):
return [x["t"] for x in r["trace"] if t0 <= x["t"] < t1
and rid in (x.get("amber") or [])]
def gave_up_at(r, t0=0, t1=1e9):
return [x["t"] for x in rows(r, t0, t1) if x["gave_up"]]
def roll_try(name, r, kc, n, *, value=0.0, taken_by=None, hold_s=0.0,
graded=True):
"""T4's bound: the new key's first try in its first cycle (at N=2 up to
max_hold_s before :00), then (if `taken_by`) the next try 60 s or more
later is taken, read back within 2 s, and (`graded`, T4's own row)
graded can-cut from that cycle (+1 s) with the CAR_CUT note once."""
w2 = [(t, a, ok) for t, a, ok, _w, _k in cut_writes(r, 1800 - hold_s - 1)]
t1 = nth(w2, 0)
lo = 1800 - (hold_s if n == 2 else 0) - 1
ok1 = present(t1) and lo <= t1[0] <= 1801 and abs(t1[1] - value) < 0.01 \
and present(kc) and abs(t1[0] - kc) <= 1
if taken_by is None:
check(f"{name}: the new key ({kc}) is tried in its first cycle "
f"({t1}, bound [{lo}, 1801]), as {value} A", ok1)
return
t2 = nth(w2, 1)
ok2 = present(t1, t2) and t2[2] and not t1[2] \
and t2[0] - t1[0] >= carmode.RETRY_S and t2[0] <= taken_by + 61
rb = [x["t"] for x in rows(r, t2[0] if present(t2) else 1e9)
if abs(x["rb"] - value) < 0.01]
can = [x["t"] for x in rows(r, t2[0] if present(t2) else 1e9)
if x["can"]]
cuts = [t for t, n_ in r["raised"] if n_ == CUT and t >= 1790]
check(f"{name}: the new key ({kc}) tried in its first cycle ({t1}, bound "
f"[{lo}, 1801]) and refused; the next try {t2} 60 s or more later "
f"is taken, read back by {first(rb)}, can-cut from {first(can)}; "
f"CAR_CUT once ({cuts})",
ok1 and ok2 and bool(rb) and rb[0] <= t2[0] + 2
and (not graded or (bool(can) and can[0] <= rb[0] + 1
and len(cuts) == 1)))
# =========================================================================== #
print("\n1. SOLAR GOES ON AFTER THE QUARTER'S TRIES (T1, T2, T3)")
# =========================================================================== #
T1R = {}
for kind in ("ignore", "error"):
r = run(house_c((1250, 900.0)), sun_c((1250, 9000.0)), dur=1800,
events=window({}, 959, 1100, kind))
T1R[kind] = r
tr = refused(r, 900, 1800)
ts = [t for t, _a in tr]
tl = t_lift(r, 1100, 1800)
nz = [(t, a, why) for t, a, ok, why in writes(r, (tl or 1e9) + 1,
(tl or 1e9) + 131)
if a > 0.0 and ok]
check(f"T1 [{kind}]: tries {tr}: 0 A at 960+-1, 1020+-2, 1080+-2, no "
f"4th in 900-1800",
len(tr) == 3 and all(a == 0.0 for _t, a in tr)
and near(nth(ts, 0), 960, 1, 1) and near(nth(ts, 1), 1020, 2, 2)
and near(nth(ts, 2), 1080, 2, 2))
check(f"T1 [{kind}]: the cap lifts at {tl} (1370+-2); the drop then: "
f"sent_a 10, taken, plan 10 ({dropped(r, tl or 0, 10.0)}); a "
f"non-zero Solar write within 130 s ({nz[:2]}); gave_up never "
f"({gave_up_at(r, 900, 1800)[:2]})",
near(tl, 1370, 2, 2) and dropped(r, tl or 0, 10.0) is not None
and bool(nz) and 6.0 <= nz[0][1] <= 16.0 and nz[0][2] == "Solar"
and not gave_up_at(r, 900, 1800))
never54(f"T1 [{kind}]", r)
ev2 = window({}, 959, None)
T2 = run(house_c(), sun_c(), dur=1800, events=ev2)
tr = refused(T2, 900, 1800)
ts = [t for t, _a in tr]
nz2 = [(t, a) for t, a, _ok, _why in writes(T2, 900, 1800) if a > 0.0]
caps = sorted({x["cap"] for x in rows(T2, 961, 1800)}, key=str)
check(f"T2: a cut needed all quarter: exactly 3 tries ({tr}), all 0 A, gaps "
f"{gaps(ts)} >= 60; no non-zero Solar write ({nz2[:2]}); the cap stays "
f"0 ({caps})",
len(tr) == 3 and all(a == 0.0 for _t, a in tr)
and all(g >= 60 for g in gaps(ts)) and not nz2 and caps == [0.0])
never54("T2", T2)
# T1 continued, in the next period: in 900-1800 the import of 960-1250 keeps
# the projection near the aim, so a sun drop there makes a new cut due, and
# with the quarter's tries used up none goes out (Q1). From 1800 the period
# is fresh: the sun falls to 7 A worth at 1900, under 6 A worth at 2000.
r = run(house_c((1250, 900.0)),
sun_c((1250, 9000.0), (1900, 5900.0), (2000, 4400.0)), dur=2350,
events=window({}, 959, 1100))
w3 = [(t, a, ok, why) for t, a, ok, why in writes(r, 1081, 2350)]
down = [x for x in w3 if 1900 <= x[0] <= 1932]
hold6 = [x for x in w3 if 2000 <= x[0] <= 2032 and x[1] == 6.0]
pause = [x for x in w3 if 2298 <= x[0] <= 2302 and x[1] == 0.0]
prev = [x for x in w3 if x[0] < 1900]
caps3 = [x["t"] for x in rows(r, 1800, 2350) if x["cap"] is not None]
check(f"T3: after the drop Solar follows the spare: a step-down by 1932 "
f"({down}), the 6 A hold by 2032 ({hold6}), the pause 0 A 'Solar' at "
f"2300+-2 ({pause}); all taken ({[x for x in w3 if not x[2]]}); no cut "
f"in that period ({caps3[:2]})",
bool(down) and bool(prev) and down[0][1] < prev[-1][1] and bool(hold6)
and bool(pause) and pause[0][3] == "Solar"
and all(x[2] for x in w3) and not caps3)
never54("T3", r)
# =========================================================================== #
print("\n2. THE NEXT QUARTER TRIES AGAIN (T4, T5, T6)")
# =========================================================================== #
T4R = {}
for n in (2, 1):
for kind in ("ignore", "error"):
r = run(house_c(), sun_c(), dur=1950, n=n,
events=window({}, 959, 1830, kind))
T4R[(n, kind)] = r
hold_s = r["c"].p1.averager.max_hold_s
rbk = refused_by_key(r)
kc = key_change(r, 1700, 1900)
k900 = [v for k, v in rbk.items() if k == row(r, 1000)["key"]] \
if present(row(r, 1000)) else []
check(f"T4 [N={n}, {kind}]: 3 refused tries in 900-1800 ({k900})",
bool(k900) and len(k900[0]) == 3)
roll_try(f"T4 [N={n}, {kind}]", r, kc, n, taken_by=1830,
hold_s=hold_s)
never54(f"T4 [N={n}, {kind}]", r)
T5R = {}
for tag, socs in (("both at 10 %", None), ("a 10 %, b 60 %",
{"a": 10.0, "b": 60.0})):
r = run(house_c(), sun_c(), dur=3600, socs=socs,
events=window({}, 959, None))
T5R[tag] = r
rbk = refused_by_key(r, 900, 3600)
per = sorted(len(v) for v in rbk.values())
allt = sorted(t for v in rbk.values() for t in v)
other = [(t, a) for t, a, ok, _why in writes(r, 900, 3600)
if t not in allt]
vals = sorted({a for t, a, ok, _w in writes(r, 900, 3600)})
check(f"T5 [{tag}]: refusal never lifted: exactly 3 tries in each of 3 "
f"quarter keys ({ {k: v for k, v in rbk.items()} }), all 0 A "
f"({vals}), gaps {gaps(allt)} >= 60 within and across; no other "
f"write ({other[:3]})",
per == [3, 3, 3] and vals == [0.0]
and all(g >= 60 for g in gaps(allt)) and not other)
never54(f"T5 [{tag}]", r)
r = run(house_c((1790, 900.0)), sun_c((1790, 9000.0)), dur=2700,
events=window({}, 959, 1900))
kc = key_change(r, 1700, 1900)
bad = [(t, a, why) for t, a, ok, why in writes(r, 1795, 2700)
if a == 0.0 or why == "peak cut"]
nxt = first(x for x in writes(r, (kc or 1e9) + 1, 2700))
check(f"T6: the new quarter starts under the aim: no 0 A and no 'peak cut' "
f"write from 1795 ({bad[:3]}); the drop at the key change {kc} "
f"(1800+-2): {dropped(r, kc or 0, 10.0)}; the next write a normal one "
f"({nxt})",
not bad and near(kc, 1800, 2 + r["c"].p1.averager.max_hold_s, 2)
and dropped(r, kc or 0, 10.0) is not None
and (nxt is None or not present(nxt) or nxt[3] == "Solar"))
never54("T6", r)
# =========================================================================== #
print("\n3. AS OFF WHILE THE CUT IS REFUSED (T7)")
# =========================================================================== #
for name, r, win in (
("T1 [ignore]", T1R["ignore"], (961, 1360)),
("T2", T2, (961, 1800)),
("T4 [N=2, ignore]", T4R[(2, "ignore")], (961, 1855)),
("T5 [both at 10 %]", T5R["both at 10 %"], (961, 3600))):
as_off(f"T7 {name}", r, twin(r), ALARMS, refused=win)
evw = merge(window({}, 959, 1830), 900, set_resp(20.0))
r = run(house_c(), sun_c(), dur=1900, socs={"a": 60.0, "b": 60.0},
events=evw)
as_off("T7 [Shape W, refusal 959-1830]", r, twin(r, {900: set_resp(20.0)}),
ALARMS, refused=(961, 1800))
never54("T7 [Shape W]", r)
# =========================================================================== #
print("\n4. THE NOTICE (T8) AND SOLAR'S OWN REFUSED WRITE (T9)")
# =========================================================================== #
for name, r, t1 in (("T2", T2, 1800), ("T5", T5R["both at 10 %"], 3600)):
ts = [t for t, _a in refused(r, 900, 1800)]
q3 = r["w"].lines(Q3_TEXT)
q3w = [(t, lv) for t, lv, _m in q3 if lv == "WARNING"]
old = [t for t, _lv, _m in r["w"].lines("until you press Solar")]
amb = amber(r, (nth(ts, 2) if present(nth(ts, 2)) else 1e9) + 1, 1800)
want_amb = list(range(int(nth(ts, 2)) + 1, 1800)) \
if present(nth(ts, 2)) else [None]
check(f"T8 [{name} run]: at the 3rd refused try ({nth(ts, 2)}) one WARNING "
f"'{Q3_TEXT}' ({q3w}) over the run (DEBUG after: "
f"{[(t, lv) for t, lv, _m in q3 if lv != 'WARNING'][:3]}); no "
f"'until you press Solar' ({old[:2]}); the amber row from the 3rd "
f"try to 1800 ({len(amb)} of {len(want_amb)} s); gave_up never "
f"({gave_up_at(r)[:2]})",
len(q3w) == 1 and present(nth(ts, 2))
and abs(q3w[0][0] - nth(ts, 2)) <= 1 and not old
and [float(t) for t in want_amb] == amb and not gave_up_at(r))
r = run(const(900.0), step_fn((1000, 6700.0), base=7900.0), dur=1900,
events=window({}, 999, None))
w9 = writes(r, 999, 1900)
hold = [(t, lv) for t, lv, _m in r["w"].lines(HOLD_TEXT)]
third = nth(w9, 2)
amb = amber(r, (third[0] if present(third) else 1e9) + 1, 1900)
check(f"T9: Solar's own step-down refused 3 times ({w9[:5]}): the existing "
f"'{HOLD_TEXT}' once ({hold}), the amber row after it ({len(amb)} s), "
f"no write after the 3rd, also across 1800 ({w9[3:5]})",
len(w9) == 3 and all(not ok for _t, _a, ok, _w in w9)
and len({a for _t, a, _o, _w in w9}) == 1 and len(hold) == 1
and hold[0][1] == "WARNING" and len(amb) >= 1800 - third[0] - 2)
never54("T9", r)
# =========================================================================== #
print("\n5. A CHARGER THAT TAKES THE CUT; MANUAL AND OFF (T10, T11)")
# =========================================================================== #
for kind in ("C", "W", "S", "F", "M"):
rec = W54()
r = shape(kind, dur=1300, on_cycle=rec)
r["w"] = rec
cw = cut_writes(r, 950)
vals = [a for _t, a, _ok, _w, _k in cw]
check(f"T10 [{kind}]: the charger takes the cut: one write per value, "
f"each taken, no retry ({[(t, a, ok) for t, a, ok, _w, _k in cw]})",
all(ok for _t, _a, ok, _w, _k in cw)
and len(vals) == len(set(vals)))
if kind in ("C", "W", "M"):
d = (digest(view_writes(r)), digest(view_guard(r)))
want = golden(f"T10 [{kind}]", d)
check(f"T10 [{kind}]: view_writes and view_guard as bdfd3e6 "
f"({d} vs {want})", d == want)
import opt11_identity as rig # noqa: E402
st = rig._Store()
st.data["car_current"], st.data["car_phases"] = 10.0, 3
evm = window({1600: act("car_current", 8)}, 1599, None)
r = run(house_c(), sun_c(), dur=1900, mode="manual", store=st, events=evm)
wm = [(x[0], x[2]) for x in r["sim"].log if x[1] == "current"
and x[0] >= 1590]
mt = [lv for _t, lv, _m in r["w"].lines(
"stops asking until you change it: CHARGER_REFUSED.")]
d = (wm, mt)
want = golden("T11 [Manual]", d)
check(f"T11 [Manual]: a change refused 3 times ({wm}), then the roll at "
f"1800: no 4th; the Manual text once ({mt}); as bdfd3e6 ({want})",
len(wm) == 3 and mt == ["WARNING"] and d == want)
evo = window({1030: act("car_mode", "off")}, 959, None)
r = run(house_c(), sun_c(), dur=1300, events=evo)
wo = [(t, a, ok) for t, a, ok, _w in writes(r, 1025)]
want = golden("T11 [Off]", wo)
check(f"T11 [Off]: Solar left to Off during a refused cut: Off's way-out "
f"0 A writes {wo} as bdfd3e6's ({want})", wo == want and bool(wo))
# =========================================================================== #
print("\n6. AN UNTRUSTED CAR (T12), A SILENT METER (T13)")
# =========================================================================== #
def no_energy(p, c):
p.ch.no_energy = True
ev12 = window({950: no_energy}, 959, 1830)
r = run(house_c(h=9000.0), sun_c(), dur=1950, events=ev12)
tr = refused(r, 900, 1795)
check(f"T12: an untrusted car figure: the cut is 0 A, 3 tries in 900-1800 "
f"({tr})", len(tr) == 3 and all(a == 0.0 for _t, a in tr))
roll_try("T12", r, key_change(r, 1700, 1900), 2, taken_by=1830,
hold_s=r["c"].p1.averager.max_hold_s, graded=False)
o = twin(r, {950: no_energy})
a_r = first(t for t, n in r["raised"] if n in ALARMS and t >= 900)
a_o = first(t for t, n in o["raised"] if n in ALARMS and t >= 900)
check(f"T12: the alarm at the Off twin's second +2 ({a_r} vs {a_o})",
present(a_r, a_o) and a_r is not None and a_o is not None
and abs(a_r - a_o) <= 2)
never54("T12", r)
def silent(on):
def f(p, c):
p.meter_on = not on
return f
seen13 = []
def fresh13(p, c):
"""Before the cycle (a refused write's read-back wait moves the model
clock inside it): is the meter fresh for the cut (N9)?"""
seen13.append((p.t, c._car_cut_meter_fresh()))
ev13 = window({1780: silent(True), 1900: silent(False)}, 959, None)
for t in range(1781, 1900):
ev13 = merge(ev13, t, fresh13)
r = run(house_c(), sun_c(), dur=2000, events=ev13)
# The bound is EV-21's N9 (`_car_cut_meter_fresh`): stale_input_s, or
# meter_max_age_s on `ha_signed` (the harness's meter source).
stale_t = first(t for t, ok in seen13 if not ok)
dark = [(t, a) for t, a, _ok, _w in writes(r, stale_t or 1e9, 1900)]
nxt = first((t, a) for t, a, _ok, _w in writes(r, 1900))
k2 = [len(v) for k, v in refused_by_key(r, 1795).items()]
check(f"T13: the meter silent 1780-1900, stale for the cut (N9) from "
f"{stale_t}: no try while stale ({dark}); the first try at {nxt} "
f"(within [1900, 1902]); at most 3 in the new key ({k2})",
present(stale_t) and stale_t is not None and stale_t < 1860
and not dark and present(nxt) and nxt is not None
and 1900 <= nxt[0] <= 1902 and all(k <= 3 for k in k2))
never54("T13", r)
# =========================================================================== #
print("\n7. A RAISING WRITE (T15), A RESTART (T16), THE KEY (T17)")
# =========================================================================== #
calls15 = []
def boom(p, c):
drv = c.charger
drv._ev54_wc = drv.write_current
async def wc(a, **kw):
calls15.append((p.t, a))
raise RuntimeError("EV-54 T15: the write raised")
drv.write_current = wc
def unboom(p, c):
c.charger.write_current = c.charger._ev54_wc
m15 = LOG.mark()
r = run(house_c(), sun_c(), dur=1950, events={959: boom, 1830: unboom})
c1 = [t for t, _a in calls15 if t < 1795]
c2 = [t for t, _a in calls15 if t >= 1795]
step_w = [m for m in LOG.since(m15, "ERROR") + LOG.since(m15, "WARNING")
if "charger step failed" in m]
tb15 = LOG.tracebacks(m15)
kc = key_change(r, 1700, 1900)
taken2 = [(t, a) for t, a, ok, _w in writes(r, 1830) if ok and a == 0.0]
check(f"T15: a write that raises counts as a refused try: {c1} in 900-1800 "
f"(3, >= 60 s apart), never once per cycle; the new key's try at "
f"{c2[:1]} (key {kc}), the next taken {taken2[:1]}; step-failed "
f"warnings {len(step_w)} (<= 1), Tracebacks {len(tb15)}",
len(c1) == 3 and all(g >= 60 for g in gaps(c1)) and bool(c2)
and present(kc) and kc is not None and abs(c2[0] - kc) <= 1
and bool(taken2) and taken2[0][0] - c2[0] >= 60
and len(step_w) <= 1 and not tb15)
r1 = run(house_c(), sun_c(), dur=1050, events=window({}, 959, None))
r2 = run(house_c(), sun_c(), t0=1050.0, dur=850, sim=r1["sim"],
store=r1["store"], plug=False, events={1830: lambda p, c:
setattr(p.ch, "refuse",
None)})
w16 = [(t, a, ok, why) for t, a, ok, why in writes(r2, 1050, 1795)]
ts = [t for t, _a, _ok, _w in w16]
keys = [k for k in r1["store"].data if "cut" in str(k).lower()
or "tries" in str(k).lower()]
check(f"T16: 2 refused tries, then a restart at 1050: D2's 0 A at 1050+-1 "
f"'start-up' ({w16[:1]}); its retries >= 60 s apart ({gaps(ts)}), at "
f"most 3 in 1050-1800 ({len(w16)}); no store key holds a count "
f"({keys})",
bool(w16) and near(w16[0][0], 1050, 1, 1) and w16[0][1] == 0.0
and w16[0][3] == "start-up" and all(g >= 60 for g in gaps(ts))
and len(w16) <= 3 and all(a == 0.0 for _t, a, _o, _w in w16)
and not keys)
roll_try("T16", r2, key_change(r2, 1700, 1900), 2, taken_by=1830,
hold_s=r2["c"].p1.averager.max_hold_s)
never54("T16", r2)
def none_proj(p, c):
orig = c._car_cut_tick
def tick(proj, guard, target, mono):
if 1801 <= p.t <= 1803:
proj = None
return orig(proj, guard, target, mono)
c._car_cut_tick = tick
r = run(house_c(), sun_c(), dur=2700, events=window({1795: none_proj},
959, None))
rbk = refused_by_key(r, 1700, 2700)
keyed = {k: v for k, v in rbk.items() if k is not None}
check(f"T17 (a): the early roll, then no projection 1801-1803, then fresh: "
f"the count reset once ({keyed}: exactly 3 in the new key, the first "
f"at the roll)",
len(keyed) == 1 and [len(v) for v in keyed.values()] == [3])
never54("T17 (a)", r)
def jump(dt):
def f(p, c):
p.utc_off = dt
return f
r = run(house_c(), sun_c(), dur=2000, events=window({1790: jump(-3600.0)},
959, None))
allt = sorted(t for t, _a, ok, _w in writes(r, 900) if not ok)
check(f"T17 (b): the wall clock jumps -3600 s at 1790: tries {allt} stay "
f">= 60 s apart on the monotonic clock",
bool(allt) and all(g >= 60 for g in gaps(allt)))
never54("T17 (b)", r)
# =========================================================================== #
print("\n8. A PHASE CHANGE (T18), A LATE TAKE (T19), COVER OFF (T20)")
# =========================================================================== #
kw18 = dict(n=2, opts={"ev_phases": "auto"}, phases=1)
r0 = run(const(900.0), const(9280.0), dur=700, **kw18)
log0 = r0["c"].car_solar.log
sel = [t for k, _a, t, _ok in log0 if k == "phases"]
zb = [t for k, a, t, _ok in log0 if k == "current" and a == 0.0
and sel and t <= sel[0]]
tb = int(nth(zb, -1)) if present(nth(zb, -1)) else 400
q1 = (tb // 900 + 1) * 900
ev18 = window({}, tb - 1, None)
r = run(step_fn((tb + 1, 9280.0 + 3400.0 + 2000.0), base=900.0),
const(9280.0), dur=q1 + 100, events=ev18, **kw18)
ph = [(t, n, ok) for k, n, t, ok in r["c"].car_solar.log
if k == "phases" and t >= tb - 1]
nz = [(t, a) for t, a, _ok, _w in writes(r, tb - 1) if a > 0.0]
cw = [(t, a, ok) for t, a, ok, _w, k in cut_writes(r, tb - 1, q1)]
sw = [x["t"] for x in rows(r, tb + 5, q1) if x["switch"]]
nq = first((t, a) for t, a, _ok, _w, _k in cut_writes(r, q1 - 15))
check(f"T18: Solar's own change sent its 0 A at {tb}, the cut due from "
f"{tb + 1}, the charger refusing: no select ({ph}), no closing current "
f"({nz[:2]}); at most 3 cut tries in the quarter ({cw}); the plan's "
f"switch ended ({sw[:2]}); the next quarter's try {nq} is 0 A",
bool(zb) and not ph and not nz and 1 <= len(cw) <= 3 and not sw
and present(nq) and nq is not None and nq[1] == 0.0)
never54("T18", r)
def late_take(p, c):
p.ch.refuse = None
p.ch.set_current(0)
r = run(house_c(), sun_c(), dur=1300, events=window({1110: late_take},
959, None))
set_l = [(t, m) for t, _lv, m in r["w"].lines("Car: set") if t >= 900]
after3 = [(t, a) for t, a, _ok, _w in writes(r, 1081)]
can = [x["t"] for x in rows(r, 1110) if x["can"]]
cuts = [t for t, n in r["raised"] if n == CUT]
new_ref = [t for t, _lv, _m in r["w"].lines("CHARGER_REFUSED") if t >= 1100]
check(f"T19: the charger shows 0 A at 1110 after the 3rd try: one 'Car: set "
f"from 10 A to 0 A (peak cut).' at 1110+-1 ({set_l}); no further try "
f"({after3}); can-cut from {can[:1]}; CAR_CUT once ({cuts}); no new "
f"CHARGER_REFUSED ({new_ref})",
len(set_l) == 1 and near(set_l[0][0], 1110, 1, 1)
and set_l[0][1] == "Car: set from 10 A to 0 A on 3 phases (peak cut)."
and not after3 and bool(can) and can[0] <= 1111 and len(cuts) == 1
and not new_ref)
r = run(house_c(), sun_c(), dur=1950, opts={"ev_batt_cover": False},
events=window({}, 959, 1830))
tr = refused(r, 900, 1795)
check(f"T20: the cover off: the cut at once at 960+-1 and 3 tries in "
f"900-1800 ({tr})", len(tr) == 3 and near(tr[0][0], 960, 1, 1))
roll_try("T20", r, key_change(r, 1700, 1900), 2, taken_by=1830,
hold_s=r["c"].p1.averager.max_hold_s, graded=False)
never54("T20", r)
# =========================================================================== #
print("\n9. TWO EPISODES (T21), A 50 W CAR (T22), A PRESS (T23)")
# =========================================================================== #
r = run(house_c(), sun_c((961, 9000.0), (1400, 0.0)), dur=1700,
opts={"ev_start_min": 1}, events=window({}, 959, 1800))
tr = refused(r, 900, 1800)
ts = [t for t, _a in tr]
tl = t_lift(r, 961, 1300)
check(f"T21: episode 1 (lifted at {tl}) and episode 2 from 1400 share the "
f"quarter's 3 refused tries ({tr}): 960, 1020, then 1400+-1; none "
f"after", len(tr) == 3 and near(nth(ts, 2), 1400, 0, 1)
and present(tl) and tl is not None and nth(ts, 1) < tl)
never54("T21", r)
def car50(p, c):
p.ch.target_w = lambda: 50.0
ev22 = window({900: car50}, 959, None)
r = run(house_c(h=9000.0), sun_c(), dur=1800, events=ev22)
o = twin(r, {900: car50})
a_r = first(t for t, n in r["raised"] if n in ALARMS and t >= 900)
a_o = first(t for t, n in o["raised"] if n in ALARMS and t >= 900)
tr = refused(r, 900, 1800)
check(f"T22: a 50 W car on 10 A: the house alarm at the Off twin's second "
f"({a_r} vs {a_o}); tries {tr} (<= 3)",
present(a_r, a_o) and a_r is not None and a_o is not None
and abs(a_r - a_o) <= 2 and len(tr) <= 3)
never54("T22", r)
for tag, ev in (("Solar pressed at 1100", {1100: act("car_mode", "solar")}),
("Off at 1100, Solar at 1200",
{1100: act("car_mode", "off"),
1200: act("car_mode", "solar")})):
r = run(house_c(), sun_c(), dur=1950, events=window(ev, 959, 1830))
tr = refused(r, 900, 1795)
check(f"T23 [{tag}]: no 4th cut try in 900-1800 ({tr})", len(tr) == 3)
roll_try(f"T23 [{tag}]", r, key_change(r, 1700, 1900), 2,
taken_by=1830, hold_s=r["c"].p1.averager.max_hold_s)
never54(f"T23 [{tag}]", r)
tb_all = LOG.tracebacks(n_log0)
check(f"N13: no traceback in this file's runs ({tb_all[:1]})", not tb_all)
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)
+702
View File
@@ -0,0 +1,702 @@
"""EV-54: the drop rule. A cut value the charger did not take is never sent
again once no cut stands: Solar takes the read-back as its own (sent, taken,
the plan's current), and the next cut try is a new episode's.
`python3 -B test_ev54_drop.py`
Rows T14 and T25-T35 of reports/EV-54-test-plan.md (G1-G6, QA, QB, QC) and
the writer-level replay of the formal check's C4. The real Controller on
`tools/ev20_sun.py` through `tools/ev54_kit.py`; Shape C as in test_ev54.py.
Golden values marked bdfd3e6 were taken on that tree with
`EV54_GOLDEN=1 python3 -B test_ev54_drop.py`.
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import asyncio
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
import ev20_sun as S # noqa: E402
from app import carmode, messages # noqa: E402
from ev20_kit import LOG, check, fails, act, step_fn # noqa: E402
from ev21_kit import ALARMS, NoGive, refuse_n1, merge, set_resp # noqa: E402
from ev54_kit import (HOLD_TEXT, as_off, cut_writes, dropped, first, # noqa: E402
house_c, key_change, never54, nth, present,
refused_by_key, row, rows, run, sun_c, t_lift, twin,
window, writes)
n_log0 = LOG.mark()
TAKE = os.environ.get("EV54_GOLDEN") == "1"
CUT = messages.ID_CAR_CUT
GOLDEN = {
'T35 (b)': [],
'T35 (c)': ([(1020.0, 0.0, True)],
['Car: set from 10 A to 0 A on 3 phases (peak cut).']),
'T38': [],
}
def golden(name, value):
if TAKE:
print(f"GOLDEN {name!r}: {value!r},")
return GOLDEN.get(name)
def refused(r, t0=0, t1=1e9):
return [(t, a) for t, a, ok, _why, _k in cut_writes(r, t0, t1) if not ok]
def near(t, want, lo, hi):
return t is not None and present(t) and want - lo <= t <= want + hi
def gave_up_at(r, t0=0, t1=1e9):
return [x["t"] for x in rows(r, t0, t1) if x["gave_up"]]
def stick(p, c):
"""The charger's reading freezes and the tracker's stuck check is armed
now: a stuck verdict STUCK_S later (chargers.py), as after a write."""
p.ch.freeze()
c.car.armed_at = float(p.t)
c.car.armed_sig = c.car.sig
def unstick(a):
"""The reading moves again and shows `a` A; the charger takes writes."""
def f(p, c):
p.ch.freeze(False)
p.ch.refuse = None
p.ch.set_current(a)
return f
def held(t0, t1):
"""The charger's read fails t0-t1 (under stale_input_s: held reads)."""
return {t0: lambda p, c: p.ch.go_unavailable(),
t1: lambda p, c: p.ch.go_unavailable(False)}
# =========================================================================== #
print("\n1. QA + QC: A STUCK READING AND THE LIFT (T14, T34, T35 (a))")
# =========================================================================== #
# The car's high import is short (960-1010) so the start rule's projection,
# with the start power counted while the car figure is untrusted, lifts the
# cap inside the stuck spell (from 1100).
ev14 = dict(held(1015, 1025))
ev14.update({1040: stick, 1600: unstick(9)})
ev14 = window(ev14, 959, None)
r = run(house_c((1010, 900.0)), sun_c((1010, 16000.0), (1600, 4900.0)),
dur=1950, events=ev14)
w14 = writes(r, 900, 1950)
tr = refused(r, 900, 1300)
ts = [t for t, _a in tr]
heldw = [(t, a) for t, a, _ok, _w in writes(r, 1015, 1025)]
tl = t_lift(r, 1100, 1600)
stuck_from = first(x["t"] for x in rows(r, 1040) if x["stuck"])
check(f"T14: tries {tr}: 0 A at 960, at the first real read after the held "
f"reads 1015-1025, then 60 s on; none while held ({heldw})",
len(tr) == 3 and near(nth(ts, 0), 960, 1, 1)
and near(nth(ts, 1), 1025, 0, 2) and not heldw
and nth(ts, 2) - nth(ts, 1) >= 60 if len(tr) == 3 else False)
pre = [(t, a) for t, a, _ok, _w in writes(r, 1090, tl or 1e9)]
check(f"T14: stuck from {stuck_from}, the cap standing to {tl}: no 0 A from "
f"the stuck path while the tries are used up ({pre})",
present(stuck_from) and tl is not None and stuck_from < tl and not pre)
sw = [(t, a, ok, why) for t, a, ok, why in writes(r, tl or 1e9, 1600)]
hold = [(t, lv) for t, lv, _m in r["w"].lines(HOLD_TEXT)]
nodrop = [x["t"] for x in rows(r, (tl or 1e9), 1600)
if x["sent"] != 0.0 or x["taken"]]
cf = sorted({x["cut_fails"] for x in rows(r, (tl or 1e9), 1600)}, key=str)
check(f"T14 (QA b, QC 1): after the lift at {tl}, while stuck: the fault "
f"path's 0 A 3 times, 60 s apart, reason Solar, refused ({sw}); not "
f"cut tries (count {cf}); at the 3rd gave_up and the hold path's text "
f"once ({hold}); no drop while stuck ({nodrop[:3]})",
len(sw) == 3 and all(a == 0.0 and not ok and why == "Solar"
for _t, a, ok, why in sw)
and near(sw[0][0], tl or 0, 0, 2) and near(sw[1][0], sw[0][0], -58, 62)
and near(sw[2][0], sw[1][0], -58, 62) and cf == [3]
and len(hold) == 1 and near(hold[0][0], sw[2][0], 1, 1)
and hold[0][1] == "WARNING" and bool(gave_up_at(r, sw[2][0], 1600))
and not nodrop if len(sw) == 3 else False)
d14 = dropped(r, 1600, 9.0)
gu = [x["t"] for x in rows(r, d14 or 1e9, 1950) if x["gave_up"]]
pause = [(t, a, ok, why) for t, a, ok, why in writes(r, 1890, 1910)
if a == 0.0]
check(f"T14 (QA a): the first good reading 1600 shows 9 A: the drop at "
f"{d14} with sent_a 9 (not the frozen 10), taken, plan 9, gave_up "
f"cleared ({gu[:2]}); Solar resumes: the pause 0 A, Solar, taken, at "
f"1900+-2 ({pause})",
near(d14, 1600, 0, 2) and not gu and len(pause) == 1
and near(pause[0][0], 1900, 2, 2) and pause[0][2]
and pause[0][3] == "Solar")
never54("T14", r)
ev34 = window({1040: stick, 2400: unstick(9)}, 959, None)
r = run(house_c((1010, 900.0)), sun_c((1010, 16000.0)), dur=2500, n=2,
events=ev34)
tl = t_lift(r, 1100, 2400)
sw = [(t, a, ok, why) for t, a, ok, why in writes(r, tl or 1e9, 2400)]
hold = [(t, lv) for t, lv, _m in r["w"].lines(HOLD_TEXT)]
gu = [x["t"] for x in rows(r, (nth(sw, 2)[0] if present(nth(sw, 2))
else 1e9) + 1, 2400) if not x["gave_up"]]
d34 = dropped(r, 2400, 9.0)
up = [(t, a, why) for t, a, ok, why in writes(r, 2401, 2500)
if a > 10.0 and ok]
check(f"T34 (QC 1): stuck 1040-2400, across the roll: after the lift at "
f"{tl} the stuck 0 A 3 times ({sw}), then gave_up and one hold-path "
f"WARNING ({hold}); nothing to 2400, also at the roll; gave_up stands "
f"({gu[:2]}); the drop at {d34} (2400+-2, the good reading 9 A); a "
f"step-up > 10 A, Solar, in [2430, 2460] ({up[:1]})",
len(sw) == 3 and len(hold) == 1 and not gu and near(d34, 2400, 0, 2)
and bool(up) and 2430 <= up[0][0] <= 2460 and up[0][1] <= 16.0
and up[0][2] == "Solar"
and not [x for x in rows(r, d34 or 0, 2500) if x["gave_up"]])
never54("T34", r)
st35 = {"lift": None, "prev": None}
def lift_watch(p, c, t):
"""T35 (a): 30 s after the lift the charger takes writes and its reading
follows again (the stuck verdict stands until it moves)."""
cap = (getattr(c, "_cut", None) or {}).get("cap")
if st35["lift"] is None and st35["prev"] is not None and cap is None \
and t > 1100:
st35["lift"] = t
st35["prev"] = cap
if st35["lift"] is not None and t == st35["lift"] + 29:
p.ch.refuse = None
p.ch.freeze(False)
r = run(house_c((1010, 900.0)), sun_c((1010, 16000.0)), dur=1600,
events=window({1040: stick}, 959, None), on_cycle=lift_watch)
tl = st35["lift"]
sw = [(t, a, ok, why) for t, a, ok, why in writes(r, tl or 1e9, 1600)
if a == 0.0]
lines = [(t, m) for t, _lv, m in r["w"].lines("Car: set") if t >= 900
and " to 0 A" in m]
pk = [(t, m) for t, _lv, m in r["w"].lines("peak cut") if t >= (tl or 0)]
check(f"T35 (a) (QC 2): the stuck 0 A after the lift at {tl}: refused, then "
f"taken at the 2nd try ({sw}), reason Solar; one 'Car: set from 10 A "
f"to 0 A ... (Solar).' ({lines}); no 'peak cut' line after the lift "
f"({pk})",
len(sw) == 2 and not sw[0][2] and sw[1][2]
and all(why == "Solar" for _t, _a, _o, why in sw)
and [m for _t, m in lines]
== ["Car: set from 10 A to 0 A on 3 phases (Solar)."] and not pk
if len(sw) == 2 else False)
never54("T35 (a)", r)
# =========================================================================== #
print("\n2. G1: A NEW QUARTER'S CUT WAIT (T25)")
# =========================================================================== #
class GiveFrom(S.SunPlant):
"""The battery gives nothing until 1800, then what it is asked, slowly
(its 20 s response from 1790): headroom at the new quarter, not used
within its first seconds."""
def batt_of(self, u, at):
v = super().batt_of(u, at)
return min(v, 0.0) if at < 1800 else v
def free(p, c):
c.batt_refused = 0
for tag, car_sun, s in (("0 A", 5830.0, 0.0), ("6 A", 7900.0, 1900.0)):
a0 = 7.0 if tag == "0 A" else 10.0
ev = {t: refuse_n1 for t in range(0, 1795)}
for t in range(1795, 1830):
ev = merge(ev, t, free)
ev = window(merge(ev, 1790, set_resp(20.0)), 959, 1810)
r = run(house_c(h=900.0), step_fn((960, s), base=car_sun), dur=1900,
n=1, socs={"a": 60.0}, events=ev, plant_cls=GiveFrom,
rows=False)
tr = refused(r, 900, 1800)
d = dropped(r, 1800, a0)
wait = [x["t"] for x in rows(r, 1800, 1830) if x["wait"] is not None]
inwait = [(t, a) for t, a, _ok, _w in writes(r, 1800, 1830)
if t <= (wait[-1] if wait else 1e9)]
cw = [(t, a, ok, why) for t, a, ok, why, _k in cut_writes(r, 1800, 1830)]
c1 = nth(cw, 0)
rb = [x["t"] for x in rows(r, c1[0] if present(c1) else 1e9)
if present(c1) and abs(x["rb"] - c1[1]) < 0.01]
cuts = [t for t, n in r["raised"] if n == CUT and t >= 1800]
want = 0.0 if tag == "0 A" else 6.0
check(f"T25 [{tag}] (G1): 3 refused tries in 900-1800 ({tr}); the drop "
f"at {d} (1800+-2: sent_a {a0}, taken, plan {a0}); the wait "
f"{wait[:1]}..{wait[-1:]} with no write in it ({inwait}); then the "
f"cut try {c1} ({want} A, peak cut, taken) after the wait, read "
f"back by {rb[:1]}, CAR_CUT once ({cuts})",
len(tr) == 3 and near(d, 1800, 0, 2) and bool(wait)
and not inwait and present(c1) and c1[0] > wait[-1]
and c1[0] <= 1817 and c1[1] == want and c1[2]
and c1[3] == "peak cut" and bool(rb) and rb[0] <= c1[0] + 2
and len(cuts) == 1 if wait else False)
never54(f"T25 [{tag}]", r)
# =========================================================================== #
print("\n3. G2, G3: THE LIFT (T26, T27, T28) AND THE C4 REPLAY")
# =========================================================================== #
r = run(house_c((1250, 900.0)), sun_c((1250, 9000.0)), dur=2700,
events=window({}, 959, 1300))
tl = t_lift(r, 1100, 1800)
d = dropped(r, tl or 0, 10.0)
paused = [x["t"] for x in rows(r, tl or 1e9, (tl or 1e9) + 30)
if x["plan"] < 6.0 or x["plan_why"] == "paused"]
z = [(t, ok) for t, a, ok, _w in writes(r, 1081, 2700) if a == 0.0]
up = [(t, a, why) for t, a, ok, why in writes(r, (tl or 1e9) + 30,
(tl or 1e9) + 61) if a > 10.0]
nxt = first((t, a, why) for t, a, _ok, why in writes(r, 1081, 2700))
check(f"T26 (G2): the lift at {tl} (1370+-2): the drop {d} (plan 10, not "
f"paused {paused[:2]}, so '0 A first' does not clear its start count); "
f"no 0 A after the 3rd try ({z[:2]}); then the first write {nxt} is a "
f"step-up > 10 A, Solar, in [t_lift+30, t_lift+60] ({up[:1]})",
near(tl, 1370, 2, 2) and d is not None and not paused and not z
and bool(up) and up[0][1] <= 16.0 and up[0][2] == "Solar"
and present(nxt) and nxt == up[0])
never54("T26", r)
for tag, H in (("6 A", 12500.0), ("0 A", 16000.0)):
ev = {t: refuse_n1 for t in range(0, 2701)}
ev = window(ev, 1699, 1900)
# The period sits near the aim (EV-21's near_end): the house steps at
# 1700 for 5 s (100 s left, so the cut is at once), the cut stands;
# it lifts only at the period's end, with tries left.
house = step_fn((900, 3350.0), (1500, 900.0), (1700, H), (1705, 900.0),
base=900.0)
sun = step_fn((900, 0.0), (1500, 7900.0), (1700, 7000.0), base=7900.0)
r = run(house, sun, dur=2700, n=1, socs={"a": 60.0}, events=ev,
plant_cls=NoGive, rows=False)
want = 6.0 if tag == "6 A" else 0.0
tr = refused(r, 1690, 1800)
d = dropped(r, 1800, 10.0)
bad = [(t, a, why) for t, a, ok, why in writes(r, 1800, 2700)
if abs(a - want) < 0.01 or why == "peak cut"]
nxt = first(x for x in writes(r, 1800, 2700))
check(f"T27 [{tag}] (G3, tries left): {tr} refused ({want} A) before the "
f"period's end; the drop at {d} (1800+-2); no re-send of {want} A "
f"and no 'peak cut' write in [1800, 2700) ({bad[:3]}); the next "
f"write the plan's ({nxt})",
1 <= len(tr) <= 2 and all(a == want for _t, a in tr)
and near(d, 1800, 0, 2) and not bad
and (not present(nxt) or nxt[3] == "Solar"))
never54(f"T27 [{tag}]", r)
class Drv:
def __init__(self):
self.calls = []
async def write_current(self, a, **kw):
self.calls.append(a)
return False
class Trk:
obs_at = None
def begin_write(self):
pass
def end_write(self, *a):
pass
def note_write(self, *a, **k):
pass
def stuck(self, now):
return False
async def c4_replay():
w = carmode.SolarWriter()
w.engaged, w.sent_a, w.taken, w.last_a = True, 10.0, True, 10.0
drv, trk = Drv(), Trk()
w.cut_a, w.cut_on = 6.0, True
await w._put(drv, 6.0, 10.0, 1000.0, trk)
first_try = list(drv.calls)
w.cut_a, w.cut_on = None, False
await w._put(drv, 6.0, 10.0, 1070.0, trk)
return first_try, drv.calls[len(first_try):], w.sent_why
try:
c4 = asyncio.run(c4_replay())
except Exception as e: # noqa: BLE001
c4 = (None, ["raised " + repr(e)], None)
check(f"T27 (formal C4 replay): a 6 A cut refused once {c4[0]}; with no "
f"cut 70 s later `_put(6)` sends nothing ({c4[1]})",
c4[0] == [6.0] and c4[1] == [])
r = run(house_c((1250, 900.0)), sun_c((1250, 7950.0)), dur=2700,
events=window({}, 959, 1900))
tl = t_lift(r, 1100, 1800)
d = dropped(r, tl or 0, 10.0)
w28 = [(t, a) for t, a, _ok, _w in writes(r, 1081, 2700)]
check(f"T28 (G3, tries used up): the lift at {tl}: the drop {d}; no write "
f"at all in (1080, 2700) ({w28[:3]}), also not at the roll; gave_up "
f"never ({gave_up_at(r, 900)[:2]})",
near(tl, 1370, 2, 2) and d is not None and not w28
and not gave_up_at(r, 900))
never54("T28", r)
# =========================================================================== #
print("\n4. G4, G5, G6: A PARTIAL CUT (T29, T30, T32), A DEEPER CUT (T31)")
# =========================================================================== #
r = run(house_c((1250, 900.0), h=900.0), sun_c((1250, 9000.0), s=1900.0),
dur=1800, events=window({}, 959, 1100))
tr = refused(r, 900, 1800)
tl = t_lift(r, 1100, 1800)
d = dropped(r, tl or 0, 10.0)
six = [(t, a) for t, a, _ok, _w in writes(r, 1081, 1800) if a == 6.0]
up = [(t, a, why) for t, a, ok, why in writes(r, (tl or 1e9),
(tl or 1e9) + 61) if a > 10.0]
check(f"T29 (G4): 6 A refused 3 times ({tr}), no 4th; the lift at {tl}: the "
f"drop {d} (sent 10, plan 10); no 6 A after 1080 ({six}); a step-up "
f"> 10 A, Solar, within t_lift+60 ({up[:1]})",
[a for _t, a in tr] == [6.0, 6.0, 6.0] and near(tl, 1370, 2, 2)
and d is not None and not six and bool(up) and up[0][1] <= 16.0
and up[0][2] == "Solar")
never54("T29", r)
as_off("T29", r, twin(r), ALARMS, refused=(961, (tl or 1371) - 1))
pre = [(t, a) for t, a, _ok, _w in writes(r, 1081, (tl or 1e9) - 2)]
hi = [(x["t"], x["plan"]) for x in rows(r, 1081, tl or 1e9)
if x["plan"] > 6.0]
check(f"T32 (G6): the tries used up, the spare about 16 A from 1250, the cap "
f"to {tl}: no write in (1080, t_lift-2) ({pre}); the plan at most 6 A "
f"until the lift ({hi[:3]})", tl is not None and not pre and not hi)
for n in (1, 2):
for tag, s2 in (("6 A", 1900.0), ("under 6 A", 1200.0)):
r = run(house_c(h=900.0), sun_c((1800, s2), s=1900.0), dur=1900,
n=n, events=window({}, 959, 1790))
tr = refused(r, 900, 1795)
hold_s = r["c"].p1.averager.max_hold_s
kc = key_change(r, 1700, 1900)
c2 = first((t, a, ok) for t, a, ok, _w, _k in
cut_writes(r, 1800 - hold_s - 1))
lo = 1800 - (hold_s if n == 2 else 0) - 1
x2 = row(r, c2[0]) if present(c2) else None
cap2 = x2["cap"] if present(x2) and x2 is not None else None
rb = [x["t"] for x in rows(r, c2[0] if present(c2) else 1e9)
if present(c2) and abs(x["rb"] - c2[1]) < 0.01]
cuts = [t for t, nn in r["raised"] if nn == CUT and t >= 1790]
# The value is the new quarter's cut, or lower when Solar's own plan
# is lower (here its pause: the spare stayed under 6 A worth).
check(f"T30 [N={n}, {tag}] (G4): 3 refused tries of 6 A ({tr}); the "
f"new key ({kc}) tried in its first cycle ({c2}, bound "
f"[{lo}, 1801]) at or under the new quarter's sized cut "
f"({cap2} A), 0 A or 6 A and more, never 1-5 A, taken, read "
f"back by {rb[:1]}; CAR_CUT once ({cuts})",
[a for _t, a in tr] == [6.0, 6.0, 6.0] and present(c2)
and c2 is not None and lo <= c2[0] <= 1801
and cap2 is not None and c2[1] <= cap2 + 0.01
and (c2[1] == 0.0 or c2[1] >= 6.0) and c2[2] and bool(rb)
and rb[0] <= c2[0] + 2 and len(cuts) == 1)
never54(f"T30 [N={n}, {tag}]", r)
if n == 2 and tag == "6 A":
as_off("T30 [N=2, 6 A]", r, twin(r), ALARMS,
refused=(961, 1790))
r = run(house_c((1030, 3000.0), h=900.0), sun_c((1030, 0.0), s=1900.0),
dur=1950, events=window({}, 959, 1830))
tr = refused(r, 900, 1795)
check(f"T31 (G5): 6 A refused at 960 and 1020, the cut deepens at 1030: 0 A "
f"at once, refused, try 3 ({tr}); no 4th refused try in 900-1800; "
f"gave_up never ({gave_up_at(r, 900, 1800)[:2]})",
[a for _t, a in tr] == [6.0, 6.0, 0.0] and near(nth(tr, 2)[0]
if present(nth(tr, 2))
else None, 1030, 0, 2)
and not gave_up_at(r, 900, 1800))
hold_s = r["c"].p1.averager.max_hold_s
kc = key_change(r, 1700, 1900)
w2 = [(t, a, ok) for t, a, ok, _w, _k in cut_writes(r, 1800 - hold_s - 1)]
check(f"T31: the new key ({kc}) tried in its first cycle and refused, the "
f"next 60 s or more later taken ({w2[:2]})",
len(w2) >= 2 and not w2[0][2] and w2[1][2]
and w2[1][0] - w2[0][0] >= 60 and present(kc) and kc is not None
and abs(w2[0][0] - kc) <= 1)
never54("T31", r)
# =========================================================================== #
print("\n5. QB: NO READ-BACK AT THE LIFT (T33)")
# =========================================================================== #
def rb_none(on):
"""The charger answers, but neither its setpoint nor its read-back is a
number: `allowed_a` and `setpoint_a` are both None."""
def f(p, c):
ch = p.ch
if on:
orig = ch.states
def st():
d = dict(orig())
for k in list(d):
if k.endswith("_power_connector_max_current_socket_1") \
or k.endswith("_main_active_max_current_socket_1"):
d[k] = dict(d[k], state="-")
return d
ch._ev54_states = orig
ch.states = st
else:
ch.states = ch._ev54_states
return f
seen33 = []
def rd33(p, c, t):
rd = c.car.reading
if rd is not None and 1340 <= t < 1400:
seen33.append((rd.available, rd.allowed_a, rd.setpoint_a))
r = run(house_c((1250, 900.0)), sun_c((1250, 7950.0)), dur=2700,
events=window({1340: rb_none(True), 1400: rb_none(False)}, 959, 1900),
on_cycle=rd33)
tl = t_lift(r, 1100, 1800)
w33 = [(t, a) for t, a, _ok, _w in writes(r, 1081, 2700)]
nod = [x["t"] for x in rows(r, 1340, 1400) if x["sent"] != 0.0 or x["taken"]]
d = dropped(r, 1400, 10.0)
check(f"T33 (QB): the read-back unknown 1340-1400 ({sorted(set(seen33))}), "
f"the lift at {tl} inside it: no write ({w33[:3]}), no drop and "
f"sent_a 0 untaken, not None ({nod[:3]}); the drop at {d} (1400+-2) "
f"with 10 A; then no write to 2700",
sorted(set(seen33)) == [(True, None, None)] and present(tl)
and tl is not None and 1340 < tl < 1400 and not w33 and not nod
and near(d, 1400, 0, 2))
never54("T33", r)
# The variant: the charger away 1100-1400, the cap lifted while it is away
# (T14's short import spell, so the start rule's projection lifts it without
# a car figure).
ev = window({1100: lambda p, c: p.ch.go_unavailable(),
1400: lambda p, c: p.ch.go_unavailable(False)}, 959, 1900)
r = run(house_c((1010, 900.0)), sun_c((1010, 16000.0)), dur=1500,
events=ev)
tl = t_lift(r, 1100, 1400)
away = [(t, a) for t, a, _ok, _w in writes(r, 1100, 1400)]
back = [(t, a, why) for t, a, _ok, why in writes(r, 1400, 1500)]
keys = [k for k in r["store"].data if "cut" in str(k).lower()]
check(f"T33 [charger away 1100-1400, the lift at {tl}]: nothing while away "
f"({away}); on return D2's 0 A as bdfd3e6 ({back[:1]}), not a re-send "
f"of the cut; no store key ({keys})",
present(tl) and tl is not None and 1100 < tl < 1400 and not away
and bool(back) and near(back[0][0], 1400, 0, 1) and back[0][1] == 0.0
and back[0][2] != "peak cut" and not keys)
never54("T33 [away]", r)
# =========================================================================== #
print("\n6. QC 2: THE WAY-OUT REASON WITH OFF (T35 (b), (c))")
# =========================================================================== #
r = run(house_c((1250, 900.0)), sun_c((1250, 9000.0)), dur=1500,
events=window({1400: act("car_mode", "off")}, 959, 1380))
wb = [(t, a, ok) for t, a, ok, _w in writes(r, 1395)]
lb = [m for t, _lv, m in r["w"].lines("Car: set") if t >= 1395]
whyb = [why for t, _a, _ok, why in writes(r, 1395)]
# bdfd3e6 writes nothing here: it is frozen with `gave_up` after the lift (C3)
# and Off does not clear it. After the drop the car's 10 A is Solar's, so Off
# writes EV-20's way-out 0 A once, at the press, as Solar's.
want = golden("T35 (b)", wb)
check(f"T35 (b): Off at 1400 after the lift: its way-out 0 A {wb} once at "
f"the press (bdfd3e6: {want}, frozen), reason Solar ({whyb}); one line "
f"({lb})",
wb == [(1400.0, 0.0, True)] and whyb == ["Solar"]
and lb == ["Car: set from 10 A to 0 A on 3 phases (Solar)."])
r = run(house_c(), sun_c(), dur=1200,
events=window({1000: act("car_mode", "off")}, 959, 999))
wc = [(t, a, ok) for t, a, ok, _w in writes(r, 995)]
lc = [m for t, _lv, m in r["w"].lines("Car: set") if t >= 995]
want = golden("T35 (c)", (wc, lc))
check(f"T35 (c): Off at 1000 while the cut stands: writes {wc} and lines "
f"{lc} as bdfd3e6's ({want})", (wc, lc) == want and bool(wc))
# =========================================================================== #
print("\n7. REVIEW ROUND 1: AWAY WHILE CAPPED (T36), F6 (T37), OFF (T38), "
"THE REASON (T39)")
# =========================================================================== #
# T36 (review r1, Major): the charger is away 1100-1200 and comes back while
# the cap stands with the quarter's 3 tries used up; then the lift. D2's 0 A
# is a cut try and stays held (ruling 3); the return does not give the
# quarter new tries; after the lift Solar's control resumes.
for tag, h, s in (("0 A", 3000.0, 0.0), ("6 A", 900.0, 1900.0)):
ev = window({1100: lambda p, c: p.ch.go_unavailable(),
1200: lambda p, c: p.ch.go_unavailable(False)}, 959, 1300)
r = run(house_c((1250, 900.0), h=h), sun_c((1250, 9000.0), s=s),
dur=2700, events=ev)
tr = refused(r, 900, 1100)
tl = t_lift(r, 1200, 1800)
held_w = [(t, a) for t, a, _ok, _w in writes(r, 1081, tl or 1e9)]
cf = sorted({x["cut_fails"] for x in rows(r, 1081, tl or 1e9)}, key=str)
nz = [(t, a, ok, why) for t, a, ok, why in writes(r, tl or 1e9,
(tl or 1e9) + 61)
if a > 0.0]
check(f"T36 [{tag}] (review r1): 3 refused tries ({tr}); the charger away "
f"1100-1200 and back while capped: no D2 0 A or other write until "
f"the lift at {tl} ({held_w}); the quarter's cut count stays 3 "
f"across the return ({cf}); after the lift a Solar write within "
f"60 s ({nz[:1]})",
len(tr) == 3 and present(tl) and tl is not None and not held_w
and cf == [3] and bool(nz) and nz[0][2] and nz[0][3] == "Solar")
never54(f"T36 [{tag}]", r)
# T37 (review r1, F6): episode 1 is lifted by the start rule (60 s) after
# 2 refused tries (960, 1020); episode 2 is due at 1040, within 60 s of the
# last refusal, with one try left: that try waits to 1080.
r = run(house_c(), sun_c((961, 9000.0), (1040, 0.0)), dur=1300,
opts={"ev_start_min": 1}, events=window({}, 959, 1800))
tl = t_lift(r, 961, 1040)
due2 = first(x["t"] for x in rows(r, (tl or 1e9) + 1, 1100)
if x["cap"] is not None or x["wait"] is not None)
tr = [t for t, _a in refused(r, 900, 1300)]
early = [t for t, _a, _ok, _w in writes(r, due2 or 1e9, 1080)]
check(f"T37 (review r1, F6): episode 1 lifted at {tl} after tries {tr[:2]}; "
f"episode 2 due at {due2}: no try before 60 s after the last refusal "
f"({early}), then try 3 at {nth(tr, 2)} (>= 1080); none after",
present(tl) and tl is not None and present(due2) and due2 is not None
and due2 < 1080 and tr[:2] == [960.0, 1020.0] and not early
and len(tr) == 3 and tr[2] >= 1080 if len(tr) >= 2 else False)
never54("T37", r)
# T38 (review r1, the fails gate): Off after the quarter's 3 refused tries,
# the refused 0 A still owed: no way-out try, as bdfd3e6 (gave_up there).
r = run(house_c(), sun_c(), dur=1300,
events=window({1100: act("car_mode", "off")}, 959, None))
w38 = [(t, a, ok) for t, a, ok, _w in writes(r, 1081)]
want = golden("T38", w38)
check(f"T38 (review r1): Off at 1100 after 3 refused cut tries: Off's "
f"way-out writes {w38} as bdfd3e6's ({want})", w38 == want)
async def reason_replay():
"""T39: a refused 6 A cut, then the next quarter sizes 7 A (above the
refused value, under the 10 A read-back)."""
w = carmode.SolarWriter()
w.engaged, w.sent_a, w.taken, w.last_a = True, 10.0, True, 10.0
drv, trk = Drv(), Trk()
w.cut_quarter("q1")
w.cut_a, w.cut_on = 6.0, True
await w._put(drv, 6.0, 10.0, 1000.0, trk)
w.cut_quarter("q2")
w.cut_a = 7.0
await w._put(drv, 7.0, 10.0, 1070.0, trk)
return list(drv.calls), w.sent_why
try:
t39 = asyncio.run(reason_replay())
except Exception as e: # noqa: BLE001
t39 = (["raised " + repr(e)], None)
check(f"T39 (review r1): a new cut value above the refused one, under the "
f"read-back, goes out as 'peak cut' ({t39})",
t39[0] == [6.0, 7.0] and t39[1] == "peak cut")
# =========================================================================== #
print("\n8. REVIEW ROUND 2: `fails` COUNTS ONLY THE OWED VALUE (T40-T42)")
# =========================================================================== #
def away_run(h, s, refuse_end, away=True):
ev = {}
if away:
ev = {1100: lambda p, c: p.ch.go_unavailable(),
1200: lambda p, c: p.ch.go_unavailable(False)}
return run(house_c((1250, 900.0), h=h), sun_c((1250, 9000.0), s=s),
dur=1800, events=window(ev, 959, refuse_end))
def after_lift(r):
tl = t_lift(r, 1200, 1800)
w = [(t, a, ok) for t, a, ok, _w in writes(r, tl or 1e9, 1800)]
hold = [t for t, _lv, _m in r["w"].lines(HOLD_TEXT)]
gu = [x["t"] for x in rows(r, tl or 1e9, 1800) if x["gave_up"]]
cf = sorted({x["cut_fails"] for x in rows(r, 1081, tl or 1e9)}, key=str)
return tl, w, hold, gu, cf
# T40 (PM row a): the charger refuses to 1430: after the return Solar's own
# write gets its own tries; the 2nd, 60 s later, is taken.
for tag, h, s in (("0 A", 3000.0, 0.0), ("6 A", 900.0, 1900.0)):
r = away_run(h, s, 1430)
tl, w, hold, gu, cf = after_lift(r)
pre = [t for t, _a, _ok, _w in writes(r, 1081, tl or 1e9)]
tk = [t for t, _a, ok in w if ok]
check(f"T40 [{tag}] (review r2): away 1100-1200 while capped, refused to "
f"1430: nothing until the lift at {tl} ({pre}); then Solar tries "
f"{w[:3]}: the 1st refused, the 2nd 60 s later, a taken write by "
f"1462 ({tk[:1]}); no gave_up ({gu[:2]}) or hold text ({hold}); "
f"the quarter's cut count unchanged across the return ({cf})",
present(tl) and tl is not None and not pre and len(w) >= 2
and not w[0][2] and w[1][0] - w[0][0] >= 60 and bool(tk)
and tk[0] <= 1462 and not gu and not hold and cf == [3])
never54(f"T40 [{tag}]", r)
def ok41(res):
tl, w, hold, gu, cf = res
if not (len(w) == 3 and len(hold) == 1 and present(tl) and tl is not None
and bool(gu)):
return False
return (not any(ok for _t, _a, ok in w) and w[0][0] <= tl + 60
and all(b[0] - a[0] >= 60 for a, b in zip(w, w[1:]))
and abs(hold[0] - w[2][0]) <= 1 and gu[0] >= w[2][0] - 1
and cf == [3])
# T41 (PM row b): refused to 1600: Solar's own 3 tries 60 s apart, then
# gave_up and the hold text, as in the same run without the away.
for tag, h, s in (("0 A", 3000.0, 0.0), ("6 A", 900.0, 1900.0)):
ra = after_lift(away_run(h, s, 1600, away=True))
rn = after_lift(away_run(h, s, 1600, away=False))
check(f"T41 [{tag}] (review r2): refused to 1600: with the away {ra[1]}, "
f"gave_up from {ra[3][:1]}, hold text {ra[2]}; without it {rn[1]}, "
f"gave_up from {rn[3][:1]}, hold text {rn[2]}: 3 tries 60 s apart, "
f"then gave_up, in both", ok41(ra) and ok41(rn))
async def replaced_value():
"""T42 (PM row c): a refused 6 A cut, then the next quarter's 7 A (the
reachable path of T39) replaces it and is refused too: `fails` counts
only the owed 7 A."""
w = carmode.SolarWriter()
w.engaged, w.sent_a, w.taken, w.last_a = True, 10.0, True, 10.0
drv, trk = Drv(), Trk()
w.cut_quarter("q1")
w.cut_a, w.cut_on = 6.0, True
await w._put(drv, 6.0, 10.0, 1000.0, trk)
w.cut_quarter("q2")
w.cut_a = 7.0
await w._put(drv, 7.0, 10.0, 1070.0, trk)
return list(drv.calls), w.fails, w.cut_fails, w.refused_cut
try:
t42 = asyncio.run(replaced_value())
except Exception as e: # noqa: BLE001
t42 = (["raised " + repr(e)], None, None, None)
check(f"T42 (review r2): 6 A refused, then 7 A written in its place and "
f"refused (calls {t42[0]}): fails {t42[1]} counts only the owed 7 A "
f"(1), the new quarter's cut count {t42[2]} (1), owed {t42[3]}",
t42[0] == [6.0, 7.0] and t42[1] == 1 and t42[2] == 1
and t42[3] == 7.0)
tb_all = LOG.tracebacks(n_log0)
check(f"N13: no traceback in this file's runs ({tb_all[:1]})", not tb_all)
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)
File diff suppressed because it is too large Load Diff
+824
View File
@@ -0,0 +1,824 @@
"""EV-59: Manual gives one value at most MAX_TRIES tries per user change, the
phase-change closes included. `python3 -B test_ev59.py`
Rows T1-T25 and N1-N14 of reports/EV-59-test-plan.md. Here: T1-T13, T14c, T15
(the answering charger, writer level), T16, T17, T18 (source checks on the
edited test files), T20-T25, T11c and N1-N14 (N8, N10, N11 as source checks).
Carried by other suites, green and unedited: T14a, T14b, T14d (test_ev56 T8,
T11, T12, T13, T19b and their T20 digests), T15's T20 digests (test_ev56
[A]), T12b/T12c's EV-28 side (test_ev28 T11-T13), T19 (the listed suites).
EDITED, not unedited: test_ev56 T5, T5b and the golden "T20 T5 [R]" (Q1, Q2),
test_ev28 T15 (Q3, T11c), test_ev13 T13 text and T26 goldens (rulings).
The `ManualWriter` / `SolarWriter` on a stub driver, a stub tracker
and a stub reading; time is the 1 s step counter, never wall time. The close
of the plan's T5 world: 0 A at t=0 and the select at t=1, both taken, so the
settle ends at s=11 and the closes are at 11, 16, 21.
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import asyncio
import logging
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
from app import carmode as CM # noqa: E402
fails = []
CLOCK = {"t": 0}
LOG = []
BIG = 1e12
REF = "CHARGER_REFUSED"
REC = "The car charger step failed"
class Cap(logging.Handler):
def emit(self, rec):
LOG.append((CLOCK["t"], rec.levelname, rec.getMessage()))
logging.getLogger("goodwe").addHandler(Cap())
logging.getLogger("goodwe").setLevel(logging.DEBUG)
def check(name, cond):
print(f" {'ok ' if cond else 'FAIL'} {name}")
if not cond:
fails.append(name)
class Rd:
def __init__(self, a, ph=1, power=None, state="C"):
self.available = True
self.allowed_a = self.setpoint_a = a
self.phases_allowed = ph
self.power_w = power
self.state = state
self.error = False
self.charging = True
self.current_a = ()
self.station_a = None
class Trk:
obs_at = None
def __init__(self):
self.notes = []
def begin_write(self):
pass
def end_write(self, *_):
pass
def note_write(self, now, was, a, ok, polls=()):
self.notes.append((now, a, ok))
def stuck(self, now):
return False
class Drv:
"""answer(a, n) -> True | False | "raise"; True sets the charger. `sel`:
the answer to write_phases. `phases_log`: (t, n, the power seen then)."""
def __init__(self, cur, answer, ph=1, sel=True):
self.cur, self.ph, self.answer, self.sel = cur, ph, answer, sel
self.calls, self.now, self.polls = [], 0.0, ()
self.phases_log, self.power = [], None
async def write_current(self, a, **kw):
self.calls.append((self.now, float(a)))
r = self.answer(float(a), len(self.calls))
if r == "raise":
raise RuntimeError("HA call error")
if r:
self.cur = float(a)
return bool(r)
async def write_phases(self, n):
self.phases_log.append((self.now, n, self.power))
if self.sel:
self.ph = n
return self.sel
def refuse(a, n):
return a == 0.0
def raises(a, n):
return True if a == 0.0 else "raise"
def snap(w):
q = w.seq
return dict(fails=w.fails, gave_up=w.gave_up, fail_at=w.fail_at,
seq=None if q is None else (q["stage"], q["tries"]),
last_a=w.last_a, reapply=w.reapply, rev_applied=w.rev_applied,
phase_done_at=w.phase_done_at, phase_fails=w.phase_fails)
class Run:
pass
def run(answer, secs, *, cls=CM.ManualWriter, cb=None, a=6.0, n=3, cur=10.0,
sel=True, power=None, avail=None, clamp=16.0, mode=CM.MANUAL,
rd_none=False, w=None):
"""One writer run, one step per second. `cb(t, st, w, drv)` may change the
request in `st` (a, n, rev, clamp, mode) or call `w.user_changed()` (use
`uc`); it may be a coroutine. Per step: the state before and after."""
LOG.clear()
w, trk = w or cls(), Trk()
drv = Drv(cur, answer, sel=sel)
st = dict(a=a, n=n, rev=1, clamp=clamp, mode=mode)
out = Run()
out.w, out.drv, out.trk, out.st = w, drv, trk, st
out.rows, out.errs, out.ucs = {}, [], []
async def main():
for t in range(secs):
drv.now = float(t)
CLOCK["t"] = t
if cb:
x = cb(t, st, w, drv)
if asyncio.iscoroutine(x):
await x
pw = power(t, drv) if power else (
0.0 if drv.cur == 0 else 1380.0)
drv.power = pw
r = Rd(None if rd_none else drv.cur, drv.ph, power=pw)
if avail is not None and not avail(t):
r.available = False
seq0 = w.seq is not None
try:
await w.step(drv, r, mode=st["mode"], want_a=st["a"],
want_phases=st["n"], rev=st["rev"],
clamp=st["clamp"], now=float(t), tracker=trk,
writing=True, status="charging")
except Exception as e: # noqa: BLE001
out.errs.append((t, e))
d = snap(w)
d["seq0"], d["ncalls"] = seq0, len(drv.calls)
out.rows[t] = d
asyncio.run(main())
out.log = list(LOG)
return out
def uc(st, w, t, out_ucs=None, **kw):
w.user_changed()
st["rev"] += 1
st.update(kw)
UCS.append(t)
UCS = []
def at(t0, **kw):
"""A callback: one user change at t0 with these request changes."""
def cb(t, st, w, drv):
if t == t0:
uc(st, w, t, **kw)
return cb
def nz(r, lo=-BIG, hi=BIG, a=None):
return [int(t) for t, x in r.drv.calls
if x > 0 and lo <= t < hi and (a is None or abs(x - a) < 0.01)]
def zeros(r):
return [int(t) for t, x in r.drv.calls if x == 0.0]
def refs(r):
return [t for t, lv, m in r.log if lv == "WARNING" and REF in m]
def recs(r):
return [t for t, lv, m in r.log if lv == "ERROR" and m == REC]
def near(got_, want, tol=1):
return len(got_) == len(want) and all(abs(g - w_) <= tol
for g, w_ in zip(got_, want))
def never(name, r, *, ucs=(), clamp=16.0):
"""N1 (no non-zero write while given up before a user change), N2 (one
REF per give-up), N5 (no select under load), N6 (nothing above the clamp
or in 0-6 A), N9 (no exception out of a step), N13 (closes at least 5 s
apart, normal tries RETRY_S apart)."""
bad1, bad3, up = [], [], 0
t_prev, gv = None, False
for t in sorted(r.rows):
row = r.rows[t]
before = r.rows.get(t - 1)
n_new = row["ncalls"] - (before["ncalls"] if before else 0)
if gv and n_new and not any(u <= t and u > (t_prev or -1) for u in ucs) \
and any(x > 0 for tt, x in r.drv.calls if tt == t):
bad1.append(t)
if row["gave_up"] and not (before or {}).get("gave_up"):
up += 1
# N3: not before MAX_TRIES tries of the value owed since the
# last user change (the last call's value, from that change on).
u0 = max([u for u in ucs if u <= t], default=-1)
last = [(tt, x) for tt, x in r.drv.calls if tt <= t and x > 0]
if last:
v = last[-1][1]
n_v = len([1 for tt, x in last if tt >= u0])
if n_v < CM.MAX_TRIES:
bad3.append((t, v, n_v))
if not row["gave_up"] and (before or {}).get("gave_up"):
gv = False
if any(u == t for u in ucs):
gv = False
elif row["gave_up"]:
gv = True
t_prev = t
nzc = [(t, x) for t, x in r.drv.calls if x > 0]
bad13 = []
for (ta, aa), (tb, ab) in zip(nzc, nzc[1:]):
inseq = r.rows[int(tb)]["seq0"]
lim = 5.0 if inseq else CM.RETRY_S
user = any(ta < u <= tb for u in ucs)
if tb - ta < lim - 1e-9 and not (user and not inseq) \
and abs(aa - ab) < 0.01:
bad13.append((ta, tb))
bad5 = [x for x in r.drv.phases_log if x[2] is not None
and x[2] >= CM.QUIET_W]
bad6 = [x for _t, x in nzc if x > clamp + 1e-9 or x < 6.0 - 1e-9]
check(f"{name}: N3 no give-up before MAX_TRIES tries of the value owed "
f"({bad3[:3]})", not bad3)
check(f"{name}: N1 no write while given up ({bad1[:3]}); N2 one REF per "
f"give-up ({len(refs(r))} for {up}); N5 no select under load "
f"({bad5[:2]}); N6 nothing above the clamp or under 6 A "
f"({bad6[:3]}); N9 no exception ({r.errs[:1]}); N13 spacing "
f"({bad13[:3]})",
not bad1 and len(refs(r)) == up and not bad5 and not bad6
and not r.errs and not bad13)
print("1. THE REPLAY, THE STATE AT THE CAP (T1, T2, T3, T23)")
UCS.clear()
R1 = run(refuse, 600)
check(f"T1: 6 A tried at {nz(R1)}: 11, 16, 21 and nothing after to 600 s; "
"the car stays at 0 A",
nz(R1) == [11, 16, 21] and R1.drv.cur == 0.0
and all(x == 6.0 for _t, x in R1.drv.calls if x > 0))
r21, r20 = R1.rows[21], R1.rows[20]
check(f"T2: at the 3rd refused close: seq None, last_a None, reapply, "
f"rev_applied None, fails MAX_TRIES, gave_up, fail_at 21, "
f"phase_done_at None ({r21}); one REF in that step ({refs(R1)})",
r21["seq"] is None and r21["last_a"] is None and r21["reapply"] is True
and r21["rev_applied"] is None and r21["fails"] == CM.MAX_TRIES
and r21["gave_up"] is True and r21["fail_at"] == 21
and r21["phase_done_at"] is None and r21["phase_fails"] == 0
and refs(R1) == [21] and r20["gave_up"] is False and r20["fails"] == 0)
check("T23: offByOne: the 2nd close (16) does not end the sequence and the "
"3rd (21) does; the states up to 16 are the base's",
R1.rows[11]["seq"] == ("settle", 1) and R1.rows[16]["seq"] ==
("settle", 2) and R1.rows[16]["fails"] == 0
and not R1.rows[16]["gave_up"] and R1.rows[21]["seq"] is None
and not any(refs(R1)[i] < 21 for i in range(len(refs(R1)))))
never("T1", R1)
RX = run(raises, 600)
strip = lambda d: {k: v for k, v in d.items() if k not in ("ncalls",)} # noqa
check("T3a: every close raises: calls, states and cycle by cycle as R; 1 "
f"ERROR record at 11 ({recs(RX)}), REF at 21 ({refs(RX)}); the "
"tracker is not told of a raise",
RX.drv.calls == R1.drv.calls
and all(strip(RX.rows[t]) == strip(R1.rows[t]) for t in range(600))
and recs(RX) == [11] and refs(RX) == [21]
and not [x for x in RX.trk.notes if x[1] > 0]
and len([x for x in R1.trk.notes if x[1] > 0]) == 3)
never("T3a", RX)
RM = run(lambda a, n: True if a == 0.0 else ("raise" if n in (2, 4)
else False), 600)
check("T3b: raise, refuse, raise: 3 tries, 1 ERROR, 1 REF at 21, fails "
f"{RM.rows[21]['fails']}",
nz(RM) == [11, 16, 21] and recs(RM) == [11] and refs(RM) == [21]
and RM.rows[21]["fails"] == CM.MAX_TRIES and RM.rows[21]["gave_up"]
and [x[1] for x in RM.trk.notes if x[1] > 0] == [6.0])
never("T3b", RM)
print("\n2. TAKEN CLOSES AND FOLLOW-UPS (T4, T5, T6, T7, T8)")
UCS.clear()
R4 = run(lambda a, n: a == 0.0 or n == 2, 400, cb=at(100, a=8.0))
r4 = R4.rows[11]
check(f"T4: the close taken on try 1: seq None, fails 0, no give-up, no REF, "
f"phase_done_at 11 ({r4['phase_done_at']}); 8 A at 100 gets 3 tries "
f"({nz(R4, 100, a=8.0)}) and one REF ({refs(R4)})",
r4["seq"] is None and r4["fails"] == 0 and not r4["gave_up"]
and r4["phase_done_at"] == 11 and near(nz(R4, 100, a=8.0),
[100, 160, 220])
and refs(R4) == [220])
never("T4", R4, ucs=[100])
for tag, tk in (("a", 3), ("b", 4)):
UCS.clear()
R5 = run(lambda a, n, tk=tk: a == 0.0 or n == tk, 400, cb=at(100, a=8.0))
r5 = R5.rows[40]
check(f"T5{tag}: close taken on try {tk - 1}: fails 0, no give-up, no "
f"REF, phase_done_at None ({r5['phase_done_at']}); 8 A at 100 gets "
f"3 full tries ({nz(R5, 100, a=8.0)})",
r5["fails"] == 0 and not r5["gave_up"] and r5["seq"] is None
and r5["phase_done_at"] is None
and near(nz(R5, 100, a=8.0), [100, 160, 220])
and refs(R5) == [220] and R5.rows[21]["fails"] == 0)
never(f"T5{tag}", R5, ucs=[100])
for tag, kw, want in (("a", dict(a=8.0), 8.0), ("b", dict(a=6.0), 6.0)):
UCS.clear()
R6 = run(refuse, 400, cb=at(100, **kw))
got6 = nz(R6, 100, a=want)
check(f"T6{tag}: after the give-up a user change to {want:.0f} A: a "
f"write at 100 and tries at +60, +120, then REF once more, never "
f"a 4th ({got6}, REF {refs(R6)})",
near(got6, [100, 160, 220]) and refs(R6) == [21, 220]
and R6.rows[100]["gave_up"] is False)
never(f"T6{tag}", R6, ucs=[100])
UCS.clear()
R6c = run(refuse, 760, cb=at(700, n=1))
check(f"T6c: after the give-up a 1 phase request (past PHASE_GAP_S): gave_up "
f"does not block it; the 0 A at 700 ({zeros(R6c)}), the select at the "
f"quiet car, then closes ({nz(R6c, 700)})",
near([z for z in zeros(R6c) if z >= 700], [700])
and R6c.rows[700]["gave_up"] is False
and [x[1] for x in R6c.drv.phases_log if x[0] >= 700] == [1]
and near(nz(R6c, 700), [711, 716, 721]) and refs(R6c) == [21, 721])
UCS.clear()
def off_then_manual(t, st, w, drv):
if t == 100:
st["mode"] = "off"
if t == 103:
st["mode"] = CM.MANUAL
uc(st, w, t)
R6d = run(refuse, 400, cb=off_then_manual)
check(f"T6d: Off, then Manual at 103: as T6b from the pick "
f"({nz(R6d, 100, a=6.0)})",
near(nz(R6d, 100, a=6.0), [103, 163, 223]) and refs(R6d) == [21, 223])
UCS.clear()
R7a = run(refuse, 600, avail=lambda t: not 130 <= t < 161)
check(f"T7a: the charger away 130-160, back at 161: no write after the "
f"return to 600 s ({nz(R7a, 100)}); gave_up stays",
nz(R7a, 100) == [] and R7a.rows[599]["gave_up"] and refs(R7a) == [21])
never("T7a", R7a)
R7b = run(refuse, 600, avail=lambda t: not 12 <= t < 31)
check(f"T7b: away between close 1 and 2, back at 31: the count goes on: 3 "
f"tries of 6 A ({nz(R7b)}), then the give-up, REF once ({refs(R7b)})",
len(nz(R7b, a=6.0)) == 3 and R7b.rows[599]["gave_up"]
and len(refs(R7b)) == 1
and all(b - a >= 5 for a, b in zip(nz(R7b), nz(R7b)[1:])))
never("T7b", R7b)
UCS.clear()
R7c = run(raises, 600, avail=lambda t: not 130 <= t < 161,
cb=at(200, a=6.0))
check(f"T7c: X, away and back, then a user change at 200: no write before "
f"200 after the return; the record is armed again: ERROR at "
f"{recs(R7c)} (1 before 200, 1 after)",
not nz(R7c, 100, 200) and len([x for x in recs(R7c) if x < 200]) == 1
and len([x for x in recs(R7c) if x >= 200]) == 1)
UCS.clear()
R8 = run(lambda a, n: a == 0.0 or n == 4, 1200, cb=at(700, n=1))
b_calls = nz(R8, 700)
check(f"T8: sequence A (refused, refused, taken): fails "
f"{R8.rows[21]['fails']}, no give-up; then sequence B: 3 tries "
f"({b_calls}), no give-up after 1 or 2 "
f"({R8.rows[711]['gave_up']}, {R8.rows[716]['gave_up']}), then the "
f"give-up and 1 REF ({refs(R8)})",
R8.rows[21]["fails"] == 0 and not R8.rows[21]["gave_up"]
and near(b_calls, [711, 716, 721])
and not R8.rows[711]["gave_up"] and not R8.rows[716]["gave_up"]
and R8.rows[721]["gave_up"] and refs(R8) == [721])
never("T8", R8, ucs=[700])
print("\n3. A USER CHANGE DURING THE CLOSE RETRIES (T9, T24)")
for tag, t0, kw, want, exp_a, exp_6 in (
("a", 18, dict(a=8.0), 8.0, [21, 81, 141], [11, 16]),
("b", 13, dict(a=8.0), 8.0, [16, 21, 81], [11])):
for how, ans in (("R", refuse), ("X", raises)):
UCS.clear()
R9 = run(ans, 600, cb=at(t0, **kw))
g8 = nz(R9, a=8.0)
refs9 = refs(R9)
check(f"T9{tag} [{how}]: user change to 8 A at {t0}: 8 A gets "
f"exactly 3 tries ({g8}), the 6 A before it ({nz(R9, a=6.0)}); "
f"the REF once, at the 3rd try ({refs9}); fails after the "
f"close end {R9.rows[21]['fails']}",
near(g8, exp_a) and nz(R9, a=6.0) == exp_6
and refs9 == [exp_a[-1]]
and not any(R9.rows[t]["gave_up"] for t in range(exp_a[-1]))
and R9.rows[exp_a[-1]]["gave_up"])
never(f"T9{tag} [{how}]", R9, ucs=[t0])
UCS.clear()
R24 = run(refuse, 600, cb=at(18, a=8.0))
check("T24b: the user change after close 2: at the close end (21) fails 1, "
f"no give-up ({R24.rows[21]['fails']}, {R24.rows[21]['gave_up']}); the "
"normal path gives 2 more tries >= RETRY_S apart, then 1 REF",
R24.rows[21]["fails"] == 1 and not R24.rows[21]["gave_up"]
and R24.rows[81]["fails"] == 2 and R24.rows[141]["fails"] == 3
and R24.rows[141]["gave_up"] and refs(R24) == [141])
check("T24a: no user change: k = 3, fails 3, gave_up, 1 REF at the close end "
f"({R1.rows[21]['fails']}, {refs(R1)})",
R1.rows[21]["fails"] == CM.MAX_TRIES and refs(R1) == [21])
UCS.clear()
R9c = run(refuse, 600, cb=at(18, a=6.0))
after = [t for t in nz(R9c, a=6.0) if t >= 18]
check(f"T9c: the same value again at 18: 3 tries after the change ({after}), "
f"REF once at the last ({refs(R9c)})",
near(after, [21, 81, 141]) and refs(R9c) == [141]
and nz(R9c, a=6.0)[:2] == [11, 16])
never("T9c", R9c, ucs=[18])
UCS.clear()
R9d = run(refuse, 600, cb=at(2, a=8.0))
check(f"T9 (change before the 1st close): 8 A gets 3 tries "
f"({nz(R9d, a=8.0)}), REF {refs(R9d)}",
len(nz(R9d, a=8.0)) == 3 and len(refs(R9d)) == 1)
print("\n4. THE CLAMP, THE RESTORE CLOSES, THE SELECT (T10, T11, T12)")
UCS.clear()
def clamp_falls(t, st, w, drv):
if t == 18:
st["clamp"] = 8.0
R10 = run(refuse, 400, a=10.0, clamp=10.0, cb=clamp_falls)
check(f"T10: the clamp falls to 8 A at 18: tries {nz(R10)} with values "
f"{[x for _t, x in R10.drv.calls if x > 0]}: never above the clamp then, "
f"at most 3 in all, REF once ({refs(R10)})",
len(nz(R10)) == 3 and [x for _t, x in R10.drv.calls if x > 0]
== [10.0, 10.0, 8.0] and refs(R10) == [21])
never("T10", R10, clamp=10.0)
UCS.clear()
R11a = run(refuse, 400, cur=16.0, a=16.0, power=lambda t, d: 1380.0,
cb=at(300))
check(f"T11a: the drawing timeout, the 16 A restore refused: 3 tries 5 s "
f"apart ({nz(R11a, 0, 300)}), fails {R11a.rows[30]['fails']}, "
f"gave_up, REF once ({refs(R11a)}); phase_fails "
f"{R11a.rows[30]['phase_fails']}; no select ({R11a.drv.phases_log}); "
f"a user change writes 16 A at once ({nz(R11a, 300)[:1]})",
near(nz(R11a, 0, 300), [20, 25, 30])
and R11a.rows[30]["fails"] == CM.MAX_TRIES and R11a.rows[30]["gave_up"]
and refs(R11a) == [30] and R11a.rows[30]["phase_fails"] == 1
and R11a.rows[20]["fails"] == 0 and R11a.rows[25]["fails"] == 0
and not R11a.drv.phases_log and nz(R11a, 300)[:1] == [300])
never("T11a", R11a, ucs=[300])
UCS.clear()
R11b = run(refuse, 400, cur=16.0, a=16.0, sel=False, cb=at(300))
check(f"T11b: the select refused, the restore close refused: 3 tries "
f"({nz(R11b, 0, 300)}), fails {R11b.rows[21]['fails']}, gave_up, "
f"REF once ({refs(R11b)}); phase_fails {R11b.rows[21]['phase_fails']}; "
f"1 select try ({len(R11b.drv.phases_log)}); a user change writes at "
"once",
near(nz(R11b, 0, 300), [11, 16, 21])
and R11b.rows[21]["fails"] == CM.MAX_TRIES and R11b.rows[21]["gave_up"]
and refs(R11b) == [21] and R11b.rows[21]["phase_fails"] == 1
and len(R11b.drv.phases_log) == 1 and nz(R11b, 300)[:1] == [300])
never("T11b", R11b, ucs=[300])
UCS.clear()
R12a = run(lambda a, n: a != 0.0, 400)
check(f"T12a: only the 0 A fails (_begin): tries {zeros(R12a)} >= 60 s "
f"apart, at most 3, no select, REF once ({refs(R12a)})",
0 < len(zeros(R12a)) <= 3 and not R12a.drv.phases_log
and all(b - a >= 60 for a, b in zip(zeros(R12a), zeros(R12a)[1:]))
and len(refs(R12a)) == 1 and R12a.rows[399]["gave_up"])
R12b = run(lambda a, n: True, 100, sel=False)
check(f"T12b: a refused select counts for the phases only: close taken, fails "
f"{R12b.rows[60]['fails']}, phase_fails {R12b.rows[60]['phase_fails']}, "
"no REF",
R12b.rows[60]["fails"] == 0 and R12b.rows[60]["phase_fails"] == 1
and R12b.rows[1]["fails"] == 0 and R12b.rows[1]["phase_fails"] == 1
and not refs(R12b) and not R12b.rows[60]["gave_up"])
R12c = run(lambda a, n: True, 100, cur=16.0, a=16.0,
power=lambda t, d: 1380.0)
check(f"T12c: the drawing timeout, the restore taken: fails "
f"{R12c.rows[60]['fails']}, no give-up, phase_fails "
f"{R12c.rows[60]['phase_fails']}",
R12c.rows[60]["fails"] == 0 and not R12c.rows[60]["gave_up"]
and R12c.rows[60]["phase_fails"] == 1 and not refs(R12c))
print("\n5. UNDO, SHUTDOWN, SOLAR, A CHARGER THAT ANSWERS (T13, T14, T15)")
UCS.clear()
def off_at(t0):
def cb(t, st, w, drv):
if t == t0:
st["mode"] = "off"
return cb
R13a = run(refuse, 100, power=lambda t, d: 1380.0, cb=off_at(5))
check(f"T13a: Off in stage zero: 10 A restored once ({nz(R13a)}), undone "
f"{R13a.w.undone}, fails {R13a.rows[99]['fails']}",
near(nz(R13a, a=10.0), [5]) and len(nz(R13a)) == 1
and R13a.w.undone == 1 and R13a.rows[99]["fails"] == 0)
R13b = run(refuse, 100, cb=off_at(12))
check(f"T13b: Off after close 1: the closes go on ({nz(R13b)}), give-up at "
f"21, REF once ({refs(R13b)}), no write after",
nz(R13b) == [11, 16, 21] and R13b.rows[21]["gave_up"]
and refs(R13b) == [21])
box = {}
def abandon_cb(t0, ans_kind):
def cb(t, st, w, drv):
if t == t0 + 1:
async def go():
n0 = len(drv.calls)
try:
await w.abandon(drv, float(t), Trk(), clamp=16.0)
box[ans_kind] = ("ok", len(drv.calls) - n0)
except RuntimeError:
box[ans_kind] = ("raised", len(drv.calls) - n0)
return go()
return cb
R13c = run(refuse, 40, cb=abandon_cb(11, "R"))
check(f"T13c: shutdown between close 1 and 2: the old 10 A restored once, "
f"strict, no exception ({box.get('R')}), seq None, calls {nz(R13c)}",
box.get("R") == ("ok", 1) and R13c.w.seq is None
and near(nz(R13c, a=10.0), [12]))
R13x = run(raises, 40, cb=abandon_cb(11, "X"))
check(f"T13c: X: the raise comes out of abandon, as base, for the caller's "
f"CHARGER_RESTORE ({box.get('X')}); the writer's seq is None",
box.get("X") == ("raised", 1) and R13x.w.seq is None)
R13d = run(refuse, 40, cb=abandon_cb(40, "D"))
n_d = len(R13d.drv.calls)
async def after_giveup():
n0 = len(R13d.drv.calls)
await R13d.w.abandon(R13d.drv, 41.0, Trk(), clamp=16.0)
return len(R13d.drv.calls) - n0
check("T13d: shutdown after the give-up: no write",
asyncio.run(after_giveup()) == 0 and R13d.w.gave_up)
def solar_writer(cur):
w = CM.SolarWriter()
w.engaged, w.mode_was = True, CM.SOLAR
w.fresh_start = w.restart = False
w.was_available = w._seen = True
w.sent_a, w.taken, w.last_a = cur, True, cur
w.plan.a, w.plan.n = cur, 1
w._plan_step = lambda *a, **k: None
return w
def sp3(press, cls=solar_writer):
LOG.clear()
drv = Drv(8.0, refuse)
w, trk = cls(8.0), Trk()
w.plan._set(8.0, 0.0, 3)
pressed = None
async def main():
nonlocal pressed
for t in range(1, 200):
if press and pressed is None and \
len([x for x in drv.calls if x[1] > 0]) == 1:
w.user_changed()
pressed = t
drv.now = float(t)
CLOCK["t"] = t
w.cut_quarter(int(t // 900))
r = Rd(drv.cur, drv.ph, power=0.0 if drv.cur == 0 else 1840.0)
await w.step(drv, r, mode=CM.SOLAR,
sun=CM.SunInputs(target_w=2000.0), clamp=16.0,
now=float(t), tracker=trk, writing=True,
status="charging")
asyncio.run(main())
nzs = [int(t) for t, x in drv.calls if x > 0]
rf = [t for t, lv, m in LOG if lv == "WARNING" and REF in m]
return nzs, w.fails, w.gave_up, rf, pressed
S_NONE = sp3(False)
S_PRESS = sp3(True)
check(f"T25/T14 (N14, EV-60): Solar has no extra _failed at its close end. "
f"No press: 8 A at 12, 17, 22, fails 3, gave_up, REF at 22 "
f"({S_NONE})",
S_NONE == ([12, 17, 22], 3, True, [22], None))
check(f"T25 (resetSuper trap, EV-60): a Solar press at 13 does not reset "
f"Solar's close tries, and the value gets MAX_TRIES tries since the "
f"press: 8 A at 12, 17, 22, 82, fails 3, gave_up, REF at 82 "
f"({S_PRESS})",
S_PRESS == ([12, 17, 22, 82], 3, True, [82], 13))
def t14c():
"""T14c: Solar's close value changes between the tries (the spare falls
during the settle): `want_a(q)` is a function of the sequence. `_advance`
driven directly on a SolarWriter in stage settle, the close refused."""
LOG.clear()
w, drv, trk = solar_writer(8.0), Drv(0.0, lambda a, n: False), Trk()
w.seq = {"stage": "settle", "t0": 0.0, "n": 3, "tries": 0, "prev": 8.0,
"t1": 0.0}
vals = {10: 8.0, 15: 7.0, 20: 6.0}
async def main():
for t in range(10, 40):
if w.seq is None:
break
drv.now = float(t)
CLOCK["t"] = t
r = Rd(drv.cur, drv.ph, power=0.0)
await w._advance(drv, r, 0.0, float(t), trk,
lambda q: vals.get(t, 5.0), 16.0, 1)
asyncio.run(main())
rf = [t for t, lv, m in LOG if lv == "WARNING" and REF in m]
return ([(int(t), x) for t, x in drv.calls], w.fails, w.gave_up, rf,
w.seq)
S14C = t14c()
check(f"T14c (N14, EV-60): Solar's close value moves between tries: 8, 7, 6 A "
f"at 10, 15, 20, then `fails` 3 (no extra _failed), gave_up, REF at "
f"20, seq None ({S14C})",
S14C == ([(10, 8.0), (15, 7.0), (20, 6.0)], 3, True, [20], None))
print("\n6. THE CAP, RESTART, UNKNOWN, NO CHARGER (T15-T22)")
UCS.clear()
RA = run(lambda a, n: True, 100)
check(f"T15: a charger that answers: 0 A at 0, 6 A at 11, nothing else "
f"({RA.drv.calls}); fails 0, no give-up, phase_done_at "
f"{RA.rows[11]['phase_done_at']}",
RA.drv.calls == [(0.0, 0.0), (11.0, 6.0)]
and RA.rows[99]["fails"] == 0 and RA.rows[11]["phase_done_at"] == 11
and not refs(RA))
for cap in (2, 4):
UCS.clear()
saved = CM.MAX_TRIES
CM.MAX_TRIES = cap
try:
R16 = run(refuse, 400)
finally:
CM.MAX_TRIES = saved
want16 = [11 + 5 * i for i in range(cap)]
check(f"T16: MAX_TRIES {cap}: tries {nz(R16)} (never {cap + 1}), give-up "
f"at {want16[-1]}, REF {refs(R16)}",
nz(R16) == want16 and refs(R16) == [want16[-1]]
and R16.rows[want16[-1]]["fails"] == cap
and R16.rows[want16[-1]]["gave_up"])
UCS.clear()
w20 = CM.ManualWriter()
check("T20: a restart: the new writer starts with 0 fails, no give-up, and "
"no count",
w20.fails == 0 and not w20.gave_up
and getattr(w20, "_close_k", 0) == 0)
R20 = run(refuse, 30, w=w20)
check(f"T20: after the restart the first write goes out once ({zeros(R20)})",
zeros(R20) == [0])
R21 = run(refuse, 400, rd_none=True)
check(f"T21: the read-back unknown (allowed and setpoint None): judged by the "
f"write's result: tries {nz(R21)}, give-up, REF once ({refs(R21)})",
len(nz(R21)) == 3 and R21.rows[399]["gave_up"] and len(refs(R21)) == 1
and not R21.errs)
R21b = run(refuse, 400, power=lambda t, d: None, cur=16.0, a=16.0)
check(f"T21: the power unknown: the drawing timeout's restore is tried 3 "
f"times (20, 25, 30), then the give-up and one REF, no exception "
f"({nz(R21b)}, {refs(R21b)}, {R21b.errs[:1]})",
nz(R21b) == [20, 25, 30] and R21b.rows[30]["gave_up"]
and refs(R21b) == [30] and not R21b.errs)
R22 = run(refuse, 600, avail=lambda t: False)
check("T22: no charger: 0 writes, no lines, no REF",
not R22.drv.calls and not R22.log and not refs(R22))
print("\n6b. A GIVE-UP NEVER BLOCKS THE UNDO, THE SHUTDOWN OR A NEW SEQUENCE (N4)")
def given_up_writer():
w = CM.ManualWriter()
w.gave_up, w.fails = True, CM.MAX_TRIES
w.seq = {"stage": "zero", "t0": 0.0, "n": 3, "tries": 0, "prev": 10.0}
return w, Drv(0.0, lambda a, n: True), Trk()
w13, d13, t13 = given_up_writer()
asyncio.run(w13._undo(d13, 1.0, t13, 16.0, False))
check(f"T13e/N4: `_undo` with gave_up set restores the 10 A ({d13.calls})",
d13.calls == [(0.0, 10.0)] and w13.seq is None)
w13, d13, t13 = given_up_writer()
asyncio.run(w13.abandon(d13, 1.0, t13, clamp=16.0))
check(f"T13e/N4: `abandon` with gave_up set gives the 10 A back "
f"({d13.calls})", d13.calls == [(0.0, 10.0)] and w13.seq is None)
w13, d13, t13 = given_up_writer()
w13.seq = None
asyncio.run(w13._begin(d13, Rd(10.0), 10.0, 3, 1.0, t13))
check(f"T13e/N4: `_begin` with gave_up set still writes the 0 A "
f"({d13.calls})", d13.calls == [(0.0, 0.0)] and w13.seq is not None)
print("\n6c. THE EDITS TO EXISTING TESTS, N7, N12 (T17, T18, T11c, N7, N11, N12)")
def tsrc(name):
return open(os.path.join(HERE, name), encoding="utf-8").read()
s56, s13, s28 = tsrc("test_ev56.py"), tsrc("test_ev13.py"), tsrc("test_ev28.py")
BASE_DIGESTS = ("905c0b8ba89bb307", "343ea01aacfa1019", "ff6306ce56b35c64",
"f1fb141275839562", "369069be9187ab3c", "2cd78dee7ee93aaa",
"f0adb058a5bbefba", "6d7bcb747d1dc5a3", "2be1a760b699b28c",
# EV-60 (Q4): "T20 T12 [R]" re-taken, was 2fd24ddbb18f14cc
"a5888e4557b4ee8f", "25a205989dc44204", "1ad97e089468d71b",
"7baf8981ab382e05", "54701b140ec6f30b", "0cfd3ccd334f378d",
"1d85595302dc032a", "5fc65dbdc730e539")
check("T17 (Q1, Q2): test_ev56 has the re-taken golden 'T20 T5 [R]' "
"(78ffe9cf72c5e214, the old ba32810fbb40d0f9 gone), T5 asserts "
"fails == MAX_TRIES and gave_up, T5b asserts len == MAX_TRIES",
'"T20 T5 [R]": "78ffe9cf72c5e214"' in s56
and "ba32810fbb40d0f9" not in s56
and 'end5[1]["fails"] == CM.MAX_TRIES' in s56
and 'end5[1]["gave_up"] is True' in s56
and "len(six) == CM.MAX_TRIES" in s56)
check("N11: every other golden digest of test_ev56 is the base's, and "
"GOLDEN['T5b'] still holds base's 5 tries",
all(f'"{d}"' in s56 for d in BASE_DIGESTS)
and '"T5b": [(111.0, 6.0), (116.0, 6.0), (121.0, 6.0), (181.0, 6.0),'
in s56)
check("T18: test_ev13 T13's check text says 'one refusal counted' and its "
"assert is still fails == 1",
"no window left, one refusal counted, the mute set" in s13
and "no refusal counted" not in s13
and "w.c.car_writer.fails == 1 and w.c.car.mute_until > 0" in s13)
check("N11: test_ev13 T26 lost only the 4th and 5th tries (1095, 1155) of "
"'T20-beside' and 'T20-inside'",
s13.count("(1035, 16.0, False)], [(11, 'current', 0.0), "
"(15, 'phases', 1)])") == 2
and "(1095, 16.0, False)" not in s13
and "(1155, 16.0, False)" not in s13)
check("T11c: test_ev28 T15 asserts fails == MAX_TRIES, gave_up, 3 tries and "
"the car at 0 A with no select (the only edit, ruled Q3)",
"w.wr.fails == MAX_TRIES" in s28 and "w.wr.gave_up" in s28
and "w.sim.readback_a == 0 and len(tries) == MAX_TRIES" in s28)
UCS.clear()
RN7 = run(lambda a, n: True, 400, cb=at(100, a=8.0))
check(f"N7: a charger that answers: the calls are 0 A at 0, 6 A at 11, 8 A at "
f"100 and nothing else ({RN7.drv.calls}); no REF, fails 0, no "
"give-up, no ERROR",
RN7.drv.calls == [(0.0, 0.0), (11.0, 6.0), (100.0, 8.0)]
and not refs(RN7) and not recs(RN7)
and RN7.rows[399]["fails"] == 0 and not RN7.rows[399]["gave_up"])
n12 = [x for x in R1.trk.notes if x[1] > 0]
check(f"N12: the tracker is told of each refused close once ({n12}) and of "
f"no raised close ({[x for x in RX.trk.notes if x[1] > 0]}, "
f"begin/end per write {RX.trk.notes[:1]})",
len(n12) == 3 and all(not ok for _t, _a, ok in n12)
and not [x for x in RX.trk.notes if x[1] > 0])
print("\n7. N4, N8, N10")
APP = os.path.join(HERE, "app")
SRC = {f: open(os.path.join(APP, f), encoding="utf-8").read()
for f in sorted(os.listdir(APP)) if f.endswith(".py")}
cm_src = SRC["carmode.py"]
check("N8 (write_phases and the peak-cut rules untouched): carmode.py still "
"has the one `write_phases(` call and no new write path; base had 1",
cm_src.count("write_phases(") == 1
and cm_src.count("drv.write_current(") == 1)
check("N10 (no new store key, setting, notification or timer): `_close_k` "
"lives in carmode.py only, never next to a store or option; the "
"asyncio.sleep, create_task and _LOG.warning counts are the base's "
"(1, 0, 10)",
[f for f, s in SRC.items() if "_close_k" in s] == ["carmode.py"]
and cm_src.count("asyncio.sleep") == 1
and cm_src.count("create_task") == 0
and cm_src.count("_LOG.warning(") == 10
and not any("_close_k" in line and ("store" in line or "opts" in line)
for line in cm_src.splitlines()))
w4 = CM.ManualWriter()
w4.gave_up, w4.fails, w4._close_k = True, 3, 3
w4.user_changed()
check("N4: user_changed clears gave_up, fails and the close count",
not w4.gave_up and w4.fails == 0 and w4._close_k == 0)
R4n = run(refuse, 400, cb=at(100, a=8.0))
check("N4: a give-up does not block the next user change or phase change "
f"({nz(R4n, 100)[:1]})", nz(R4n, 100)[:1] == [100])
print()
if fails:
print(f"FAIL: {len(fails)} check(s)")
for f in fails:
print(" -", f)
sys.exit(1)
print("ok: EV-59")
File diff suppressed because it is too large Load Diff
+583
View File
@@ -0,0 +1,583 @@
"""EV-69: a close value an ended phase change tried stays the add-on's own, so
the charger taking it late is never read as another writer (no false
CHARGER_OTHER, the peak cut never blocked). `python3 -B test_ev69.py`
Rows T1-T20, T23-T25 and the Never rules N1-N9 of reports/EV-69-test-plan.md
(T21 is test_ev69_fuzz.py, T14 and T22 are the existing suites CI runs). Every
check's label starts with its id. Writer level, `tools/ev69_kit.py`: a
`SolarWriter` / `ManualWriter` on a stub driver, a stub tracker and a stub
reading; time is a 1 s step counter on the model clock. `Base69` is de733f4's
behaviour (the carry switched off): the red side of a row, and the equal side
of T17 (i).
"S1" is the EV-22 review repro (round 2): own 3 -> 1 select taken (window from
122), clamp 16 up to 134 and 8 from 135, close tries 12 A at 132, 8 A at 137
and 142 (all refused), a press at 138, MAX_TRIES ends the change at 142, the
12 A shown at 140. "S1-np": no press. "S1-nt": no take at 140. "CE": the
EV-60 cap end (cut_fails 2, close 1 refused, cap 6 A, close 2 = 6 A refused,
then the cap end E). "MW": the Manual shape.
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
from app import carmode as CM # noqa: E402
from named_absence import nth, present # noqa: E402
from ev69_kit import (Base69, BaseM69, Drv, LOG, LOOP, Rd, Run, CLOCK, # noqa: E402,F401
REC, cap, check, done, evs, n_other, n_some, near,
nev, press, set_cap, show, swriter, LAST)
# ------------------------------------------------------------------ worlds
def mk_s1(cls=None, take=None):
w = swriter(0.0, ph=3, cls=cls)
w.plan.a, w.plan.n = 12.0, 1
drv = Drv(0.0, take or (lambda a, d: False), ph=1)
w.seq = {"stage": "settle", "t0": 119.0, "t1": 122.0, "n": 1, "tries": 0,
"prev": None, "from": 3, "own": [0.0], "sel": True}
w.last_done = 122.0
w._own_n = 3
w._select_try(1, True)
return w, drv
def clamp_s1(t):
return 16.0 if t < 135 else 8.0
def s1(until=400, ev=(), press_at=138, show_at=140, take=None, cls=None,
cur=None, stale=None, gone=None, writing=None):
w, drv = mk_s1(cls, take)
pairs = list(ev)
if press_at is not None:
pairs.append((press_at, press))
if show_at is not None:
pairs.append((show_at, lambda w_, d, s: setattr(
d, "cur", d.calls[0][1])))
r = Run(w, drv)
return r.go(123, until, ev=evs(*pairs), clamp=clamp_s1, cur=cur,
stale=stale, gone=gone, writing=writing)
def mk_ce(cls=None, take=None, cut_fails=2, plan_a=8.0):
w = swriter(plan_a, ph=1, cls=cls)
w.cut_key, w.cut_fails, w.cut_fail_at = 0, cut_fails, -100.0
w.plan._set(plan_a, 130.0, 3)
drv = Drv(plan_a, take or (lambda a, d: a == 0.0), ph=1)
return w, drv
def ce(until=960, cls=None, hook=None, ev=(), plan_a=8.0, take=None,
press_after_close2=False):
"""Close 1 refused, the cap comes in the step after it, close 2 (a cut
try, 6 A) refused, then the cap end E."""
w, drv = mk_ce(cls, take, plan_a=plan_a)
st = {"cap": False}
def h(t, w_, d, s):
nz = [1 for tt, a in d.calls if a > 0]
if nz and not s["cap"]:
s["cap"] = True
set_cap(w_, 6.0)
if press_after_close2 and len(nz) == 2 and not s.get("pr"):
s["pr"] = True
w_.user_changed()
if hook:
hook(t, w_, d, s)
r = Run(w, drv, st=st)
return r.go(130, until, ev=evs(*ev), hook=h)
def close_times(r):
return [int(t) for t, a in r.drv.calls if a > 0]
def mw(until, user=False, hook2=None, cls=None):
"""Manual at 12 A on 1 phase; the user picks 3 phases at 100. Every
current write but the 0 A is refused. Close 1 = 12 A, then the clamp
falls to 8 (or the user lowers the current to 8) before try 2."""
w = (cls or CM.ManualWriter)()
drv = Drv(12.0, lambda a, d: a == 0.0, ph=1)
st = {"a": 12.0, "n": 1, "rev": 1, "clamp": 16.0}
r = Run(w, drv, kind="manual", st=st)
def hook(t, w_, d, s):
if t == 100:
w_.user_changed()
s["rev"] += 1
s["n"] = 3
nzc = [1 for tt, a in d.calls if a > 0]
if len(nzc) == 1 and not s.get("low"):
s["low"] = True
if user:
w_.user_changed()
s["rev"] += 1
s["a"] = 8.0
else:
s["clamp"] = 8.0
if hook2:
hook2(t, w_, d, s)
return r.go(0, until, hook=hook)
# =========================================================================== #
print("S1 (the reviewer's clamp shape), Solar")
# =========================================================================== #
cut150 = (150, cap(6.0))
base = s1(400, ev=[cut150], cls=Base69)
check(f"T1 [red on base]: S1 on de733f4 (the carry off): mismatch "
f"{base.first_ms(140)}, hold {base.first_hold()}, no peak cut write "
f"({base.calls_from(143, 400, True)[:3]})",
near(base.first_ms(140), 143, 144) and near(base.first_hold(), 173, 174)
and 6.0 not in [a for _, a in base.calls_from(143, 200)])
r = s1(400, ev=[cut150])
cut_w = [x for x in r.calls_from(150, 152) if x[1] == 6.0]
check(f"T1: S1 (12 A shown at 140), the cut due at 150: 140-400 no mismatch, "
f"hold, CHARGER_OTHER or 'Something else' line ({r.first_ms(140)}, "
f"{n_other()}, {n_some()}), the 6 A peak cut write "
f"at 150-151 ({cut_w}), gave_up never True",
r.clean(140, 400) and n_other() == 0 and n_some() == 0 and cut_w
and not any(r.gu[t] for t in range(140, 401)))
nev("T1", r)
r = s1(400)
check("T2: S1 to 400, no cut: no mismatch, hold or CHARGER_OTHER 140-400",
r.clean(140, 400) and n_other() == 0 and n_some() == 0)
w8 = [x for x in r.calls_from(190, 215) if x[1] == 8.0]
check(f"T2: the 8 A retry goes out at about 202 and is refused ({w8}); 12 A "
f"stays own after that write: prior_a = was = 12 "
f"({r.prior[205]}, {r.att[205]})",
len(w8) == 1 and near(w8[0][0], 202, 203) and r.prior[205] == 12.0
and r.att[205] == 8.0 and r.carry[205] == [])
nev("T2", r)
# T3 (changed, GUR): H2 and the reset of fails / gave_up
rb = s1(400, press_at=None, ev=[cut150], cls=Base69)
rc = s1(400, press_at=None, ev=[cut150])
cw = [x for x in rc.calls_from(150, 152) if x[1] == 6.0]
check(f"T3: S1-np, the cut from 150: the 6 A cut write at 150-151 ({cw}), no "
f"mismatch, hold or CHARGER_OTHER 140-400 ({n_other()})",
cw and rc.clean(140, 400) and n_other() == 0)
nev("T3", rc)
rp = s1(400, press_at=None)
check(f"T3: H2, the press is not needed: S1-np on de733f4 gives mismatch "
f"{rb.first_ms(140)}, hold {rb.first_hold()}, gave_up {rb.gu[142]}, "
f"and no cut write ({rb.calls_from(143, 200, True)[:2]}) (B1)",
near(rb.first_ms(140), 143, 144) and rb.first_hold() is not None
and rb.gu[142] is True
and 6.0 not in [a for _, a in rb.calls_from(143, 200)])
check(f"T3: S1-np, no cut: no mismatch, hold or CHARGER_OTHER 140-400 "
f"({n_other()})", rp.clean(140, 400) and n_other() == 0)
check(f"T3 (GUR): the carried 12 A take resets fails/gave_up only: gave_up "
f"True at 142 ({rp.gu[142]}), False and fails 0 from 143 "
f"({rp.gu[143]}, {rp.fl[143]}); the clamp value 8 A is re-sent at the "
f"next retry ({rp.calls_from(190, 215)}). EV-69 GUR: a carried take "
f"resets fails/gave_up only",
rp.gu[142] is True and not any(rp.gu[t] for t in range(143, 202))
and all(rp.fl[t] == 0 for t in range(143, 202))
and rp.calls_from(190, 215) == [(202, 8.0)])
# T23 (GUR): a carried take is not an adopt
check(f"T23: S1-np, the carried 12 A take: taken stays False, last_a None, "
f"sent_a 8 A unchanged 143-201 "
f"({set(rp.taken[t] for t in range(143, 202))}, "
f"{set(rp.last_a[t] for t in range(143, 202))}, "
f"{set(rp.sent_a[t] for t in range(143, 202))}); the 8 A goes out at "
f"the next RETRY_S step ({rp.calls_from(143, 400)[:1]})",
all(rp.taken[t] is False for t in range(143, 202))
and all(rp.last_a[t] is None for t in range(143, 202))
and all(rp.sent_a[t] == 8.0 for t in range(143, 202))
and (142 + int(CM.RETRY_S), 8.0) in rp.calls_from(143, 400))
# T4: a late take after the end
for tk in (150, 143, 170, 199):
ev = [(tk, show(12.0))]
rb = s1(400, show_at=None, ev=ev, cls=Base69)
r = s1(400, show_at=None, ev=ev)
check(f"T4: S1-nt, 12 A from {tk}: no mismatch 142-400 (the standing 0 A "
f"is no take and does not end the carry) ({r.first_ms(142)}); "
f"base: {rb.first_ms(142)}",
r.clean(142, 400) and n_other() == 0
and rb.first_ms(142) is not None)
# T6 (c): a foreign value after the end is still counted and held
r = s1(400, ev=[(160, show(16.0))])
check(f"T6 (i): S1 then foreign 16 A at 160: mismatch at 160-161 "
f"({r.first_ms(150)}), hold at +30 ({r.first_hold()}) and not +29, "
f"exactly 1 CHARGER_OTHER ({n_other()}), nothing non-zero written 160-"
f"400 ({r.calls_from(160, 400, True)})",
near(r.first_ms(150), 160, 161) and near(r.first_hold(), 190, 191)
and r.first_hold() - r.first_ms(150) == 30 and n_other() == 1
and not r.calls_from(160, 400, True) and not r.viol)
nev("T6 (i)", r)
r = s1(400, show_at=None, ev=[(150, show(5.0))])
check(f"T6 (iii): S1-nt, foreign 5 A at 150: mismatch at 150-151 "
f"({r.first_ms(142)}), hold 30 s later ({r.first_hold()}), 1 "
f"CHARGER_OTHER ({n_other()}), nothing non-zero written after "
f"({r.calls_from(150, 400, True)})",
near(r.first_ms(142), 150, 151) and r.first_hold() - r.first_ms(142)
== 30 and n_other() == 1 and not r.calls_from(150, 400, True))
nev("T6 (iii)", r)
# T7: OQ3, the known limit and its edge
r = s1(400, show_at=None, ev=[(150, show(12.0))])
check(f"T7 (i): S1-nt, a foreign value exactly 12 A at 150: no mismatch "
f"150-200 (the accepted OQ3 limit, EV-67 class) ({r.first_ms(150)})",
r.clean(150, 200))
r = s1(400, show_at=None, ev=[(230, show(12.0))],
take=lambda a, d: a == 8.0 and d.now >= 200)
check(f"T7 (ii): the 8 A retry taken at 202 (an own take ends the bound), "
f"foreign 12 A at 230: mismatch at 230 ({r.first_ms(203)}), hold at "
f"260 ({r.first_hold()}), 1 CHARGER_OTHER ({n_other()})",
near(r.first_ms(203), 230, 231) and near(r.first_hold(), 260, 261)
and n_other() == 1)
# T10-T13: the bound
r = s1(400, show_at=None, ev=[(150, show(8.0)), (160, show(12.0))])
check(f"T10: S1-nt, the charger takes 8 A (sent_a, an adopt) at 150, then "
f"shows 12 A at 160: mismatch at 160 ({r.first_ms(150)}), hold at 190 "
f"({r.first_hold()}), 1 CHARGER_OTHER ({n_other()}), nothing non-zero "
f"written 160-400 ({r.calls_from(160, 400, True)})",
near(r.first_ms(150), 160, 161) and near(r.first_hold(), 190, 191)
and n_other() == 1 and not r.calls_from(160, 400, True)
and r.carry[151] == [])
nev("T10", r)
r = s1(400, show_at=None, ev=[(210, show(12.0))])
check(f"T11: S1-nt, the 8 A retry at about 202 refused on 0 A (prior_a 0), "
f"12 A at 210: mismatch at 210 ({r.first_ms(150)}), hold at 240 "
f"({r.first_hold()}), 1 CHARGER_OTHER ({n_other()})",
near(r.first_ms(150), 210, 211) and near(r.first_hold(), 240, 241)
and n_other() == 1 and r.prior[205] == 0.0)
r = s1(400, show_at=None, ev=[(190, cap(6.0)), (210, show(12.0))])
check(f"T11 variant: the new write is a cut try (cap 6 at 190): 12 A at 210: "
f"mismatch ({r.first_ms(150)}), hold ({r.first_hold()}), 1 "
f"CHARGER_OTHER ({n_other()}), cut written "
f"({r.calls_from(190, 195, True)})",
near(r.first_ms(150), 210, 211) and near(r.first_hold(), 240, 241)
and n_other() == 1 and (190, 6.0) in r.calls_from(190, 192, True))
r = s1(400, show_at=None, ev=[(145, press), (150, show(12.0))])
check(f"T12: S1-nt, a press at 145 (no hold: the carry ends), 12 A at 150: "
f"mismatch at 150 ({r.first_ms(146)}), hold at 180 ({r.first_hold()}), "
f"1 CHARGER_OTHER ({n_other()}), no write at or above 12 A "
f"({[x for x in r.calls_from(145) if x[1] >= 12.0]})",
near(r.first_ms(146), 150, 151) and near(r.first_hold(), 180, 181)
and n_other() == 1 and not [x for x in r.calls_from(145)
if x[1] >= 12.0])
nev("T12", r)
# The press's own retry write ends the carry too, so the row above cannot see
# the press end it. Here no step after the press is fresh (no write): the
# press alone is graded on the state.
# EV-71 P1: a press that lifts nothing ends nothing. This press lifts no count
# and no hold, so the carry stands (it was: gone with the press).
r = s1(400, show_at=None, ev=[(145, press), (146, show(12.0))],
stale=lambda t: 145 <= t <= 149)
check(f"T12 (press alone): S1-nt, a press at 145 that lifts nothing, no fresh "
f"read and no write until 150: the carry stands "
f"({r.carry[144]}, {r.carry[145]}), 12 A is an own value "
f"({r.own[149]})",
r.carry[144] != [] and all(r.carry[t] == r.carry[144]
for t in range(145, 150))
and 12.0 in r.own[149] and not r.calls_from(145, 149))
r = s1(400, show_at=None, ev=[(145, show(16.0)), (200, show(12.0))])
check(f"T13: S1-nt, foreign 16 A at 145 (hold at 175), the writer then sets "
f"12 A at 200: the hold stands 175-400 (no lift by match on an old "
f"value) ({r.first_hold()}, {all(r.hold[t] for t in range(176, 401))}), "
f"1 CHARGER_OTHER ({n_other()}), nothing written 145-400 "
f"({r.calls_from(145, 400)})",
near(r.first_hold(), 175, 176) and all(r.hold[t] for t in range(177, 401))
and n_other() == 1 and not r.calls_from(145, 400, True)
and r.carry[176] == [])
nev("T13", r)
# T15: unknown read-backs
r = s1(400, show_at=None, ev=[(151, show(12.0))],
cur=lambda t, d: None if 143 <= t <= 150 else d.cur)
check(f"T15 (i): S1-nt, an unknown read-back 143-150 and 12 A at 151: no "
f"mismatch 143-400 ({r.first_ms(140)}), no hold, no CHARGER_OTHER "
f"({n_other()})", r.clean(143, 400) and n_other() == 0)
r = s1(400, show_at=None, ev=[(145, show(16.0))],
cur=lambda t, d: None if 150 <= t <= 160 else d.cur)
check(f"T15 (ii): foreign 16 A at 145, unknown 150-160, 16 A again from 161: "
f"mismatch from 145 ({r.first_ms(140)}), the count stands through "
f"None ({all(r.ms[t] is not None for t in range(146, 175))}), hold at "
f"175 ({r.first_hold()})",
near(r.first_ms(140), 145, 146)
and all(r.ms[t] is not None for t in range(146, 175))
and near(r.first_hold(), 175, 176) and n_other() == 1)
# T16: stale reads
r = s1(400, show_at=None, ev=[(143, show(12.0))],
stale=lambda t: 143 <= t <= 147)
check(f"T16 (i): S1-nt, 12 A shown from 143 but stale for 143-147: those "
f"steps decide nothing, 148-400 no mismatch ({r.first_ms(140)}), no "
f"CHARGER_OTHER ({n_other()}); the carry stands through them "
f"({r.carry[147]})",
r.clean(143, 400) and n_other() == 0 and r.carry[147] != [])
r = s1(400, show_at=None, ev=[(145, show(16.0))])
check(f"T16 (ii): a frozen foreign read is a mismatch, then a hold, as "
f"before ({r.first_ms(140)}, {r.first_hold()})",
near(r.first_ms(140), 145, 146) and near(r.first_hold(), 175, 176))
# T17: restart and return
rn = s1(400, show_at=None, cur=lambda t, d: 12.0 if t >= 156 else d.cur,
gone=lambda t: 145 <= t <= 155)
rbs = s1(400, show_at=None, cur=lambda t, d: 12.0 if t >= 156 else d.cur,
gone=lambda t: 145 <= t <= 155, cls=Base69)
same = all((rn.ms[t], rn.hold[t], rn.ncalls[t]) ==
(rbs.ms[t], rbs.hold[t], rbs.ncalls[t]) for t in range(156, 401))
check(f"T17 (i): the charger gone 145-155, back showing 12 A: from 156 every "
f"cycle's writes, mismatch and hold equal de733f4 on the same run "
f"({same}); the carry stands while it is gone ({rn.carry[155]}) and is "
f"gone with the return ({rn.carry[156]})",
same and rn.carry[156] == [] and rn.carry[155] != [])
src = open(os.path.join(HERE, "app", "carmode.py")).read()
others = [f for f in os.listdir(os.path.join(HERE, "app"))
if f.endswith(".py") and f != "carmode.py"
and "_carry" in open(os.path.join(HERE, "app", f)).read()]
w2, m2 = CM.SolarWriter(), CM.ManualWriter()
check(f"T17 (ii): a new writer (a process restart) carries nothing "
f"({w2._carry}, {m2._carry}); the carry is in no other module (no state "
f"file key) ({others})",
w2._carry == [] and m2._carry == [] and not others)
# T18: a raised try is carried
for lab, val in (("(i) try 2 (8 A) raising", 8.0),
("(ii) try 1 (12 A) raising", 12.0)):
take = (lambda v: lambda a, d: "raise" if a == v else False)(val)
rb = s1(400, show_at=None, ev=[(150, show(12.0))], take=take,
cls=Base69, press_at=None)
r = s1(400, show_at=None, ev=[(150, show(12.0))], take=take,
press_at=None)
errs = [t for t, lv, m in r.log if lv == "ERROR" and m == REC]
check(f"T18 {lab}: 12 A shown at 150: no mismatch 150-400 "
f"({r.first_ms(150)}), the raised value counted as a try, one "
f"ERROR record per value ({len(errs)}); base: {rb.first_ms(150)}",
r.clean(150, 400) and n_other() == 0 and len(errs) == 1
and rb.first_ms(150) is not None)
# T20: Stop / the 0 A rule
t0 = lambda a, d: a == 0.0 and d.now >= 158 # noqa: E731
r = s1(400, show_at=140, take=t0, writing=lambda t: t < 160)
z = [x for x in r.calls_from(160) if x[1] == 0.0]
check(f"T20 (i): S1 (12 A own), Stop at 160: the way-out 0 A at 160 ({z[:1]}), "
f"no mismatch at 160 ({r.ms[160]}), no hold, no CHARGER_OTHER "
f"({n_other()})",
z and near(z[0][0], 160, 161) and r.ms[160] is None
and not any(r.hold.values()) and n_other() == 0)
r = s1(400, take=t0, ev=[(160, show(16.0))], writing=lambda t: t < 170)
z = [x for x in r.calls_from(160) if x[1] == 0.0]
check(f"T20 (ii): T6 (i) with Stop at 170 (the count running since 160): the "
f"0 A goes out in the count ({z[:2]}), no hold after it "
f"({r.first_hold()}), no CHARGER_OTHER ({n_other()})",
z and near(z[0][0], 170, 171) and r.first_hold() is None
and n_other() == 0)
r = s1(400, take=t0, ev=[(160, show(16.0))], writing=lambda t: t < 200)
check(f"T20 (iii): T6 (i) with Stop at 200 (the hold stands): nothing "
f"written 160-400 ({r.calls_from(160, 400)}), the hold stands "
f"({r.hold[300]}), 1 CHARGER_OTHER ({n_other()})",
not r.calls_from(160, 400) and r.hold[300] and n_other() == 1)
# =========================================================================== #
print("CE (the EV-60 cap end), Solar")
# =========================================================================== #
r = ce(960)
ct = close_times(r)
E = nth(ct, 1) + 5
check(f"T5 setup: close 1 (8 A) at {nth(ct, 0)}, the cap, close 2 (6 A) at "
f"{nth(ct, 1)}, the cap end at {E} with no write ({r.ended})",
present(E) and len(ct) >= 2 and r.drv.calls[0][1] == 0.0
and [a for t, a in r.drv.calls if a > 0][:2] == [8.0, 6.0]
and r.ended == E)
for lab, at_ in (("at E+8", E + 8), ("between close 2 and E", E - 2)):
rb = ce(960, ev=[(at_, show(8.0))], cls=Base69)
r = ce(960, ev=[(at_, show(8.0))])
k1 = [x for x in r.calls_from(E + 1, 959) if x[1] > 0]
check(f"T5: CE, the charger shows 8 A (close 1) {lab}: no mismatch, hold "
f"or CHARGER_OTHER E..960 ({r.first_ms(E)}, {n_other()}), no write "
f"in key 0 after E, the 6 A cut try at the key roll 900-901 "
f"({k1[:2]}), cut_fails never above 3",
r.clean(E, 960) and n_other() == 0
and not [x for x in k1 if x[0] < 900]
and [x for x in k1 if 900 <= x[0] <= 901 and x[1] == 6.0]
and not r.viol)
check(f"T5 [red on base] {lab}: base mismatch ({rb.first_ms(E)}), hold "
f"({rb.first_hold()}), no cut try at 900 "
f"({[x for x in rb.calls_from(E + 1, 959) if x[1] > 0][:2]})",
rb.first_ms(E) is not None and rb.first_hold() is not None
and not [x for x in rb.calls_from(900, 905) if x[1] > 0])
nev("T5", r)
r = ce(960, ev=[(E + 20, show(10.0))])
check(f"T6 (ii): CE, foreign 10 A at E+20: mismatch at the change "
f"({r.first_ms(E)}), hold at +30 ({r.first_hold()}), 1 CHARGER_OTHER "
f"({n_other()}), nothing non-zero written from the change to 960 "
f"({r.calls_from(E + 20, 960, True)})",
near(r.first_ms(E), E + 20, E + 21)
and r.first_hold() - r.first_ms(E) == 30 and n_other() == 1
and not r.calls_from(E + 20, 960, True))
nev("T6 (ii)", r)
# T19: the quarter boundary
rb = ce(960, ev=[(900, show(8.0))], cls=Base69)
r = ce(960, ev=[(900, show(8.0))])
check(f"T19: CE, the cap standing to 960, the charger shows 8 A at the step "
f"of 900: no mismatch 900-960, the key-1 cut try at 900-901 "
f"({r.calls_from(899, 905)}), its refusal keeps 8 A own "
f"(prior_a {r.prior[902]})",
r.clean(900, 960) and n_other() == 0
and [x for x in r.calls_from(900, 901) if x[1] == 6.0]
and r.prior[902] == 8.0)
check(f"T19 [red on base]: mismatch at 900 ({rb.first_ms(895)})",
rb.first_ms(895) is not None)
# T24 (formal Dev note 1): the 0 A is carried
r = ce(500, press_after_close2=True)
E = close_times(r)[1] + 5
r = ce(500, press_after_close2=True, ev=[(E + 3, show(0.0))])
check(f"T24: cap end with a press inside the sequence (prior_a kept), the "
f"charger then shows its own 0 A: no mismatch_since, no hold "
f"({r.first_ms(E)}, {r.first_hold()}); the carry holds the 0 A "
f"({r.carry[E + 4]})",
r.ended == E and r.clean(E, 500) and 0.0 in r.carry[E + 4]
# EV-71 P1: a press that lifts nothing ends nothing
and r.prior[E - 1] is not None)
# T25 (formal Dev note 2): no carry when the end's own value is taken
def ce25():
w, drv = mk_ce(plan_a=12.0)
st = {"cap": False}
def hook(t, w_, d, s):
nz = [(tt, a) for tt, a in d.calls if a > 0]
if nz and not s["cap"]:
s["cap"] = True
set_cap(w_, 6.0)
if len(nz) >= 2 and t == nz[1][0] + 5:
d.cur = 6.0 # close 2 taken late, read at E
if len(nz) >= 2 and t == nz[1][0] + 5 + 10:
d.cur = 12.0 # an earlier close value
return Run(w, drv, st=st).go(130, 600, hook=hook)
r = ce25()
E = close_times(r)[1] + 5
check(f"T25: CE, the read at E adopts sent_a (6 A taken late) before the cap "
f"end: nothing is carried ({r.carry[E]}, {r.carry[E + 10]}), the 12 A "
f"(an earlier close value) is no own value when it shows at E+10 "
f"({r.own[E + 10]}), 6 A stays taken (taken {r.taken[E]}, sent_a "
f"{r.sent_a[E + 10]}); no write in key 0 after E "
f"({r.calls_from(E, 899)})",
r.ended == E and all(r.carry[t] == [] for t in range(E, 601))
and 12.0 not in r.own[E + 10] and r.taken[E] is True
and r.sent_a[E + 10] == 6.0 and not r.calls_from(E, 899))
# The test plan reads T25 as "a mismatch, a hold at +30". It cannot, by the
# code: the cap end sets last_a None (F5) and the adopt cleared attempted_a /
# prior_a, so no own value is left at all and `_watch` judges nothing (the
# EV-22 start-state blind spot, not EV-69's). The row asserts the rule itself:
# nothing carried (red under carryAfterTake, which carries 0, 12 and 6).
# =========================================================================== #
print("MW (Manual, OQ2)")
# =========================================================================== #
r = mw(300)
nzc = [int(t) for t, a in r.drv.calls if a > 0]
E = nth(nzc, -1)
check(f"T8 setup: Manual closes 12 A, the clamp falls, tries 2 and 3 are 8 A "
f"({[(int(t), a) for t, a in r.drv.calls]}), the :589 end at {r.ended}",
present(E) and [a for t, a in r.drv.calls if a > 0] == [12.0, 8.0, 8.0]
and r.ended == E and r.gu[E] is True)
for lab, kw in (("the clamp falls", dict()),
("the user lowers car_current 12 -> 8", dict(user=True))):
r0 = mw(300, **kw)
E = r0.ended
rb = mw(E + 300, cls=BaseM69, hook2=lambda t, w, d, s, E=E: setattr(
d, "cur", 12.0) if t == E + 3 else None, **kw)
r = mw(E + 300, hook2=lambda t, w, d, s, E=E: setattr(
d, "cur", 12.0) if t == E + 3 else None, **kw)
check(f"T8: Manual, {lab}, the charger shows 12 A at E+3: no mismatch, "
f"hold or 'Something else changes the charger' line E..E+300 "
f"({r.first_ms(E)}, {n_some()}); the EV-59 count is unchanged "
f"(gave_up {r.gu[E + 4]}); base: hold at {rb.first_hold(E)}",
r.clean(E, E + 300) and n_some() == 0
and r.gu[E + 4] is (not kw) # clamp: EV-59 gave up; user: the
# count restarted, it asks again
and rb.first_hold(E) is not None and near(
rb.first_hold(E), E + 33, E + 34))
nev(f"T8 ({lab})", r)
r0 = mw(300)
E = r0.ended
r = mw(E + 300, hook2=lambda t, w, d, s: setattr(d, "cur", 16.0)
if t == E + 5 else None)
check(f"T9: Manual, foreign 16 A at E+5: mismatch at E+5 ({r.first_ms(E)}), "
f"hold at E+35 ({r.first_hold(E)}), 1 INFO line ({n_some()}), no write "
f"over 16 A to E+300 ({r.calls_from(E + 1, 10 ** 9, True)})",
near(r.first_ms(E), E + 5, E + 6) and near(r.first_hold(E), E + 35,
E + 36)
and n_some() == 1 and not r.calls_from(E + 1, 10 ** 9, True))
# Manual version of T10 (formal Dev note 3: Manual's adopt ends the carry)
r0 = mw(300)
E = r0.ended
r = mw(E + 200, hook2=lambda t, w, d, s: setattr(
d, "cur", 8.0 if t == E + 3 else 12.0 if t == E + 20 else d.cur))
check(f"T10 (Manual): the charger takes the target 8 A at E+3 (Manual's adopt "
f"ends the carry: {r.carry[E + 4]}), then shows the old close 12 A at "
f"E+20: mismatch at E+20 ({r.first_ms(E)}), hold at E+50 "
f"({r.first_hold(E)}), 1 INFO line ({n_some()})",
r.carry[E + 4] == [] and near(r.first_ms(E), E + 20, E + 21)
and near(r.first_hold(E), E + 50, E + 51) and n_some() == 1)
# T17 (i) in the cap-end shape (M14): the 0 A after a return is blocked by
# the used-up cut tries, so only the return itself can end the carry.
def ce_gone(cls, lo, hi, show_at, show_a):
w, drv = mk_ce(cls)
st = {"cap": False}
def h(t, w_, d, s):
nz = [1 for tt, a in d.calls if a > 0]
if nz and not s["cap"]:
s["cap"] = True
set_cap(w_, 6.0)
if t == show_at:
d.cur = show_a
return Run(w, drv, st=st).go(130, 600, hook=h,
gone=lambda t: lo <= t <= hi)
E = ce_gone(None, -1, -1, 10 ** 6, 0.0).ended
rn = ce_gone(None, E + 3, E + 8, E + 9, 10.0)
rbs = ce_gone(Base69, E + 3, E + 8, E + 9, 10.0)
same = all((rn.ms[t], rn.hold[t], rn.ncalls[t]) ==
(rbs.ms[t], rbs.hold[t], rbs.ncalls[t]) for t in range(E + 9, 601))
check(f"T17 (i, cap end): the charger gone E+3..E+8 and back at E+9 showing "
f"10 A, the cut tries used up: the carry stands while it is gone "
f"({rn.carry[E + 8]}) and ends with the return ({rn.carry[E + 9]}); no "
f"mismatch ({rn.first_ms(E + 9)}) and every cycle equals de733f4",
E is not None and rn.carry[E + 8] != [] and rn.carry[E + 9] == []
and rn.clean(E + 9, 600) and same)
# R-MB: the standing 0 A is no take (the cur > TOL_A guard in `_watch`)
r = s1(400, press_at=None, show_at=None)
check(f"T4 (0 A guard): S1-np-nt, the charger stands at the carried 0 A: "
f"gave_up stays True 142-400 and nothing non-zero is written "
f"({r.calls_from(143, 400, True)})",
all(r.gu[t] for t in range(142, 401))
and not r.calls_from(143, 400, True))
# =========================================================================== #
print("Rules the code keeps (Dev notes)")
# =========================================================================== #
check("T1 [Dev note 1]: one helper `_carry_end` serves both ends and both "
"writers (ManualWriter defines it, SolarWriter does not redefine it)",
"_carry_end" in vars(CM.ManualWriter)
and "_carry_end" not in vars(CM.SolarWriter)
and src.count("self._carry_end(q)") == 2)
check("T1 [Dev note 6]: `_put` keeps `stopped and not cut_try` (the cut never "
"waits on gave_up)", "(stopped and not cut_try)" in src)
done()
+618
View File
@@ -0,0 +1,618 @@
"""EV-69 T21: the fuzz for the carry (N1-N9 of reports/EV-69-test-plan.md).
`python3 -B test_ev69_fuzz.py`
Two passes, each SEEDS (10) seeds x STEPS (1200) s for Solar and for Manual,
both cycle orders. Writer level (`tools/ev69_kit.py`: `SolarWriter` /
`ManualWriter` on a stub driver). Order A applies a cycle's events before its
step, order B after it (read one cycle later).
- Mixed pass (`fuzz_mixed`): the round-1 event model of 9b09158, unchanged
(same random stream, same rates, PHASE_GAP_S as shipped). Random clamp steps,
a peak cut cap, refused and raised writes (0 A and the select are taken),
phase changes begun by the plan (Solar) or the user (Manual), late takes of
ANY value the writer tried, foreign values (some equal to a tried value),
presses, unknown and stale reads, the charger gone and back. Its floors are
a fixed list (MIXED_FLOOR), each asserted on the mixed counts alone.
- Directed pass (`fuzz_directed`, 4 x SEEDS seeds), in addition, with its
own floors (DIRECTED_FLOOR) asserted on the directed counts alone: Solar
changes run
calm (no late take, foreign value or 0 A reading inside a change, refuse
0.97 / 1.0 only, the clamp falls only after a close, a cap with `cut_fails`
2 after the first close) so that cap ends and Solar's distinct close values
are reached; presses that lift a hold or a give-up, the charger gone while a
bound stands, the plan's phases set from the read phases, PHASE_GAP_S 40 (as
test_ev22_fuzz does), and N1b's directed old-value take.
Every cycle checks, by an oracle that does not read the carry:
- N1: after a phase change ends without its value taken (MAX_TRIES, or
Solar's cap end), while nothing has ended the bound (a write, a press, a
hold or count, a return, a take of what the writer sent or wants), the
charger showing a value the change tried gives no mismatch and no hold.
- N1b (directed pass): once a bound has ended (an own take, a new own write, a
user change, a hold, Solar's return) a late take of an old value is another
writer's: the fuzz shows it for WRITER_S + 3 s with nothing else happening
and asserts the hold (skipped when no own value is left to judge against:
the EV-22 start-state blind spot).
- N2: no non-zero write while a count runs (Solar) or a hold stands.
- N4: no carry under a hold, after a press, or after a write that is not
itself followed by an end.
- N5: no write above the clamp or the cap, none in 0-6 A.
- N6: at most MAX_TRIES cut tries per quarter key.
- N7: no 0 A written under a hold.
- N8: a select only at 0 A.
- N9: at most one CHARGER_OTHER (Solar) / one INFO line (Manual) per hold.
N3 (the cut never waits on a false hold) follows from N1 and the rows T1, T5,
T19.
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import os
import random
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
import ev69_kit as K # noqa: E402
from app import carmode as CM # noqa: E402
SEEDS = int(os.environ.get("EV69_FUZZ_SEEDS", "10"))
STEPS = int(os.environ.get("EV69_FUZZ_STEPS", "1200"))
COUNT = {}
def bump(k, n=1):
COUNT[k] = COUNT.get(k, 0) + n
def fuzz_mixed(kind, seed):
"""9b09158's fuzz, event model unchanged. Only counters were added (no
random draw): late_nonlast_<kind>, cap_end_take, foreign_hold_after_end.
"""
rnd = random.Random(seed * 7 + (0 if kind == "solar" else 1))
order_b = seed % 2 == 1
st = {"a": rnd.choice([8.0, 10.0, 12.0]), "n": 1, "rev": 1,
"clamp": 16.0}
if kind == "solar":
w = K.swriter(8.0, ph=1)
w.cut_key = 0
else:
w = CM.ManualWriter()
mode = {"refuse": 0.97, "raise": 0.0}
def take(a, d):
if a == 0.0:
return True
if rnd.random() < mode["raise"]:
return "raise"
return rnd.random() >= mode["refuse"]
drv = K.Drv(8.0 if kind == "solar" else st["a"], take, ph=1)
run = K.Run(w, drv, kind=kind, st=st)
bad = []
s = dict(armed=False, vals=[], seq_own=[], hold_rises=0, press_t=-1,
prev_hold=False, was_gone=False, gone=False, tried=set(),
nsel=0, cap=False, cap_counted=False, fv=None, end_t=-9999,
lift_t=-1, ev_t=-1)
clamp = {"v": 16.0}
_uc = w.user_changed
def user_changed():
# EV-71 P1: a press that lifts nothing ends nothing; N4 asks only of
# a press that lifts a running count or a hold.
if w._other_stands():
s["lift_t"] = s["ev_t"]
_uc()
w.user_changed = user_changed
def ev(t):
s["ev_t"] = t
if rnd.random() < (0.25 if w.seq is not None else 0.01):
clamp["v"] = rnd.choice([16.0, 12.0, 10.0, 8.0, 8.0])
st["clamp"] = clamp["v"]
if kind == "solar" and rnd.random() < 0.01:
K.set_cap(w, rnd.choice([None, 6.0, 6.0, 7.0]))
if rnd.random() < 0.004:
mode["refuse"] = rnd.choice([0.0, 0.5, 0.97, 1.0, 1.0, 1.0])
mode["raise"] = rnd.choice([0.0, 0.0, 0.3])
# a phase change: Solar's plan decides it, Manual's user asks for it
if w.seq is None and rnd.random() < 0.03:
n_to = 3 if drv.ph == 1 else 1
if kind == "solar":
if not w.plan.switch:
w.plan._set(rnd.choice([8.0, 10.0, 12.0]), float(t), n_to)
else:
w.user_changed()
st["rev"] += 1
st["n"] = n_to
st["a"] = rnd.choice([8.0, 10.0, 12.0, 14.0])
s["press_t"] = t
# a late take of any value the writer tried (the ended change's
# values first)
if rnd.random() < 0.08:
pool = [v for v in s["vals"] if v > 0] if (
s["armed"] and rnd.random() < 0.6) else sorted(
v for v in s["tried"] if v > 0)
if pool:
v = rnd.choice(pool)
drv.cur = v
bump("late_take")
if s["armed"] and v in s["vals"]:
bump("late_take_ended_val")
if v != s["vals"][-1]:
bump("late_take_nonlast")
bump(f"late_nonlast_{kind}")
if rnd.random() < 0.005:
drv.cur = rnd.choice([5.0, 7.0, 9.0, 11.0, 13.0, 15.0]
+ sorted(s["tried"]))
s["fv"] = (t, drv.cur)
bump("foreign")
if rnd.random() < 0.005:
w.user_changed()
if kind == "manual":
st["rev"] += 1
s["press_t"] = t
bump("press")
if rnd.random() < 0.01:
drv.cur = 0.0
s["gone"] = rnd.random() < (0.8 if s["gone"] else 0.003)
for t in range(STEPS):
if not order_b:
ev(t)
gone, unk, stale = s["gone"], rnd.random() < 0.02, rnd.random() < 0.02
n0, sel0 = len(drv.calls), len(drv.sel)
before_seq = w.seq is not None
if before_seq:
s["seq_own"] = list(w.seq.get("own", ()))
drv.now = float(t)
K.CLOCK["t"] = t
if hasattr(w, "cut_quarter"):
w.cut_quarter(int(t // 900))
seen = None if unk else drv.cur
rd = K.Rd(seen, drv.ph, power=0.0 if drv.cur == 0 else 1840.0)
rd.available = not gone
run.trk.obs_at = (w.last_done if (stale and w.last_done is not None)
else None)
cl = clamp["v"]
if kind == "solar":
K.LOOP.run_until_complete(w.step(
drv, rd, mode=CM.SOLAR, sun=CM.SunInputs(target_w=2000.0),
clamp=cl, now=float(t), tracker=run.trk, writing=True,
status="charging"))
else:
K.LOOP.run_until_complete(w.step(
drv, rd, mode=CM.MANUAL, want_a=st["a"],
want_phases=st["n"], rev=st["rev"], clamp=cl, now=float(t),
tracker=run.trk, writing=True, status="charging"))
new = drv.calls[n0:]
wrote = bool(new)
press_now = s["press_t"] == t
for tt, a in new:
if a > 0:
s["tried"].add(a)
if a > 0 and (w.hold or (kind == "solar"
and w.mismatch_since is not None)):
# judged after the step's own watch (a count a read cleared
# in this step is no count when the write goes out); Manual
# writes through a count and stops at the hold (EV-22)
bad.append((kind, seed, t, "N2 write while a count/hold "
"stood", a))
if a == 0.0 and w.hold:
bad.append((kind, seed, t, "N7 0 A under a hold"))
cutv = getattr(w, "cut_a", None)
if a > cl + 1e-9 and not (cutv is not None and a <= cutv + 1e-9):
bad.append((kind, seed, t, "N5 above the clamp", a, cl))
if 0 < a < CM.CH.MIN_A - 1e-9:
bad.append((kind, seed, t, "N5 in 0-6 A", a))
if getattr(w, "cut_fails", 0) > CM.MAX_TRIES:
bad.append((kind, seed, t, "N6 cut tries over the cap"))
for tt, n_, cur_ in drv.sel[sel0:]:
if cur_ > CM.TOL_A:
bad.append((kind, seed, t, "N8 select over load", cur_))
if w.hold and not s["prev_hold"]:
s["hold_rises"] += 1
bump("hold")
fv = s["fv"]
if fv is not None and 0 <= t - fv[0] <= 60 \
and drv.cur == fv[1] and 0 <= t - s["end_t"] <= 300:
bump("foreign_hold_after_end")
s["prev_hold"] = w.hold
lines = len([1 for _t, lv, m in K.LOG
if (kind == "solar" and K.OTHER in m)
or (kind == "manual" and K.SOMETHING in m)])
if lines > s["hold_rises"]:
bad.append((kind, seed, t, "N9 more lines than holds", lines,
s["hold_rises"]))
ended_now = before_seq and w.seq is None
if w.hold and w._carry:
bad.append((kind, seed, t, "N4 carry under a hold", w._carry))
# EV-71 P1: a press that lifts nothing ends nothing
if press_now and s["lift_t"] == t and w._carry and not ended_now:
bad.append((kind, seed, t, "N4 carry after a press", w._carry))
if wrote and w._carry and not ended_now:
bad.append((kind, seed, t, "N4 carry after a write", w._carry))
# the oracle's bound: armed by an end whose last value is not taken,
# disarmed by anything that ends it (a superset of the code's ends)
took = (kind == "solar" and w.taken) or (
kind == "manual" and w.last_a is not None)
if ended_now and not took and not gone:
s["vals"] = [0.0] + [a for a in s["seq_own"] if a > 0] + [
a for tt, a in new if a > 0]
s["armed"] = True
s["end_t"] = t
s["cap"] =kind == "solar" and w.cut_fails >= CM.MAX_TRIES
s["cap_counted"] = False
bump("end")
if s["cap"]:
bump("end_cap")
elif s["armed"]:
if wrote or press_now or w.hold or gone or s["was_gone"] \
or took:
s["armed"] = False
elif w.mismatch_since is not None:
if seen is not None and seen > CM.TOL_A and seen in s["vals"]:
bad.append((kind, seed, t, "N1 a late take of a tried "
"value is held as another writer's", seen,
s["vals"]))
s["armed"] = False # a foreign value: judged as ever
bump("armed_foreign")
elif seen is not None and seen > CM.TOL_A and seen in s["vals"]:
bump("armed_take_seen")
if s["cap"] and not s["cap_counted"]:
s["cap_counted"] = True
bump("cap_end_take")
s["was_gone"] = gone
if order_b:
ev(t)
return bad
def fuzz_directed(kind, seed):
"""The directed pass (round 3's calm Solar pass), in addition."""
rnd = random.Random(seed * 7 + (0 if kind == "solar" else 1) + 1000)
order_b = seed % 2 == 1
st = {"a": rnd.choice([8.0, 10.0, 12.0]), "n": 1, "rev": 1,
"clamp": 16.0}
if kind == "solar":
w = K.swriter(8.0, ph=1)
w.cut_key = 0
else:
w = CM.ManualWriter()
mode = {"refuse": 1.0 if kind == "solar" else 0.97, "raise": 0.0}
def take(a, d):
if a == 0.0:
return True
if rnd.random() < mode["raise"]:
return "raise"
return rnd.random() >= mode["refuse"]
drv = K.Drv(8.0 if kind == "solar" else st["a"], take, ph=1)
run = K.Run(w, drv, kind=kind, st=st)
bad = []
s = dict(armed=False, vals=[], seq_own=[], hold_rises=0, press_t=-1,
prev_hold=False, was_gone=False, gone=False, tried=set(),
kind=None, cap_counted=False, seq_n0=0, fv=None, pend=None,
inj=None, end_t=-9999, lift_t=-1, ev_t=-1)
clamp = {"v": 16.0}
_uc = w.user_changed
def user_changed():
# EV-71 P1: a press that lifts nothing ends nothing; N4 and N1b's
# "user" cause concern only a press that lifts a count or a hold.
if w._other_stands():
s["lift_t"] = s["ev_t"]
_uc()
w.user_changed = user_changed
def ev(t):
s["ev_t"] = t
if s["inj"] is not None: # a directed old-value take
drv.cur = s["inj"]["v"]
return
closed = w.seq is not None and (kind == "manual" or [
1 for tt, a in drv.calls[s["seq_n0"]:] if a > 0])
if rnd.random() < (0.4 if closed else 0.01): # falls after a close
clamp["v"] = rnd.choice([16.0, 14.0, 12.0, 10.0, 8.0, 7.0, 6.0])
st["clamp"] = clamp["v"]
if kind == "solar" and rnd.random() < 0.01:
K.set_cap(w, rnd.choice([None, 6.0, 6.0, 7.0]))
if kind == "solar" and w.seq is not None and w.cut_a is None \
and [1 for tt, a in drv.calls[s["seq_n0"]:] if a > 0] \
and rnd.random() < 0.4:
# the EV-60 cap end shape: a close went, then the cap comes, the
# earlier cut tries of this key being used up
K.set_cap(w, 6.0)
w.cut_fails, w.cut_fail_at = max(w.cut_fails, 2), -100.0
if w.hold and rnd.random() < 0.03:
w.user_changed() # a press lifts a hold
if kind == "manual":
st["rev"] += 1
s["press_t"] = t
bump("press")
if kind == "solar" and not s["armed"] and w.seq is None \
and (w.gave_up or w.fail_at is not None) \
and rnd.random() < 0.05:
w.user_changed() # a press lifts the give-up
s["press_t"] = t
bump("press")
if rnd.random() < 0.004:
mode["refuse"] = rnd.choice(
[0.97, 1.0, 1.0, 1.0, 1.0, 1.0] if kind == "solar" else
[0.0, 0.5, 0.97, 1.0, 1.0, 1.0])
mode["raise"] = rnd.choice([0.0, 0.0, 0.3])
# a phase change: Solar's plan decides it, Manual's user asks for it
if w.seq is None and rnd.random() < (0.1 if kind == "solar" else 0.03):
n_to = 3 if drv.ph == 1 else 1
if kind == "solar":
if not w.plan.switch:
w.plan.n = drv.ph # the plan believes the phases read
w.plan._set(rnd.choice([10.0, 12.0, 14.0]), float(t), n_to)
clamp["v"] = st["clamp"] = 16.0 # it falls later
K.set_cap(w, None) # a cap comes later
w.cut_fails = 0
else:
w.user_changed()
st["rev"] += 1
st["n"] = n_to
st["a"] = rnd.choice([8.0, 10.0, 12.0, 14.0])
s["press_t"] = t
# a late take of any value the writer tried (the ended change's
# values first)
calm = kind == "solar" and w.seq is not None
if rnd.random() < (0.0 if calm else 0.08):
pool = [v for v in s["vals"] if v > 0] if (
s["armed"] and rnd.random() < 0.6) else sorted(
v for v in s["tried"] if v > 0)
if pool:
v = rnd.choice(pool)
drv.cur = v
bump("late_take")
if s["armed"] and v in s["vals"]:
bump("late_take_ended_val")
if v != s["vals"][-1]:
bump(f"late_nonlast_{kind}")
if rnd.random() < (0.0 if calm else 0.005):
drv.cur = rnd.choice([5.0, 7.0, 9.0, 11.0, 13.0, 15.0]
+ sorted(s["tried"]))
s["fv"] = (t, drv.cur)
bump("foreign")
if rnd.random() < 0.005:
w.user_changed()
if kind == "manual":
st["rev"] += 1
s["press_t"] = t
bump("press")
if rnd.random() < (0.0 if calm else 0.01):
drv.cur = 0.0
s["gone"] = s["gone"] and rnd.random() < 0.8 or (
not s["gone"] and rnd.random() < 0.003)
if kind == "solar" and s["armed"] and rnd.random() < 0.08:
s["gone"] = True # a charger return inside the bound
for t in range(STEPS):
if not order_b:
ev(t)
# EV-71 I2: during an N1b injection this pass skips the gone / unknown
# / stale draws (`ev()` returns early, and `gone`, `unk` and `stale`
# are False below), so the injected old value is read, held, as is.
inj = s["inj"]
gone = False if inj else s["gone"]
unk = False if inj else rnd.random() < 0.02
stale = False if inj else rnd.random() < 0.02
n0, sel0 = len(drv.calls), len(drv.sel)
before_seq = w.seq is not None
if before_seq:
s["seq_own"] = list(w.seq.get("own", ()))
drv.now = float(t)
K.CLOCK["t"] = t
if hasattr(w, "cut_quarter"):
w.cut_quarter(int(t // 900))
seen = None if unk else drv.cur
rd = K.Rd(seen, drv.ph, power=0.0 if drv.cur == 0 else 1840.0)
rd.available = not gone
run.trk.obs_at = (w.last_done if (stale and w.last_done is not None)
else None)
cl = clamp["v"]
if kind == "solar":
K.LOOP.run_until_complete(w.step(
drv, rd, mode=CM.SOLAR, sun=CM.SunInputs(target_w=2000.0),
clamp=cl, now=float(t), tracker=run.trk, writing=True,
status="charging"))
else:
K.LOOP.run_until_complete(w.step(
drv, rd, mode=CM.MANUAL, want_a=st["a"],
want_phases=st["n"], rev=st["rev"], clamp=cl, now=float(t),
tracker=run.trk, writing=True, status="charging"))
new = drv.calls[n0:]
wrote = bool(new)
press_now = s["press_t"] == t
for tt, a in new:
if a > 0:
s["tried"].add(a)
if a > 0 and (w.hold or (kind == "solar"
and w.mismatch_since is not None)):
bad.append((kind, seed, t, "N2 write while a count/hold "
"stood", a))
if a == 0.0 and w.hold:
bad.append((kind, seed, t, "N7 0 A under a hold"))
cutv = getattr(w, "cut_a", None)
if a > cl + 1e-9 and not (cutv is not None and a <= cutv + 1e-9):
bad.append((kind, seed, t, "N5 above the clamp", a, cl))
if 0 < a < CM.CH.MIN_A - 1e-9:
bad.append((kind, seed, t, "N5 in 0-6 A", a))
if getattr(w, "cut_fails", 0) > CM.MAX_TRIES:
bad.append((kind, seed, t, "N6 cut tries over the cap"))
for tt, n_, cur_ in drv.sel[sel0:]:
if cur_ > CM.TOL_A:
bad.append((kind, seed, t, "N8 select over load", cur_))
if w.hold and not s["prev_hold"]:
s["hold_rises"] += 1
bump("hold")
fv = s["fv"]
if fv is not None and s["inj"] is None and 0 <= t - fv[0] <= 60 \
and drv.cur == fv[1] and 0 <= t - s["end_t"] <= 300:
# the hold rose over a value the random foreign branch set
# (never one of N1b's directed old-value takes)
bump("foreign_hold_after_end")
s["prev_hold"] = w.hold
lines = len([1 for _t, lv, m in K.LOG
if (kind == "solar" and K.OTHER in m)
or (kind == "manual" and K.SOMETHING in m)])
if lines > s["hold_rises"]:
bad.append((kind, seed, t, "N9 more lines than holds", lines,
s["hold_rises"]))
ended_now = before_seq and w.seq is None
if not before_seq and w.seq is not None:
bump(f"seq_start_{kind}")
s["seq_n0"] = len(drv.calls)
if ended_now:
tk = (kind == "solar" and w.taken) or (
kind == "manual" and w.last_a is not None)
bump(f"seq_end_{kind}_{'taken' if tk else 'refused'}")
if w.hold and w._carry:
bad.append((kind, seed, t, "N4 carry under a hold", w._carry))
# EV-71 P1: a press that lifts nothing ends nothing
lifted_now = press_now and s["lift_t"] == t
if lifted_now and w._carry and not ended_now:
bad.append((kind, seed, t, "N4 carry after a press", w._carry))
if wrote and w._carry and not ended_now:
bad.append((kind, seed, t, "N4 carry after a write", w._carry))
# the directed old-value take (N1b)
if inj is not None:
inj["n"] += 1
if wrote or press_now or w.seq is not None \
or drv.cur != inj["v"] or inj["n"] > 60:
s["inj"] = None # something else happened: no verdict
bump("inj_aborted")
elif inj["n"] >= CM.WRITER_S + 3:
s["inj"] = None
if w.hold:
bump(f"bound_{inj['cause']}_held")
bump("bound_held")
else:
bad.append((kind, seed, t, "N1b an old value after the "
f"bound ended ({inj['cause']}) is not held",
inj["v"], w.mismatch_since))
# the oracle's bound: armed by an end whose last value is not taken,
# disarmed by anything that ends it (a superset of the code's ends)
took = (kind == "solar" and w.taken) or (
kind == "manual" and w.last_a is not None)
if ended_now and not took and not gone:
s["vals"] = [0.0] + [a for a in s["seq_own"] if a > 0] + [
a for tt, a in new if a > 0]
s["armed"] = True
s["end_t"] = t
s["cap_counted"] = False
s["pend"] = None
s["kind"] = "cap" if (kind == "solar" and not wrote
and w.cut_fails >= CM.MAX_TRIES) else "max"
bump("end")
bump(f"end_{kind}")
if len(set(a for a in s["vals"] if a > 0)) > 1:
bump(f"end_distinct_{kind}")
if s["kind"] == "cap":
bump("end_cap")
elif s["armed"]:
# EV-71 P1: a press that lifts nothing ends nothing, so it is no
# "user" cause (a lifting press leaves nothing armed: see below)
cause = ("hold" if w.hold else "user" if lifted_now
else "write" if wrote
else "return" if (gone or s["was_gone"])
else "take" if took else None)
if cause is not None:
s["armed"] = False
if not (kind == "manual" and cause == "return"):
s["pend"] = (cause, list(s["vals"]))
elif w.mismatch_since is not None:
if seen is not None and seen > CM.TOL_A and seen in s["vals"]:
bad.append((kind, seed, t, "N1 a late take of a tried "
"value is held as another writer's", seen,
s["vals"]))
s["armed"] = False # a foreign value: judged as ever
s["pend"] = ("hold", list(s["vals"]))
bump("armed_foreign")
elif seen is not None and seen > CM.TOL_A and seen in s["vals"]:
bump("armed_take_seen")
if s["kind"] == "cap" and not s["cap_counted"]:
s["cap_counted"] = True
bump("cap_end_take")
# EV-71 P1: a press that lifts the count or hold of a "hold" end is the
# "user" end of that bound: it ends everything (DA1)
if lifted_now and s["pend"] is not None and s["pend"][0] == "hold":
s["pend"] = ("user", s["pend"][1])
# start a directed old-value take once the bound has ended and the
# writer is calm: the value must not be own by any other route
if s["pend"] is not None and s["pend"][0] == "hold" \
and not w.hold and w.mismatch_since is None:
s["pend"] = None # the foreign value went: no hold
if s["pend"] is not None and s["inj"] is None and not gone \
and not unk and not stale and w.seq is None and not wrote \
and not press_now and rnd.random() < 0.5 \
and (s["pend"][0] != "hold" or w.hold):
cause, vals = s["pend"]
# EV-71 I1/F5: the writer's own fields, the kept value included,
# never `_carry` (a carried value is exactly what N1b injects)
own = [x for x in (w.last_a, w.attempted_a, w.prior_a,
getattr(w, "_kept", None)) if x is not None]
pool = [v for v in vals if v > CM.TOL_A
and all(abs(v - o) > CM.TOL_A for o in own)]
if not pool: # any other value the writer tried
pool = [v for v in sorted(s["tried"]) if v > CM.TOL_A
and all(abs(v - o) > CM.TOL_A for o in own)]
s["pend"] = None
if not pool:
bump(f"inj_no_value_{cause}")
elif not own and not w.hold:
bump("inj_blind") # nothing own to judge against
elif cause != "hold" and w.hold:
bump("inj_other_hold")
else:
s["inj"] = dict(v=rnd.choice(pool), cause=cause, n=0)
drv.cur = s["inj"]["v"]
bump("inj_started")
s["was_gone"] = gone
if order_b:
ev(t)
return bad
# Fixed floor lists (no fallback between passes). MIXED_FLOOR is 9b09158's
# list, each floor asserted on the mixed counts alone. DIRECTED_FLOOR holds
# the plan floors the mixed pass does not reach, asserted on the directed
# counts alone.
MIXED_FLOOR = {"end": 20, "end_cap": 3, "late_take_ended_val": 10,
"late_take_nonlast": 5, "armed_take_seen": 20, "foreign": 20,
"hold": 5}
DIRECTED_FLOOR = {"late_nonlast_solar": 10, "late_nonlast_manual": 5,
"cap_end_take": 5, "bound_take_held": 5,
"bound_write_held": 5, "bound_user_held": 5,
"bound_hold_held": 5, "bound_return_held": 5,
"foreign_hold_after_end": 5}
TAGS = {"mixed": ("N1", "N2", "N4", "N5", "N6", "N7", "N8", "N9"),
"directed": ("N1", "N1b", "N2", "N4", "N5", "N6", "N7", "N8", "N9")}
MIXED, DIRECTED = {}, {}
GAP = CM.PHASE_GAP_S
# The directed pass runs 4 x SEEDS seeds (foreign_hold_after_end is rare when
# Solar changes run calm); the mixed pass keeps 9b09158's SEEDS.
for name, fn, counts, gap, nseeds, floor in (
("mixed", fuzz_mixed, MIXED, GAP, SEEDS, MIXED_FLOOR),
("directed", fuzz_directed, DIRECTED, 40.0, 4 * SEEDS,
DIRECTED_FLOOR)):
COUNT = counts
CM.PHASE_GAP_S = gap # the directed pass: many changes in 1200 s
allbad = []
for kind in ("solar", "manual"):
for seed in range(nseeds):
allbad += fn(kind, seed)
CM.PHASE_GAP_S = GAP
for tag in TAGS[name]:
hit = [b for b in allbad if b[3].startswith(tag + " ")]
K.check(f"T21 {tag}: holds in every cycle of {nseeds} seeds x {STEPS} "
f"s, Solar and Manual, both orders, {name} pass ({hit[:2]})",
not hit)
print(f" {name} counts", dict(sorted(counts.items())))
if STEPS >= 1200 and SEEDS >= 10:
for k, v in floor.items():
K.check(f"T21 floor {k} >= {v} in the {name} pass alone "
f"({counts.get(k, 0)})", counts.get(k, 0) >= v)
K.done()
+612
View File
@@ -0,0 +1,612 @@
"""EV-71: Solar and Manual keep the add-on's own untaken non-zero write as
their own (the kept value), so the charger taking it late is never read as
another writer's value (no false CHARGER_OTHER, the peak cut never blocked).
`python3 -B test_ev71.py`
Rows T1-T19, T24-T39 and the Never rules N1-N15 of reports/EV-71-test-plan.md
(T20 and T21 are in test_ev69_fuzz.py, T22 is the existing suites CI runs, T23
is the formal check). Every check's label starts with its id. Writer level on
`tools/ev69_kit.py`: a `SolarWriter` / `ManualWriter` on a stub driver, a stub
tracker and a stub reading; one step per second on the model clock, which is
WRITER_S's clock.
Worlds (the charger's reading is a function of the second):
- C9: Solar at its own 0 A, taken; the plan is 12 A. The 12 A written at 200
returns False but the charger takes it. A held read at 201 shows 12 A and
`held_pause` writes 0 A (refused). The press comes at 202.
- F1a: as C9, but the held read at 201 shows 0 A (the :1345 adopt of base).
- F1b: Solar at its own 8 A; the held read at 201 shows 8 A, and the refused
0 A overwrites `attempted_a`.
- S1-adopt / S1-nt: EV-69's S1 shapes (see test_ev69.py).
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
from app import carmode as CM # noqa: E402
from named_absence import nth, present # noqa: E402
from ev69_kit import (Drv, LOG, LOOP, Run, CLOCK, cap, check, chain, # noqa: E402,F401
done, evs, n_other, n_some, near, nev, press, show,
swriter)
START = {"c9": 0.0, "f1a": 0.0, "f1b": 8.0}
PRE = {"c9": 12.0, "f1a": 0.0, "f1b": 8.0} # what the held read at 201 shows
def held_wrap(w, held):
"""Run `held_pause` instead of `step` on the seconds in `held`: the charger
missed that read, the last reading stands in."""
orig = w.step
async def step(drv, rd, **kw):
if int(kw["now"]) in held:
await w.held_pause(
drv, rd, sun=CM.SunInputs(target_w=2000.0, silent=True,
unknown_s=1000.0),
now=kw["now"], tracker=kw["tracker"])
return
await orig(drv, rd, **kw)
w.step = step
def world(kind="c9", until=400, after=None, ev=(), press_at=202, held=(201,),
clamp=16.0, stale=None, gone=None, cls=None, take=None):
"""C9 / F1a / F1b: 12 A written at 200 (refused by the call, taken by the
charger), the held read(s), then the reading `after(t)` from 202."""
start = START[kind]
w = swriter(start, ph=1, cls=cls)
w.plan.a, w.plan.n = 12.0, 1
held_wrap(w, set(held))
drv = Drv(start, take or (lambda a, d: False), ph=1)
after = after or (lambda t: 12.0)
def cur(t, d):
if t <= 200:
return start
if t in held:
return PRE[kind]
return after(t)
pairs = list(ev)
if press_at is not None:
pairs.insert(0, (press_at, press)) # the press first, then ev
return Run(w, drv).go(200, until, ev=evs(*pairs), cur=cur, clamp=clamp,
stale=stale, gone=gone)
def calls0(r, lo, hi=10 ** 9):
return [(t, a) for t, a in r.calls_from(lo, hi) if a == 0.0]
def spaced(calls, lo=60, hi=10 ** 9):
ts = [t for t, _ in calls]
return all(lo <= b - a <= hi for a, b in zip(ts, ts[1:]))
def clamp_s1(t):
return 16.0 if t < 135 else 8.0
def clamp_16(t):
return 16.0
def s1w(until=400, ev=(), press_at=None, take=None, clamp=clamp_s1,
cur=None, stale=None, held=()):
"""EV-69's S1 world (own 3 -> 1 select taken, settle from 122, the close
tries at 132, 137, 142 refused), no take at 140."""
w = swriter(0.0, ph=3)
w.plan.a, w.plan.n = 12.0, 1
drv = Drv(0.0, take or (lambda a, d: False), ph=1)
w.seq = {"stage": "settle", "t0": 119.0, "t1": 122.0, "n": 1, "tries": 0,
"prev": None, "from": 3, "own": [0.0], "sel": True}
w.last_done = 122.0
w._own_n = 3
w._select_try(1, True)
if held:
held_wrap(w, set(held))
pairs = list(ev)
if press_at is not None:
pairs.append((press_at, press))
return Run(w, drv).go(123, until, ev=evs(*pairs), clamp=clamp, cur=cur,
stale=stale)
def s1_adopt(until=260, ev=(), press_at=None, clamp=clamp_s1):
"""The charger shows the 132 close of 12 A from 133 (adopted); the clamp
is 8 from 135, so the closes at 137 and 142 are 8 A, refused."""
return s1w(until, ev=[(133, show(12.0))] + list(ev), press_at=press_at,
clamp=clamp)
def snap(box):
def f(w, d, s):
box.update(att=w.attempted_a, prior=w.prior_a, last=w.last_a,
carry=list(w._carry), own=list(w._own_values()),
kept=getattr(w, "_kept", None))
return f
def man(until, ev=(), gone=None, last_switch=None, take=None, cur=None,
start_cur=8.0):
w = CM.ManualWriter()
w.last_switch = last_switch
drv = Drv(start_cur, take or (lambda a, d: False), ph=1)
st = {"a": 8.0, "n": 1, "rev": 1, "clamp": 16.0}
return Run(w, drv, kind="manual", st=st).go(
0, until, ev=evs(*ev), gone=gone, cur=cur)
def set_a(a):
return lambda w, d, s: s.__setitem__("a", a)
def set_n(n):
return lambda w, d, s: s.__setitem__("n", n)
# =========================================================================== #
print("C9 (the press), Solar")
# =========================================================================== #
box = {}
r = world(ev=[(202, snap(box))])
r2 = world(ev=[])
c1 = calls0(r, 202)
check(f"T1: C9, 12 A read from 202 to 400: no mismatch, hold or CHARGER_OTHER "
f"({r.first_ms(202)}, {r.first_hold()}, {n_other()}); the owed 0 A retry "
f"goes at 202 and 262 ({c1[:3]})",
r.clean(202, 400) and n_other() == 0 and (202, 0.0) in c1
and (262, 0.0) in c1)
nev("T1", r)
rr = world(ev=[(202, snap(box))])
check(f"T2: C9 end of 201: attempted_a {rr.att[201]}, prior_a "
f"{rr.prior[201]}, last_a {rr.last_a[201]}, sent_a {rr.sent_a[201]}, "
f"not taken ({rr.taken[201]})",
rr.att[201] == 0.0 and rr.prior[201] == 12.0 and rr.last_a[201] == 0.0
and rr.sent_a[201] == 0.0 and rr.taken[201] is False)
check(f"T2: just after the press at 202 (it lifts nothing) attempted_a, "
f"prior_a, last_a and the carry are what they were; 12.0 is own "
f"({box})",
box.get("att") == 0.0 and box.get("prior") == 12.0
and box.get("last") == 0.0 and box.get("carry") == []
and 12.0 in box.get("own", []))
rc = world(ev=[(202, cap(6.0))])
c3 = rc.calls_from(202)
check(f"T3: C9, cap 6 A from 202: the 0 A cut try goes at 202 ({c3[:3]}), "
f"retries at least 60 s apart, cut_fails at most 3 "
f"({rc.w.cut_fails}), no hold ({rc.first_hold()})",
c3 and near(c3[0][0], 202, 203) and c3[0][1] == 0.0
and spaced(c3) and rc.w.cut_fails <= 3 and rc.first_hold() is None
and rc.clean(202, 400))
nev("T3", rc)
r = world(press_at=None)
check(f"T4: C9-np (no press) as base: writes {r.calls_from(200, 300)}, no "
f"mismatch 200-400 ({r.first_ms(200)})",
r.calls_from(200, 300) == [(200, 12.0), (201, 0.0), (261, 0.0)]
and r.clean(200, 400))
r = world(after=lambda t: 16.0)
check(f"T5: C9, foreign 16 A from 202: mismatch {r.first_ms(202)}, hold "
f"{r.first_hold()}, 1 CHARGER_OTHER ({n_other()}), no non-zero write "
f"{r.calls_from(202, 400, True)}, no 0 A after 232 "
f"({r.calls_from(233, 400)})",
near(r.first_ms(202), 202, 203) and near(r.first_hold(), 232, 233)
and n_other() == 1 and not r.calls_from(202, 400, True)
and not r.calls_from(233, 400))
nev("T5", r)
r = world(after=lambda t: 12.0 if t < 210 or t >= 260 else 16.0)
check(f"T6: C9, own 12 A to 209, foreign 16 A 210-259, 12 A again from 260: "
f"clean 202-209 ({r.clean(202, 209)}), mismatch {r.first_ms(210)}, hold "
f"{r.first_hold()}, 1 line ({n_other()}); the kept value ended at the "
f"hold, so the hold stands 241-400 with no write "
f"({all(r.hold[t] for t in range(241, 401))}, "
f"{r.calls_from(210, 400)})",
r.clean(202, 209) and near(r.first_ms(210), 210, 211)
and near(r.first_hold(), 240, 241) and n_other() == 1
and all(r.hold[t] for t in range(241, 401))
and not r.calls_from(210, 400) and 12.0 not in r.own[300])
nev("T6", r)
r = world(after=lambda t: 0.0 if t < 210 else 12.0)
check(f"T7: C9, 0 A shown 202-209 (a fresh take of the owed 0 A), 12 A from "
f"210: taken at 202 ({r.taken[202]}), mismatch {r.first_ms(210)}, hold "
f"{r.first_hold()}, 1 line ({n_other()})",
r.taken[202] is True and near(r.first_ms(210), 210, 211)
and near(r.first_hold(), 240, 241) and n_other() == 1)
nev("T7", r)
r = world(after=lambda t: 12.0 if t < 230 else 0.0 if t < 240 else 12.0)
check(f"T8: C9, 12 A to 229, 0 A 230-239 (a fresh take), 12 A from 240: clean "
f"202-239 ({r.clean(202, 239)}), taken at 230 ({r.taken[230]}), "
f"mismatch {r.first_ms(230)}, hold {r.first_hold()}, 1 line "
f"({n_other()})",
r.clean(202, 239) and r.taken[230] is True
and near(r.first_ms(230), 240, 241) and near(r.first_hold(), 270, 271)
and n_other() == 1)
nev("T8", r)
r = world(after=lambda t: None if t < 270 else 12.0,
ev=[(262, lambda w, d, s: setattr(w.plan, "a", 10.0))])
w10 = [x for x in r.calls_from(262, 265)]
check(f"T9: C9, None reads 202-269, the plan raises to 10 A at 262 (written, "
f"refused), 12 A from 270: the write {w10[:2]}, own after it "
f"{r.own[263]} (10 replaced 12), mismatch {r.first_ms(270)}, hold "
f"{r.first_hold()}, 1 line ({n_other()})",
(262, 10.0) in w10 and 12.0 not in r.own[263] and 10.0 in r.own[263]
and near(r.first_ms(270), 270, 271) and near(r.first_hold(), 300, 301)
and n_other() == 1)
nev("T9", r)
r = world(after=lambda t: None if t < 207 else 12.0)
check(f"T10: C9, None 202-206, then 12 A from 207 (the same-value 0 A retry "
f"at 202 keeps the kept value): clean 202-400 ({r.clean(202, 400)}), "
f"retry {r.calls_from(202, 203)}",
r.clean(202, 400) and n_other() == 0 and (202, 0.0) in r.calls_from(202, 203)
and 12.0 in r.own[210])
nev("T10", r)
r = world(after=lambda t: 16.0 if t < 205 else None if t < 211 else 16.0)
check(f"T11: C9, 16 A 202-204, None 205-210, 16 A from 211: the count stands "
f"through None ({[r.ms[t] for t in range(205, 211)]}), hold "
f"{r.first_hold()}, 1 line ({n_other()})",
all(r.ms[t] == 202.0 for t in range(205, 211))
and near(r.first_hold(), 232, 233) and n_other() == 1)
r = world(after=lambda t: 12.0, stale=lambda t: 202 <= t <= 206)
check(f"T12: C9, stale reads 202-206, then 12 A: no mismatch 202-400 "
f"({r.first_ms(202)}), no CHARGER_OTHER ({n_other()})",
r.clean(202, 400) and n_other() == 0)
# T13 / T14: DA1, a press that lifts a hold or a count ends everything
def w8(until, ev, press_at):
w = swriter(8.0, ph=1)
w.plan.a, w.plan.n = 12.0, 1
drv = Drv(8.0, lambda a, d: False, ph=1)
box = {}
pairs = list(ev) + [(press_at, chain(press, snap(box)))]
r = Run(w, drv).go(199, until, ev=evs(*pairs),
cur=lambda t, d: 8.0 if t < 205 else 16.0)
return r, box
r, bx = w8(330, [], 250)
check(f"T13: Solar 8 A, 12 A refused at 199, foreign 16 A from 205 (hold "
f"{r.first_hold()}); a press at 250 lifts the hold: from 250 no "
f"mismatch or hold ({r.clean(251, 330)}), own right after the press "
f"{bx.get('own')} (empty: the lifting press ends everything), carry "
f"{bx.get('carry')}, kept {bx.get('kept')}, writes "
f"{r.calls_from(250, 330)}",
near(r.first_hold(), 235, 236) and r.clean(251, 330)
and bx.get("own") == [] and bx.get("carry") == []
and bx.get("kept") is None
and [x for x in r.calls_from(250, 330)] == [(250, 12.0), (310, 12.0)])
nev("T13", r)
r, bx = w8(330, [], 215)
check(f"T14: as T13, the press at 215 while the count runs (mismatch "
f"{r.first_ms(205)}): no count and no line from 216 "
f"({r.clean(216, 330)}), carry {r.carry[215]}, writes "
f"{r.calls_from(215, 330)}",
near(r.first_ms(205), 205, 206) and r.clean(216, 330)
and r.carry[215] == [] and n_other() == 0
and r.calls_from(215, 330) == [(215, 12.0), (275, 12.0)])
# =========================================================================== #
print("Manual")
# =========================================================================== #
cur12 = lambda t, d: 8.0 if t <= 100 else 12.0 # noqa: E731
r = man(200, ev=[(100, chain(set_a(12.0), press)),
(101, chain(set_n(3), press))], last_switch=50.0, cur=cur12)
check(f"T15: Manual 8 A, 12 A at 100 (refused by the call, taken), 3 phases "
f"pressed at 101 (lifts nothing): no mismatch, hold or 'Something "
f"else' line 100-200 ({r.first_ms(100)}, {r.first_hold()}, "
f"{n_some()}), no write 101-200 ({r.calls_from(101, 200)})",
r.clean(100, 200) and n_some() == 0 and not r.calls_from(101, 200))
nev("T15", r)
r = man(200, ev=[(100, chain(set_a(12.0), press))], last_switch=50.0,
cur=cur12)
check(f"T16 (a): T15 with no press: writes {r.calls_from(0)}, no mismatch",
r.calls_from(0) == [(100, 12.0)] and r.clean(100, 200))
r = man(260, ev=[(100, chain(set_a(12.0), press)),
(101, chain(set_n(3), press))],
take=lambda a, d: a == 0.0,
cur=lambda t, d: 8.0 if t <= 100 else 12.0 if t == 101 else d.cur)
check(f"T16 (b): last_switch None, 12 A read at 101: 0 A at 101, select at "
f"102 ({r.calls_from(100, 103)}, {r.drv.sel[:1]}), no mismatch at 101 "
f"({r.ms[101]})",
r.calls_from(100, 103) == [(100, 12.0), (101, 0.0)]
and r.drv.sel and near(r.drv.sel[0][0], 102, 103) and r.ms[101] is None)
# =========================================================================== #
print("Restart, press and S1")
# =========================================================================== #
r = world(gone=lambda t: 203 <= t <= 210,
after=lambda t: 12.0 if t < 203 else 16.0)
check(f"T17 (i): C9, the charger gone 203-210, back at 211 showing 16 A: no "
f"mismatch at 211 ({r.ms[211]}), the D2 0 A at 211 "
f"({r.calls_from(211, 212)}), the kept value is gone ({r.own[211]})",
r.ms[211] is None and (211, 0.0) in r.calls_from(211, 212)
and 12.0 not in r.own[211])
w2, m2 = CM.SolarWriter(), CM.ManualWriter()
src = open(os.path.join(HERE, "app", "carmode.py")).read()
others = [f for f in os.listdir(os.path.join(HERE, "app"))
if f.endswith(".py") and f != "carmode.py"
and "._kept" in open(os.path.join(HERE, "app", f)).read()]
check(f"T17 (ii): a new writer (a process restart) has no kept value and no "
f"carry ({getattr(w2, '_kept', None)}, {getattr(m2, '_kept', None)}, "
f"{w2._carry}); the kept value is in no other module (no store key) "
f"({others})",
getattr(w2, "_kept", None) is None
and getattr(m2, "_kept", None) is None and w2._carry == []
and not others)
# T18: S1-nt, the closes 12, 8, 8 refused, carry [0, 12, 8] at the end (142)
r = s1w(400, ev=[(145, press)], stale=lambda t: 145 <= t <= 149)
check(f"T18 (i): S1-nt, a press at 145 that lifts nothing, stale reads to 149: "
f"the carry is as at 144 ({r.carry[144]}) at every step 145-149 "
f"({[r.carry[t] for t in range(145, 150)]}), 12.0 is own "
f"({r.own[149]}), no write ({r.calls_from(145, 149)})",
r.carry[144] == [0.0, 12.0, 8.0, 8.0]
and all(r.carry[t] == r.carry[144] for t in range(145, 150))
and 12.0 in r.own[149] and not r.calls_from(145, 149))
r = s1w(400, ev=[(143, show(16.0)), (145, press)])
check(f"T18 (ii): foreign 16 A from 143, a press at 145 that lifts the count "
f"(mismatch {r.ms[144]}): the carry is empty after it "
f"({r.carry[145]}), 12.0 is no own value ({r.own[145]})",
r.ms[144] is not None and r.carry[145] == [] and 12.0 not in r.own[145])
nev("T18", r)
r = s1w(400, ev=[(145, press), (150, show(12.0))])
check(f"T18 (EV-69 T12 shape): press at 145, 12 A at 150: mismatch "
f"{r.first_ms(146)}, hold {r.first_hold()}, 1 line ({n_other()}), no "
f"write at or above 12 A",
near(r.first_ms(146), 150, 151) and near(r.first_hold(), 180, 181)
and n_other() == 1
and not [x for x in r.calls_from(145) if x[1] >= 12.0])
# T19: the T8 trace, labelled: the known limit
r = world(after=lambda t: 12.0 if t < 230 else 0.0 if t < 240 else 12.0)
check(f"T19: C9, the 12 A shown 202-229 may be another writer's 12 A exactly "
f"(the accepted limit, EV-67 class: it counts as own): no mismatch to "
f"229 ({r.clean(202, 229)}); after the fresh take at 230, 12 A at 240: "
f"mismatch {r.first_ms(230)}, hold {r.first_hold()}",
r.clean(202, 229) and near(r.first_ms(230), 240, 241)
and near(r.first_hold(), 270, 271))
# =========================================================================== #
print("F1: the held read and the 0 A overwrite")
# =========================================================================== #
r = world("f1a", press_at=None)
z = calls0(r, 201)
check(f"T24: F1a (the held read shows 0 A, the :1345 adopt of base), 12 A "
f"from 202: no mismatch, hold or CHARGER_OTHER ({r.first_ms(202)}, "
f"{n_other()}); the held read takes nothing (taken "
f"{set(r.taken[t] for t in range(201, 401))}); the owed 0 A goes out "
f"at 201-202 and is retried within RETRY_S+2 ({z[:4]})",
r.clean(202, 400) and n_other() == 0
and all(r.taken[t] is False for t in range(201, 401))
and z and near(z[0][0], 201, 202) and spaced(z, 60, 62))
nev("T24", r)
r = world("f1b", press_at=None)
z = calls0(r, 201)
check(f"T25: F1b (the refused 0 A overwrites attempted_a), 12 A from 202: no "
f"mismatch, hold or line ({r.first_ms(202)}, {n_other()}); attempted_a "
f"{r.att[201]}, prior_a {r.prior[201]}, 12.0 is own after the 0 A "
f"({r.own[201]}); the 0 A retry at 261 ({z[:3]})",
r.clean(202, 400) and n_other() == 0 and r.att[201] == 0.0
and r.prior[201] == 8.0 and 12.0 in r.own[201] and (261, 0.0) in z)
nev("T25", r)
r = world("f1a", press_at=None, ev=[(202, cap(6.0))])
c = r.calls_from(202)
# The held 0 A went at 201, before the cap; the cut try follows it RETRY_S
# later (the same spacing T27 has), not blocked by any hold.
check(f"T26: F1a, cap 6 A from 202: the 0 A cut try goes RETRY_S after the "
f"201 try ({c[:3]}), retries at least 60 s apart, cut_fails "
f"{r.w.cut_fails} at most 3, no hold",
c and c[0] == (261, 0.0) and spaced(c)
and r.w.cut_fails <= 3 and r.first_hold() is None)
nev("T26", r)
r = world("f1b", press_at=None, ev=[(202, cap(6.0))])
c = r.calls_from(202)
check(f"T27: F1b, cap 6 A from 202: the 0 A cut try at 261 ({c[:3]}), retries "
f"at least 60 s apart, cut_fails {r.w.cut_fails} at most 3, no hold",
c and c[0] == (261, 0.0) and spaced(c) and r.w.cut_fails <= 3
and r.first_hold() is None)
nev("T27", r)
for kind, tid in (("f1a", "T28"), ("f1b", "T29")):
r = world(kind, press_at=None, after=lambda t: 16.0)
check(f"{tid}: {kind.upper()}, foreign 16 A from 202: mismatch "
f"{r.first_ms(202)}, hold {r.first_hold()}, 1 CHARGER_OTHER "
f"({n_other()}), no non-zero write, no 0 A after 232 "
f"({r.calls_from(202, 400)})",
near(r.first_ms(202), 202, 203) and near(r.first_hold(), 232, 233)
and n_other() == 1 and not r.calls_from(202, 400, True)
and not r.calls_from(233, 400))
nev(tid, r)
r = world("f1b", press_at=None, after=lambda t: None if t < 270 else 12.0,
ev=[(261, lambda w, d, s: setattr(w.plan, "a", 10.0))])
check(f"T30: F1b, None 202-260, the plan raises to 10 A at 261 (written, "
f"refused), 12 A from 270: own {r.own[262]}, mismatch "
f"{r.first_ms(270)}, hold {r.first_hold()}, 1 line ({n_other()})",
(261, 10.0) in r.calls_from(261, 263) and 12.0 not in r.own[262]
and near(r.first_ms(270), 270, 271)
and near(r.first_hold(), 300, 301) and n_other() == 1)
nev("T30", r)
# T31: the ruled limit. A foreign value equal to our own untaken 12 A is taken
# as ours (EV-67 class, formal C9, E5): "it already stands" adopts it at 280
# and the clamp fall at 300 writes 8 A over it. Accepted by the PM (P3).
r = world("f1b", press_at=None,
after=lambda t: 8.0 if t < 210 else 12.0,
ev=[(280, lambda w, d, s: setattr(w.plan, "a", 12.0)),
(300, lambda w, d, s: setattr(w.plan, "a", 8.0))])
check(f"T31: F1b, 8 A (the taken last_a) 202-209, 12 A from 210: clean "
f"202-400 ({r.clean(202, 400)}); at 280 the 'it already stands' adopt "
f"takes the 12 A on show as Solar's own (last_a {r.last_a[280]}, taken "
f"{r.taken[280]}); at 300 8 A is written over it "
f"({r.calls_from(280, 303, True)}). The accepted limit (EV-67 class)",
r.clean(202, 400) and r.last_a[281] == 12.0 and r.taken[281] is True
and (300, 8.0) in r.calls_from(300, 303))
# T32-T34: Manual, the 0 A overwrite
gone32 = lambda t: 101 <= t <= 104 # noqa: E731
def man32(foreign=False):
return man(260, ev=[(100, chain(set_a(12.0), press)),
(101, lambda w, d, s: setattr(d, "ph", 3))],
gone=gone32,
cur=lambda t, d: 8.0 if t < 170 else (16.0 if foreign else 12.0))
r = man32()
check(f"T32: Manual 8 A, 12 A at 100 (the charger keeps 8), it is gone "
f"101-104 and back on 3 phases; _begin's 0 A at 160 refused "
f"({r.calls_from(100, 170)}); 12 A from 170: no mismatch, hold or "
f"'Something else' line 160-260 ({r.first_ms(160)}, {n_some()})",
(160, 0.0) in r.calls_from(160, 161) and r.clean(160, 260)
and n_some() == 0)
nev("T32", r)
r = man(200, ev=[(100, chain(set_a(12.0), press)),
(101, chain(set_n(3), press))],
cur=lambda t, d: 8.0 if t <= 101 else 12.0)
check(f"T33: Manual, 3 phases pressed at 101 (no gap block, the press lifts "
f"nothing), the read still 8 A: _begin's 0 A at 101 refused "
f"({r.calls_from(100, 103)}), 12 A from 102: clean 101-200 "
f"({r.first_ms(101)}, {n_some()})",
(101, 0.0) in r.calls_from(101, 102) and r.clean(101, 200)
and n_some() == 0)
nev("T33", r)
r = man32(foreign=True)
check(f"T34: Manual, T32 with a foreign 16 A from 170: mismatch "
f"{r.first_ms(170)}, hold {r.first_hold()}, 1 line ({n_some()})",
near(r.first_ms(170), 170, 171) and near(r.first_hold(), 200, 201)
and n_some() == 1)
# =========================================================================== #
print("The press and the held read in the S1 shapes")
# =========================================================================== #
r = s1_adopt(260, ev=[(150, press)])
check(f"T35: S1-adopt (12 A adopted, closes 12, 8, 8; state at 142 last_a "
f"{r.last_a[142]}, carry {r.carry[142]}, attempted_a {r.att[142]}, "
f"prior_a {r.prior[142]}, sent_a {r.sent_a[142]}), a press at 150 that "
f"lifts nothing, 12 A still shown: no mismatch, hold or line 150-260 "
f"({r.first_ms(150)}, {n_other()}), 12.0 is own at 150 ({r.own[150]}), "
f"writes {r.calls_from(143, 260)}",
r.last_a[142] is None and r.carry[142] == [0.0, 12.0, 8.0, 8.0]
and r.att[142] == 8.0 and r.prior[142] == 0.0 and r.sent_a[142] == 8.0
and r.clean(150, 260) and n_other() == 0 and 12.0 in r.own[150]
and r.calls_from(143, 260) == [(150, 8.0), (210, 8.0)])
nev("T35", r)
r = s1w(260, ev=[(145, press)], clamp=clamp_16,
cur=lambda t, d: 0.0)
check(f"T36: S1-nt with the clamp at 16 (closes 12, 12, 12 refused, the 0 A "
f"shown), a press at 145 that lifts nothing: no mismatch or hold "
f"145-260 ({r.first_ms(145)}), 0.0 is own ({r.own[145]}), writes "
f"{r.calls_from(143, 260)}",
r.clean(145, 260) and 0.0 in r.own[145]
and r.calls_from(143, 260) == [(145, 12.0), (205, 12.0)])
nev("T36", r)
# T37: a test-side spy on the writer's `_write` records the carry at its entry.
spy = []
w37 = swriter(0.0, ph=3)
w37.plan.a, w37.plan.n = 12.0, 1
drv37 = Drv(0.0, lambda a, d: False, ph=1)
w37.seq = {"stage": "settle", "t0": 119.0, "t1": 122.0, "n": 1, "tries": 0,
"prev": None, "from": 3, "own": [0.0], "sel": True}
w37.last_done = 122.0
w37._own_n = 3
w37._select_try(1, True)
held_wrap(w37, {143})
orig_w = w37._write
async def spy_w(*a, **k):
spy.append((CLOCK["t"], list(w37._carry), getattr(w37, "_kept", None)))
return await orig_w(*a, **k)
w37._write = spy_w
r = Run(w37, drv37).go(123, 260, ev=evs((150, show(12.0))), clamp=16.0)
at142 = r.carry[142]
at143 = [x for x in spy if x[0] == 143]
check(f"T37: S1-nt, clamp 16 (carry {at142} at 142), the held read at 143 "
f"shows 0 A: it takes nothing (taken {r.taken[143]}), the owed 0 A goes "
f"out at 143 ({r.calls_from(143, 143)}), the spy at the _write entry "
f"sees the carry as at 142 ({at143}), after the step it is "
f"{r.carry[143]} (the 0 A write ended it); the kept value is 12 A "
f"at the entry ({at143})",
at142 == [0.0, 12.0, 12.0, 12.0] and r.taken[143] is False
and (143, 0.0) in r.calls_from(143, 143) and len(at143) == 1
and at143[0][1] == at142 and at143[0][2] == 12.0
and r.carry[143] == [])
nev("T37", r)
# T37b: known limit, card EV-73. A refused non-zero value, then an acknowledged
# own 0 A (a taken write ends the kept value), then the charger takes the
# refused value late: today that is a count, then a hold at WRITER_S. This row
# pins it, so a later fix flips it on purpose.
r = world("f1a", press_at=None, take=lambda a, d: a == 0.0)
check(f"T37b [known limit, card EV-73]: the 12 A refused, the own 0 A taken "
f"(taken {r.taken[201]}), the charger shows 12 A from 202: mismatch "
f"{r.first_ms(202)}, hold {r.first_hold()}, 1 CHARGER_OTHER "
f"({n_other()}), kept value gone ({r.own[202]})",
r.taken[201] is True and near(r.first_ms(202), 202, 203)
and near(r.first_hold(), 232, 233) and n_other() == 1
and 12.0 not in r.own[202])
r = s1_adopt(260, ev=[(150, show(16.0))],
clamp=lambda t: 16.0 if t < 135 else 8.0 if t < 160 else 6.0)
check(f"T38: S1-adopt, foreign 16 A from 150, the clamp falls to 6 at 160 "
f"during the count: mismatch {r.first_ms(150)}, hold "
f"{r.first_hold()}, 1 CHARGER_OTHER ({n_other()}), no write 150-260 "
f"({r.calls_from(150, 260)}), state at 149: last_a {r.last_a[149]}, "
f"attempted_a {r.att[149]}, prior_a {r.prior[149]}, sent_a "
f"{r.sent_a[149]}",
near(r.first_ms(150), 150, 151) and near(r.first_hold(), 180, 181)
and n_other() == 1 and not r.calls_from(150, 260)
and r.last_a[149] is None and r.att[149] == 8.0 and r.prior[149] == 0.0
and r.sent_a[149] == 8.0)
nev("T38", r)
# T39: the accepted limit again (EV-67 class, E5): another writer's 8 A equal
# to our own untaken 8 A is taken as ours by the late read-back adopt, and the
# later own 12 A goes over it. No mutant: it documents the limit.
r = s1_adopt(260, ev=[(150, show(8.0)),
(200, lambda w, d, s: setattr(w.plan, "a", 12.0))],
clamp=lambda t: 16.0 if t < 135 else 8.0 if t < 200 else 16.0)
check(f"T39: S1-adopt, another writer's 8 A (= the kept 8 A) at 150, the clamp "
f"back to 16 and the plan 12 A at 200: not seen, no mismatch or hold "
f"150-260 ({r.first_ms(150)}); at 150 the read-back adopt takes it "
f"(last_a {r.last_a[150]}, taken {r.taken[150]}); 12 A is written over "
f"it at 200 and retried at 260 ({r.calls_from(200, 260)}). The accepted "
f"limit, EV-67",
r.clean(150, 260) and r.last_a[150] == 8.0 and r.taken[150] is True
and (200, 12.0) in r.calls_from(200, 201)
and (260, 12.0) in r.calls_from(260, 261))
# =========================================================================== #
print("Never rules not already inside a row")
# =========================================================================== #
# N4: the hole is no wider than EV-67: the own list holds only values the
# writer wrote, saw or had, never a made-up one, in the C9 and F1 traces.
for tag, r in (("C9", world()), ("F1a", world("f1a", press_at=None)),
("F1b", world("f1b", press_at=None))):
seen = {0.0, 8.0, 12.0} | {a for _, a in r.drv.calls}
stray = [(t, v) for t in r.own for v in r.own[t] if v not in seen]
check(f"N4 {tag}: every own value is one the writer wrote or had "
f"({stray[:2]})", not stray)
# N10: the kept value is never persisted (T17 ii names the modules); it is no
# key of the writer's own state dicts either.
check("N10: the kept value is not part of the carry list or the log",
all(not hasattr(CM, n) for n in ("KEY_KEPT", "KEY_OWN_KEPT")))
# N15: a kept value is never own after a hold (T6 reads it back from 260)
r = world(after=lambda t: 16.0 if t < 260 else 12.0)
check(f"N15: C9, a hold over 16 A (hold {r.first_hold()}), then the old 12 A "
f"from 260 does not lift it ({all(r.hold[t] for t in range(241, 401))})",
near(r.first_hold(), 232, 233)
and all(r.hold[t] for t in range(241, 401)))
done()
+335
View File
@@ -0,0 +1,335 @@
"""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)
+308
View File
@@ -0,0 +1,308 @@
"""EV-69: the writer-level harness of test_ev69.py and test_ev69_fuzz.py: a
`SolarWriter` / `ManualWriter` on a stub driver, a stub tracker and a stub
reading, one step per second on a model clock; `Run` records what every step
ended with. `Base69` / `BaseM69` are de733f4's writers (the carry switched
off): the red side of a row.
Each check file is its own process, so `fails` and `LOG` are its own."""
import asyncio
import logging
import os
import sys
_KIT = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(_KIT))
from app import carmode as CM # noqa: E402
fails = []
CLOCK = {"t": 0}
LOG = []
OTHER = "CHARGER_OTHER"
SOMETHING = "Something else changes the charger"
REC = "The car charger step failed"
class Cap(logging.Handler):
def emit(self, rec):
LOG.append((CLOCK["t"], rec.levelname, rec.getMessage()))
logging.getLogger("goodwe").addHandler(Cap())
logging.getLogger("goodwe").setLevel(logging.DEBUG)
def check(name, cond):
print(f" {'ok ' if cond else 'FAIL'} {name}")
if not cond:
fails.append(name)
def done():
print("\nall passed" if not fails else f"\n{len(fails)} FAILED")
for f in fails:
print(" FAIL:", f)
sys.exit(1 if fails else 0)
class Rd:
def __init__(self, a, ph=1, power=None, state="C"):
self.available = True
self.allowed_a = self.setpoint_a = a
self.phases_allowed = ph
self.power_w = power
self.state = state
self.error = False
self.charging = True
self.current_a = ()
self.station_a = None
class Trk:
obs_at = None
def begin_write(self):
pass
def end_write(self, *_):
pass
def note_write(self, *a, **k):
pass
def stuck(self, now):
return False
class Drv:
"""`take(a, drv)` -> True (the charger takes it), False (refused) or
"raise" (the call raises)."""
def __init__(self, cur, take, ph=1):
self.cur, self.ph, self.take = cur, ph, take
self.calls, self.now, self.polls, self.sel = [], 0.0, (), []
async def write_current(self, a, **kw):
self.calls.append((self.now, float(a)))
r = self.take(float(a), self)
if r == "raise":
raise RuntimeError("HA call error")
if r is True:
self.cur = float(a)
return r is True
async def write_phases(self, n):
self.sel.append((self.now, n, self.cur))
self.ph = n
return True
def _clock(self):
return self.now
async def _sleep(self, s):
self.now += s
class Base69(CM.SolarWriter):
"""de733f4's Solar: an ended sequence's values are not carried."""
def _carry_end(self, q):
self._carry = []
class BaseM69(CM.ManualWriter):
"""de733f4's Manual."""
def _carry_end(self, q):
self._carry = []
LOOP = asyncio.new_event_loop()
def swriter(cur, ph=1, cls=None):
w = (cls or CM.SolarWriter)()
w.engaged, w.mode_was = True, CM.SOLAR
w.fresh_start = w.restart = False
w.was_available = w._seen = True
w.sent_a, w.taken, w.last_a = cur, True, cur
w.plan.a, w.plan.n = cur, ph
def plan_step(sun, now, clamp, n, gap):
c = w.cut_a
if c is not None and c >= CM.CH.MIN_A and w.plan.a > c + 1e-9:
w.plan._cut(c)
w._plan_step = plan_step
return w
def set_cap(w, a):
w.cut_a, w.cut_on = a, a is not None
def show(a):
return lambda w, d, s: setattr(d, "cur", float(a))
def press(w, d, s):
w.user_changed()
s["rev"] = s.get("rev", 1) + 1
def cap(a):
return lambda w, d, s: set_cap(w, a)
def chain(*fns):
def f(w, d, s):
for fn in fns:
fn(w, d, s)
return f
def evs(*pairs):
"""{t: fn(w, drv, st)}; two at one second run both."""
out = {}
for t, fn in pairs:
out[t] = chain(out[t], fn) if t in out else fn
return out
class Run:
"""One writer-level run; per second: mismatch, hold, counts."""
def __init__(self, w, drv, kind="solar", st=None):
del LOG[:]
self.w, self.drv, self.kind = w, drv, kind
self.trk, self.st = Trk(), st if st is not None else {}
self.ms, self.hold, self.gu, self.fl, self.seq = {}, {}, {}, {}, {}
self.taken, self.last_a, self.sent_a = {}, {}, {}
self.prior, self.att, self.carry, self.ncalls = {}, {}, {}, {}
self.own = {}
self.viol, self.ended, self.log = [], None, []
def go(self, t0, t1, ev=None, hook=None, clamp=16.0, writing=None,
cur=None, stale=None, gone=None):
w, drv = self.w, self.drv
for t in range(t0, t1 + 1):
drv.now = float(t)
CLOCK["t"] = t
if ev and t in ev:
ev[t](w, drv, self.st)
if hook:
hook(t, w, drv, self.st)
if hasattr(w, "cut_quarter"):
w.cut_quarter(int(t // 900))
c = drv.cur if cur is None else cur(t, drv)
rd = Rd(c, drv.ph, power=0.0 if drv.cur == 0 else 1840.0)
if gone is not None and gone(t):
rd.available = False
cl = clamp(t) if callable(clamp) else clamp
if self.kind == "manual":
cl = self.st.get("clamp", cl)
self.trk.obs_at = None
if stale is not None and stale(t):
self.trk.obs_at = w.last_done if w.last_done is not None \
else 0.0
wr = True if writing is None else writing(t)
n0, s0 = len(drv.calls), w.seq is not None
if self.kind == "solar":
LOOP.run_until_complete(w.step(
drv, rd, mode=CM.SOLAR, sun=CM.SunInputs(target_w=2000.0),
clamp=cl, now=float(t), tracker=self.trk, writing=wr,
status="charging"))
else:
LOOP.run_until_complete(w.step(
drv, rd, mode=CM.MANUAL, want_a=self.st["a"],
want_phases=self.st["n"], rev=self.st["rev"], clamp=cl,
now=float(t), tracker=self.trk, writing=wr,
status="charging"))
if s0 and w.seq is None and self.ended is None:
self.ended = t
# N2 is judged on the state after the step's own watch: a count
# a read cleared in this step (the foreign value went) is no
# count when the write goes out.
stood = bool(w.hold or (self.kind == "solar"
and w.mismatch_since is not None))
for tt, a in drv.calls[n0:]:
# N2 / N5 per write
if a > 0 and stood:
self.viol.append((t, "N2 write while a count/hold stood",
a))
if a > cl + 1e-9 or 0 < a < CM.CH.MIN_A - 1e-9:
if not (w.cut_a is not None and a <= w.cut_a + 1e-9):
self.viol.append((t, "N5 write outside clamp/6 A", a))
if getattr(w, "cut_fails", 0) > CM.MAX_TRIES:
self.viol.append((t, "N6 cut tries over the cap"))
self.ms[t], self.hold[t] = w.mismatch_since, w.hold
self.gu[t], self.fl[t] = w.gave_up, w.fails
self.seq[t], self.taken[t] = w.seq is not None, getattr(
w, "taken", None)
self.last_a[t], self.sent_a[t] = w.last_a, getattr(
w, "sent_a", None)
self.prior[t], self.att[t] = w.prior_a, w.attempted_a
self.carry[t] = list(getattr(w, "_carry", []))
self.own[t] = list(w._own_values())
self.ncalls[t] = len(drv.calls)
self.log = list(LOG)
LAST[0] = self
return self
# ---------------------------------------------------------- readings
def calls_from(self, t0, t1=10 ** 9, nz=False):
return [(int(t), a) for t, a in self.drv.calls
if t0 <= t <= t1 and (not nz or a > 0)]
def clean(self, lo, hi):
"""No mismatch, no hold, no CHARGER_OTHER line, no 'Something else
changes' line in lo..hi."""
return (all(self.ms[t] is None and not self.hold[t]
for t in range(lo, hi + 1) if t in self.ms)
and not [1 for t, lv, m in self.log if lo <= t <= hi
and (OTHER in m or SOMETHING in m)])
def first_ms(self, lo=0):
for t in sorted(self.ms):
if t >= lo and self.ms[t] is not None:
return t
return None
def first_hold(self, lo=0):
for t in sorted(self.hold):
if t >= lo and self.hold[t]:
return t
return None
LAST = [None] # the run that ended last: what `n_other` / `n_some` count
def n_other():
return len([1 for t, lv, m in LAST[0].log if OTHER in m])
def n_some():
return len([1 for t, lv, m in LAST[0].log if SOMETHING in m])
def near(x, lo, hi):
return x is not None and lo <= x <= hi
def nev(tag, run):
"""N2, N5, N6 over one run (collected per step by `Run.go`), N9 (one
CHARGER_OTHER per hold rise), N8 (a select only at 0 A)."""
rises = 0
prev = False
for t in sorted(run.hold):
if run.hold[t] and not prev:
rises += 1
prev = run.hold[t]
sel_bad = [x for x in run.drv.sel if x[2] > CM.TOL_A]
check(f"N2/N5/N6 {tag}: no write over a count or hold, none above the "
f"clamp or in 0-6 A, at most 3 cut tries ({run.viol[:2]})",
not run.viol)
check(f"N8/N9 {tag}: a select only at 0 A ({sel_bad[:1]}), at most one "
f"CHARGER_OTHER per hold ({n_other()} for {rises})",
not sel_bad and n_other() <= rises)