Files
brewpi/components/sud_forecast.py
T
jens 567ab80c9c Add a simulation-based Sud forecast, computed server-side
New components/sud_forecast.py: SudForecastEstimator simulates a whole
schedule with the same kind of plant/controller (and the same
configured params - ambient, plant params, pid_type, TempCtrl gains,
heater max power) the server uses for real, by driving a throwaway
Sud/Pot/controller trio through it exactly as tasks/sud.py's SudTask
would. It's pure CPU-bound iteration (no real time/IO), so a multi-
hour brew simulates in well under a second.

tasks/sud.py: SudTask now takes an optional forecast_estimator and
sends its result ({'Forecast': {'T': ..., 'Theta': ...}}) on the Sud
channel after every successful Save/Load, run in a worker thread via
run_in_executor so the ~100-500ms simulation doesn't stall the other
tasks. server/brewpi.py constructs one with the real server's config
and wires it in; AmbientTemp changes update it too.

client/brewpi_gui.py: the quick naive show_schedule() estimate (drawn
immediately on Load, before the server's simulation finishes) is now
superseded by show_precomputed_course() once the Forecast message
arrives - only while not actively running, so it doesn't fight the
dynamic re-anchored view.

Verified: matches a standalone run of the estimator (177 min for
sude/sud_0010.json) and replaces the old naive 164 min estimate live
within a couple seconds of loading.
2026-06-21 16:46:52 +02:00

99 lines
3.6 KiB
Python

from components.plant import Pot
from components.pid import PidFactory
from components.sud import Sud, SudState
# Real schedules need real time to spin up each ramp and settle within this
# tolerance before "reached" fires - matching tasks/sud.py's
# TEMP_REACHED_TOLERANCE exactly is what makes this simulation's predicted
# duration line up with the real run's.
TEMP_REACHED_TOLERANCE = 0.2
# 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): parallel lists of elapsed simulated seconds
and temperature, one point per tick, for the given sud.json
document. 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]
pot = Pot(self.dt, self.plant_params, self.theta_amb)
pot.initial(start_theta)
tc = PidFactory.create(self.pid_type, self.dt, self.tempctrl_params, self.plant_params, theta_amb=self.theta_amb)
tc.set_enabled(True)
tc.set_theta_ist(pot.get_temperature())
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_thermal_params(params['M'], params['C'])
if hasattr(tc, 'set_model_params'):
tc.set_model_params(params['M'], params['C'])
ramp = step.get('ramp')
if sud.state == SudState.RAMPING and ramp is not None:
tc.set_theta_soll(step['temperature'])
tc.set_heatrate_soll(ramp['rate'])
sud.set_on_changed('step', on_step_changed)
t = [0.0]
theta = [pot.get_temperature()]
sud.start()
ticks = 0
while sud.state != SudState.DONE and ticks < MAX_TICKS:
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 abs(tc.get_theta_ist() - tc.get_theta_soll_set()) < TEMP_REACHED_TOLERANCE:
sud.temp_reached()
elif sud.state == SudState.WAIT_USER:
# A real user's confirm time isn't predictable - count it
# as instant for estimation purposes.
sud.confirm()
sud.tick(self.dt)
t.append(t[-1] + self.dt)
theta.append(pot.get_temperature())
ticks += 1
return t, theta