SciPy Mini Project
In this project you'll analyse a month of readings from a (simulated) greenhouse temperature sensor, step by step. Real sensor data is messy: it has gaps, glitches and noise on top of the patterns you care about. Cleaning it and extracting the patterns brings together much of the course:
| Step | Task | SciPy tools |
|---|---|---|
| 1 | Generate and inspect the raw data | scipy.stats |
| 2 | Fill gaps and remove glitches | scipy.interpolate, scipy.signal.medfilt |
| 3 | Find the daily cycle | scipy.fft |
| 4 | Fit a model of trend + daily cycle | scipy.optimize.curve_fit |
| 5 | Compare the first and last week | scipy.stats tests |
| 6 | The complete pipeline with a report and a plot | everything |
Every step is a complete program you can run and modify. Because there is no real sensor here, a function make_readings() creates the data from a seeded generator: a slow warming trend, a daily cycle peaking in the afternoon, random noise, a few glitches and some missing readings.
Step 1: Generate and inspect the data
The sensor reports once per hour for 30 days (720 readings). Missing readings are stored as NaN.
import numpy as np
from scipy import stats
def make_readings(seed=2024):
rng = np.random.default_rng(seed)
hours = np.arange(30 * 24)
trend = 18 + 0.05 * hours / 24 # +0.05 C per day
daily = 4 * np.sin(2 * np.pi * (hours - 9) / 24) # peak at 15:00
temp = trend + daily + rng.normal(0, 0.6, hours.size)
glitches = rng.choice(hours.size, 8, replace=False)
temp[glitches] += rng.choice([-15, 15], 8) # sensor spikes
gaps = rng.choice(hours.size, 25, replace=False)
temp[gaps] = np.nan # lost readings
return hours, temp
hours, temp = make_readings()
valid = temp[~np.isnan(temp)]
summary = stats.describe(valid)
print("readings :", temp.size)
print("missing :", int(np.isnan(temp).sum()))
print(f"min / max : {summary.minmax[0]:.2f} / {summary.minmax[1]:.2f}")
print(f"mean : {summary.mean:.2f}")
print(f"kurtosis : {summary.kurtosis:.2f} (large values hint at outliers)")readings : 720
missing : 25
min / max : -0.40 / 37.46
mean : 18.77
kurtosis : 3.58 (large values hint at outliers)
The minimum and maximum are far outside a sensible greenhouse range, and the high kurtosis confirms a few extreme values. Those are the glitches.
Step 2: Clean the data
Two problems to fix, in this order:
- Gaps: interpolate across missing readings. Gaps are short (one or two hours), so linear interpolation is enough.
- Glitches: a median filter over 5 hours removes isolated spikes but keeps the daily shape. We only replace readings that differ a lot from the median-filtered value, so normal readings are untouched.
import numpy as np
from scipy.interpolate import make_interp_spline
from scipy.signal import medfilt
def make_readings(seed=2024):
rng = np.random.default_rng(seed)
hours = np.arange(30 * 24)
temp = 18 + 0.05 * hours / 24 + 4 * np.sin(2 * np.pi * (hours - 9) / 24)
temp = temp + rng.normal(0, 0.6, hours.size)
glitches = rng.choice(hours.size, 8, replace=False)
temp[glitches] += rng.choice([-15, 15], 8)
temp[rng.choice(hours.size, 25, replace=False)] = np.nan
return hours, temp
def clean(hours, temp, threshold=3.0):
ok = ~np.isnan(temp)
filled = temp.copy()
filled[~ok] = make_interp_spline(hours[ok], temp[ok], k=1)(hours[~ok])
smooth = medfilt(filled, kernel_size=5)
spikes = np.abs(filled - smooth) > threshold
filled[spikes] = smooth[spikes]
return filled, int((~ok).sum()), int(spikes.sum())
hours, temp = make_readings()
cleaned, n_filled, n_spikes = clean(hours, temp)
print("gaps filled :", n_filled)
print("spikes fixed :", n_spikes)
print(f"new min / max : {cleaned.min():.2f} / {cleaned.max():.2f}")
print("any NaN left? :", bool(np.isnan(cleaned).any()))gaps filled : 25
spikes fixed : 9
new min / max : 13.18 / 24.45
any NaN left? : False
All eight planted glitches were caught, plus one more reading: hour 47 was a gap right next to the glitch at hour 48, so the interpolation that filled it was dragged towards the spike. The median filter fixed that value too. Filling gaps before removing spikes has this side effect; swapping the order (or ignoring gaps inside the median window) is a possible refinement.
Step 3: Find the daily cycle
Is there really a 24-hour rhythm? The FFT answers without assuming anything. We remove the mean first so the zero-frequency bin doesn't dominate, and express frequencies in cycles per day:
import numpy as np
from scipy.fft import rfft, rfftfreq
from scipy.interpolate import make_interp_spline
from scipy.signal import medfilt
def make_readings(seed=2024):
rng = np.random.default_rng(seed)
hours = np.arange(30 * 24)
temp = 18 + 0.05 * hours / 24 + 4 * np.sin(2 * np.pi * (hours - 9) / 24)
temp = temp + rng.normal(0, 0.6, hours.size)
glitches = rng.choice(hours.size, 8, replace=False)
temp[glitches] += rng.choice([-15, 15], 8)
temp[rng.choice(hours.size, 25, replace=False)] = np.nan
return hours, temp
def clean(hours, temp, threshold=3.0):
ok = ~np.isnan(temp)
filled = temp.copy()
filled[~ok] = make_interp_spline(hours[ok], temp[ok], k=1)(hours[~ok])
smooth = medfilt(filled, kernel_size=5)
spikes = np.abs(filled - smooth) > threshold
filled[spikes] = smooth[spikes]
return filled
hours, temp = make_readings()
cleaned = clean(hours, temp)
spectrum = np.abs(rfft(cleaned - cleaned.mean()))
freqs = rfftfreq(cleaned.size, d=1 / 24) # samples are 1/24 day apart
best = np.argmax(spectrum)
print(f"strongest cycle: {freqs[best]:.2f} cycles per day")
print(f"period : {24 / freqs[best]:.1f} hours")
print(f"amplitude : {2 * spectrum[best] / cleaned.size:.2f} C")strongest cycle: 1.00 cycles per day
period : 24.0 hours
amplitude : 4.01 C
One cycle per day with an amplitude close to 4 °C — exactly the pattern that was built in.
Step 4: Fit a model
Now that we know the period, we fit a model with a meaning for every parameter:
T(h) = base + slope · (h / 24) + amp · sin(2π (h − shift) / 24)base is the starting temperature, slope the warming per day, amp the size of the daily swing and shift the hour at which the sine crosses upward (the daily peak comes 6 hours later).
import numpy as np
from scipy.optimize import curve_fit
from scipy.interpolate import make_interp_spline
from scipy.signal import medfilt
def make_readings(seed=2024):
rng = np.random.default_rng(seed)
hours = np.arange(30 * 24)
temp = 18 + 0.05 * hours / 24 + 4 * np.sin(2 * np.pi * (hours - 9) / 24)
temp = temp + rng.normal(0, 0.6, hours.size)
glitches = rng.choice(hours.size, 8, replace=False)
temp[glitches] += rng.choice([-15, 15], 8)
temp[rng.choice(hours.size, 25, replace=False)] = np.nan
return hours, temp
def clean(hours, temp, threshold=3.0):
ok = ~np.isnan(temp)
filled = temp.copy()
filled[~ok] = make_interp_spline(hours[ok], temp[ok], k=1)(hours[~ok])
smooth = medfilt(filled, kernel_size=5)
spikes = np.abs(filled - smooth) > threshold
filled[spikes] = smooth[spikes]
return filled
def model(h, base, slope, amp, shift):
return base + slope * h / 24 + amp * np.sin(2 * np.pi * (h - shift) / 24)
hours, temp = make_readings()
cleaned = clean(hours, temp)
params, cov = curve_fit(model, hours, cleaned, p0=[18, 0, 3, 8])
errors = np.sqrt(np.diag(cov))
for name, value, err in zip(["base", "slope", "amp", "shift"], params, errors):
print(f"{name:5} = {value:7.3f} +/- {err:.3f}")
residuals = cleaned - model(hours, *params)
print(f"residual std = {residuals.std():.3f} C")
print(f"daily peak at hour {(params[3] + 6) % 24:.1f} of the day")base = 17.968 +/- 0.046
slope = 0.052 +/- 0.003
amp = 3.999 +/- 0.032
shift = 8.949 +/- 0.031
residual std = 0.611 C
daily peak at hour 14.9 of the day
The fitted values land close to the true ones (18, 0.05, 4 and 9), and the residual spread matches the 0.6 °C sensor noise.
Step 5: Is the greenhouse getting warmer?
A slope of 0.05 °C per day sounds small. Is the difference between the first and the last week statistically significant? We compare daily means, which removes the daily cycle, with Welch's t-test, and confirm with the rank-based Mann–Whitney test:
import numpy as np
from scipy import stats
from scipy.interpolate import make_interp_spline
from scipy.signal import medfilt
def make_readings(seed=2024):
rng = np.random.default_rng(seed)
hours = np.arange(30 * 24)
temp = 18 + 0.05 * hours / 24 + 4 * np.sin(2 * np.pi * (hours - 9) / 24)
temp = temp + rng.normal(0, 0.6, hours.size)
glitches = rng.choice(hours.size, 8, replace=False)
temp[glitches] += rng.choice([-15, 15], 8)
temp[rng.choice(hours.size, 25, replace=False)] = np.nan
return hours, temp
def clean(hours, temp, threshold=3.0):
ok = ~np.isnan(temp)
filled = temp.copy()
filled[~ok] = make_interp_spline(hours[ok], temp[ok], k=1)(hours[~ok])
smooth = medfilt(filled, kernel_size=5)
spikes = np.abs(filled - smooth) > threshold
filled[spikes] = smooth[spikes]
return filled
hours, temp = make_readings()
daily_means = clean(hours, temp).reshape(30, 24).mean(axis=1)
first, last = daily_means[:7], daily_means[-7:]
t_res = stats.ttest_ind(last, first, equal_var=False)
u_res = stats.mannwhitneyu(last, first, alternative="greater")
print("first week:", np.round(first, 2))
print("last week :", np.round(last, 2))
print(f"difference of means: {last.mean() - first.mean():.3f} C")
print(f"Welch t-test : t = {t_res.statistic:.2f}, p = {t_res.pvalue:.2e}")
print(f"Mann-Whitney : p = {u_res.pvalue:.5f}")
trend = stats.linregress(np.arange(30), daily_means)
print(f"trend from daily means: {trend.slope:.4f} C/day (R^2 = {trend.rvalue ** 2:.3f})")first week: [18.03 17.97 18.1 18.22 18.13 18.14 18.57]
last week : [19.17 19.21 19.43 19.34 19.37 19.35 19.49]
difference of means: 1.171 C
Welch t-test : t = 13.79, p = 1.11e-07
Mann-Whitney : p = 0.00029
trend from daily means: 0.0517 C/day (R^2 = 0.931)
Both tests give tiny p-values, so the warming is real, and the regression on daily means recovers the 0.05 °C/day trend independently of the curve fit.
Step 6: The complete pipeline
Finally, everything in one program: a GreenhouseReport class that cleans the data, fits the model, runs the test and draws a summary figure. Keeping each stage in its own method makes it easy to test and to swap parts out.
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from scipy.optimize import curve_fit
from scipy.interpolate import make_interp_spline
from scipy.signal import medfilt
def make_readings(seed=2024):
rng = np.random.default_rng(seed)
hours = np.arange(30 * 24)
temp = 18 + 0.05 * hours / 24 + 4 * np.sin(2 * np.pi * (hours - 9) / 24)
temp = temp + rng.normal(0, 0.6, hours.size)
glitches = rng.choice(hours.size, 8, replace=False)
temp[glitches] += rng.choice([-15, 15], 8)
temp[rng.choice(hours.size, 25, replace=False)] = np.nan
return hours, temp
def model(h, base, slope, amp, shift):
return base + slope * h / 24 + amp * np.sin(2 * np.pi * (h - shift) / 24)
class GreenhouseReport:
def __init__(self, hours, raw):
self.hours, self.raw = hours, raw
def clean(self, threshold=3.0):
ok = ~np.isnan(self.raw)
filled = self.raw.copy()
filled[~ok] = make_interp_spline(self.hours[ok], self.raw[ok], k=1)(self.hours[~ok])
smooth = medfilt(filled, kernel_size=5)
spikes = np.abs(filled - smooth) > threshold
filled[spikes] = smooth[spikes]
self.clean_temp = filled
self.n_gaps, self.n_spikes = int((~ok).sum()), int(spikes.sum())
def fit(self):
self.params, _ = curve_fit(model, self.hours, self.clean_temp, p0=[18, 0, 3, 8])
def test_warming(self):
days = self.clean_temp.reshape(-1, 24).mean(axis=1)
self.p_value = stats.ttest_ind(days[-7:], days[:7], equal_var=False).pvalue
def run(self):
self.clean()
self.fit()
self.test_warming()
base, slope, amp, shift = self.params
return "\n".join([
f"readings : {self.raw.size} ({self.n_gaps} gaps, {self.n_spikes} spikes repaired)",
f"daily swing : +/- {amp:.2f} C, warmest around {(shift + 6) % 24:.0f}:00",
f"warming trend : {slope:.3f} C/day ({slope * 30:.2f} C over the month)",
f"significant? : {'yes' if self.p_value < 0.05 else 'no'} (p = {self.p_value:.1e})",
])
def plot(self):
fig, (top, bottom) = plt.subplots(2, 1, figsize=(8, 6))
days = self.hours / 24
top.plot(days, self.raw, ".", ms=2, color="gray", label="raw")
top.plot(days, model(self.hours, *self.params), lw=1, label="fitted model")
top.set_ylabel("temperature (C)")
top.set_title("Greenhouse temperature, 30 days")
top.legend(loc="upper left")
week = slice(0, 7 * 24)
bottom.plot(days[week], self.clean_temp[week], label="cleaned")
bottom.plot(days[week], model(self.hours[week], *self.params), "--", label="model")
bottom.set_xlabel("day")
bottom.set_title("First week in detail")
bottom.legend(loc="upper left")
fig.tight_layout()
plt.show()
report = GreenhouseReport(*make_readings())
print(report.run())
report.plot()readings : 720 (25 gaps, 9 spikes repaired)
daily swing : +/- 4.00 C, warmest around 15:00
warming trend : 0.052 C/day (1.55 C over the month)
significant? : yes (p = 1.1e-07)
Make it your own
Ideas for extending the project:
| Idea | Skills practised |
|---|---|
| Add a second sensor (humidity) and test its correlation with temperature | stats.pearsonr, stats.spearmanr |
| Alert when the temperature stays above 24 °C for more than 3 hours | boolean masks, ndimage.label on 1-D masks |
Replace linear gap filling with PchipInterpolator and compare the errors |
scipy.interpolate |
| Low-pass filter the data with a Butterworth filter instead of fitting a model | signal.butter, signal.sosfiltfilt |
| Forecast the next 3 days with the fitted model, with an uncertainty band | curve_fit covariance |
| Estimate daily heating energy by integrating the gap to a 20 °C target | integrate.trapezoid |
Tip: Notice how each stage takes arrays in and returns arrays out. Keeping data generation, cleaning, modelling and reporting separate is what let us test each step on its own — and what lets you replace
make_readings()with real sensor data later.
Test yourself
Why are gaps filled before running the median filter?
- medfilt is faster on NaN
- NaN values would spread through the filter and break the comparison with the smoothed signal
- Interpolation removes spikes
- The order doesn't matter at all
In Step 3, why is d=1/24 passed to rfftfreq?
- To convert temperatures to Kelvin
- Samples are one hour apart, i.e. 1/24 of a day, so frequencies come out in cycles per day
- To remove the mean
- To use 24 FFT bins
Why compare daily means instead of all hourly readings in Step 5?
- There are too many hourly readings for a t-test
- Averaging each day removes the daily cycle, so the comparison focuses on the trend
- Daily means are always normally distributed
- Hourly readings contain NaN