Files
brewpi/components/sud_forecast.py
T
jensandClaude Sonnet 4.6 f1688d3c71 Derive Pot's L/Td from the Sud doc instead of a fixed server default
Sud now parses top-level L/Td fields from sude/*.json (defaulting to 0.2/30,
matching the old hardcoded server constants), and derive_plant_params()
returns them alongside M/C - constant for the whole brew, unlike M/C which
vary per step with grain/water mass. All sude/*.json docs gain explicit
L/Td fields.

Callers (tasks/sud.py, SudForecastEstimator, demo_sud.py) switch from the
narrow set_thermal_params(M, C)/set_model_params(M, C) to the full
set_plant_params(params)/set_model_plant_params(params), since
derive_plant_params() now always returns all four keys; both narrow setters
are removed as dead code.

Caught along the way: Pot.set_plant_params() unconditionally rebuilt the
Delay ring buffer, which was harmless when only ever called once at
construction - but now running on every Sud step change, it was wiping
in-flight delayed power at each step boundary. Fixed to only rebuild when
Td actually changes; verified this restores the exact original forecast
result for sud_0010.json.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DkkuG48uHFCGKe6dPSERFk
2026-06-22 18:45:07 +02:00

127 lines
5.0 KiB
Python

from components.plant import Pot
from components.pid import PidFactory
from components.sud import Sud, SudState
# Safety cap so a schedule whose target a step can never actually reach
# (e.g. a "hold" colder than ambient with no active cooling) can't hang the
# simulation forever - the estimate is simply cut off there.
MAX_TICKS = 200000
class SudForecastEstimator:
"""Predicts how long a Sud schedule will actually take by simulating it
with the same machinery (and params) the real server's brewpi.py wires
up - a fresh Pot and temperature controller of the configured pid_type,
driven through the schedule exactly as tasks/sud.py's SudTask would.
This is deliberately independent of wall-clock/asyncio time: it just
iterates dt-sized ticks as fast as the CPU allows (a multi-hour brew
simulates in well under a second), so it can be run synchronously
whenever a client needs an estimate - the naive "abs(delta)/rate" model
the GUI used to compute itself has no way to see the real PID cascade's
spin-up/settling lag, which is exactly why its estimate drifted so far
from reality (see README.md's "Forecast vs. actual duration")."""
def __init__(self, dt, theta_amb, plant_params, pid_type, tempctrl_params, heater_max_power):
self.dt = dt
self.theta_amb = theta_amb
self.plant_params = plant_params
self.pid_type = pid_type
self.tempctrl_params = tempctrl_params
self.heater_max_power = heater_max_power
def set_ambient_temperature(self, theta_amb):
self.theta_amb = theta_amb
def estimate(self, doc, start_theta=None):
"""Returns (t, theta, final_state, confirm_points): t/theta are
parallel lists of elapsed simulated seconds and temperature,
covering doc['steps'] from the start all the way to the end
(final_state is SudState.DONE), or, in the pathological case of
a step whose target can never actually be reached, wherever
MAX_TICKS cut the simulation off.
A step requiring user confirmation doesn't stop the simulation
either - a human's response time genuinely can't be forecast,
so it's modeled as zero delay (auto-confirmed the instant that
step's hold completes) rather than leaving the estimate stuck
there forever. confirm_points records every place that
assumption was made, as (step_index, t) pairs, so the caller
(tasks/sud.py's SudTask) can correct it once a real
confirmation actually happens: truncate the forecast at that
point and splice in a freshly anchored simulation of the
remaining steps in place of the optimistic guess.
start_theta defaults to the configured ambient temperature - i.e.
a cold start, same as the GUI's static estimate."""
if start_theta is None:
start_theta = self.theta_amb
sud = Sud()
if not sud.load(doc) or not sud.schedule:
return [0.0], [start_theta], SudState.DONE, []
pot = Pot(self.dt)
pot.set_plant_params(self.plant_params)
pot.set_ambient_temperature(self.theta_amb)
pot.initial(start_theta)
tc = PidFactory.create(self.pid_type, self.dt)
tc.set_params(self.tempctrl_params)
if hasattr(tc, 'set_model_plant_params'):
tc.set_model_plant_params(self.plant_params)
if hasattr(tc, 'set_ambient_temperature'):
tc.set_ambient_temperature(self.theta_amb)
tc.set_enabled(True)
tc.set_theta_ist(pot.get_temperature())
# Seed the target at start_theta - this tc is a fresh, throwaway
# instance (unlike the real run's persistent one), so without this
# its theta_soll_set defaults to 0 until a step pushes its own.
# Steps without their own 'temperature' (common now that ramping
# isn't gated by a 'ramp' key - see components/sud.py) rely on
# inheriting whatever target was already running, which for a
# schedule starting mid-brew (the dynamic remaining forecast) is
# start_theta, not 0 - without this, such a schedule's first step
# would have the simulated controller chase 0 degrees indefinitely,
# hitting MAX_TICKS and producing a needlessly huge result.
tc.set_theta_soll(start_theta)
def on_step_changed(step):
if step is None:
return
params = sud.derive_plant_params(step.get('grain_mass', 0), step.get('water_mass', 0))
pot.set_plant_params(params)
if hasattr(tc, 'set_model_plant_params'):
tc.set_model_plant_params(params)
if sud.state == SudState.RAMPING and step['temperature'] is not None:
tc.set_theta_soll(step['temperature'])
tc.set_heatrate_soll(step['ramp']['rate'])
sud.set_on_changed('step', on_step_changed)
t = [0.0]
theta = [pot.get_temperature()]
confirm_points = []
sud.start()
ticks = 0
while sud.state != SudState.DONE and ticks < MAX_TICKS:
if sud.state == SudState.WAIT_USER:
confirm_points.append((sud.index, t[-1]))
sud.confirm()
continue
pot.process()
tc.set_theta_ist(pot.get_temperature())
tc.process()
pot.set_power(max(0, self.heater_max_power * tc.get_power()))
if sud.state == SudState.RAMPING:
if tc.is_holding():
sud.temp_reached()
sud.tick(self.dt)
t.append(t[-1] + self.dt)
theta.append(pot.get_temperature())
ticks += 1
return t, theta, sud.state, confirm_points