Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9ba3008eb8 | ||
|
|
6881748660 | ||
|
|
831c33c96b | ||
|
|
3a883fc9ae | ||
|
|
1886a9f1ba | ||
|
|
0eb332d93f | ||
|
|
278041b25c | ||
|
|
fe5e3ee477 | ||
|
|
8a40343a84 | ||
|
|
0f3d5d75e5 | ||
|
|
9b09158ef8 | ||
|
|
7d1ed1bbcf | ||
|
|
de733f44bf | ||
|
|
7710d45393 | ||
|
|
e0e51dac12 | ||
|
|
b7c91ff746 | ||
|
|
c7b1b7dbd1 | ||
|
|
19c5d5a61e | ||
|
|
bba10f44c3 | ||
|
|
392f9c2b57 | ||
|
|
5ddabfbd93 | ||
|
|
1c387441c7 | ||
|
|
5bd2b1ec97 | ||
|
|
2e09622fe1 |
@@ -2,6 +2,8 @@
|
||||
|
||||
### Not in a release yet
|
||||
|
||||
- **Each battery can have its own round-trip efficiency, and a battery that loses too much is not charged from the grid for the price gap.** New optional setting per inverter, *Round-trip efficiency* (`inverters.round_trip_eff`, 0.5 to 1). Set on a battery, its cheap hour counts at its price divided by it, so a battery at 0.75 is not charged at night for the day when a battery at 0.86 would be. The day plan and Home use each battery's own number, and the status page shows it, or "not set". If you set it, lower *Battery cycle cost* to wear only: the add-on never changes that value. Not set, nothing changes. How the work is split between the batteries is unchanged ([[TARIFF-30]]).
|
||||
- **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]]).
|
||||
|
||||
@@ -183,6 +183,7 @@ The label and description each setting shows on the Configuration tab, in tab or
|
||||
| Hardware · Inverter list | Battery power entity (W) (optional) | `inverters.batt_entity` | This inverter's own battery power sensor. Leave it empty if it has none. |
|
||||
| Hardware · Inverter list | Battery power sign is reversed (optional) | `inverters.batt_invert` | Switch this on if this inverter's sensor shows giving power as a negative number. |
|
||||
| Hardware · Inverter list | Usable battery capacity (kWh) (optional) | `inverters.capacity_kwh` | This battery's usable capacity from its datasheet. Fill it in on every inverter or on none. The add-on then shares the work by the energy each battery has left. |
|
||||
| Hardware · Inverter list | Round-trip efficiency (0.5 to 1) (optional) | `inverters.round_trip_eff` | The share of energy this battery gives back, for example 0.86. Leave it empty if unknown. If you set round-trip efficiency, lower the cycle cost to wear only. |
|
||||
| Hardware | RS485 emergency stop is fitted | `estop_fitted` | Switch this on if the emergency stop is installed. It only changes a warning on the status page. |
|
||||
| Hardware | Battery modes | `battery_modes_enabled` | Give each battery an on and off switch and a mode, set on the Batteries screen. |
|
||||
| Hardware | Solar forecast, today (kWh) | `pv_forecast_entity` | Optional. A forecast sensor with today's remaining solar energy, such as Forecast.Solar or Solcast. A battery then buys only what the sun will not give. |
|
||||
@@ -229,7 +230,7 @@ The label and description each setting shows on the Configuration tab, in tab or
|
||||
| Tariff | Current price entity (older) | `price_now_entity` | The older way to get a price, used only to charge in a cheap window during maintenance. Do not combine it with a dynamic price source. |
|
||||
| Tariff | Average price entity (older) | `price_avg_entity` | The average the current price is compared with. Use it only with the current price entity, not with a dynamic price source. |
|
||||
| Tariff | Trade on the price spread | `arbitrage_enabled` | Charge in the cheapest hour and draw the battery down in the dearest, when the spread covers the cost. Turning it off does not turn the price feed off. |
|
||||
| Tariff | Battery cycle cost (EUR/kWh) | `cycle_cost_threshold_eur` | What one full battery cycle costs per kWh. A smaller price spread is not traded, and the value is a product choice, not a measured one. |
|
||||
| Tariff | Battery cycle cost (EUR/kWh) | `cycle_cost_threshold_eur` | Cost of one cycle per kWh. Smaller gaps are not traded. A product choice, not a measured one. If you set round-trip efficiency, lower the cycle cost to wear only. |
|
||||
| Tariff | Trading keeps at least (%) | `arbitrage_soc_floor` | Price trading will not draw the battery below this level. It is separate from the maintenance settings. |
|
||||
| Tariff | Trading charges at most (%) | `arbitrage_soc_ceiling` | Price trading will not charge the battery above this level. |
|
||||
| Maintenance | Run the monthly battery cycle | `maintenance_enabled` | Once a month, empty the battery deeply, charge it full and hold it there, so its level reading stays accurate. Off by default. |
|
||||
@@ -283,6 +284,7 @@ When the add-on refuses to start, each reason names the setting by its label and
|
||||
- **Battery power entity** (`batt_entity`): on the reference installation this is holding register 0x0518, read by the control board. The wrong-direction checks and the opposing-inverters alarm both grade each inverter against it.
|
||||
- **Inverter list** (`inverters`): empty means the single-inverter settings describe the one inverter you have. Filled in, the list replaces them and nothing is inherited: each entry names its own setpoint entity, rating and cut-out level, so no inverter is judged by another's numbers. “Inverter setpoint entity” must then be empty, and the add-on refuses to start when both are set. Each entry's name keys its own safety stop and records in the add-on's state, so two entries may not share one.
|
||||
- **Usable battery capacity** (`inverters.capacity_kwh`): read only to share the site target by the energy each battery has left rather than by its rating. The reference batteries are 5000 W with 15.36 kWh and 4600 W with 20.48 kWh, so the two ways of sharing give the work to different batteries. Stated on some entries and not others, the add-on refuses to start.
|
||||
- **Round-trip efficiency** (`inverters.round_trip_eff`, 0.5 to 1, optional per entry): the share of the energy a battery gives back after it took it in, measured by you (for example 0.86 and 0.75 on two batteries). Set, the cheap hour for that battery counts at its price divided by this number, and it is charged from the grid only when the price gap still covers that and the cycle cost. Not set, nothing changes. A battery can have it while another does not. The day plan then uses the square root of it for each way in and out. **Settings impact:** *Battery cycle cost* then means wear only, so lower it when you set this; the add-on never changes your cycle cost by itself. Taking the key out again leaves the add-on as it was; nothing is stored. The status page shows each battery's value, or "not set". How the work is split between the batteries when giving power does not depend on it.
|
||||
- **Solar production entities** (`pv_entity`, `pv_entities`, `pv_invert_entities`): measurement only, no control behaviour changes. The unit is read off each entity, so a sensor without one is refused rather than guessed. With several entities, one that stops reporting gives no site total at all, because a partial sum looks like a real one. Setting `pv_entities` ignores `pv_entity`.
|
||||
- **Where the meter reading comes from** (`meter_source`): 'off' keeps “Grid power entity”. ha_dsmr follows the DSMR integration, mqtt_p1 reads an MQTT topic, ha_signed reads one signed entity (what a HomeWizard P1 publishes), and homewizard_local polls the meter's own local API. Only homewizard_local can tell "the meter did not answer" from "the value did not change", so the stuck-meter alarm only means something there.
|
||||
- **Grid import and export entities** (`p1_import_entity`, `p1_export_entity`, `p1_net_entity`): the add-on computes net power itself, so the sign convention lives in tested code rather than in a template sensor.
|
||||
@@ -3370,10 +3372,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.
|
||||
|
||||
@@ -267,6 +267,55 @@ def threshold_eur_kwh(opts: dict) -> float:
|
||||
return v
|
||||
|
||||
|
||||
# TARIFF-30. A unit's own losses are the whole reason the buy leg is refused.
|
||||
IDLE_LOSSES = ("the price gap does not cover the energy these batteries lose "
|
||||
"on the way in and out")
|
||||
|
||||
|
||||
def leg_clears(v, eta) -> bool:
|
||||
"""TARIFF-30. Does ONE unit's buy leg clear on the verdict `v`?
|
||||
|
||||
With no efficiency set (`eta` None) the verdict itself is the answer, as
|
||||
today. With one set, the cheap hour is priced at `price / eta` and the gap
|
||||
to the dear hour must still reach what this cycle needs
|
||||
(`v.required_spread_eur_kwh`). That figure is the cycle cost widened for
|
||||
doubt and is NOT widened again for the loss: `eta` is a configured number,
|
||||
not price uncertainty. The sell leg has no `eta`. Rounded to six places like
|
||||
the verdict's own spread, so the boundary agrees with it."""
|
||||
if eta is None:
|
||||
return True
|
||||
net = round(float(v.dearest.eur_per_kwh)
|
||||
- float(v.cheapest.eur_per_kwh) / float(eta), 6)
|
||||
return net >= float(v.required_spread_eur_kwh)
|
||||
|
||||
|
||||
def clearing(plan, now: datetime, *, min_spread_eur_kwh, uncertainty, etas):
|
||||
"""TARIFF-30. `{name: bool}`: which units' own buy legs clear, or None.
|
||||
|
||||
`etas` is `{name: round_trip_eff or None}`. None is returned when nobody
|
||||
has an efficiency (nothing to decide: today's behaviour) and when the
|
||||
verdict does not allow a trade at all (the caller's own gate speaks). The
|
||||
peak guard is asked as clear: the interlock is the caller's, and an
|
||||
efficiency can only narrow a verdict, never widen it."""
|
||||
if plan is None or not any(e is not None for e in etas.values()):
|
||||
return None
|
||||
verdict = plan.arbitrage(peak_guard_active=False,
|
||||
min_spread_eur_kwh=min_spread_eur_kwh,
|
||||
uncertainty=uncertainty, now=now)
|
||||
return verdict.match(
|
||||
refused=lambda _v: None,
|
||||
allowed=lambda v: {n: leg_clears(v, e) for n, e in etas.items()})
|
||||
|
||||
|
||||
def idle_for_losses(decision: ArbitrageDecision) -> ArbitrageDecision:
|
||||
"""TARIFF-30. `decision` (an IDLE_NO_SIZE refusal) as the efficiency
|
||||
refusal it really is, with the same numbers: no unit's own leg cleared, so
|
||||
the buy was sized at 0 W. Still no claim (never a 0 W one)."""
|
||||
return _idle(IDLE_LOSSES, spread=decision.spread_eur_kwh,
|
||||
required=decision.required_eur_kwh,
|
||||
price=decision.price_now_eur_kwh)
|
||||
|
||||
|
||||
def weather_uncertainty(modes_on: bool, solar_fc, held: bool = False) -> frozenset:
|
||||
"""The "no weather" doubt (x1.5) a trade must clear. TARIFF-24.
|
||||
|
||||
|
||||
@@ -150,11 +150,25 @@ class ManualWriter:
|
||||
self._late = None # (a, was, why, n) of a write not taken
|
||||
self._rec_a = None # EV-56: the raised value already logged
|
||||
self._close_k = 0 # EV-59: not-taken closes of the value owed
|
||||
self._ph_diff = False # EV-22: the phases differ from our own
|
||||
# (Solar only; Manual never sets it)
|
||||
self._carry = [] # EV-69: the closes an ended sequence tried
|
||||
self._kept = None # EV-71: an own non-zero write not seen taken
|
||||
|
||||
# ------------------------------------------------------------------ user
|
||||
def user_changed(self) -> None:
|
||||
"""The user changed the mode or a value: one more write is allowed,
|
||||
and another writer's hold is lifted."""
|
||||
and another writer's hold is lifted. EV-22 (DA1): a change that lifts
|
||||
a difference inside a phase change ends the change at its 0 A; the
|
||||
raise check never holds over the value the user's change took.
|
||||
EV-71 (P1): a press that lifts no count and no hold ends nothing of
|
||||
our own: `attempted_a`, `prior_a`, the carry and the kept value stay."""
|
||||
lifts = self._other_stands()
|
||||
if self.seq is not None:
|
||||
if self._other_stands():
|
||||
self.seq = None
|
||||
else:
|
||||
self.seq["pressed"] = True # the raise check holds off
|
||||
self.boot = False
|
||||
self.rev_applied = None
|
||||
self.hold = self.other = False
|
||||
@@ -162,7 +176,12 @@ class ManualWriter:
|
||||
self.fails, self.fail_at, self.gave_up = 0, None, False
|
||||
self._close_k = 0 # EV-59
|
||||
self.phase_fails, self.phases_gave_up = 0, False
|
||||
self.attempted_a = self.prior_a = None
|
||||
if lifts:
|
||||
# EV-71 P1: a press that lifts a count or hold ends everything
|
||||
# (EV-22 DA1); one that lifts nothing ends nothing.
|
||||
self.attempted_a = self.prior_a = None
|
||||
self._carry = [] # EV-69: a lifting user change ends the carry
|
||||
self._kept = None
|
||||
self._late = None # EV-52: that request is not current now
|
||||
self._rec_a = None # EV-56 (G2): a raise is logged again
|
||||
|
||||
@@ -192,6 +211,9 @@ class ManualWriter:
|
||||
self._rec_a = None # EV-56 (G2): logged again
|
||||
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
|
||||
if self.seq is not None:
|
||||
# EV-22 (C7): the watch runs in every step of a phase change; the
|
||||
# change's own values count as own (`_own_values`).
|
||||
self._watch(cur, now)
|
||||
if self.seq["stage"] in ("zero", "select") \
|
||||
and (mode != MANUAL or not writing):
|
||||
await self._undo(drv, now, tracker, clamp, shadow)
|
||||
@@ -227,7 +249,9 @@ class ManualWriter:
|
||||
self.fails, self.blocked = 0, False
|
||||
self._close_k = 0
|
||||
if cur is not None:
|
||||
self._kept_end() # EV-71 (Q6): a take ends it too
|
||||
self.last_a = cur # adopt what is already set
|
||||
self._carry = [] # EV-69: an own take ends the carry
|
||||
# EV-52 (PM Q2): a write taken late is logged once, here.
|
||||
late, self._late = self._late, None
|
||||
if late is not None and abs(cur - float(late[0])) <= TOL_A:
|
||||
@@ -275,26 +299,90 @@ class ManualWriter:
|
||||
self.fails = max(min(self._close_k, MAX_TRIES) - 1, 0)
|
||||
self._failed(now)
|
||||
|
||||
def _watch(self, cur, now) -> None:
|
||||
def _other_stands(self) -> bool:
|
||||
"""EV-22: another writer's value is held, or its count is running:
|
||||
nothing non-zero is written over it."""
|
||||
return bool(self.hold or self.mismatch_since is not None)
|
||||
|
||||
def _own_values(self) -> list:
|
||||
"""The currents that are ours: what we wrote, tried or saw before a
|
||||
try, and (EV-22, C7) every value of the phase change under way: its
|
||||
0 A and each closing current it tried (also after a user change
|
||||
cleared `attempted_a`)."""
|
||||
vals = [x for x in (self.last_a, self.attempted_a, self.prior_a,
|
||||
self._kept) if x is not None] # EV-71: kept
|
||||
if self.seq is not None:
|
||||
vals += self.seq.get("own", ())
|
||||
return vals + self._carry
|
||||
|
||||
def _kept_end(self) -> None:
|
||||
"""EV-71: the kept value ends (a hold over another writer's value, a
|
||||
fresh take, a lifting press, Solar's return). It is also no longer
|
||||
`attempted_a` or `prior_a`, where the same untaken value may sit."""
|
||||
k, self._kept = self._kept, None
|
||||
if k is not None:
|
||||
if self.attempted_a is not None \
|
||||
and abs(self.attempted_a - k) <= TOL_A:
|
||||
self.attempted_a = None
|
||||
if self.prior_a is not None and abs(self.prior_a - k) <= TOL_A:
|
||||
self.prior_a = None
|
||||
|
||||
def _carry_ok(self) -> bool:
|
||||
"""EV-69: may an ended sequence's values be carried? Manual: yes."""
|
||||
return True
|
||||
|
||||
def _carry_end(self, q) -> None:
|
||||
"""EV-69 (OQ1, OQ2): a sequence ended (MAX_TRIES, or Solar's EV-60 cap
|
||||
end): every value it tried, its 0 A too, stays own on the lifetime of
|
||||
`attempted_a`/`prior_a`, for a late take of an earlier close. Not when
|
||||
the end's own value is already taken (`_carry_ok`). It ends at an own
|
||||
take, any own current write, a user change, a hold, Solar's return."""
|
||||
self._carry = list(q.get("own", ())) if self._carry_ok() else []
|
||||
|
||||
def _carried_take(self) -> None:
|
||||
"""EV-69 (GUR): the charger shows a carried close. Own; the carry
|
||||
stays. Manual: nothing changes."""
|
||||
|
||||
def _watch(self, cur, now, judge=True) -> None:
|
||||
"""Is the read-back what we wrote? A difference that stands for
|
||||
`WRITER_S` is another writer."""
|
||||
known = [x for x in (self.last_a, self.attempted_a, self.prior_a)
|
||||
if x is not None]
|
||||
if not known or cur is None:
|
||||
self.mismatch_since = None
|
||||
`WRITER_S` is another writer. EV-22: one count and one hold for the
|
||||
current and (Solar) the phases; `judge=False`: the reading is from
|
||||
before our own write of this step, so the current is not judged and
|
||||
the count stands."""
|
||||
known, diff = [], None
|
||||
if cur is None:
|
||||
judge = False # an unknown read: the count neither starts
|
||||
# nor clears (phases are still judged)
|
||||
if judge:
|
||||
known = self._own_values()
|
||||
if known and cur is not None:
|
||||
diff = not any(abs(cur - k) <= TOL_A for k in known)
|
||||
if not diff and cur > TOL_A and any(
|
||||
abs(cur - k) <= TOL_A for k in self._carry):
|
||||
self._carried_take()
|
||||
if diff or self._ph_diff:
|
||||
if self.mismatch_since is None:
|
||||
self.mismatch_since = now
|
||||
elif now - self.mismatch_since >= WRITER_S and not self.hold:
|
||||
self.hold = self.other = True
|
||||
self._carry = [] # EV-69: never own after a hold
|
||||
self._kept_end() # EV-71 (OQ1): nor the kept value
|
||||
if diff:
|
||||
_LOG.info("Something else changes the charger (read-back "
|
||||
"%.0f A, the add-on set %.0f A), so the add-on "
|
||||
"stops writing to it until you change it.",
|
||||
cur, known[0])
|
||||
else:
|
||||
_LOG.info("Something else changes the charger (the "
|
||||
"phases are not the ones the add-on chose), so "
|
||||
"the add-on stops writing to it until you "
|
||||
"change it.")
|
||||
return
|
||||
if any(abs(cur - k) <= TOL_A for k in known):
|
||||
self.mismatch_since = None
|
||||
if self.hold:
|
||||
self.hold = self.other = False
|
||||
if not judge:
|
||||
return
|
||||
if self.mismatch_since is None:
|
||||
self.mismatch_since = now
|
||||
elif now - self.mismatch_since >= WRITER_S and not self.hold:
|
||||
self.hold = self.other = True
|
||||
_LOG.info("Something else changes the charger (read-back %.0f A, "
|
||||
"the add-on set %.0f A), so the add-on stops writing "
|
||||
"to it until you change it.", cur, known[0])
|
||||
self.mismatch_since = None
|
||||
if diff is False and self.hold:
|
||||
self.hold = self.other = False
|
||||
|
||||
# ----------------------------------------------------- EV-52: the info line
|
||||
def _why_default(self) -> str:
|
||||
@@ -339,6 +427,7 @@ class ManualWriter:
|
||||
# EV-56: a raise at shutdown is left to the caller (CHARGER_RESTORE).
|
||||
strict = kw.pop("strict", False)
|
||||
self._late = None
|
||||
self._carry = [] # EV-69: a new own write ends the carry
|
||||
if self._rec_a is not None and abs(self._rec_a - float(a)) > TOL_A:
|
||||
self._rec_a = None # EV-56 (G2): another value
|
||||
tracker.begin_write() # EV-12: the read-back is ours
|
||||
@@ -367,13 +456,23 @@ class ManualWriter:
|
||||
if ok:
|
||||
self.last_a = a
|
||||
self.attempted_a = self.prior_a = None
|
||||
self._kept = None # EV-71 (Q6): a taken write
|
||||
self._rec_a = None # EV-56 (G2): a taken write
|
||||
self._log_set(a, was, why, n)
|
||||
else:
|
||||
self.attempted_a, self.prior_a = a, was
|
||||
self._keep(a)
|
||||
self._late = (a, was, why, n) # logged if it is adopted later
|
||||
return ok
|
||||
|
||||
def _keep(self, a) -> None:
|
||||
"""EV-71 (Q4-Q6): a non-zero write the charger did not take is kept
|
||||
own, whatever the next try overwrites in `attempted_a`/`prior_a`. A
|
||||
0 A never ends it (Q5) and never sets it; another non-zero value
|
||||
replaces it, the same one keeps it (Q2)."""
|
||||
if float(a) > TOL_A:
|
||||
self._kept = float(a)
|
||||
|
||||
def _raised(self, err, a, was, now, why, n) -> None:
|
||||
"""EV-56: a write that raised (an HA call error, a setup error, a bug)
|
||||
is a try the charger did not take, counted by the caller as a refusal
|
||||
@@ -381,6 +480,7 @@ class ManualWriter:
|
||||
ERROR record, with the traceback, comes once per raised value (Q1)."""
|
||||
self.log.append(("current", a, now, False))
|
||||
self.attempted_a, self.prior_a = a, was
|
||||
self._keep(a) # EV-71
|
||||
self._late = (a, was, why, n) # logged if it is adopted later
|
||||
if self._rec_a is None:
|
||||
self._rec_a = float(a)
|
||||
@@ -410,7 +510,8 @@ class ManualWriter:
|
||||
self.undone += 1
|
||||
self.rev_applied, self.reapply = None, True
|
||||
a = self._restore_a(q.get("prev"), clamp)
|
||||
if a is not None:
|
||||
if a is not None and not self._other_stands(): # EV-22: not over theirs
|
||||
q.setdefault("own", []).append(a)
|
||||
await self._write(drv, a, 0.0, now, tracker, why="Manual")
|
||||
|
||||
async def _begin(self, drv, r, cur, n, now, tracker) -> None:
|
||||
@@ -428,7 +529,7 @@ class ManualWriter:
|
||||
self._failed(now)
|
||||
return
|
||||
self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0,
|
||||
"prev": cur}
|
||||
"prev": cur, "own": [0.0]}
|
||||
|
||||
async def abandon(self, drv, now, tracker, clamp=None) -> None:
|
||||
"""The add-on is stopping in the middle of a phase change: give the car
|
||||
@@ -436,13 +537,22 @@ class ManualWriter:
|
||||
like every write. The phases stay as the select left them."""
|
||||
q, self.seq = self.seq, None
|
||||
a = None if q is None else self._restore_a(q.get("prev"), clamp)
|
||||
if a is not None:
|
||||
if a is not None and not self._other_stands(): # EV-22: not over theirs
|
||||
self._clock = self._clock or (lambda: now)
|
||||
await self._write(drv, a, 0.0, now, tracker, why="shutdown",
|
||||
strict=True)
|
||||
|
||||
def _select_try(self, n, ok) -> None:
|
||||
"""EV-22: a phase select of ours went out and returned (Solar's
|
||||
window and own phases; Manual does not judge phases)."""
|
||||
|
||||
def _took_as_is(self) -> None:
|
||||
"""EV-22 (DA1): a user's change took the charger's value as it is
|
||||
(Solar forgets what it sent)."""
|
||||
|
||||
async def _advance(self, drv, r, cur, now, tracker, want_a, clamp, rev):
|
||||
q = self.seq
|
||||
pressed = q.pop("pressed", False) # covers the first reading only
|
||||
if q["stage"] in ("zero", "select") and cur is not None \
|
||||
and cur >= CH.MIN_A:
|
||||
# Something else raised the current while the car was being
|
||||
@@ -450,11 +560,24 @@ class ManualWriter:
|
||||
# change, and leave the charger to whoever set it until the user
|
||||
# changes something.
|
||||
self.seq = None
|
||||
self.hold = self.other = True
|
||||
self.last_a = self.attempted_a = self.prior_a = None
|
||||
self._kept = None # EV-71: the change is given up
|
||||
if pressed:
|
||||
# EV-22 (DA1): the user's change came during this change and
|
||||
# this is the first reading judged after it: the charger is
|
||||
# taken as it is, never held over that value. A later raise
|
||||
# is held as ever.
|
||||
self._took_as_is()
|
||||
return
|
||||
self.hold = self.other = True
|
||||
self._carry = []
|
||||
_LOG.info("Something else raised the charger's current during a "
|
||||
"phase change, so the phases were not touched.")
|
||||
return
|
||||
if self._other_stands():
|
||||
# EV-22 (C7): another writer's value stands (its count runs, or
|
||||
# it is held): no select, no restore, no closing current over it.
|
||||
return
|
||||
if q["stage"] == "zero":
|
||||
# A power reading decides; only without one does mode3 (not C,
|
||||
# not D) say the car is quiet. Still drawing at the timeout: no
|
||||
@@ -486,6 +609,7 @@ class ManualWriter:
|
||||
self.last_switch = now
|
||||
self.log.append(("phases", q["n"], now, ok))
|
||||
q["stage"], q["t1"] = "settle", self.last_done # from its return
|
||||
self._select_try(q["n"], bool(ok))
|
||||
if not ok:
|
||||
q["failed"] = True # EV-15: no grace for the alarm
|
||||
# The charger did not take it: the car gets its current back
|
||||
@@ -506,6 +630,7 @@ class ManualWriter:
|
||||
# on whether the phases changed); Manual a number, as before.
|
||||
want = want_a(q) if callable(want_a) else want_a
|
||||
a = min(max(float(want), CH.MIN_A), hi)
|
||||
q.setdefault("own", []).append(a) # EV-22: a value we tried is ours
|
||||
if await self._write(drv, a, 0.0, now, tracker,
|
||||
why=self._close_why(q),
|
||||
n=q["n"] if q.get("sel_ok") else None):
|
||||
@@ -522,6 +647,7 @@ class ManualWriter:
|
||||
self._close_k += 1 # EV-59: read by Manual's end only
|
||||
if q["tries"] >= MAX_TRIES:
|
||||
# Left at 0 A is the safe side; the next reading re-applies.
|
||||
self._carry_end(q) # EV-69: the closes tried stay own
|
||||
self.seq, self.last_a, self.reapply = None, None, True
|
||||
self._close_end(now)
|
||||
self.rev_applied = None
|
||||
@@ -840,6 +966,11 @@ class SolarPlan:
|
||||
self.a, self.set_at, self.last_dir = CH.MIN_A, now, -1
|
||||
|
||||
|
||||
class _CloseHeld(Exception):
|
||||
"""EV-60: Solar's cut gate holds the close (raised inside `_advance`'s
|
||||
want-a call, caught in `SolarWriter._advance`; never leaves it)."""
|
||||
|
||||
|
||||
class SolarWriter(ManualWriter):
|
||||
"""What Solar does to the charger, one `step()` per cycle. It shares
|
||||
ManualWriter's write, phase sequence and other-writer watch.
|
||||
@@ -901,6 +1032,15 @@ class SolarWriter(ManualWriter):
|
||||
self.cut_warned = False # ... and its one CHARGER_REFUSED was given
|
||||
self.sent_cut = False # `sent_a` went out as a cut try
|
||||
self.refused_cut = None # a cut value the charger did not take
|
||||
self._cap_end = False # EV-60: a capped close ended the change
|
||||
# EV-22 (D4): the phases Solar itself chose. `_own_n`: the last it
|
||||
# TOOK (or the start state); `_sel_n` and `_win_t1`: its latest
|
||||
# select try and when that try returned; SETTLE_S after it (and the
|
||||
# one step that closes there, `_win_last`) a read-back is not judged.
|
||||
self._own_n = None
|
||||
self._sel_n = None
|
||||
self._win_t1 = None
|
||||
self._win_last = False
|
||||
|
||||
def owe_start(self) -> None:
|
||||
"""C1: the add-on starts in Off while an exit 0 A of its own was still
|
||||
@@ -1003,10 +1143,16 @@ class SolarWriter(ManualWriter):
|
||||
"""The user PRESSED SOLAR: another writer's hold is lifted and Solar
|
||||
takes the charger as it is (its value is no longer a difference);
|
||||
Solar's own value is decided and written afresh."""
|
||||
held = self.hold or self.mismatch_since is not None
|
||||
super().user_changed()
|
||||
held = self._other_stands()
|
||||
had_seq = self.seq is not None
|
||||
super().user_changed() # EV-22 (DA1): ends a change it lifts
|
||||
self.gave_up, self.fails, self.fail_at = False, 0, None
|
||||
self._stuck_end()
|
||||
# EV-22: the phases are taken afresh (the start state again); an own
|
||||
# select's window stays.
|
||||
self._own_n, self._ph_diff = None, False
|
||||
if held and had_seq:
|
||||
self.plan.end_switch(False)
|
||||
if held:
|
||||
self.last_a = None
|
||||
self.sent_a, self.taken = None, True
|
||||
@@ -1061,6 +1207,7 @@ class SolarWriter(ManualWriter):
|
||||
_LOG.debug("The peak cut write failed: %s", e)
|
||||
self.log.append(("current", a, now, False))
|
||||
self.attempted_a, self.prior_a = a, was
|
||||
self._keep(a) # EV-71
|
||||
ok = False
|
||||
finally:
|
||||
if zero:
|
||||
@@ -1084,7 +1231,62 @@ class SolarWriter(ManualWriter):
|
||||
return "peak cut" if q.get("cut") else "Solar"
|
||||
|
||||
def _close_end(self, now) -> None:
|
||||
self._failed(now) # EV-59: Solar stays as it was (EV-60)
|
||||
"""EV-60: no extra `_failed`. Each refused close was counted when it
|
||||
went (`_write`), a cut try in `cut_fails` too, so the sequence's end
|
||||
adds nothing (Manual's `_close_end` is EV-59's, unchanged)."""
|
||||
|
||||
def _carry_ok(self) -> bool:
|
||||
"""EV-69 (formal Dev note 2): the end's own value (`sent_a`) was
|
||||
already taken (an `_adopt` earlier in the step): nothing is carried."""
|
||||
return not self.taken
|
||||
|
||||
def _carried_take(self) -> None:
|
||||
"""EV-69 GUR: a carried take resets `fails` and `gave_up` only, never
|
||||
`taken` or `last_a`: `sent_a` stays owed, so the clamp value is sent
|
||||
again at the next RETRY_S step."""
|
||||
self.fails, self.gave_up = 0, False
|
||||
|
||||
def _cut_gate(self, now) -> bool:
|
||||
"""EV-60 (Q1): the quarter key's cut tries are used up, or the last
|
||||
refused one is less than RETRY_S old (`_put`'s two gates)."""
|
||||
return self.cut_fails >= MAX_TRIES or (
|
||||
self.cut_fail_at is not None and now - self.cut_fail_at < RETRY_S)
|
||||
|
||||
async def _advance(self, drv, r, cur, now, tracker, want_a, clamp, rev):
|
||||
"""EV-60: Solar's capped close is a cut try, so it passes the cut's
|
||||
gates. Tries used up: the change ends at its 0 A, nothing written
|
||||
(`_cap_end`: `step` then leaves the plan as `end_switch(False)` put
|
||||
it). The sequence's first cut close waits at 0 A until RETRY_S after
|
||||
the last refused cut try (counts nothing, ends nothing); after a cut
|
||||
close of the sequence went, the 5 s spacing of `_advance` rules."""
|
||||
self._cap_end = False # set again below, read by `step` only
|
||||
if callable(want_a):
|
||||
# The gate runs where `_advance` asks for the close value, just
|
||||
# before it writes: also on the "car kept drawing" path, which
|
||||
# turns zero into settle and closes in the same call.
|
||||
inner, hi = want_a, (CH.ENTITY_MAX_A if clamp is None
|
||||
else float(clamp))
|
||||
|
||||
def want_a(q):
|
||||
v = inner(q)
|
||||
if self._cut_try(min(max(float(v), CH.MIN_A), hi)):
|
||||
if self.cut_fails >= MAX_TRIES:
|
||||
self._carry_end(q) # EV-69: the closes stay own
|
||||
self.seq, self.last_a, self.reapply = None, None, True
|
||||
self.rev_applied = None
|
||||
self.plan.end_switch(False)
|
||||
self._cap_end = True
|
||||
raise _CloseHeld
|
||||
if not q.get("cut_went") and self.cut_fail_at is not None \
|
||||
and now - self.cut_fail_at < RETRY_S:
|
||||
raise _CloseHeld
|
||||
q["cut_went"] = True
|
||||
return v
|
||||
try:
|
||||
await super()._advance(drv, r, cur, now, tracker, want_a, clamp,
|
||||
rev)
|
||||
except _CloseHeld:
|
||||
pass
|
||||
|
||||
def _failed(self, now) -> None:
|
||||
if self.sent_cut:
|
||||
@@ -1120,8 +1322,10 @@ class SolarWriter(ManualWriter):
|
||||
self._owed(False)
|
||||
self.taken = True
|
||||
self.startup_zero = False
|
||||
self._kept = None # EV-71 (Q6): a fresh take ends it
|
||||
self.last_a = cur
|
||||
self.attempted_a = self.prior_a = None
|
||||
self._carry = [] # EV-69: an own take ends the carry
|
||||
self.fails, self.fail_at, self.gave_up = 0, None, False
|
||||
self.refused_cut = None
|
||||
if self.sent_cut:
|
||||
@@ -1173,7 +1377,10 @@ class SolarWriter(ManualWriter):
|
||||
await self._write(drv, want, cur, now, tracker,
|
||||
why=self.sent_why)
|
||||
return
|
||||
if not stuck and cur is not None and abs(cur - want) <= TOL_A:
|
||||
if not stuck and cur is not None and abs(cur - want) <= TOL_A \
|
||||
and not self.held_step:
|
||||
# EV-71 (P2): a held read shows the reading from before our write,
|
||||
# so it takes nothing: the owed 0 A below goes out instead.
|
||||
self.sent_a = want # it already stands
|
||||
self._adopt(cur)
|
||||
return
|
||||
@@ -1217,9 +1424,59 @@ class SolarWriter(ManualWriter):
|
||||
if self.live and not self.hold:
|
||||
await self._put(drv, 0.0, cur, now, tracker, stuck, out=True)
|
||||
|
||||
def _watch(self, cur, now) -> None:
|
||||
def _took_as_is(self) -> None:
|
||||
self.sent_a, self.taken = None, True
|
||||
self.refused_cut = None
|
||||
|
||||
def _reset_phases(self, window=True) -> None:
|
||||
"""EV-22: the phases Solar judges start afresh (entering Solar, the
|
||||
charger's return, a press). The window of an own select goes too
|
||||
unless it is kept."""
|
||||
self._own_n, self._ph_diff = None, False
|
||||
if window:
|
||||
self._sel_n = self._win_t1 = None
|
||||
self._win_last = False
|
||||
|
||||
def _select_try(self, n, ok) -> None:
|
||||
"""EV-22 (DA3): our own select try returned. SETTLE_S from now a
|
||||
read-back is not judged (A7: from its return, not from its send); a
|
||||
taken select is our phases at once, one the charger did not confirm
|
||||
becomes ours if a read inside the window shows it."""
|
||||
self._sel_n = n
|
||||
self._win_t1 = float(self.last_done)
|
||||
self._win_last = False
|
||||
if ok:
|
||||
self._own_n, self._ph_diff = n, False
|
||||
|
||||
def _judge_phases(self, r, now) -> None:
|
||||
"""EV-22 (D4): the read-back phases against the phases Solar itself
|
||||
chose (never the plan's adopted `n`). Unknown phases and reads inside
|
||||
a select's window start nothing and lift nothing. The window is the
|
||||
sequence's settle time on the same clock and with the same
|
||||
comparison as the close (`now - t1 < SETTLE_S`), and the one step
|
||||
that closes at its end is still inside it, whatever fraction of a
|
||||
second `last_done` lies after the step's `now`."""
|
||||
p = getattr(r, "phases_allowed", None)
|
||||
if self._win_t1 is not None:
|
||||
inside = now - self._win_t1 < SETTLE_S
|
||||
if not inside and not self._win_last:
|
||||
self._win_last = inside = True # the closing step
|
||||
if inside:
|
||||
if p in (1, 3) and p == self._sel_n:
|
||||
self._own_n, self._ph_diff = p, False # the take
|
||||
return
|
||||
self._sel_n = self._win_t1 = None
|
||||
if p not in (1, 3):
|
||||
return
|
||||
if self._own_n is None:
|
||||
self._own_n, self._ph_diff = p, False # the start state
|
||||
return
|
||||
self._ph_diff = p != self._own_n
|
||||
|
||||
def _watch(self, cur, now, judge=True) -> None:
|
||||
was = self.hold
|
||||
super()._watch(cur, now)
|
||||
self._judge_phases(self._r, now)
|
||||
super()._watch(cur, now, judge)
|
||||
if self.hold and not was:
|
||||
_LOG.warning("Something else changes the charger, so the add-on "
|
||||
"stops writing to it until you press Solar: "
|
||||
@@ -1257,6 +1514,7 @@ class SolarWriter(ManualWriter):
|
||||
self.out, self.fault = False, None
|
||||
self.restart = True
|
||||
self.mismatch_since = None
|
||||
self._reset_phases()
|
||||
self.plan.reset(self.plan.n)
|
||||
|
||||
def _gap_ok(self, now) -> bool:
|
||||
@@ -1321,15 +1579,20 @@ class SolarWriter(ManualWriter):
|
||||
async def _begin_solar(self, drv, r, cur, n, now, tracker) -> None:
|
||||
"""Step 1 of the safe sequence: 0 A (kept when it already stands).
|
||||
A 0 A the charger does not take ends the change; tried again later
|
||||
by the plan's own dwell."""
|
||||
by the plan's own dwell. EV-60: under a cap that 0 A is a cut try and
|
||||
passes the cut's gates; stopped by them the change waits (nothing
|
||||
written or counted, never a give-up) for the next quarter key."""
|
||||
owed = not (cur is not None and cur <= TOL_A and self.sent_a == 0.0
|
||||
and self.taken)
|
||||
if owed and self._cut_try(0.0) and self._cut_gate(now):
|
||||
return
|
||||
self.phase_done_at = None
|
||||
if not (cur is not None and cur <= TOL_A and self.sent_a == 0.0
|
||||
and self.taken):
|
||||
if owed:
|
||||
if not await self._write(drv, 0.0, cur, now, tracker):
|
||||
self.plan.end_switch(False)
|
||||
return
|
||||
self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0,
|
||||
"prev": None, "from": r.phases_allowed}
|
||||
"prev": None, "from": r.phases_allowed, "own": [0.0]}
|
||||
|
||||
# ------------------------------------------------------------- step
|
||||
async def held_pause(self, drv, r, *, sun, now, tracker) -> None:
|
||||
@@ -1378,6 +1641,7 @@ class SolarWriter(ManualWriter):
|
||||
# notice. The quarter's try count stays (Q5).
|
||||
self.refused_cut, self.sent_cut, self.cut_warned = None, False, \
|
||||
False
|
||||
self._reset_phases() # EV-22: a fresh entry starts clean
|
||||
if not self.engaged:
|
||||
return
|
||||
if sun is not None:
|
||||
@@ -1409,7 +1673,11 @@ class SolarWriter(ManualWriter):
|
||||
self.startup_zero = self.boot and not self._returned
|
||||
self.fresh_start = self.restart = True
|
||||
self.mismatch_since = None
|
||||
if not self.hold:
|
||||
self._reset_phases(window=False) # EV-22: start state again
|
||||
self.last_a = self.attempted_a = self.prior_a = None
|
||||
self._carry = [] # EV-69: the return ends the carry
|
||||
self._kept = None # EV-71: and the kept value
|
||||
self._rec_a = None # EV-56 (G2): logged again
|
||||
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
|
||||
stuck = bool(tracker is not None and tracker.stuck(now))
|
||||
@@ -1443,8 +1711,11 @@ class SolarWriter(ManualWriter):
|
||||
# owed, then nothing. The watch goes on (another writer is held
|
||||
# for every reader) and so does the plan, for the card.
|
||||
self.out = True
|
||||
n_log = len(self.log)
|
||||
await self._zero(drv, cur, now, tracker, stuck)
|
||||
self._watch(cur, now)
|
||||
# EV-22 (DA2): `cur` is from before our own 0 A of this step:
|
||||
# the current is not judged then (the phases are).
|
||||
self._watch(cur, now, judge=len(self.log) == n_log)
|
||||
self._shadow_plan(sun, now, clamp, n_now)
|
||||
self.restart = True
|
||||
return
|
||||
@@ -1517,8 +1788,8 @@ class SolarWriter(ManualWriter):
|
||||
if self.drop_ready(cur, stuck):
|
||||
# EV-54 (drop rule): the refused cut value is not sent again.
|
||||
self._drop(cur, now)
|
||||
self._watch(cur, now) # EV-22 (C7): inside a change too
|
||||
if self.seq is None:
|
||||
self._watch(cur, now)
|
||||
if self.hold or self.mismatch_since is not None:
|
||||
# Another writer's value, held or not yet: nothing is written
|
||||
# over it; the plan goes on for the card.
|
||||
@@ -1569,6 +1840,9 @@ class SolarWriter(ManualWriter):
|
||||
clamp, None)
|
||||
if any(x[0] == "phases" for x in self.log[n_log:]):
|
||||
q["sel"] = True # a select went out, taken or not
|
||||
if self.seq is None and self._cap_end:
|
||||
self._cap_end = False # EV-60: ended at 0 A, plan as it was
|
||||
return
|
||||
if self.seq is None:
|
||||
# Back on the old phases only when no select went out; after
|
||||
# one the plan keeps the current it wrote (the lower one) and
|
||||
|
||||
@@ -23,7 +23,6 @@ from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from . import arbitrage, dayplan, modetrade, packshare, priceruns
|
||||
from .dayplan import EFF
|
||||
from .price import required_spread, uncertainty_of
|
||||
|
||||
SLOT_S = 900 # a price slot
|
||||
@@ -32,7 +31,7 @@ LIMIT = 24 # rolls at most (a day of one-hour runs)
|
||||
|
||||
|
||||
def roll_end(run, points, packs_at, *, required, floor_pct, ceiling_pct,
|
||||
targets=None, limit=LIMIT):
|
||||
targets=None, limit=LIMIT, legs=None):
|
||||
"""Where the cheap run `run` ends once control has rolled it on.
|
||||
|
||||
`packs_at(end)` gives the `modetrade.Pack`s as they stand when a run
|
||||
@@ -43,7 +42,7 @@ def roll_end(run, points, packs_at, *, required, floor_pct, ceiling_pct,
|
||||
end_t = run.end
|
||||
for _ in range(limit):
|
||||
e = modetrade.energy(packs_at(end_t), floor_pct, ceiling_pct,
|
||||
targets=targets)
|
||||
targets=targets, legs=legs)
|
||||
if e[0] <= 1e-6:
|
||||
break
|
||||
new = priceruns.plan(points, end_t, required_eur_kwh=required,
|
||||
@@ -89,7 +88,9 @@ class _Charge:
|
||||
the room the peak limit leaves: `min(sum of ratings, aim - house)`, shared
|
||||
by room left to full as control does (`_shares()`), each stopping at `modetrade.charge_to()`."""
|
||||
|
||||
def __init__(self, packs, t0, ceiling_pct, targets, aim_w, house):
|
||||
def __init__(self, packs, t0, ceiling_pct, targets, aim_w, house,
|
||||
legs=None):
|
||||
self.legs = legs
|
||||
self.packs = {p.name: p for p in packs}
|
||||
self.t = t0
|
||||
self.ceil = ceiling_pct
|
||||
@@ -147,7 +148,7 @@ class _Charge:
|
||||
|
||||
def _charge(self, s, e, hour):
|
||||
ch = modetrade.chargers(list(self.packs.values()), self.ceil,
|
||||
targets=self.targets)
|
||||
targets=self.targets, legs=self.legs)
|
||||
total = sum(abs(p.rating_w) for p in ch)
|
||||
if not ch or total <= 0.0:
|
||||
return
|
||||
@@ -159,7 +160,7 @@ class _Charge:
|
||||
if not p.capacity_kwh:
|
||||
continue
|
||||
to = modetrade.charge_to(p, self.ceil, self.targets)
|
||||
kwh = share[p.name] * hrs / 1000.0 * EFF
|
||||
kwh = share[p.name] * hrs / 1000.0 * dayplan.eff_of(p.eta)
|
||||
room = (to - p.soc) / 100.0 * float(p.capacity_kwh)
|
||||
if kwh <= 0.0:
|
||||
continue
|
||||
@@ -185,9 +186,10 @@ def for_today(c, rp, now):
|
||||
return None
|
||||
floor, ceil = arbitrage.soc_bounds(c.o)
|
||||
hp = getattr(c, "house_profile", None)
|
||||
legs = getattr(c, "charge_legs", lambda *_a: None)(plan, now)
|
||||
sim = _Charge(c._mode_packs(), max(now, rp.cheap.start), ceil,
|
||||
c.plan_targets(), c.peak_aim_w(),
|
||||
None if hp is None else hp.estimator())
|
||||
None if hp is None else hp.estimator(), legs)
|
||||
required = required_spread(
|
||||
arbitrage.threshold_eur_kwh(c.o),
|
||||
uncertainty_of(plan.read.product)
|
||||
@@ -195,7 +197,7 @@ def for_today(c, rp, now):
|
||||
bool(c.weather_held(now))))
|
||||
end = roll_end(rp.cheap, plan.read.points, sim.at, required=required,
|
||||
floor_pct=floor, ceiling_pct=ceil,
|
||||
targets=c.plan_targets())
|
||||
targets=c.plan_targets(), legs=legs)
|
||||
if end <= rp.cheap.end:
|
||||
return None
|
||||
return Roll(end, dict(sim.stops))
|
||||
|
||||
@@ -512,7 +512,14 @@ class CycleMixin:
|
||||
self._peak_proj)
|
||||
if site_trade:
|
||||
floor_pct, ceiling_pct = arbitrage.soc_bounds(self.o)
|
||||
charge_w, discharge_w = self.trade_power_w(floor_pct, ceiling_pct)
|
||||
# TARIFF-30. WHOSE OWN BUY LEG CLEARS (None: no efficiency is set,
|
||||
# which is today's behaviour exactly). The buy is sized to those
|
||||
# units alone; the others are held out of it below.
|
||||
legs = (self.charge_legs(self.fresh_tariff_plan(now), now)
|
||||
if any(e is not None for e in self.unit_etas().values())
|
||||
else None)
|
||||
charge_w, discharge_w = self.trade_power_w(floor_pct, ceiling_pct,
|
||||
legs)
|
||||
self.arb = arbitrage.decide(
|
||||
self.fresh_tariff_plan(now), now,
|
||||
peak_guard_active=arbitrage.guard_state(self.peak_guard),
|
||||
@@ -539,6 +546,9 @@ class CycleMixin:
|
||||
# it. (DECISIONS/MAIN-orchestration-archive.md)
|
||||
charge_w=charge_w, discharge_w=discharge_w,
|
||||
soc_floor_pct=floor_pct, soc_ceiling_pct=ceiling_pct)
|
||||
if legs is not None or self._lossy_hold[0]:
|
||||
self._hold_out_lossy(claims, maint_results, legs, charge_w,
|
||||
discharge_w, floor_pct, ceiling_pct, now)
|
||||
# SITE, and arbitrage.claim() says so on the object it builds. It
|
||||
# buys and sells at the grid against a day-ahead price: the price is
|
||||
# a property of the connection and the energy crosses the meter.
|
||||
|
||||
@@ -9,7 +9,7 @@ from datetime import datetime, timedelta, timezone
|
||||
|
||||
from . import arbitrage
|
||||
from .arbiter import (
|
||||
ACTUATOR_SITE, Claim, P_MAINTENANCE, P_MAINT_SHAPE, P_PEAK, SET,
|
||||
ACTUATOR_SITE, Claim, P_MAINTENANCE, P_MAINT_SHAPE, P_MODE, P_PEAK, SET,
|
||||
pre_resolve, resolve,
|
||||
)
|
||||
from . import allocator
|
||||
@@ -90,7 +90,7 @@ MAINT_CHARGING_W = 50.0
|
||||
|
||||
|
||||
class TradeMixin:
|
||||
def trade_power_w(self, floor_pct, ceiling_pct) -> tuple:
|
||||
def trade_power_w(self, floor_pct, ceiling_pct, legs=None) -> tuple:
|
||||
"""OPT-09. `(charge_w, discharge_w)`: how hard a trade may be SIZED:
|
||||
what the site can push AND STILL HAVE SOMEWHERE TO PUT. The bounds are
|
||||
arbitrage's own (`arbitrage_soc_floor` / `_ceiling`), NOT the BMS
|
||||
@@ -101,7 +101,79 @@ class TradeMixin:
|
||||
park order). DECISIONS/MAIN-orchestration.md."""
|
||||
# The reduction lives in `packshare`; `test_packshare.py` part 9 calls
|
||||
# the SAME function (a transcription in a check is a copy that drifts).
|
||||
return packshare.trade_power_w(self.pack_energy, floor_pct, ceiling_pct)
|
||||
return packshare.trade_power_w(self.pack_energy, floor_pct, ceiling_pct,
|
||||
legs)
|
||||
|
||||
# TARIFF-30: units whose own buy leg failed while the site traded, and
|
||||
# until when they stay held after it stopped (see `_hold_out_lossy()`).
|
||||
_lossy_hold = (frozenset(), None)
|
||||
LOSSY_WIND_S = 120.0
|
||||
|
||||
def _hold_out_lossy(self, claims, maint_results, legs, charge_w,
|
||||
discharge_w, floor_pct, ceiling_pct, now) -> None:
|
||||
"""TARIFF-30, site trade only, with an efficiency set on some unit.
|
||||
|
||||
1. A buy that no unit's own leg can take is idle, and says why: the
|
||||
sizing is 0 W for the losses (a charge asked of the packs without
|
||||
`legs` was possible), so the refusal is `IDLE_LOSSES` rather than
|
||||
the pack-state one. Still no claim, never a 0 W one.
|
||||
2. While the site charges, a unit whose own leg does not clear is held
|
||||
at 0 W charge: a unit limit at P_MODE, `lo` 0. The weights are only
|
||||
a preference and `_fill()`'s last-resort pass would otherwise hand
|
||||
it watts when the others are full. It may still give (`hi` its
|
||||
rating), and a unit in a maintenance phase keeps its own claim.
|
||||
3. When the trade stops, the loop starts from the trade's last target
|
||||
and gives it up at its slew. That tail is the trade's, so the hold
|
||||
stays while the site target is still charging, for LOSSY_WIND_S at
|
||||
most: the unit whose leg failed takes none of it."""
|
||||
arb = self.arb
|
||||
if (arb is not None and arb.action is None
|
||||
and arb.reason == arbitrage.IDLE_NO_SIZE
|
||||
and legs is not None
|
||||
and not charge_w > 0.0 and discharge_w > 0.0
|
||||
and self.trade_power_w(floor_pct, ceiling_pct)[0] > 0.0):
|
||||
self.arb = arb = arbitrage.idle_for_losses(arb)
|
||||
names, until = self._lossy_hold
|
||||
if arb is not None and arb.action == arbitrage.CHARGE \
|
||||
and legs is not None:
|
||||
names, until = frozenset(n for n, ok in legs.items() if not ok), \
|
||||
None
|
||||
elif names:
|
||||
if until is None:
|
||||
until = now + timedelta(seconds=self.LOSSY_WIND_S)
|
||||
if now >= until or float(self.target or 0.0) >= 0.0:
|
||||
names, until = frozenset(), None
|
||||
self._lossy_hold = (names, until)
|
||||
if len(self.inverters) <= 1:
|
||||
return
|
||||
for inv, result in zip(self.inverters, maint_results):
|
||||
if inv.name not in names or result.phase != IDLE:
|
||||
continue
|
||||
claims.append(Claim.limit(
|
||||
"mode", P_MODE, 0.0, float(inv.max_w),
|
||||
"round-trip losses", actuator=self.actuator_of("mode", inv)))
|
||||
|
||||
def unit_etas(self) -> dict:
|
||||
"""TARIFF-30. `{unit name: round_trip_eff or None}`, from the roster."""
|
||||
return {inv.name: getattr(inv, "round_trip_eff", None)
|
||||
for inv in self.inverters}
|
||||
|
||||
def charge_legs(self, plan, now):
|
||||
"""TARIFF-30. `{name: bool}`: whose OWN buy leg clears this cycle
|
||||
(`arbitrage.clearing()`), or None: no unit has an efficiency, or the
|
||||
verdict allows no trade. None is today's behaviour exactly. The same
|
||||
figure for the site trade, the battery modes, the day plan and Home."""
|
||||
etas = self.unit_etas()
|
||||
if plan is None or all(e is None for e in etas.values()):
|
||||
return None
|
||||
return arbitrage.clearing(
|
||||
plan, now,
|
||||
min_spread_eur_kwh=arbitrage.threshold_eur_kwh(self.o),
|
||||
uncertainty=arbitrage.weather_uncertainty(
|
||||
bool(getattr(self, "modes_on", False)),
|
||||
getattr(self, "solar_fc", None),
|
||||
bool(self.weather_held(now))),
|
||||
etas=etas)
|
||||
|
||||
def peak_aim_w(self) -> float:
|
||||
"""SAFETY-79. `peak_cap_w` less `peak_margin_w`: what the forecast
|
||||
@@ -175,7 +247,8 @@ class TradeMixin:
|
||||
inv.name, pm.use, pm.mode, pm.sell and pm.can_sell,
|
||||
float(inv.max_w), inv.soc, inv.capacity_kwh,
|
||||
live=inv.name in live, idle=idle, refused=int(refused),
|
||||
probing=probing))
|
||||
probing=probing,
|
||||
eta=getattr(inv, "round_trip_eff", None)))
|
||||
return out
|
||||
|
||||
def _wx_track(self, now) -> None:
|
||||
@@ -219,6 +292,11 @@ class TradeMixin:
|
||||
key = (id(plan), slot, tuple((p.name, p.use, p.mode, p.sell)
|
||||
for p in packs))
|
||||
held = self.weather_held(now)
|
||||
# TARIFF-30: which batteries' own buy legs clear (None: no efficiency
|
||||
# set, today's plan). In the key, so a change rebuilds the plan.
|
||||
legs = self.charge_legs(plan, now)
|
||||
if legs is not None:
|
||||
key += (tuple(sorted(legs.items())),)
|
||||
if self.fc_entity is not None:
|
||||
# P4: a forecast arriving or going rebuilds the plan at once (and
|
||||
# so does the end of a run that held the gap, TARIFF-24).
|
||||
@@ -227,7 +305,7 @@ class TradeMixin:
|
||||
done_c = self._run_done.get("charge", (None, set()))[1]
|
||||
done_s = self._run_done.get("sell", (None, set()))[1]
|
||||
e = modetrade.energy(packs, floor_pct, ceiling_pct, done_c,
|
||||
done_s)
|
||||
done_s, legs=legs)
|
||||
required = price_required_spread(
|
||||
arbitrage.threshold_eur_kwh(self.o),
|
||||
price_uncertainty_of(plan.read.product)
|
||||
@@ -281,7 +359,8 @@ class TradeMixin:
|
||||
self._plan_targets, dp.targets,
|
||||
{p.name: p.capacity_kwh for p in packs})
|
||||
e2 = modetrade.energy(packs, floor_pct, ceiling_pct, done_c, (),
|
||||
targets=self._plan_targets)
|
||||
targets=self._plan_targets,
|
||||
legs=self.charge_legs(plan, now))
|
||||
return priceruns.plan(
|
||||
plan.read.points, now, required_eur_kwh=required,
|
||||
charge_kwh=e2[0], charge_kw=e2[1], sell_kwh=e[2], sell_kw=e[3],
|
||||
@@ -442,7 +521,8 @@ class TradeMixin:
|
||||
draining=any(r.phase == DRAIN for r in maint_results or ()),
|
||||
wait=wait,
|
||||
maint_charging=any(r.phase == CHARGE
|
||||
for r in maint_results or ()))
|
||||
for r in maint_results or ()),
|
||||
legs=self.charge_legs(plan, now))
|
||||
self._latch_charge(now, runs, targets, packs)
|
||||
# A charge the guard or the headroom stopped stays off this period.
|
||||
# OPT-15: only a MEASURED stop latches; the first unmeasured headroom
|
||||
|
||||
@@ -30,7 +30,7 @@ import math
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .dayplan import EFF, _hour_slices, _local
|
||||
from .dayplan import _hour_slices, _local, eff_of
|
||||
from .modetrade import CHARGE, GIVE, HOLD, HOUSE, REST
|
||||
|
||||
EPS = 1e-9
|
||||
@@ -52,6 +52,7 @@ class Batt:
|
||||
grid: tuple = () # ((start, end, to_pct), ...) grid blocks
|
||||
give: tuple = () # ((start, end), ...) give runs
|
||||
stop_at: datetime | None = None # a monthly cycle starts: no level after
|
||||
eta: float | None = None # TARIFF-30: its own round-trip efficiency
|
||||
|
||||
|
||||
def _role(b, t, charging, own):
|
||||
@@ -97,7 +98,8 @@ def _give_caps(roles, level, by, floor, hrs):
|
||||
"""`(first, rest, held)`: what each battery that may give can give in a
|
||||
step of `hrs` hours (its rating, or what it holds above the floor), those
|
||||
in a give run first, and what each holds above the floor (as given)."""
|
||||
held = {n: max(0.0, level[n] - floor) / 100.0 * by[n].capacity_kwh * EFF
|
||||
held = {n: max(0.0, level[n] - floor) / 100.0 * by[n].capacity_kwh
|
||||
* eff_of(by[n].eta)
|
||||
for n, r in roles.items() if r[2]}
|
||||
caps = {n: min(by[n].rating_kw * hrs, h) for n, h in held.items()}
|
||||
first = {n: c for n, c in caps.items() if roles[n][0] == GIVE}
|
||||
@@ -180,7 +182,7 @@ def curve(batts, start, end, sun_kwh, use_kwh, *, floor_pct, ceiling_pct,
|
||||
for n, to in want.items():
|
||||
b = by[n]
|
||||
room = (to - level[n]) / 100.0 * b.capacity_kwh
|
||||
rate = b.rating_kw * hrs * EFF
|
||||
rate = b.rating_kw * hrs * eff_of(b.eta)
|
||||
if EPS < room < rate * (1.0 - 1e-9):
|
||||
t_r = a + (z - a) * (room / rate)
|
||||
if a < t_r < z and (cut is None or t_r < cut):
|
||||
@@ -203,12 +205,12 @@ def curve(batts, start, end, sun_kwh, use_kwh, *, floor_pct, ceiling_pct,
|
||||
for n, to in want.items(): # charging from the grid
|
||||
b = by[n]
|
||||
room = (to - level[n]) / 100.0 * b.capacity_kwh
|
||||
level[n] += min(b.rating_kw * hrs * EFF, room) \
|
||||
level[n] += min(b.rating_kw * hrs * eff_of(b.eta), room) \
|
||||
/ b.capacity_kwh * 100.0
|
||||
if net > EPS:
|
||||
caps = {n: min(by[n].rating_kw * hrs,
|
||||
max(0.0, ceil - level[n]) / 100.0
|
||||
* by[n].capacity_kwh / EFF)
|
||||
* by[n].capacity_kwh / eff_of(by[n].eta))
|
||||
for n, r in roles.items() if r[1]}
|
||||
first = {n: c for n, c in caps.items() if by[n].solar_first}
|
||||
rest = {n: c for n, c in caps.items() if n not in first}
|
||||
@@ -216,14 +218,16 @@ def curve(batts, start, end, sun_kwh, use_kwh, *, floor_pct, ceiling_pct,
|
||||
for grp in (first, rest):
|
||||
got, left = _spread(left, grp, dict(grp))
|
||||
for n, v in got.items():
|
||||
level[n] += v * EFF / by[n].capacity_kwh * 100.0
|
||||
level[n] += v * eff_of(by[n].eta) \
|
||||
/ by[n].capacity_kwh * 100.0
|
||||
elif net < -EPS:
|
||||
first, rest, held = _give_caps(roles, level, by, floor, hrs)
|
||||
left = -net
|
||||
for grp in (first, rest):
|
||||
got, left = _spread(left, grp, {n: held[n] for n in grp})
|
||||
for n, v in got.items():
|
||||
level[n] -= v / EFF / by[n].capacity_kwh * 100.0
|
||||
level[n] -= v / eff_of(by[n].eta) \
|
||||
/ by[n].capacity_kwh * 100.0
|
||||
for b in batts:
|
||||
if b.name in alive:
|
||||
out[b.name].append((z, level[b.name]))
|
||||
|
||||
@@ -44,6 +44,7 @@ The site's own solar readings are not used: TEL-11 keeps them out of every
|
||||
control decision.
|
||||
"""
|
||||
|
||||
import math
|
||||
import statistics
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta, timezone
|
||||
@@ -52,7 +53,7 @@ from .packmode import CHEAP_HOURS, LEFTOVER_SOLAR, SOLAR_FIRST
|
||||
from .tariff import BILLING_TZ
|
||||
|
||||
EFF = 0.95 # charge (and discharge) efficiency
|
||||
HYST_KWH = 1.0 # a kept level moves only by this much...
|
||||
HYST_KWH = 1.0 # a kept level moves only by this much...
|
||||
HYST_FRAC = 0.10 # ...or this share of the battery's shortfall
|
||||
PROFILE_DAYS = 7
|
||||
MIN_HOURS = 20 # hours of a day recorded before it counts
|
||||
@@ -183,6 +184,14 @@ class Plan:
|
||||
solar_first_kwh: float = 0.0
|
||||
|
||||
|
||||
def eff_of(eta) -> float:
|
||||
"""TARIFF-30. One charge (or discharge) efficiency for ONE battery: `EFF`
|
||||
where it has no round-trip efficiency set (today's number, unchanged), else
|
||||
the square root of its round trip (one way). An approximation: B was
|
||||
measured at about 93 % in and 81 % out; the in/out split is TARIFF-31's."""
|
||||
return EFF if eta is None else math.sqrt(float(eta))
|
||||
|
||||
|
||||
def _hour_slices(t0, t1):
|
||||
"""Local-hour slices of [t0, t1): (start, end, local hour).
|
||||
|
||||
@@ -283,13 +292,14 @@ def _cheap_give_kwh(runs, now, house, packs, *, floor_pct, ceiling_pct,
|
||||
hrs = (e - s).total_seconds() / 3600.0
|
||||
for p in ps:
|
||||
gain[p.name] += w * rate[p.name] / total * hrs \
|
||||
/ 1000.0 * EFF
|
||||
/ 1000.0 * eff_of(getattr(p, "eta", None))
|
||||
out = 0.0
|
||||
for p in ps:
|
||||
cap = float(p.capacity_kwh)
|
||||
lvl = max(float(p.soc), min(float(ceiling_pct),
|
||||
float(p.soc) + gain[p.name] / cap * 100.0))
|
||||
out += max(0.0, lvl - float(floor_pct)) / 100.0 * cap * EFF
|
||||
out += max(0.0, lvl - float(floor_pct)) / 100.0 * cap \
|
||||
* eff_of(getattr(p, "eta", None))
|
||||
return out
|
||||
|
||||
|
||||
@@ -312,6 +322,11 @@ def _solar_first_give_kwh(house, now, start, packs, *, floor_pct):
|
||||
for s, e, h in _hour_slices(now, start))
|
||||
have = {p.name: max(0.0, float(p.soc) - float(floor_pct)) / 100.0
|
||||
* float(p.capacity_kwh) for p in ps}
|
||||
if any(getattr(p, "eta", None) is not None for p in ps):
|
||||
# TARIFF-30: each battery gives at its own one-way efficiency.
|
||||
eff = {p.name: eff_of(getattr(p, "eta", None)) for p in ps}
|
||||
took, _ = _spread(use, {n: have[n] * eff[n] for n in have}, have)
|
||||
return sum(have[n] * eff[n] - took[n] for n in have)
|
||||
took, _ = _spread(use / EFF, have, have)
|
||||
return sum(have[n] - took[n] for n in have) * EFF
|
||||
|
||||
@@ -341,6 +356,7 @@ def plan(forecast, house, runs, now, packs, *, trust_pct, floor_pct,
|
||||
use = max(house_w(h), base_w) * hrs / 1000.0
|
||||
sun += max(0.0, pv - use)
|
||||
fc_sum += pv
|
||||
sun_raw = sun
|
||||
sun *= trust * EFF
|
||||
|
||||
usable = [p for p in packs if p.use and p.live and p.idle
|
||||
@@ -348,9 +364,28 @@ def plan(forecast, house, runs, now, packs, *, trust_pct, floor_pct,
|
||||
sf = [p for p in usable if p.mode == SOLAR_FIRST]
|
||||
price = [p for p in usable if p.mode == LEFTOVER_SOLAR]
|
||||
sf_room = sum(_room(p, ceiling_pct) for p in sf)
|
||||
# TARIFF-30: with a round-trip efficiency on any battery, each one is
|
||||
# charged and gives at its own one-way efficiency (`eff_of()`). With none
|
||||
# set this is the code that shipped, unchanged.
|
||||
per_unit = any(getattr(p, "eta", None) is not None for p in usable)
|
||||
eff = {p.name: eff_of(getattr(p, "eta", None)) for p in usable}
|
||||
excess = max(0.0, sun - sf_room)
|
||||
rooms = {p.name: _room(p, ceiling_pct) for p in price}
|
||||
total_room = sum(rooms.values())
|
||||
sun_in = {}
|
||||
if per_unit:
|
||||
# The sun is counted in kWh in front of the batteries, then stored at
|
||||
# each one's own efficiency: Solar first fill first, the rest by room.
|
||||
raw = sun_raw * trust
|
||||
sf_need = sum(_room(p, ceiling_pct) / eff[p.name] for p in sf)
|
||||
sf_eff = sf_room / sf_need if sf_need > 0.0 else EFF
|
||||
used = min(raw, sf_need)
|
||||
rest = max(0.0, raw - sf_need)
|
||||
sun_in = {n: (rest * rooms[n] / total_room * eff[n]
|
||||
if total_room > 0 else 0.0) for n in rooms}
|
||||
sun = used * sf_eff + (sum(sun_in.values()) if total_room > 0
|
||||
else rest * EFF)
|
||||
sf_short = raw < sf_need
|
||||
|
||||
# OPT-28: what the house draws in the expensive runs, from the one this
|
||||
# plan is for until the next cheap run (or a day), that the sun will not
|
||||
@@ -385,12 +420,26 @@ def plan(forecast, house, runs, now, packs, *, trust_pct, floor_pct,
|
||||
sfirst = min(sfirst, short - cheap)
|
||||
others = cheap + sfirst
|
||||
room_of = {n: span / 100.0 * c for n, c in caps.items()}
|
||||
held, left = _spread((short - others) / EFF, room_of, caps)
|
||||
held0 = _spread(short / EFF, room_of, caps)[0] if others > 0.0 else held
|
||||
if per_unit:
|
||||
# Shared by capacity in kWh given to the house; each battery's own
|
||||
# grid kWh is that over its own efficiency.
|
||||
room_d = {n: room_of[n] * eff[n] for n in room_of}
|
||||
got, left = _spread(short - others, room_d, caps)
|
||||
held = {n: got[n] / eff[n] for n in got}
|
||||
if others > 0.0:
|
||||
got0 = _spread(short, room_d, caps)[0]
|
||||
held0 = {n: got0[n] / eff[n] for n in got0}
|
||||
else:
|
||||
held0 = held
|
||||
else:
|
||||
held, left = _spread((short - others) / EFF, room_of, caps)
|
||||
held0 = _spread(short / EFF, room_of, caps)[0] if others > 0.0 \
|
||||
else held
|
||||
|
||||
targets, need, share, cover, saved = {}, {}, {}, {}, {}
|
||||
for p in price:
|
||||
sh = excess * rooms[p.name] / total_room if total_room > 0 else 0.0
|
||||
sh = (sun_in[p.name] if per_unit else
|
||||
excess * rooms[p.name] / total_room if total_room > 0 else 0.0)
|
||||
sh_pct = sh / caps[p.name] * 100.0
|
||||
top = float(floor_pct) + held[p.name] / caps[p.name] * 100.0
|
||||
level = max(0.0, top - sh_pct)
|
||||
@@ -400,8 +449,9 @@ def plan(forecast, house, runs, now, packs, *, trust_pct, floor_pct,
|
||||
saved[p.name] = round(
|
||||
_room(p, max(0.0, top0 - sh_pct)) - need[p.name], 3)
|
||||
share[p.name] = round(sh, 3)
|
||||
cover[p.name] = round(held[p.name] * EFF, 3)
|
||||
if sun < sf_room:
|
||||
cover[p.name] = round(held[p.name] * (eff[p.name] if per_unit
|
||||
else EFF), 3)
|
||||
if (sf_short if per_unit else sun < sf_room):
|
||||
verdict = DARK
|
||||
elif any(v > 0.05 for v in need.values()):
|
||||
verdict = PARTLY
|
||||
@@ -409,7 +459,8 @@ def plan(forecast, house, runs, now, packs, *, trust_pct, floor_pct,
|
||||
verdict = SUNNY
|
||||
return Plan(verdict, round(sun, 3), round(fc_sum, 3), until.start,
|
||||
targets, need, share, round(short, 3), cover,
|
||||
round(left * EFF if price else 0.0, 3), round(cheap, 3),
|
||||
round((left if per_unit else left * EFF) if price else 0.0,
|
||||
3), round(cheap, 3),
|
||||
saved, round(sfirst, 3))
|
||||
|
||||
|
||||
|
||||
@@ -167,7 +167,8 @@ def _levels(c, est, fc, trust, now, end, runs, floor, ceil, notes_b, shadow,
|
||||
batts.append(Batt(inv.name, float(inv.capacity_kwh),
|
||||
inv.max_w / 1000.0, float(inv.soc),
|
||||
pm.mode == SOLAR_FIRST, priced, grid, give,
|
||||
min(cyc) if cyc else None))
|
||||
min(cyc) if cyc else None,
|
||||
getattr(inv, "round_trip_eff", None)))
|
||||
return batts
|
||||
|
||||
def sun(a, z):
|
||||
@@ -222,7 +223,8 @@ def _levels(c, est, fc, trust, now, end, runs, floor, ceil, notes_b, shadow,
|
||||
for n in lv) if v is not None]
|
||||
end_t = cheaproll.roll_end(
|
||||
cheap, plan.read.points, packs_at, required=required,
|
||||
floor_pct=floor, ceiling_pct=ceil, targets=targets)
|
||||
floor_pct=floor, ceiling_pct=ceil, targets=targets,
|
||||
legs=getattr(c, "charge_legs", lambda *_a: None)(plan, now))
|
||||
ext = dataclasses.replace(rp, cheap=priceruns.Run(
|
||||
cheap.start, end_t, cheap.mean_eur_kwh))
|
||||
rt, lv = settle(ext, lv0)
|
||||
|
||||
@@ -395,6 +395,9 @@ def trade_runs(c, plan, verdict, day0, day1, now, shadow, ahead=False):
|
||||
for i, inv in enumerate(c.inverters):
|
||||
if _off(c, inv):
|
||||
continue # OPT-11: an Off battery does not trade
|
||||
if kind == "grid" and not arbitrage.leg_clears(
|
||||
verdict, getattr(inv, "round_trip_eff", None)):
|
||||
continue # TARIFF-30: its own losses eat the gap
|
||||
kwh = inv.max_w / 1000.0 * hrs
|
||||
cap = inv.capacity_kwh
|
||||
if cap:
|
||||
@@ -452,6 +455,12 @@ def mode_runs(c, day0, day1, now, shadow, ahead=False, rp=None):
|
||||
# UX-77: today's grid block runs to where control stops charging (the run
|
||||
# rolls on when it ends), each battery's to its own stop.
|
||||
roll = cheaproll.for_today(c, rp, now) if today else None
|
||||
# TARIFF-30: whose own buy leg clears (None: none has an efficiency set).
|
||||
legs = None
|
||||
if now is not None and hasattr(c, "charge_legs") and any(
|
||||
getattr(inv, "round_trip_eff", None) is not None
|
||||
for inv in c.inverters):
|
||||
legs = c.charge_legs(c.fresh_tariff_plan(now), now)
|
||||
out = []
|
||||
for i, inv in enumerate(c.inverters):
|
||||
pm = c.pack_mode(inv)
|
||||
@@ -484,6 +493,7 @@ def mode_runs(c, day0, day1, now, shadow, ahead=False, rp=None):
|
||||
need = plan_need(c, inv.name, start_pct("grid", rp.cheap.start)
|
||||
if ahead and rp.cheap is not None else None)
|
||||
if gate is None and rp.charge_useful() and (
|
||||
legs is None or legs.get(inv.name, True)) and (
|
||||
need > 0.0 if need is not None
|
||||
else pm.mode in GRID_CHARGE_MODES):
|
||||
cheap = rp.cheap if roll is None else priceruns.Run(
|
||||
@@ -938,6 +948,12 @@ def battery_rows(c, shadow, running, held=False):
|
||||
"level_pct": None if inv.soc is None else float(inv.soc),
|
||||
"power_w": None if inv.batt is None else float(inv.batt),
|
||||
"capacity_kwh": cap,
|
||||
# TARIFF-30: this battery's configured round-trip efficiency in %,
|
||||
# or None ("not set"). Config only, never a reading.
|
||||
"round_trip_pct": (None if getattr(inv, "round_trip_eff", None)
|
||||
is None
|
||||
else round(float(inv.round_trip_eff) * 100.0,
|
||||
1)),
|
||||
"stored_kwh": (None if cap is None or inv.soc is None
|
||||
else round(cap * float(inv.soc) / 100.0, 2)),
|
||||
"state": flow(inv.batt, shadow=shadow),
|
||||
|
||||
@@ -171,6 +171,10 @@ LINK_STALE_S = GOODWE_LINK_STALE_S
|
||||
# only ever have belonged to a single-inverter install.
|
||||
UNIT_A = "inverter-a"
|
||||
|
||||
# TARIFF-30. The range `round_trip_eff` may take, per inverter entry. The
|
||||
# schema in config.yaml says the same (`float(0.5,1)?`).
|
||||
RTE_MIN, RTE_MAX = 0.5, 1.0
|
||||
|
||||
# The per-unit keys this object keeps in the Store, namespaced by unit name.
|
||||
# ⚠️ THE VALUES ARE THE PRE-DEV-02 FLAT KEY NAMES, and that is what makes the
|
||||
# migration mechanical rather than transcribed: `store.migrate_unit_keys()`
|
||||
@@ -202,8 +206,15 @@ class Inverter:
|
||||
def __init__(self, name, *, setpoint_entity="", soc_entity="",
|
||||
batt_entity="", batt_invert=False, max_w=2000.0,
|
||||
bms_soc_floor=None, capacity_kwh=None, store=None,
|
||||
sign_cfg=None, delivery_cfg=None, driver=None):
|
||||
sign_cfg=None, delivery_cfg=None, driver=None,
|
||||
round_trip_eff=None):
|
||||
self.name = str(name)
|
||||
# TARIFF-30. THIS PACK'S OWN ROUND-TRIP EFFICIENCY (0.5 to 1.0), or None
|
||||
# when the entry did not set one - which is today's behaviour exactly.
|
||||
# Config only: never a reading, never learned (TARIFF-31), and never
|
||||
# taken from a sibling.
|
||||
self.round_trip_eff = (None if round_trip_eff is None
|
||||
else float(round_trip_eff))
|
||||
# SMA-2. HOW THIS UNIT IS READ AND STEERED. The entity keywords above
|
||||
# are the GoodWe driver's, kept so every existing caller builds the
|
||||
# same unit; a roster entry that selects another driver passes
|
||||
@@ -677,6 +688,8 @@ def build_roster(opts: dict, store, sign_cfg=None,
|
||||
# though it were a 20.48 kWh one, which is the split this card
|
||||
# exists to stop being wrong.
|
||||
capacity_kwh=_entry_capacity_kwh(entry),
|
||||
# TARIFF-30: this entry's own, never a sibling's.
|
||||
round_trip_eff=entry_round_trip_eff(entry),
|
||||
store=store, sign_cfg=sign_cfg, delivery_cfg=delivery_cfg))
|
||||
return roster
|
||||
|
||||
@@ -773,6 +786,26 @@ def _entry_capacity_kwh(entry: dict):
|
||||
return val if val > 0.0 else None
|
||||
|
||||
|
||||
def entry_round_trip_eff(entry):
|
||||
"""TARIFF-30. One entry's OWN round-trip efficiency (0.5 to 1.0), or None.
|
||||
|
||||
None means "not set", and it is today's behaviour exactly. A value that is
|
||||
not a usable number in range also answers None here: validate.py rule 9
|
||||
refuses it at startup with a message, and withholding is the direction that
|
||||
cannot invent a preference. Never read from a sensor or the store, and
|
||||
never defaulted from another unit."""
|
||||
if not isinstance(entry, dict):
|
||||
return None
|
||||
raw = entry.get("round_trip_eff")
|
||||
if raw is None or raw == "" or isinstance(raw, bool):
|
||||
return None
|
||||
try:
|
||||
val = float(raw)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return val if (math.isfinite(val) and RTE_MIN <= val <= RTE_MAX) else None
|
||||
|
||||
|
||||
def _entry_max_w(entry: dict) -> float:
|
||||
"""One entry's supervised cap, or 0.0 when it did not state a usable one.
|
||||
|
||||
|
||||
@@ -1921,6 +1921,7 @@ LABELS = {
|
||||
"max_w": "Inverter rating",
|
||||
"bms_soc_floor": "Battery cut-out level",
|
||||
"capacity_kwh": "Usable battery capacity",
|
||||
"round_trip_eff": "Round-trip efficiency",
|
||||
"inverters": "Inverter list",
|
||||
"name": "Name",
|
||||
"meter_source": "Where the meter reading comes from",
|
||||
@@ -2012,6 +2013,7 @@ LABELS_NL = {
|
||||
"max_w": "Vermogen van de omvormer",
|
||||
"bms_soc_floor": "Uitschakelniveau van de batterij",
|
||||
"capacity_kwh": "Bruikbare capaciteit",
|
||||
"round_trip_eff": "Rendement heen en terug",
|
||||
"inverters": "Lijst met omvormers",
|
||||
"name": "Naam",
|
||||
"meter_source": "Waar de meterstand vandaan komt",
|
||||
|
||||
@@ -102,6 +102,7 @@ class Pack:
|
||||
idle: bool = True # not in a maintenance phase
|
||||
refused: int = 0 # SAFETY-52/73: +1 refuses to give, -1 to charge
|
||||
probing: bool = False # OPT-15: its SAFETY-73 probe window is open
|
||||
eta: float | None = None # TARIFF-30: its own round-trip efficiency
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -140,18 +141,26 @@ def charge_to(p: Pack, ceiling_pct, targets=None):
|
||||
return None if t is None else min(float(ceiling_pct), float(t))
|
||||
|
||||
|
||||
def chargers(packs, ceiling_pct, done=(), targets=None, probe=False) -> list:
|
||||
def chargers(packs, ceiling_pct, done=(), targets=None, probe=False,
|
||||
legs=None) -> list:
|
||||
"""Batteries that may charge from the grid in a cheap run: below the
|
||||
level `charge_to()` allows them (P4: the day plan's). With `probe`, also
|
||||
one refusing to charge while its SAFETY-73 probe is open: its own P_SAFETY
|
||||
pin keeps it at PROBE_W (OPT-15)."""
|
||||
pin keeps it at PROBE_W (OPT-15).
|
||||
|
||||
TARIFF-30. `legs` is `{name: bool}` (`arbitrage.clearing()`) or None. A
|
||||
battery whose own buy leg does not clear (its round-trip losses eat the
|
||||
spread) is not a charger. None is today's list. The SAFETY-73 probe is not
|
||||
an economic charge and runs unchanged (a probing refuser stays a charger)."""
|
||||
out = []
|
||||
for p in packs:
|
||||
to = charge_to(p, ceiling_pct, targets)
|
||||
probing = probe and p.probing and p.refused < 0
|
||||
if (to is not None and p.use and p.idle and p.live
|
||||
and p.soc is not None and p.soc < to
|
||||
and (p.refused >= 0 or (probe and p.probing))
|
||||
and p.name not in done):
|
||||
and p.name not in done
|
||||
and (probing or legs is None or legs.get(p.name, True))):
|
||||
out.append(p)
|
||||
return out
|
||||
|
||||
@@ -166,11 +175,11 @@ def sellers(packs, floor_pct, done=()) -> list:
|
||||
|
||||
|
||||
def energy(packs, floor_pct, ceiling_pct, done_charge=(), done_sell=(),
|
||||
targets=None):
|
||||
targets=None, legs=None):
|
||||
"""`(charge_kwh, charge_kw, sell_kwh, sell_kw)` for `priceruns.plan()`.
|
||||
With a day plan the charge is each battery's shortfall, so the cheap run
|
||||
is only as long as the shortfall needs."""
|
||||
ch = chargers(packs, ceiling_pct, done_charge, targets)
|
||||
is only as long as the shortfall needs. `legs`: see `chargers()`."""
|
||||
ch = chargers(packs, ceiling_pct, done_charge, targets, legs=legs)
|
||||
se = sellers(packs, floor_pct, done_sell)
|
||||
return (sum(_room_kwh(p, charge_to(p, ceiling_pct, targets))
|
||||
for p in ch),
|
||||
@@ -183,7 +192,7 @@ def decide(runs, now, packs, *, charge_ok, sell_ok, trade_why, price_now,
|
||||
headroom_w, floor_pct, ceiling_pct, house_w, charging_now=False,
|
||||
blocked=False, done_charge=(), done_sell=(),
|
||||
targets=None, draining=False, wait=None,
|
||||
maint_charging=False) -> Tick:
|
||||
maint_charging=False, legs=None) -> Tick:
|
||||
"""This tick's ranges, roles and site ask.
|
||||
|
||||
`runs` is the kept `priceruns.RunPlan` or None (no fresh prices).
|
||||
@@ -200,7 +209,8 @@ def decide(runs, now, packs, *, charge_ok, sell_ok, trade_why, price_now,
|
||||
why) says no charge may start yet (SAFETY-135). `maint_charging` says a
|
||||
battery is in its maintenance CHARGE phase: no grid charge for the others
|
||||
either, same why, but a refusal probe goes on (MAINT-24,
|
||||
DECISIONS/MAINT-24-charge-first.md).
|
||||
DECISIONS/MAINT-24-charge-first.md). `legs` (TARIFF-30): `{name: bool}`,
|
||||
which batteries' own buy legs clear (`chargers()`), or None.
|
||||
"""
|
||||
plan_on = runs is not None and runs.on
|
||||
in_cheap = plan_on and runs.cheap.holds(now) and runs.charge_useful()
|
||||
@@ -208,8 +218,8 @@ def decide(runs, now, packs, *, charge_ok, sell_ok, trade_why, price_now,
|
||||
in_sell = plan_on and runs.sell is not None and runs.sell.holds(now)
|
||||
|
||||
why = None
|
||||
ch = chargers(packs, ceiling_pct, done_charge, targets, probe=True) \
|
||||
if in_cheap else []
|
||||
ch = chargers(packs, ceiling_pct, done_charge, targets, probe=True,
|
||||
legs=legs) if in_cheap else []
|
||||
if ch and draining:
|
||||
ch, why = [], "cycle"
|
||||
elif ch and maint_charging:
|
||||
|
||||
@@ -420,7 +420,7 @@ def weights(packs, target_w) -> dict | None:
|
||||
return out
|
||||
|
||||
|
||||
def trade_power_w(packs, floor_pct, ceiling_pct) -> tuple:
|
||||
def trade_power_w(packs, floor_pct, ceiling_pct, legs=None) -> tuple:
|
||||
"""`(charge_w, discharge_w)` - how hard an arbitrage trade may be SIZED.
|
||||
|
||||
The site rating is what the site can push; this is what the site can push
|
||||
@@ -457,8 +457,14 @@ def trade_power_w(packs, floor_pct, ceiling_pct) -> tuple:
|
||||
the buy gate refuses when every pack is at the ceiling; `arbitrage.decide()`
|
||||
refuses a 0 W sizing by name anyway, so that is structural rather than a
|
||||
coincidence of the gates.
|
||||
|
||||
TARIFF-30. `legs` is `{name: bool}` (`arbitrage.clearing()`) or None. A pack
|
||||
whose own buy leg does not clear is not counted on the BUY side: the trade
|
||||
is sized to what may actually charge. None is today's sum. The sell side
|
||||
never reads it.
|
||||
"""
|
||||
return (float(sum(p.max_w for p in packs
|
||||
if p.soc is not None and float(p.soc) < ceiling_pct)),
|
||||
if p.soc is not None and float(p.soc) < ceiling_pct
|
||||
and (legs is None or legs.get(p.name, True)))),
|
||||
float(sum(p.max_w for p in packs
|
||||
if p.soc is not None and float(p.soc) > floor_pct)))
|
||||
|
||||
@@ -467,6 +467,7 @@
|
||||
levelBar(b.level_pct, b.name),
|
||||
h("dl", { class: "kv" },
|
||||
h("dt", {}, t("batteries.level")), h("dd", {}, lvl + stored),
|
||||
h("dt", {}, t("batteries.round_trip")), h("dd", {}, b.round_trip_pct != null ? dec(String(b.round_trip_pct)) + " %" : t("batteries.round_trip_unset")),
|
||||
h("dt", {}, t("batteries.now")), h("dd", {}, b.now),
|
||||
h("dt", {}, t("batteries.today")), h("dd", {}, todayLines(b)),
|
||||
h("dt", {}, t("batteries.why")), h("dd", { class: "muted" }, b.why || "–")),
|
||||
|
||||
@@ -105,7 +105,7 @@
|
||||
"toast": {"started": "Control started.", "stopped": "Control stopped.", "done": "Done.", "failed": "That did not work. Try again."},
|
||||
"offline": {"name": "Cannot reach the add-on", "description": "The page tries again every 3 seconds."},
|
||||
"setup_only": {"name": "Setup: nothing is controlled yet", "description": "Nothing is sent to any inverter until setup is saved and the add-on restarts.", "control": "Control starts after setup.", "open": "Open Setup"},
|
||||
"batteries": {"name": "Batteries", "description": "To choose a mode for each battery, turn on battery modes in the settings.", "level": "Level", "now": "Now", "stored": "Stored", "mode": "Mode", "settings": "Change inverter settings",
|
||||
"batteries": {"name": "Batteries", "description": "To choose a mode for each battery, turn on battery modes in the settings.", "level": "Level", "now": "Now", "stored": "Stored", "round_trip": "Efficiency", "round_trip_unset": "not set", "mode": "Mode", "settings": "Change inverter settings",
|
||||
"on": "On", "off": "Off",
|
||||
"choice": {
|
||||
"solar_first": {"name": "Solar first", "description": "Charges from solar before the other batteries, covers the house and never charges from the grid."},
|
||||
|
||||
@@ -102,7 +102,7 @@
|
||||
"toast": {"started": "Regeling gestart.", "stopped": "Regeling gestopt.", "done": "Klaar.", "failed": "Dat lukte niet. Probeer opnieuw."},
|
||||
"offline": {"name": "Add-on niet bereikbaar", "description": "De pagina probeert het elke 3 seconden opnieuw."},
|
||||
"setup_only": {"name": "Installatie: nog niets wordt geregeld", "description": "Er gaat niets naar een omvormer tot de installatie bewaard is en de add-on herstart.", "control": "De regeling start na de installatie.", "open": "Installatie openen"},
|
||||
"batteries": {"name": "Batterijen", "description": "Zet batterijmodi aan in de instellingen om per batterij een modus te kiezen.", "level": "Laadniveau", "now": "Nu", "stored": "Opgeslagen", "mode": "Modus", "settings": "Instellingen van omvormers wijzigen",
|
||||
"batteries": {"name": "Batterijen", "description": "Zet batterijmodi aan in de instellingen om per batterij een modus te kiezen.", "level": "Laadniveau", "now": "Nu", "stored": "Opgeslagen", "round_trip": "Rendement", "round_trip_unset": "niet ingesteld", "mode": "Modus", "settings": "Instellingen van omvormers wijzigen",
|
||||
"on": "Aan", "off": "Uit",
|
||||
"choice": {
|
||||
"solar_first": {"name": "Eerst zonne-energie", "description": "Laadt met zonne-energie vóór de andere batterijen, dekt het huis en laadt nooit van het net."},
|
||||
|
||||
@@ -92,6 +92,10 @@ ROSTER_FIELDS = (
|
||||
Field("inverters.batt_invert", TOGGLE, wizard=2),
|
||||
Field("inverters.capacity_kwh", NUMBER, "kWh", step=0.1, show=_LISTED,
|
||||
wizard=2),
|
||||
# TARIFF-30: optional, 0.5 to 1; not shown for the flat single inverter
|
||||
# (it stores no per-unit keys).
|
||||
Field("inverters.round_trip_eff", NUMBER, step=0.01, show=_LISTED,
|
||||
wizard=2),
|
||||
)
|
||||
|
||||
GROUPS = (
|
||||
|
||||
@@ -829,6 +829,26 @@ def _roster_problems(opts: dict) -> list[str]:
|
||||
f"{S('capacity_kwh')} is set on {', '.join(stated)} but empty on "
|
||||
f"{', '.join(blank)}. Set it on every inverter, or on none.")
|
||||
|
||||
# --- (i) TARIFF-30: `round_trip_eff`, optional per entry, 0.5 to 1.0 -----
|
||||
# Mixed installs are allowed (unlike capacity_kwh): each unit's buy leg uses
|
||||
# its own meaning, so there is no all-or-none rule here.
|
||||
for i, entry in enumerate(entries):
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
raw = entry.get("round_trip_eff")
|
||||
if raw is None or raw == "":
|
||||
continue
|
||||
nm = str(entry.get("name") or "").strip()
|
||||
who = f"inverters[{i}] ({nm})" if nm else f"inverters[{i}]"
|
||||
try:
|
||||
val = None if isinstance(raw, bool) else float(raw)
|
||||
except (TypeError, ValueError):
|
||||
val = None
|
||||
if val is None or not math.isfinite(val) or not (0.5 <= val <= 1.0):
|
||||
problems.append(
|
||||
f"{who} has {S('round_trip_eff')} {messages.shown(raw)}, which "
|
||||
"is not usable. Set it from 0.5 to 1, or leave it empty.")
|
||||
|
||||
flat_sp = str(opts.get("setpoint_entity") or "").strip()
|
||||
if entries and flat_sp:
|
||||
problems.append(
|
||||
|
||||
@@ -969,7 +969,8 @@ schema:
|
||||
# no `max_w` would have to borrow a rating, which is the sibling-grading
|
||||
# defect DEV-02 removed; `bms_soc_floor` is SAFETY-32's (options block above).
|
||||
# The optional keys are the sensors, whose absence honestly means "this unit
|
||||
# reports none", and `capacity_kwh`.
|
||||
# reports none", `capacity_kwh`, and TARIFF-30's `round_trip_eff` (0.5 to 1;
|
||||
# absent means today's behaviour exactly, so nothing is invented for it).
|
||||
#
|
||||
# ⚠️ THIS BLOCK IS DECLARED BEFORE `max_w:` ON PURPOSE. `max_w` now appears
|
||||
# TWICE under `schema:` - once nested here, once flat below - and a reader
|
||||
@@ -986,6 +987,7 @@ schema:
|
||||
batt_entity: str?
|
||||
batt_invert: bool?
|
||||
capacity_kwh: float(0.1,200)?
|
||||
round_trip_eff: float(0.5,1)?
|
||||
|
||||
estop_fitted: bool
|
||||
battery_modes_enabled: bool
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"arbitrage_decide": {
|
||||
"n": 5184,
|
||||
"sha256": "ea73ac21d4f466851e61582dbf208007c109c97ef04e0f929b13a22de2a39757"
|
||||
},
|
||||
"modetrade": {
|
||||
"n": 1944,
|
||||
"sha256": "2ccf41a247136f933df95615fd3ee6222a44d77c34e54636f08f23bb6925411d"
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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()
|
||||
@@ -58,7 +58,10 @@ GOLDEN = {
|
||||
"T20 T5 [A]": "369069be9187ab3c", "T20 T5 [R]": "78ffe9cf72c5e214", # EV-59
|
||||
"T20 T8 [A]": "2cd78dee7ee93aaa", "T20 T8 [R]": "f0adb058a5bbefba",
|
||||
"T20 T11 [A]": "6d7bcb747d1dc5a3", "T20 T11 [R]": "2be1a760b699b28c",
|
||||
"T20 T12 [A]": "a5888e4557b4ee8f", "T20 T12 [R]": "2fd24ddbb18f14cc",
|
||||
"T20 T12 [A]": "a5888e4557b4ee8f",
|
||||
# EV-60 (Q4): re-taken; the only change from 2fd24ddbb18f14cc is Solar's
|
||||
# `fails` 4 -> 3 in cycles 323-372 (after the 3rd close: no extra _failed).
|
||||
"T20 T12 [R]": "25a205989dc44204",
|
||||
"T20 T13 [A]": "1ad97e089468d71b", "T20 T13 [R]": "7baf8981ab382e05",
|
||||
"T20 T15 [A]": "54701b140ec6f30b", "T20 T15 [R]": "0cfd3ccd334f378d",
|
||||
"T20 T15d [A]": "1d85595302dc032a", "T20 T15d [R]": "5fc65dbdc730e539",
|
||||
@@ -889,12 +892,13 @@ e12 = row_at(x12, t12)
|
||||
check(f"T12: the change's close raises: writer equal to R ({eq12[:1]})",
|
||||
not eq12)
|
||||
check(f"T12: 3 close tries 5 s apart ({ts(c12)[:3]}); then seq None, the "
|
||||
f"change ended ({e12 and e12[2]['plan']}), fails 4 as with R "
|
||||
f"change ended ({e12 and e12[2]['plan']}), fails MAX_TRIES as with R "
|
||||
f"(EV-60: no extra _failed at Solar's close end) "
|
||||
f"({e12 and e12[2]['fails']}); the car at 0 A; one select only "
|
||||
f"({sel12})",
|
||||
len(c12) >= 3 and gaps(ts(c12)[:3]) == [5.0, 5.0]
|
||||
and e12 is not None and e12[2]["seq"] is None
|
||||
and e12[2]["fails"] == 4 and e12[2]["plan"][2] is False
|
||||
and e12[2]["fails"] == CM.MAX_TRIES and e12[2]["plan"][2] is False
|
||||
and x12["sim"].setpoint_a == 0.0 and len(sel12) == 1)
|
||||
never("T12", x12, close_ok=True)
|
||||
|
||||
@@ -1036,6 +1040,12 @@ def c4b(kind):
|
||||
return r
|
||||
drv = Drv(8.0, answer)
|
||||
w, trk, run = solar_writer(8.0), Trk(), Runner()
|
||||
# EV-60: the capped change ends and the plan is back at 8 A; the real
|
||||
# plan lowers it to the cap again at its next step (SolarPlan.step), so
|
||||
# nothing above the cap is written.
|
||||
w._plan_step = lambda *a, **k: (
|
||||
w.plan._cut(w.cut_a) if w.cut_a is not None and w.cut_a >= CH.MIN_A
|
||||
and w.plan.a > w.cut_a else None)
|
||||
w.cut_a, w.cut_on = 0.0, True
|
||||
w.plan.a = 0.0
|
||||
t = 0
|
||||
@@ -1055,12 +1065,13 @@ def c4b(kind):
|
||||
return tries, w.cut_fails, run
|
||||
|
||||
|
||||
for route, fn, want, cf in (("a", c4c, [0, 60, 120, 180], 4),
|
||||
("b", c4b, [0, 60, 120, 192, 197, 202], 7)):
|
||||
for route, fn, want, cf in (("a", c4c, [0, 60, 120], 3),
|
||||
("b", c4b, [0, 60, 120], 3)):
|
||||
res = {k: fn(k) for k in "RX"}
|
||||
check(f"T19b [{route}] (H4, not worse than base): refused cut tries per "
|
||||
f"key R {res['R'][0]} cut_fails {res['R'][1]}, X {res['X'][0]} "
|
||||
f"cut_fails {res['X'][1]} = base {want} / {cf}; no record",
|
||||
check(f"T19b [{route}] (H4, EV-60: never past the cap of MAX_TRIES): "
|
||||
f"refused cut tries per key R {res['R'][0]} cut_fails "
|
||||
f"{res['R'][1]}, X {res['X'][0]} cut_fails {res['X'][1]} = "
|
||||
f"{want} / {cf} (base had 4 / 7 tries); no record",
|
||||
res["R"][0] == res["X"][0] == want
|
||||
and res["R"][1] == res["X"][1] == cf
|
||||
and not res["X"][2].recs() and not res["R"][2].recs())
|
||||
|
||||
@@ -617,12 +617,15 @@ def sp3(press, cls=solar_writer):
|
||||
|
||||
S_NONE = sp3(False)
|
||||
S_PRESS = sp3(True)
|
||||
check(f"T25/T14 (N14): Solar equals base. No press: 8 A at 12, 17, 22, fails "
|
||||
f"4, gave_up, REF at 22 ({S_NONE})",
|
||||
S_NONE == ([12, 17, 22], 4, True, [22], None))
|
||||
check(f"T25 (resetSuper trap): a Solar press at 13 does not reset Solar's "
|
||||
f"tries: 8 A at 12, 17, 22, fails 3, gave_up, REF at 22 ({S_PRESS})",
|
||||
S_PRESS == ([12, 17, 22], 3, True, [22], 13))
|
||||
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
|
||||
@@ -650,10 +653,10 @@ def t14c():
|
||||
|
||||
|
||||
S14C = t14c()
|
||||
check(f"T14c (N14): Solar's close value moves between tries: 8, 7, 6 A at "
|
||||
f"10, 15, 20, then `fails` 4, gave_up, REF at 20, seq None, as base "
|
||||
f"({S14C})",
|
||||
S14C == ([(10, 8.0), (15, 7.0), (20, 6.0)], 4, True, [20], None))
|
||||
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()
|
||||
@@ -737,7 +740,8 @@ 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",
|
||||
"a5888e4557b4ee8f", "2fd24ddbb18f14cc", "1ad97e089468d71b",
|
||||
# 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]' "
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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 cleared), 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()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,613 @@
|
||||
"""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 re
|
||||
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()
|
||||
# Any mention of the field, `._kept` or a getattr string (review: the dot form
|
||||
# alone missed `getattr(w, "_kept")`); `was_kept` and `fc.kept` do not match.
|
||||
others = [f for f in os.listdir(os.path.join(HERE, "app"))
|
||||
if f.endswith(".py") and f != "carmode.py"
|
||||
and re.search(r"\b_kept\b",
|
||||
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) is asserted by T17 (ii): no other
|
||||
# module names `_kept` (red under M11), and a new writer starts empty.
|
||||
# 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()
|
||||
@@ -1558,13 +1558,13 @@ check("...and the schema half declares it as a LIST OF OBJECTS whose `name`, "
|
||||
"refuses every options blob written before it existed",
|
||||
set(_decl9) == {"name", "setpoint_entity", "max_w", "bms_soc_floor",
|
||||
"soc_entity", "batt_entity", "batt_invert",
|
||||
"capacity_kwh"}
|
||||
"capacity_kwh", "round_trip_eff"}
|
||||
and not any(_decl9[k].endswith("?")
|
||||
for k in ("name", "setpoint_entity", "max_w",
|
||||
"bms_soc_floor"))
|
||||
and all(_decl9[k].endswith("?")
|
||||
for k in ("soc_entity", "batt_entity", "batt_invert",
|
||||
"capacity_kwh")))
|
||||
"capacity_kwh", "round_trip_eff")))
|
||||
|
||||
# ⚠️ NOTHING IS INHERITED, AND THIS IS DEV-02 RESTATED AS A CONFIG RULE.
|
||||
# ⚠️ THE FLAT KEYS ARE SET TO REAL ENTITIES HERE, AND THAT IS THE WHOLE CHECK.
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -75,7 +75,7 @@ check(f"the option surface was actually read - {len(ORDER)} options, not zero",
|
||||
check("...and the repeatable `inverters:` section's per-entry keys were read "
|
||||
"too, which is the half a top-level-only reader would miss",
|
||||
NESTED.get("inverters", [])[:2] == ["name", "setpoint_entity"]
|
||||
and len(NESTED["inverters"]) == 8)
|
||||
and len(NESTED["inverters"]) == 9) # TARIFF-30: + round_trip_eff
|
||||
|
||||
print("\n2. AC: every option and every per-entry key is translated, in BOTH "
|
||||
"languages")
|
||||
@@ -282,7 +282,7 @@ check("...and the accepted subset really does round-trip the shipped files - "
|
||||
f"per-entry keys came back out of each, which is what says the "
|
||||
f"strictness above is not just refusing everything",
|
||||
all(len(TR[lg]["configuration"]) == len(ORDER)
|
||||
and len(TR[lg]["configuration"]["inverters"]["fields"]) == 8
|
||||
and len(TR[lg]["configuration"]["inverters"]["fields"]) == 9
|
||||
for lg in LANGS))
|
||||
print(" ⚠️ the licence for this hand parser is NOT this file. "
|
||||
"tools/supervisor_shape_probe.py section F loads the same two files with "
|
||||
|
||||
@@ -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)
|
||||
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env python3
|
||||
"""TARIFF-30 (T8): a decision trace of the grid-charge code with NO efficiency
|
||||
set, to be compared with one captured on release/1.0 831c33c.
|
||||
|
||||
It uses only the API 831c33c already has, so the same file runs on the base and
|
||||
on the head: `python3 tools/tariff30_trace.py` prints one JSON object, per group
|
||||
the number of calls and the sha256 of every outcome in order. The golden copy in
|
||||
scenarios/tariff30-base-trace.json was printed on 831c33c. The test compares
|
||||
the head's against it, so with no efficiency set arbitrage.decide(), the
|
||||
battery-mode charge/sell decision and its energy sizing give the same answers
|
||||
as before the change, field by field.
|
||||
"""
|
||||
import hashlib
|
||||
import itertools
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
# T30_TREE: another checkout's goodwe_controller/ (how the golden was printed,
|
||||
# from a 831c33c worktree, with this very file).
|
||||
HERE = os.environ.get("T30_TREE") or os.path.dirname(
|
||||
os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, HERE)
|
||||
sys.path.insert(0, os.path.join(HERE, "tools"))
|
||||
|
||||
import ux54_scenarios as S # noqa: E402
|
||||
from app import arbitrage, modetrade, priceruns # noqa: E402
|
||||
from app.price import Uncertainty # noqa: E402
|
||||
from app.static_tariff import static_plan # noqa: E402
|
||||
from app.tariff import BILLING_TZ # noqa: E402
|
||||
|
||||
UTC = timezone.utc
|
||||
NO_WX = frozenset({Uncertainty.NO_WEATHER})
|
||||
|
||||
|
||||
def _plan(now):
|
||||
opts = dict(S.BASE)
|
||||
opts.update(static_profile=json.dumps(S.DN))
|
||||
return static_plan(opts, S.day0_of(now), S.day0_of(now)
|
||||
+ timedelta(hours=48), now=now)
|
||||
|
||||
|
||||
def _digest(rows):
|
||||
h = hashlib.sha256()
|
||||
for r in rows:
|
||||
h.update(repr(r).encode())
|
||||
h.update(b"\n")
|
||||
return {"n": len(rows), "sha256": h.hexdigest()}
|
||||
|
||||
|
||||
def arbitrage_rows():
|
||||
"""`arbitrage.decide()` over buy, sell and off-peak instants, every SoC,
|
||||
headroom, guard state, threshold and size the call can be given."""
|
||||
rows = []
|
||||
for hh, mm in ((22, 5), (23, 30), (3, 0), (7, 0), (10, 0), (21, 59)):
|
||||
now = datetime(2026, 11, 1, hh, mm, tzinfo=BILLING_TZ).astimezone(UTC)
|
||||
plan = _plan(now)
|
||||
for soc, room, guard, thr, cw, dw in itertools.product(
|
||||
(None, 5.0, 50.0, 96.0), (None, 0.0, 1200.0, 10000.0),
|
||||
(True, False, None), (0.0, 0.03, 0.10), (0.0, 5000.0, 9600.0),
|
||||
(0.0, 9600.0)):
|
||||
d = arbitrage.decide(
|
||||
plan, now, peak_guard_active=guard, charge_headroom_w=room,
|
||||
soc=soc, min_spread_eur_kwh=thr, uncertainty=NO_WX,
|
||||
charge_w=cw, discharge_w=dw, soc_floor_pct=10.0,
|
||||
soc_ceiling_pct=95.0)
|
||||
rows.append((hh, mm, soc, room, guard, thr, cw, dw, d.action,
|
||||
d.power_w, d.reason, d.spread_eur_kwh,
|
||||
d.required_eur_kwh, d.price_now_eur_kwh))
|
||||
return rows
|
||||
|
||||
|
||||
def mode_rows():
|
||||
"""`modetrade.chargers()`, `energy()` and `decide()` over mode, level,
|
||||
refusal and probe states of two batteries, in a cheap run."""
|
||||
rows = []
|
||||
now = datetime(2026, 11, 1, 23, 30, tzinfo=BILLING_TZ).astimezone(UTC)
|
||||
plan = _plan(now)
|
||||
modes = ("solar_first", "leftover_solar", "cheap_hours")
|
||||
for ma, mb, soca, socb, refb, probb, ok, room, blk in itertools.product(
|
||||
modes, modes, (20.0, 99.0, None), (50.0,), (0, -1, 1),
|
||||
(False, True), (True, False), (None, 300.0, 6000.0),
|
||||
(False, True)):
|
||||
packs = [modetrade.Pack("A", True, ma, False, 5000.0, soca, 15.36),
|
||||
modetrade.Pack("B", True, mb, False, 4600.0, socb, 20.48,
|
||||
refused=refb, probing=probb)]
|
||||
e = modetrade.energy(packs, 10.0, 95.0)
|
||||
rp = priceruns.plan(plan.read.points, now, required_eur_kwh=0.0,
|
||||
charge_kwh=e[0], charge_kw=e[1], sell_kwh=e[2],
|
||||
sell_kw=e[3])
|
||||
ch = [p.name for p in modetrade.chargers(packs, 95.0, probe=True)]
|
||||
t = modetrade.decide(
|
||||
rp, now, packs, charge_ok=ok, sell_ok=ok, trade_why="not_worth",
|
||||
price_now=0.2333, headroom_w=room, floor_pct=10.0,
|
||||
ceiling_pct=95.0, house_w=500.0, blocked=blk)
|
||||
rows.append((ma, mb, soca, socb, refb, probb, ok, room, blk, e, ch,
|
||||
sorted(t.ranges.items()), sorted(t.roles.items()),
|
||||
t.action, t.ask_w, t.why, t.probe_w,
|
||||
modetrade.size(t, (-9600.0, 9600.0), room)))
|
||||
return rows
|
||||
|
||||
|
||||
def trace():
|
||||
return {"arbitrage_decide": _digest(arbitrage_rows()),
|
||||
"modetrade": _digest(mode_rows())}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(json.dumps(trace(), indent=1, sort_keys=True))
|
||||
@@ -79,6 +79,9 @@ configuration:
|
||||
capacity_kwh:
|
||||
name: "Usable battery capacity (kWh) (optional)"
|
||||
description: "This battery's usable capacity from its datasheet. Fill it in on every inverter or on none. The add-on then shares the work by the energy each battery has left."
|
||||
round_trip_eff:
|
||||
name: "Round-trip efficiency (0.5 to 1) (optional)"
|
||||
description: "The share of energy this battery gives back, for example 0.86. Leave it empty if unknown. If you set round-trip efficiency, lower the cycle cost to wear only."
|
||||
estop_fitted:
|
||||
name: "Hardware · RS485 emergency stop is fitted"
|
||||
description: "Switch this on if the emergency stop is installed. It only changes a warning on the status page."
|
||||
@@ -219,7 +222,7 @@ configuration:
|
||||
description: "Charge in the cheapest hour and draw the battery down in the dearest, when the spread covers the cost. Turning it off does not turn the price feed off."
|
||||
cycle_cost_threshold_eur:
|
||||
name: "Tariff · Battery cycle cost (EUR/kWh)"
|
||||
description: "What one full battery cycle costs per kWh. A smaller price spread is not traded, and the value is a product choice, not a measured one."
|
||||
description: "Cost of one cycle per kWh. Smaller gaps are not traded. A product choice, not a measured one. If you set round-trip efficiency, lower the cycle cost to wear only."
|
||||
arbitrage_soc_floor:
|
||||
name: "Tariff · Trading keeps at least (%)"
|
||||
description: "Price trading will not draw the battery below this level. It is separate from the maintenance settings."
|
||||
|
||||
@@ -60,6 +60,9 @@ configuration:
|
||||
capacity_kwh:
|
||||
name: "Bruikbare capaciteit (kWh) (optioneel)"
|
||||
description: "De bruikbare capaciteit van deze batterij, van het datablad. Vul ze bij elke omvormer in of bij geen. Dan verdeelt de add-on het werk volgens de energie in elke batterij."
|
||||
round_trip_eff:
|
||||
name: "Rendement heen en terug (optioneel)"
|
||||
description: "Het deel energie dat de batterij teruggeeft, bijvoorbeeld 0,86. Leeg laten als onbekend. Stelt u het rendement in, verlaag dan de kosten van een batterijcyclus tot alleen slijtage."
|
||||
estop_fitted:
|
||||
name: "Hardware · RS485-noodstop is geplaatst"
|
||||
description: "Zet dit aan als de noodstop geïnstalleerd is. Het verandert alleen een waarschuwing op de statuspagina."
|
||||
@@ -200,7 +203,7 @@ configuration:
|
||||
description: "Laden in het goedkoopste uur en de batterij laten leveren in het duurste, als het verschil de kosten dekt. Dit uitzetten zet de prijsfeed niet uit."
|
||||
cycle_cost_threshold_eur:
|
||||
name: "Tarief · Kosten van een batterijcyclus (EUR/kWh)"
|
||||
description: "Wat één volledige batterijcyclus per kWh kost. Een kleiner prijsverschil wordt niet verhandeld. De waarde is een productkeuze, geen meting."
|
||||
description: "Wat één cyclus per kWh kost. Een kleiner prijsverschil wordt niet verhandeld. Stelt u het rendement in, verlaag dan de kosten van een batterijcyclus tot alleen slijtage."
|
||||
arbitrage_soc_floor:
|
||||
name: "Tarief · Handel houdt minstens (%)"
|
||||
description: "Prijshandel laat de batterij niet onder dit niveau zakken. Dit staat los van de onderhoudsinstellingen."
|
||||
|
||||
Reference in New Issue
Block a user