DEV Community

Piccione Lassan
Piccione Lassan

Posted on

Record and Fit a Wort Cooling Curve in Python

This technical guide is published by BeerCoolin, a UK brand making stainless steel immersion wort chillers. It includes one link to our website.

After the boil, the useful question is not “is the wort cooling?” It is “when will it reach the temperature I actually intend to pitch at?” Guessing from the side of the kettle is how batches get pitched too hot, or sit too long in a lukewarm range you did not plan for. A short temperature log and a simple model will answer the question more honestly than a single probe glance.

This article is a repeatable workflow you can run on a brew day: capture a cooling curve as a CSV file, load it in Python, fit an exponential cooling model, and estimate the remaining time to a target pitch temperature. The maths is ordinary Newton cooling. The code is short, and you can complete the same steps with a USB temperature probe or with a thermometer and a kitchen timer if that is what you have.

What you need

  • Python 3.10 or newer, plus numpy and matplotlib. A virtual environment is enough:
python3 -m venv .venv
source .venv/bin/activate
pip install numpy matplotlib
Enter fullscreen mode Exit fullscreen mode
  • A temperature probe you trust in hot wort, or a brewing thermometer and a timer. If you use a USB or serial probe, confirm it is rated for the liquid and the temperature range. Do not drop an unsealed board into the kettle.
  • A notebook, laptop, or any machine that can write a CSV file during the chill.
  • The target pitching temperature for the yeast you are using, in the same unit as the log. This workflow uses Celsius.

Create a working folder before you start the chill, so you are not inventing filenames later.

mkdir -p "$HOME/brew-logs"
cd "$HOME/brew-logs"
Enter fullscreen mode Exit fullscreen mode

Capture a cooling curve

You need elapsed time and wort temperature, nothing more. Start the clock when the chiller is already in the kettle, the flow is on, and you have stirred once so the first reading is not just a hot surface layer. Keep the probe in the same region of the wort, away from the kettle wall and away from the coldest spot right against the coil.

If you are logging by hand, write a row every one or two minutes. A simple file named cool-down.csv is enough:

time_s,temp_c
0,98.2
60,91.4
120,85.1
180,79.6
240,74.8
300,70.6
360,66.9
420,63.6
480,60.6
540,57.9
600,55.5
Enter fullscreen mode Exit fullscreen mode

The numbers above are an example curve, not a promise of what your kettle will do. Volume, starting temperature, mains-water temperature, flow rate, and how often you stir will all move the line. That is exactly why you should log your own brew day instead of reusing someone else's table.

If you already have a serial probe that prints Celsius readings, you can append rows as they arrive. The sketch below assumes a line-oriented device on /dev/ttyUSB0. Change the port, baud rate, and parse logic to match your probe. Stop if the values look impossible, such as a sudden jump to zero or a reading above boiling at your altitude.

import csv
import time
from pathlib import Path

import serial

port = serial.Serial("/dev/ttyUSB0", 9600, timeout=2)
out = Path("cool-down.csv")

with out.open("w", newline="") as fh:
    writer = csv.writer(fh)
    writer.writerow(["time_s", "temp_c"])
    t0 = time.monotonic()
    while True:
        line = port.readline().decode("utf-8", errors="ignore").strip()
        if not line:
            continue
        try:
            temp_c = float(line.split()[0])
        except ValueError:
            continue
        elapsed = int(time.monotonic() - t0)
        writer.writerow([elapsed, temp_c])
        fh.flush()
        print(f"{elapsed:>5}s  {temp_c:.1f} C")
Enter fullscreen mode Exit fullscreen mode

Stop the script when you reach pitching temperature, or when you decide to change the process. Keep the CSV. The later fit is only as good as this file.

Load the log and look at it first

Before fitting anything, plot the raw points. A messy start, a probe that was lifted out for a moment, or a flow rate you changed halfway through will show up as a kink. If you fit a single exponential through a kink, the remaining-time estimate will look precise and still be wrong.

from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np

path = Path("cool-down.csv")
time_s, temp_c = np.loadtxt(path, delimiter=",", skiprows=1, unpack=True)

plt.figure()
plt.plot(time_s / 60, temp_c, marker="o", linestyle="none")
plt.xlabel("Elapsed time (min)")
plt.ylabel("Wort temperature (C)")
plt.title("Raw cooling curve")
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig("cooling-raw.png", dpi=120)
plt.show()
Enter fullscreen mode Exit fullscreen mode

If the first one or two points are clearly outliers, for example a reading taken before the wort was stirred, drop them in a copy of the file and keep the original. Do not silently edit the only log.

Fit a simple Newton cooling model

Newton's law of cooling says the temperature approaches the temperature of the cooling water at a rate proportional to the difference between them. In discrete form, after you have a series of points, a practical model is:

T(t) = T_w + (T0 - T_w) * exp(-k t)

T_w is the effective temperature the wort is heading towards. For an immersion chiller that is usually close to the mains-water temperature, but not always identical to a single tap reading, because the coil, flow, and mixing are imperfect. k is a rate constant in 1/s. T0 is the temperature at the start of the window you are fitting.

You can fit T0, T_w, and k together, or you can measure the inlet-water temperature and hold T_w fixed. Holding it fixed is cleaner when you trust that measurement. Letting it float is useful when you only have the wort log. The code below lets T_w float, then tells you what it found so you can compare it with a thermometer in the outflow or at the tap.

from numpy.linalg import lstsq

def fit_cooling(time_s, temp_c, tw_guess=15.0):
    """Fit T(t) = Tw + (T0 - Tw) * exp(-k t). Returns T0, Tw, k."""
    t = np.asarray(time_s, dtype=float)
    y = np.asarray(temp_c, dtype=float)

    def residuals(params):
        t0, tw, k = params
        return y - (tw + (t0 - tw) * np.exp(-k * t))

    def pack_error(params):
        r = residuals(params)
        return float(np.dot(r, r))

    t0 = y[0]
    tw = min(tw_guess, y.min() - 0.5)
    # A rough k from a two-point estimate, then a small grid refinement.
    later = max(1, len(y) // 2)
    dt = max(t[later] - t[0], 1.0)
    ratio = max((y[later] - tw) / (t0 - tw), 1e-6)
    k = -np.log(ratio) / dt

    best = (t0, tw, k)
    best_err = pack_error(best)
    for t0_try in (t0 - 1.0, t0, t0 + 1.0):
        for tw_try in np.linspace(max(1.0, tw - 4), tw + 2, 25):
            for k_try in np.linspace(max(k * 0.4, 1e-5), k * 1.8, 25):
                params = (t0_try, tw_try, k_try)
                err = pack_error(params)
                if err < best_err:
                    best, best_err = params, err
    return best, best_err

(params, sse) = fit_cooling(time_s, temp_c)
t0, tw, k = params
rmse = np.sqrt(sse / len(temp_c))
print(f"T0={t0:.2f} C  Tw={tw:.2f} C  k={k:.5f} /s  RMSE={rmse:.2f} C")
Enter fullscreen mode Exit fullscreen mode

The small grid search is deliberate. It is easy to read, it needs no extra solver package, and it is good enough for a brew-day curve with a few dozen points. If you already use scipy.optimize.curve_fit, you can swap it in. Either way, look at the RMSE and at a plot of the fit before you trust the time estimate.

t_line = np.linspace(time_s.min(), time_s.max(), 200)
y_fit = tw + (t0 - tw) * np.exp(-k * t_line)

plt.figure()
plt.plot(time_s / 60, temp_c, "o", label="Measured")
plt.plot(t_line / 60, y_fit, label="Fitted curve")
plt.xlabel("Elapsed time (min)")
plt.ylabel("Wort temperature (C)")
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig("cooling-fit.png", dpi=120)
plt.show()
Enter fullscreen mode Exit fullscreen mode

If the fitted T_w comes out far above your measured mains-water temperature, the model is telling you the wort is not actually approaching the water temperature in this window. Common causes are a low flow rate, a coil that is not fully immersed, or a long stretch with no stirring. Fix the process, then log another few minutes instead of forcing the fit.

Estimate time to pitching temperature

Once you have T0, T_w, and k, the time to a target temperature T_p is just the inverse of the same equation, provided T_p is above T_w. If your target is at or below the fitted water temperature, the model cannot get there and you should not pretend it can. In that case, cooler water, more flow, or more coil surface is a process change, not a spreadsheet trick.

def time_to_target(t0, tw, k, target_c, t_now=0.0):
    if target_c <= tw:
        raise ValueError(
            f"Target {target_c:.1f} C is at or below fitted Tw {tw:.1f} C"
        )
    t_total = -np.log((target_c - tw) / (t0 - tw)) / k
    remaining = t_total - t_now
    return t_total, remaining

TARGET_C = 20.0
t_now = float(time_s[-1])
t_total, remaining = time_to_target(t0, tw, k, TARGET_C, t_now=t_now)
print(f"Target {TARGET_C:.1f} C")
print(f"Estimated total time from t=0: {t_total/60:.1f} min")
print(f"Estimated time still needed:   {remaining/60:.1f} min")
Enter fullscreen mode Exit fullscreen mode

Treat the remaining time as a planning number, not a laboratory certificate. Update it if you change the flow, add ice to a pre-chiller, or start stirring more often. Those changes move k and sometimes T_w, so the honest method is to fit again on the newest stretch of the curve rather than keep an old constant.

A quick check is worth doing after the first ten minutes. Fit on the early window, note the predicted time to target, then compare it with the later measurements. If the later points fall consistently below the prediction, cooling is faster than the early window suggested. If they sit above it, flow or mixing probably dropped off.

Measurement mistakes that wreck the fit

The model is simple, and it will absorb bad data without complaining. These are the failures I watch for.

Do not start the log while the wort is still boiling and the coil is still warming up. The first moments are not Newton cooling of a well-mixed pot; they are a coil coming up to temperature and a surface layer being disturbed. Start after one deliberate stir.

Do not leave the probe against the coil. That reading is the local metal and water film, not the bulk wort you will pitch into. The same is true of a probe sitting in a dead corner while the rest of the kettle is being chilled.

Do not change units mid-file. A couple of Fahrenheit readings in a Celsius column will flatten or invert the curve. Keep the header honest, and convert in the script if you have to.

Do not fit across a process change. If you opened the tap further, or you paused to clean a blockage, split the CSV at that moment and fit the current regime. A single k cannot represent two different flow rates.

Do not ignore a fitted T_w that is obviously wrong, such as 40 C when the tap water is 12 C. The curve may still look smooth. The remaining-time estimate will still be fiction.

What the curve is actually measuring

An immersion chiller is a coil of tubing in the kettle. Cold water runs through the coil, heat moves from the wort into that water, and the warmed water leaves through the outlet hose. The Python model does not need the coil geometry, but it does assume the wort is mixed enough to have one temperature that matters, and that the cooling water is providing a reasonably stable sink temperature.

If you want a straightforward look at the kind of stainless steel immersion chiller this logging method is built around, the official BeerCoolin homepage is here: https://beercoolin.co.uk/.

The same workflow still applies if you chill another way. The CSV format does not change. The only thing that changes is how you interpret k and T_w. A poorly mixed kettle will often produce a low k and a T_w that sits above the true water temperature. That is useful information. It is telling you the probe is watching a slow pocket, or that the coil is not doing much work in the bulk liquid.

Stirring on a schedule, keeping the coil fully immersed, and watching the outlet-water temperature are process controls. The log is how you check whether those controls did what you thought they did.

A small brew-day checklist

  1. Set the target pitch temperature before you start chilling, and write it at the top of the CSV or in a comment file beside it.
  2. Start the clock after the coil is immersed, the flow is on, and the wort has been stirred once.
  3. Log in one unit, at a steady interval, with the probe in the bulk wort.
  4. Plot the raw curve before you fit it.
  5. Fit, inspect T_w and the RMSE, then estimate the remaining time.
  6. If you change the process, start a new fit window.
  7. Keep the CSV with the rest of the brew-day notes so you can compare later batches.

The point of the script is not to decorate a brew day with a chart. It is to replace a vague sense that the kettle is “nearly there” with a number you can check, and with a record you can compare the next time you brew. If the estimate and the later measurements disagree, believe the measurements, change the process or the probe placement, and fit again.

Top comments (0)