Skip to content

feat(planner): Phase 4 – PR 4-F HiGHS-Planer, Laufzeit alle 15 min und Übergabe an den Regler - #31

Open
PXLJAKE wants to merge 18 commits into
phase-4/e-load-riskfrom
phase-4/f-planner
Open

PXLJAKE wants to merge 18 commits into
phase-4/e-load-riskfrom
phase-4/f-planner

Conversation

@PXLJAKE

@PXLJAKE PXLJAKE commented Oct 24, 2026

Copy link
Copy Markdown
Owner

Gestapelt auf #30 (PR 4-E). Zusätzlich ist #27 (PR 4-C, Tarife) hineingemergt, weil der Planer Preise braucht. Die Basis wird nach dem Merge der Vorgänger umgestellt.

Was

WP8 – Planer (suncore/planner/, importiert nur core, mypy --strict):

  • build_inputs: Aus Preisen, Prognosen, Risikozielen, Akku, Grenzen und Geräten wird ein unveränderliches Eingabeobjekt (15 min, jetzt bis +48 h). spot_only ohne Formel und fehlende Preise führen in den Modus „flat“ (nur Autarkie), jeweils mit Begründung.
  • LP mit HiGHS (highspy 1.15.1, NumPy 2.5.4):
    • Flussaufteilung: PV deckt zuerst die Grundlast, Geräte bekommen nur PV-Überschuss (strukturell, nie Netzstrom), der Akku entlädt nur für die Grundlast.
    • Getrennte Wirkungsgrade, Untergrenze effective_reserve_pct, Import- und Exportgrenze.
    • Netzladen nur bei bekanntem Preis, innerhalb von Preisgrenze und Zeitplan und wenn sich die Spreizung lohnt.
    • Morgenpuffer, Abendziel und Nutzerziel sind weiche Ziele mit Strafkosten.
    • Zielfunktion: Kosten + Degradation + Autarkiegewicht 0,01 − Gerätewert − Wert der Restenergie im Akku am Horizontende.
    • Keine Binärvariablen. Warmstart, Zeitbudget 8 s.
  • Heuristik als Fallback, gleiches Plan-Format.
  • Fallback-Kette: optimal → Zwischenlösung → Heuristik. Jeder Wechsel hat eine Begründung (timeout, infeasible, error, invalid_solution, solver_unavailable, heuristic_better).
  • „Warum?“ je Intervall (46 Schlüssel planner.*, en/de).
  • BatteryBand/DeviceBand je Intervall nach ADR-0013, inkl. priority_until_soc_pct, discharge_lock und grid_charge_max_w (bis 4-G nur Vorbereitung).
  • scripts/bench_planner.py mit dem Referenzhaus des Maintainers.

WP9 – Laufzeit (suncore/app/planning.py):

  • Wann geplant wird: alle 15 min, außerdem bei neuen Preisen, neuer Prognose, Konfigurationsänderung, Override, manuellem Neuplanen und Abweichung (SoC > 10 %-Punkte, Netz > 1,5 kW über 30 min).
  • Ablauf:
    • Debounce und immer nur ein Lauf gleichzeitig.
    • Der Solver läuft in einem Daemon-Thread, der Plan wird atomar an den Regler übergeben.
    • Pro Lauf wird ein Snapshot gespeichert.
  • Fehlerfall: Ein Plan ohne erfolgreichen Folgelauf gilt nach 2 h als veraltet. Ein veralteter oder fehlender Plan bedeutet für den Regler Plan.default(), also das Verhalten aus Phase 3.
  • Regler:
    • priority_until_soc_pct wird in jedem Takt gegen den gemessenen SoC geprüft.
    • goals.battery_target bleibt eine Untergrenze: Unter dem Ziel hat der Akku Vorrang, egal was der Plan sagt.
    • Bänder wirken nur, solange ein Plan-Intervall den aktuellen Zeitpunkt abdeckt.
  • API:
    • GET /api/v1/plan (Plan mit Flüssen, Preisen, Bändern, Begründungen, Status)
    • GET /api/v1/plan/status
    • POST /api/v1/plan/replan (202)
    • Live-Nachricht plan
  • Demo: zeigt einen echten Plan.

Warum

Das ist das Herzstück von Phase 4: ein Fahrplan mit Akku-Strategie und „Warum?“ (BRIEF §4.8, Plan §0).

Wie getestet

  • ./scripts/check.sh grün: 4353 Python-Tests, 219 Frontend-Tests. markdownlint ohne Fehler.

  • Hypothesis-Tests, jeweils für Solver und Heuristik:

    • Energiebilanz und SoC-Korridor halten.
    • Netzladen nur nach Policy und nur mit bekanntem Preis (auch im Flat-Modus geprüft).
    • Importgrenze hält; kein Export in Slots, in denen die Negativpreis-Regel greift.
    • Geräte nie über dem PV-Überschuss.
    • Kein Export, solange ein erlaubtes Gerät mit Wert über dem Einspeisepreis noch Luft hat.
    • Kosten LP ≤ Heuristik unter derselben Kostenfunktion.
    • Ziele werden erreicht, wenn das möglich ist (geprüft mit einem unabhängigen Max-SoC-LP).
  • Neun Szenarien:

    Szenario Ergebnis
    Sonniger Tag Geräte bekommen den Überschuss, sobald der Akku voll ist
    Referenzhaus wie oben, auch an Tag 1
    prefer_full wie oben
    Zwei schwache Tage Abendziel auf Maximum, Geräte gesperrt
    Preisspitze Akku wird für die Spitze aufgespart
    Negative Preise Abregeln statt Einspeisen, Akku hält Platz frei
    Netzladen nach Preisgrenze nur unter der Grenze und im Zeitplan
    Zu optimistische Prognose stündliche Neuplanung
    Fallback-Kette Wechsel greift jeweils mit Begründung
  • Regler:

    • Property: Ein Plan hebt ein Gerät nie über das Verhalten ohne Plan.
    • Property: Unter max(Priorität, Nutzerziel) bekommen Verbraucher nie mehr als ohne Plan.
    • Test mit Bändern, die alle 15 min zwischen erlaubt und gesperrt wechseln: Schaltspiele/h ≤ Grenze, Mindestlaufzeit hält.
  • Szenario planner_in_shadow (6 h mit echtem Planer): Es wird nichts geschrieben, keine BatteryAction, und controller.plan_blocked taucht als „hätte“-Grund auf.

  • Laufzeit:

    • Ein hängender Solver verzögert die Geräte-Freigabe beim Stoppen nicht.
    • GIL-Test mit großem Modell: HiGHS gibt den GIL frei (gemessen auf amd64).
  • Rechenzeit Referenzhaus (17 kWp Ost-West, 29,6 kWh, Tibber, 13,5 kW Exportgrenze, 2 Klimageräte; 193 Slots, 2318 Variablen, 0 Binärvariablen): Solve ≈ 4–5 ms, ganzer Lauf ≈ 25–35 ms (amd64).

Risiken

  • Rechenzeit auf aarch64 (Raspberry Pi 4, HA Green) noch nicht gemessen (UNVERIFIED). Das Budget beträgt 8 s; das gemessene Ergebnis liegt bei Millisekunden.
  • Gewichte (Zielstrafen, Wert der Restenergie, automatischer Gerätewert) und Abweichungsschwellen sind begründet, aber nicht am echten System eingestellt.
  • Neue Abhängigkeiten highspy und numpy: musllinux-Wheels für aarch64 und x86_64 sind vorhanden, das Image wird größer. Der Speichertest im Smoke-Test bleibt bestehen.
  • Commit-Historie enthält einen WIP-Sicherungscommit. Squash-Merge empfohlen.

Safety-Review

control-safety: freigegeben nach Behebung von M1 (Commit 5349b3b).

  • Invarianten aus BRIEF §5 erfüllt: Die Safety-Schicht ist unverändert, apply() wird nur aus safety/ aufgerufen.
  • Geräte: Ein Plan kann Geräte nur einschränken (allowed=False / max_power_w senken die Obergrenze, prefer_on erzwingt nichts). Erzwungenes Herunterschalten respektiert Mindestlaufzeit, Mindestpause und Schaltspiele pro Stunde.
  • Akku: Der Regler erzeugt keine BatteryAction. Das Gate lehnt sie auch mit Plan weiter ab.
  • Rückfall: Ein fehlender, abgelaufener oder älter als 2 h gewordener Plan sowie ein Fehler im Plan-Provider führen zum Verhalten aus Phase 3. Bei unbekanntem SoC und gesetzter Priorität bleibt der Akku vorn.
  • Stoppen: Die Geräte werden freigegeben, bevor auf den Planer-Task gewartet wird.
  • M1 (behoben): Ein Plan-Band konnte das Akku-Ziel des Nutzers übersteuern. Jetzt wirkt goals.battery_target als Untergrenze; dazu gibt es einen Property-Test.
  • Kleinere Punkte (alle behoben): Schwingungstest mit wechselnden Plänen, Hysterese für knappe Ziele, Plan-Alter ab Übergabe, Shadow-Szenario ohne BatteryAction, GIL-Test, kein Band ohne Akku-Modell.

Checkliste

  • Tests für neues Verhalten, Lint/Typen/Tests grün
  • Keine hardcodierten UI-Strings; neue Keys in en und de
  • Doku aktualisiert (Plan-Abweichungen, architecture.md, Experten-Umgebungsvariablen in DOCS.md)
  • docs/STATUS.md aktualisiert
  • Nichts erfunden; Offenes als UNVERIFIED

Offene Fragen an den Maintainer

Ohne Antwort gilt jeweils der Standard.

  1. Gerätebudget: Vor dem Abendziel bekommen Geräte den Überschuss bei P50, plus allen PV-Strom, den ein voller Akku nicht mehr aufnehmen kann. Die Vorsicht steckt nur im Abendziel (Plan §0, keine doppelte Vorsicht). Standard: so lassen.
  2. Ohne Preise oder bei Börsenpreis ohne Formel plant SunCore nur auf Autarkie, ohne Netzladen. Standard: so lassen.
  3. Negativpreis-Slots (Regel de): abregeln statt mit 0 vergütet einspeisen. Das Abregeln ist bis Phase 6 nur informativ. Standard: so lassen.
  4. Planer-Gewichte kommen in Phase 5 in den Expertenmodus. Standard: ja.
  5. Veralteter Plan: Älter als 2 h heißt für den Regler „wie ohne Plan“. Standard: so lassen.
  6. POST /plan/replan bekommt keine eigene Admin-Berechtigung, nur den Peer-Check wie die anderen ändernden Routen. Standard: so lassen.
  7. UNVERIFIED: Rechenzeit und GIL-Freigabe auf aarch64; Abweichungsschwellen.

Generated by Claude Code

claude added 18 commits October 17, 2026 03:39
…e (WP4)

Template-driven price adapter (action or attribute source, list or mapping shape, per-MWh
conversion, native 15/60-minute grid from the data, gaps as None, DST safe), templates for Tibber,
Nord Pool, ENTSO-E, EPEX Spot, Octopus Energy and a generic price list, fixed and HT/NT sources,
the price formula on spot-only sources, export fixed/tiered/none, the region's negative-price
rule, and a TariffService that keeps the prices fresh, stores them in timeseries.db and serves
them on GET /api/v1/prices. The simulator answers tibber.get_prices through the same template
path; new scenario negative_prices.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
…es (review M1-M3)

M1: a failed fetch consumes the dirty flag and a change triggers at most one attribute fetch per
30 s, so a failing attribute source no longer refetches on every poll.
M2: a fetch without any known price is a failure; unknown slots of a fetch are filled from the
earlier data and reported as quality.carried_slots.
M3: the old tail starts at the next whole old slot (no overlap when the grids differ); the
series assembly for storing runs inside the try block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
… list-end gaps (review M4, m2, m4)

M4: pynordpool/HA source show that `date` is the CET delivery day (deliveryDateCET); the template
gets the additive `date_tz` field (schema changelog), request dates are computed in that zone and
the "tomorrow covered" test uses the market's end of day, so it terminates west of CET too.
Research note with repo@sha paths in docs/research/integrations.md.
m2: a source in another currency than the region (sensor unit, template unit, `currency` action
field) raises CurrencyMismatchError (en/de key).
m4: core/series.py segments_from_points (4-A code): at the end of a list a gap that is a multiple
of the running step is a gap (None), not a resolution change; the rhythm needs a confirming
distance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
…its (review m1, m3, m5, n1-n5)

m1: system check warns about a spot-only import price without a price formula; PriceReport
carries price_includes and formula_missing; PUT /config/tariff rejects a missing required
request field of the template (422, en/de key); STATUS records that the 4-F planner must refuse
spot_only prices without a formula.
m3: the three tariff settings are documented as expert environment variables in both app
DOCS.md files (no app options); plan question wording fixed.
m5: plan question on the per-plant opt-out of the section 51 EEG rule (commissioning date).
n1: architecture table and diagram: tariff no longer depends on ha. n2: EPEX market template
text. n3: ambiguous-series names are joined before ICU. n4: adapters docstring. n5: tests use
end_price, apply is marked as a deprecated alias.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
Resolves runtime.stop (tariff task joins the storage tasks that are awaited after the
devices are released) and STATUS; the fake-price test uses rate-limit sub-keys now that
the fake is rate limited like the real connection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
The planner needs prices (4-C) and forecasts (4-D/4-E); both sides are kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
…tests (WP8, part 1)

HiGHS LP behind a SolverBackend protocol, pure PlannerInputs builder, rule-based
fallback with the same schedule shape, interval explanations, additive plan v2
fields (BatteryBand.grid_charge_max_w/discharge_lock, IntervalFlows.devices_w/
curtail_w) and planner scenarios of the virtual house.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
…anations (WP8)

Scenario tests, rolling replay with a too optimistic forecast, the device budget
on PV at the risk quantile, fallback-chain tests with fake backends, the
reference-house benchmark (scripts/bench_planner.py, slow test < 3 s) and the
contract tests for the additive plan v2 fields.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
…numbers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
Snapshot so nothing is lost when the usage limit stops the session; not yet checked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
…controller (WP9)

PlanningService (suncore/app/planning.py): quarter-hour cadence plus events (prices,
forecasts, deviation, configuration, override, manual replan), debounce, single flight, solve
in a daemon thread with budget and warm start, plan snapshots, last good plan kept on failure,
stale after 2 h and Plan.default() for the controller. Controller: priority_until_soc_pct is
judged against the live SoC, a battery band applies only while a plan interval covers now.
API: GET /api/v1/plan, GET /api/v1/plan/status, POST /api/v1/plan/replan, live message
"plan". Demo and scenario planner_in_shadow run the planner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
… flapping-band and shadow tests (review D1, cs m1, m4)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
…rid charging without a price, curtail in negative-rule slots, early-charge tie-breaker, band hysteresis (review D2-D4, B1, M3, m1-m6, n2, cs m2/m5/m6)

- grid charging needs a known price (flat mode included); property generator covers flat mode
- export where the negative-price rule zeroed the export price costs more than curtailment
- device budget: battery-first day on P50 plus the PV overflow it cannot absorb
- PV charging tie-breaker falling over the horizon (part of objective())
- numpy declared; full evening target due at the start of the evening deficit
- morning-buffer reason names the reachable SoC, priority only until the buffer's slot
- no load forecast: flat 500 W (or a passed recent mean) and no devices, with a reason
- IntervalPrices.estimated for median stand-ins, never cited in hold_for_price
- violations() checks the flow split and the import limit
- heuristic battery-first window equals the LP's; tight hysteresis against the previous plan
- no planner battery: PlanInterval.battery is None (goal rules stay in charge)
- GIL test: HiGHS releases it while solving (slow test)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
…m the hand-over (review m8, n3)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHXsfH6PkT62o9idByAd6e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants