Reading a cumulative sum plot
The slope of
A pipe that leaks one cubic metre an hour loses 720 cubic metres in a month, and every one of them was pumped and paid for. A pump that needs a little more energy for each cubic metre every week is never “broken” on any single day, so nobody reports it until the bill is a tenth higher. In both cases the readings held the answer for weeks. After “has something changed?” comes “since when?”, because the date tells you what was lost. This lesson shows how to date a sudden step with a cumulative sum, and how to measure a slow drift with a slope and an honest range. #CUSUM #ChangeDetection #LeakDetection
By the end of this lesson, you will be able to:
A borehole pump supplies a small estate. A flow meter and a power meter are read every hour for 60 days. In the day the users draw about 4.6 m³/h. At night, between 22:00 and 06:00, they draw about 0.6 m³/h. The operator has two questions about these 60 days.
The first: the monthly volume has risen, and nobody on the estate reports using more water. Is there a leak, since which day, and how much water has it cost? A leak flows at every hour. In the day it hides inside a demand that moves by half a cubic metre an hour from one hour to the next; at night the demand is small and steady, which is why water engineers watch the night flow.
The second: the pump is some years old. Is the energy used for each cubic metre rising, how fast, and when will it reach the level at which the pump is taken out for overhaul?
The first change happened on one date. The second has no date at all, only a rate. They need different tools.
A step is a change of the mean at one time, with one mean before it and another after: a pipe breaks, a valve is left open, a sensor is replaced. The questions are when, and how large.
A drift is a change that grows a little in every period: a pump impeller wears, a condenser collects dust, a sensor ages. The question is how fast.
Choose a reference mean
Reading a cumulative sum plot
The slope of
Only the slope carries meaning, not the height of
The plot is read by eye. To give an alarm by rule, the tabular CUSUM is used. For an upward change it keeps one number:
Two things differ from the plain cumulative sum: a reference value
Both
The tabular CUSUM also dates the change. Count
Dating and sizing a step
The change is estimated to have begun in the first period after the last time the statistic was zero before the signal. At the signal, the size of the step is estimated as
Once the date is known, a better estimate of the size is the mean of all readings after the date minus
For a drift, fit a straight line to the daily values
Confidence interval of a slope
A slope is well known when the scatter
The interval is honest only if the residuals of the line are close to independent and the drift really is a straight line. Autocorrelated residuals make the true uncertainty larger than the formula says.
If the line continues, it reaches a limit
This range assumes that the wear continues at the same rate. That is an assumption about the machine, not a result of the statistics.
Each tool gives a wrong but confident answer on the other kind of change. A line fitted through a step reports a “drift” that does not exist. A CUSUM run on a drift signals correctly that the mean has moved, but its start date has no meaning, because a drift has no start inside the record. When a series has both, date the step with the CUSUM, then fit one model with a slope term and a step term (0 before the date, 1 from it), and read each coefficient with its own interval.
Night flow of each day. The mean of the eight night hours gives 60 values. Days 33 to 36 are 0.621, 0.554, 1.513 and 1.486 m³/h. ✅
Reference mean. The mean of days 0 to 19 is
Reference standard deviation. The sample standard deviation of the same 20 values is
Level part.
Rising part. On day 59,
Slope after the turn.
The mean night flow of days 35 to 59 is 0.901 m³/h above the reference. ✅
Settings.
Before day 35. The largest value of
Day 35.
This is above
Date. The statistic was last zero on day 34 and
Size at the signal.
Size from all days after the date. The mean night flow of days 35 to 59 is 1.4989, so the step is
Each day.
To the end of the record. Days 35 to 59 are 25 days:
This leak is 33 times the standard deviation of the night flow, so any method finds it on the first day. The check asks what the same method does with a leak of 0.03 m³/h (1.1 standard deviations), made by subtracting 0.87 m³/h from the night flow of days 35 to 59.
Single readings. The first night flow above
Tabular CUSUM. It signals on day 40, with
Size.
Check it on site. A method that has never seen a known leak is not yet proven. Open a hose at night with a flow measured by a bucket and a stopwatch, for example 0.10 m³/h for three nights, and confirm that the night flow rises by that amount and the CUSUM signals. Some flow meters do not register flow below a starting value, and a leak smaller than that never reaches the data; the hose test shows this too. ✅
Daily values. On day 0 the pump used 31.81 kWh for 76.75 m³, which is 0.4144 kWh per m³. On day 59 the value is 0.4602. ✅
Sums. With
Slope.
The specific energy rises by about 0.00065 kWh per m³ each day. ✅
Intercept.
Scatter about the line.
Standard error of the slope.
The slope is known to about 4 percent of its value. ✅
Interval. The t value for 95 percent and 58 degrees of freedom is 2.002.
The interval is far from zero (the slope is 27 standard errors). The drift is real. ✅
In plain terms. Over the 60 days the fitted value rose by
Compare with the truth. This data set was generated with a drift of exactly 0.0006 a day. The interval, 0.000604 to 0.000699, just misses it. That is not an error in the calculation. A 95 percent interval misses the true value for about one data set in twenty, and this is one of them. ✅
Best estimate.
The line reaches 0.50 kWh per m³ during day 124, which is 3 July 2026. ✅
Earliest, with the upper end of the slope interval.
Day 118 is 27 June 2026. ✅
Latest, with the lower end.
Day 132 is 11 July 2026. ✅
The honest statement. “At the present rate the pump reaches 0.50 kWh per m³ about day 125, with a range of day 118 to day 132, if the wear continues in a straight line.” The true line of the generator reaches the limit on day 133, just outside this range, for the reason given in Step 2. The prediction also lies 65 days beyond the last reading, more than the length of the record itself. ✅
Check the range a second way. The shortcut above turns the line about
Library check. scipy.stats.linregress returns a slope of 0.000652 and a standard error of 0.0000239, the same as the hand formulas. ✅
Check without regression. The mean of the last 10 days is 0.4542 and the mean of the first 10 days is 0.4220. Their centres are 50 days apart, so the rate is
Independence. The lag-1 autocorrelation of the residuals is
A line through the night flow. It gives a slope of 0.0218 m³/h a day with
A CUSUM on the specific energy. With days 0 to 19 as reference it signals on day 24 and reports a start on day 15. The signal is correct, the date is meaningless: the wear began before the record did. ✅
Both terms together. A model of the night flow with a slope and a step at day 35 gives a slope of
The script generates the borehole data, forms the night flow, runs both forms of the CUSUM, then fits the drift of the specific energy and its interval. It saves one plot with the night flow, the two CUSUM curves and the fitted line.
"""A step found with a CUSUM and a drift found with a regression slope (borehole pump)."""import datetimeimport numpy as npfrom scipy import statsimport matplotlib.pyplot as plt
def borehole_hourly(seed=37, days=60): rng = np.random.default_rng(seed) h = np.arange(days * 24); hour = h % 24 demand = np.where((hour >= 6) & (hour < 22), 4.6, 0.6) # m3/h drawn by users demand = demand * (1.0 + rng.normal(0, 0.12, h.size)) leak = np.where(h >= 35 * 24, 0.9, 0.0) # a leak starts on day 35 flow = np.clip(demand + leak, 0, None) # m3/h kwh_per_m3 = 0.42 + 0.0006 * (h / 24.0) # slow wear: rising power = flow * kwh_per_m3 * (1.0 + rng.normal(0, 0.03, h.size)) # kW return h, flow, power
def tabular_cusum(x, mu0, k, h): """Upper tabular CUSUM. Returns C, the count N since the last zero, first signal index.""" c = np.zeros(x.size) n = np.zeros(x.size, dtype=int) prev, count, signal = 0.0, 0, None for i, v in enumerate(x): prev = max(0.0, prev + v - mu0 - k) count = count + 1 if prev > 0.0 else 0 c[i], n[i] = prev, count if signal is None and prev > h: signal = i return c, n, signal
h_idx, flow, power = borehole_hourly()flow_d = flow.reshape(60, 24) # row = day, column = hour of the daypower_d = power.reshape(60, 24)days = np.arange(60)
# ---------- Application 1: night flow and the leak ----------NIGHT = [0, 1, 2, 3, 4, 5, 22, 23] # the eight night hours of one calendar daynight = flow_d[:, NIGHT].mean(axis=1)mu0 = night[:20].mean()sigma = night[:20].std(ddof=1)print("Application 1: mean night flow of each day (m3/h)")print(f" reference, days 0 to 19: mean {mu0:.4f}, s {sigma:.4f}")print(f" days 33 to 36: " + " ".join(f"{v:.3f}" for v in night[33:37]))
S = np.cumsum(night - mu0)print(f" cumulative sum: day 19 {S[19]:.3f}, day 34 {S[34]:.3f}, day 59 {S[59]:.3f}")print(f" slope of the cumulative sum, days 35 to 59: {(S[59] - S[34]) / 25:.4f} m3/h")
k, h = 0.5 * sigma, 5.0 * sigmaC, N, sig = tabular_cusum(night, mu0, k, h)start = sig - N[sig] + 1print(f" tabular CUSUM: k {k:.4f}, h {h:.4f}")print(f" largest C before day 35: {C[:35].max():.4f} on day {int(C[:35].argmax())}")print(f" signal on day {sig}: C {C[sig]:.4f}, N {N[sig]}, estimated start day {start}")print(f" step from the CUSUM, k + C/N: {k + C[sig] / N[sig]:.3f} m3/h")step = night[start:].mean() - mu0print(f" mean night flow from day {start}: {night[start:].mean():.4f}, step {step:.4f} m3/h")left = 60 - startprint(f" water lost: {step * 24:.1f} m3 a day, {step * 24 * left:.0f} m3 in {left} days")
# the same data with a leak of 0.03 m3/h (the clip in the generator is never active)small = night.copy()small[35:] -= 0.9 - 0.03C2, N2, sig2 = tabular_cusum(small, mu0, k, h)beyond = np.where(small > mu0 + 3.0 * sigma)[0]print(f" leak of 0.03 m3/h: CUSUM signal day {sig2}, N {N2[sig2]}, start day " f"{sig2 - N2[sig2] + 1}, step {k + C2[sig2] / N2[sig2]:.3f} m3/h")print(f" leak of 0.03 m3/h: first single day above mean + 3 s: day {beyond[0]}")
# ---------- Application 2: drift of the specific energy ----------energy = power_d.sum(axis=1) * 1.0 # kWh a day (hourly kW x 1 h)volume = flow_d.sum(axis=1) * 1.0 # m3 a dayy = energy / volume # kWh per m3x = days.astype(float)n = x.sizeprint("Application 2: daily kWh per m3")print(f" day 0: {energy[0]:.2f} kWh / {volume[0]:.2f} m3 = {y[0]:.4f}; day 59: {y[59]:.4f}")
x_bar, y_bar = x.mean(), y.mean()Sxx = ((x - x_bar) ** 2).sum()b1 = ((x - x_bar) * (y - y_bar)).sum() / Sxxb0 = y_bar - b1 * x_barres = y - (b0 + b1 * x)s_e = np.sqrt((res ** 2).sum() / (n - 2))se_b1 = s_e / np.sqrt(Sxx)t = stats.t.ppf(0.975, n - 2)lo, hi = b1 - t * se_b1, b1 + t * se_b1print(f" x mean {x_bar:.1f}, y mean {y_bar:.5f}, Sxx {Sxx:.0f}, Sxy {b1 * Sxx:.3f}")print(f" line: {b0:.5f} + {b1:.7f} day, RMSE {s_e:.5f}")print(f" SE of slope {se_b1:.7f}, t {t:.3f}, 95 % interval {lo:.7f} to {hi:.7f}")print(f" slope / SE = {b1 / se_b1:.1f}; rise over 60 days {100 * b1 * 60 / b0:.1f} %")r1 = np.corrcoef(res[1:], res[:-1])[0, 1]print(f" lag-1 autocorrelation of the residuals {r1:.2f}")chk = stats.linregress(x, y)print(f" scipy linregress: slope {chk.slope:.6f}, SE {chk.stderr:.7f}")print(f" last 10 days minus first 10 days, over 50 days: " f"{(y[-10:].mean() - y[:10].mean()) / 50:.6f}")
LIMIT = 0.50cross = (LIMIT - b0) / b1early = x_bar + (LIMIT - y_bar) / hilate = x_bar + (LIMIT - y_bar) / loprint(f" line reaches {LIMIT:.2f} on day {cross:.1f} (range {early:.1f} to {late:.1f})")day0 = datetime.date(2026, 3, 1) # an example start date for day 0for label, v in (("best", cross), ("early", early), ("late", late)): print(f" {label}: {day0 + datetime.timedelta(days=int(v))}")
# the wrong tool for each jobwrong = stats.linregress(x, night)print(f" a line through the night flow: slope {wrong.slope:.4f} m3/h a day, " f"R2 {wrong.rvalue ** 2:.2f}")A = np.column_stack([np.ones(n), x, (x >= start).astype(float)])coef, *_ = np.linalg.lstsq(A, night, rcond=None)r3 = night - A @ coefse3 = np.sqrt(np.diag((r3 ** 2).sum() / (n - 3) * np.linalg.inv(A.T @ A)))t3 = stats.t.ppf(0.975, n - 3)print(f" line plus a step at day {start}: slope {coef[1]:.4f} +/- {t3 * se3[1]:.4f}, " f"step {coef[2]:.3f} +/- {t3 * se3[2]:.3f} m3/h")mu_y, s_y = y[:20].mean(), y[:20].std(ddof=1)C3, N3, sig3 = tabular_cusum(y, mu_y, 0.5 * s_y, 5.0 * s_y)print(f" a CUSUM on kWh per m3: signal day {sig3}, 'start' day {sig3 - N3[sig3] + 1}")
# ---------- Plot ----------fig, ax = plt.subplots(3, 1, figsize=(8, 10))ax[0].plot(days, night, "o-", markersize=3)ax[0].axhline(mu0, color="gray", linewidth=0.8, linestyle="--")ax[0].set_ylabel("night flow (m3/h)")ax[0].set_title("Mean night flow of each day")ax[1].plot(days, S, label="cumulative sum of deviations")ax[1].plot(days, C, label="tabular CUSUM")ax[1].axhline(h, color="gray", linewidth=0.8, linestyle="--")ax[1].set_ylabel("m3/h")ax[1].set_title("Both forms of the CUSUM")ax[1].legend()ax[2].plot(days, y, ".", label="daily value")ax[2].plot(days, b0 + b1 * x, label="fitted line")ax[2].set_xlabel("day")ax[2].set_ylabel("kWh per m3")ax[2].set_title("Drift of the specific energy")ax[2].legend()fig.tight_layout()fig.savefig("step_and_drift.png", dpi=120)print("Saved step_and_drift.png")Expected output
Application 1: mean night flow of each day (m3/h) reference, days 0 to 19: mean 0.5977, s 0.0269 days 33 to 36: 0.621 0.554 1.513 1.486 cumulative sum: day 19 0.000, day 34 0.085, day 59 22.614 slope of the cumulative sum, days 35 to 59: 0.9012 m3/h tabular CUSUM: k 0.0134, h 0.1345 largest C before day 35: 0.0861 on day 26 signal on day 35: C 0.9020, N 1, estimated start day 35 step from the CUSUM, k + C/N: 0.915 m3/h mean night flow from day 35: 1.4989, step 0.9012 m3/h water lost: 21.6 m3 a day, 541 m3 in 25 days leak of 0.03 m3/h: CUSUM signal day 40, N 6, start day 35, step 0.040 m3/h leak of 0.03 m3/h: first single day above mean + 3 s: day 48Application 2: daily kWh per m3 day 0: 31.81 kWh / 76.75 m3 = 0.4144; day 59: 0.4602 x mean 29.5, y mean 0.43799, Sxx 17995, Sxy 11.726 line: 0.41877 + 0.0006516 day, RMSE 0.00320 SE of slope 0.0000239, t 2.002, 95 % interval 0.0006038 to 0.0006994 slope / SE = 27.3; rise over 60 days 9.3 % lag-1 autocorrelation of the residuals -0.06 scipy linregress: slope 0.000652, SE 0.0000239 last 10 days minus first 10 days, over 50 days: 0.000644 line reaches 0.50 on day 124.7 (range 118.1 to 132.2) best: 2026-07-03 early: 2026-06-27 late: 2026-07-11 a line through the night flow: slope 0.0218 m3/h a day, R2 0.72 line plus a step at day 35: slope -0.0002 +/- 0.0008, step 0.905 +/- 0.030 m3/h a CUSUM on kWh per m3: signal day 24, 'start' day 15Saved step_and_drift.png1. A bearing temperature has a reference mean of 12.0 °C above ambient. Ten daily values follow: 12.1, 11.9, 12.0, 12.2, 11.8, 12.6, 12.5, 12.7, 12.4, 12.6. Calculate the cumulative sum of deviations. After which reading does the slope change, and what is the size of the step?
2. A process has
3. A night-flow CUSUM dates a leak of 0.35 m³/h to 18 days ago. The pump uses 0.45 kWh for each cubic metre. Find the water and the energy lost so far, assuming the leak flows at every hour.
4. A motor winding temperature is recorded at the same load once a day for 30 days (
5. For the motor of exercise 4, the mean of the 30 temperatures is 62.0 °C at
Best estimate:
The night flow of a borehole is 0.60 m³/h and moves by about 0.03 m³/h from night to night. A small leak of 0.03 m³/h starts on day 35. Which method shows it first?
The night flow of the borehole in Application 1, day by day. The reference is days 0 to 19 (mean 0.5977, s 0.0269 m³/h), with k = 0.5 s and h = 5 s. The plain cumulative sum turns where the mean changes. The tabular CUSUM subtracts k from every night, cannot fall below zero, and signals when it passes h. Its start date is the day after it was last zero.
Three questions. Each wrong choice is a mistake people really make, so read the note after you answer.
1. A tabular CUSUM has μ₀ = 20, k = 0.5 and h = 5. The readings are 20.5, 19.8, 21.6, 21.4, 21.8, 21.7, 21.9. It signals at the seventh reading. From which reading do you date the change?
2. A colleague fits a straight line to 60 days of night flow and reports: drift of 0.0218 m³/h a day, R² = 0.72. What do you do before anyone acts on it?
3. A drift line has a slope of 0.0010 kWh per m³ a day, with a 95 percent interval of 0.0006 to 0.0014. The fitted value is 0.44 at day 29.5 and the overhaul limit is 0.50. What goes in the report?
No comments yet. Questions, results from your own build, a better way to explain it: all welcome.
Kept on this device only. Nothing is sent anywhere.
Tip: select words in the lesson, or tap a figure or an equation, to put a note right there.
The lesson has changed and these words are no longer in it. Your notes are kept, with the words you chose.