23. NumPy — Mini-project
You support the facilities team of a server room. Four sensors log temperature, humidity and vibration every 10 minutes. After two weeks, the team asks four questions:
- Is the data complete?
- Which readings are spikes, and how do they distort the averages?
- Is any sensor drifting, and by how many degrees per day?
- Is any machine wearing out, and does the
statuscolumn follow the documented rule?
Write a script, sensor_health.py, that answers these questions with NumPy only: no pandas and no loops over rows. It prints a short report and saves the cleaned temperatures to output/clean_temperature.npy for the next tool in the chain.
The project uses the core of the module: loading with genfromtxt and loadtxt, reshaping to 3 dimensions, boolean masks, broadcasting with keepdims, NaN-aware aggregations over several axes, np.where and np.select, lstsq with several targets at once, and saving arrays. Stretch goal 3 adds sorting and np.unravel_index.
Dataset
Section titled “Dataset”data/sensors.csv: 8,064 rows, 4 sensors × 2,016 ten-minute readings from 2024-05-01 00:00 to 2024-05-14 23:50. The rows are sorted by timestamp and then by sensor_id (S1, S2, S3, S4).
| Column | Position | Content |
|---|---|---|
timestamp |
0 | ISO date and time |
sensor_id |
1 | S1 to S4 |
temperature_c |
2 | float, 22 blank |
humidity_pct |
3 | float, 29 blank |
vibration_mm_s |
4 | float, 30 blank |
status |
5 | ok, warn or fail, never blank |
The documented status rule: fail if vibration ≥ 11.2 or temperature ≥ 42; warn if vibration ≥ 4.5 or temperature ≥ 33; otherwise ok. The rule was applied before the blanks were injected.
A day has 144 ten-minute slots, so every measurement fits a (14, 144, 4) array: day, slot, sensor.
Requirements
Section titled “Requirements”Your script must:
- Load the three numeric columns into one float array with
np.genfromtxt, and thesensor_idandstatuscolumns withnp.loadtxt(..., dtype=str). - Check that the rows follow the S1–S4 pattern before any reshape, with an
assert. - Reshape temperature and vibration to
(14, 144, 4). - Report the missing values per sensor for each measurement.
- Flag temperature spikes: readings more than 5 °C above the median of the same sensor at the same time of day (the median over the 14 days). Report the count per sensor.
- Flag vibration spikes: readings more than 2 times the median of the same sensor on the same day. Report the count per sensor.
- Set the temperature spikes to NaN in a copy. Report the mean temperature per sensor before and after.
- Measure drift: fit a straight line to the daily mean (clean) temperature of each sensor with one
np.linalg.lstsqcall, and report the slope in °C per day. Flag the sensors with a slope above 0.1 °C per day. - Measure wear: compare each sensor’s median vibration over the last 3 days with its median over the first 11 days. Flag the sensors where the ratio is above 1.5.
- Rebuild the status column from the rule with
np.selectand report the number of rows that disagree with the file. - Save the clean temperature cube with
np.save, load it back and check it withassert. - Print the report below exactly.
Sensor health report: 2024-05-01 to 2024-05-14 (14 days x 144 slots x 4 sensors)Missing temperature: [6 4 6 6]Missing humidity: [11 8 5 5]Missing vibration: [10 3 10 7]Temperature spikes: [ 8 13 11 8] (total 40)Vibration spikes: [ 7 10 13 11] (total 41)Mean temp raw: [22.05 24.6 23.53 26.04]Mean temp clean: [22. 24.52 23.46 25.99]Drift (degC/day): [-0.001 0.004 0.352 0.001]Drifting sensors: ['S3']Vibration ratio: [1.01 1.01 1.01 2.17]Wearing sensors: ['S4']Status rule: 8063 of 8064 rows agreeSaved: output/clean_temperature.npy (64,512 bytes of data)Step plan
Section titled “Step plan”-
Load. Read columns 2–4 with
genfromtxtand columns 1 and 5 withloadtxt. Print the shapes and dtypes once to check, then remove the prints. -
Check the layout. Reshape the ids to
(-1, 4)and compare them withnp.array(["S1", "S2", "S3", "S4"]). Broadcasting does the comparison for every row. Assert that all are equal. -
Build the cubes.
temperature.reshape(14, 144, 4)and the same for vibration. Remember: axis 0 is the day, axis 1 the slot, axis 2 the sensor. -
Count the gaps.
np.isnan(...)gives a mask. Sum it over every axis except the sensor axis, or reshape to(-1, 4)and sum over axis 0. -
Find temperature spikes. The time-of-day baseline is
np.nanmedian(cube, axis=0, keepdims=True), with shape(1, 144, 4). Subtract it from the cube and compare with 5.0. -
Find vibration spikes. The daily baseline is the median over axis 1 (the slots) with
keepdims=True, shape(14, 1, 4). -
Clean and compare.
np.where(spike, np.nan, cube)makes a cleaned copy. Comparenanmeanover axes 0 and 1 before and after. -
Fit the drift. The daily means have shape
(14, 4). Build a(14, 2)design matrix[1, day].np.linalg.lstsq(design, daily_means)accepts a matrix on the right side and fits all 4 sensors at once: the result has shape(2, 4), and row 1 holds the slopes. -
Measure wear. Compute the daily median vibration
(14, 4), then the median of rows:11and of rows11:. Divide. -
Check the status rule. Use the flat columns of length 8,064 with
np.select, as in the lesson. -
Save. Create the
outputfolder withPath("output").mkdir(exist_ok=True).np.save(path, array)writes the binary.npyformat, which keeps the shape and dtype;np.load(path)reads it back. -
Print the report. Pass
precision=3, suppress=Truetonp.set_printoptionsand round the arrays where the report shows 2 decimals.
A skeleton to start from:
# sensor_health.py: a two-week health report for four sensors, NumPy only.from pathlib import Path
import numpy as np
np.set_printoptions(precision=3, suppress=True)SENSORS = np.array(["S1", "S2", "S3", "S4"])DAYS, SLOTS = 14, 144
# --- Load and check ---# TODO: numeric columns, ids, status; assert the S1-S4 pattern
# --- Cubes and gaps ---# TODO: temperature and vibration as (DAYS, SLOTS, 4); missing per sensor
# --- Spikes ---# TODO: time-of-day baseline for temperature, daily baseline for vibration
# --- Drift and wear ---# TODO: lstsq on daily means; vibration ratio last 3 days / first 11 days
# --- Status rule ---# TODO: np.select, count agreements
# --- Save and report ---# TODO: np.save, np.load, assert, print the reportRubric
Section titled “Rubric”| Criterion | Points | Full points when |
|---|---|---|
| Runs as a script | 2 | python sensor_health.py runs with no error and no warning |
| Loading and layout check | 2 | numeric and text columns load with the right readers; an assert checks the S1–S4 pattern |
| Reshaping | 2 | the cubes have shape (14, 144, 4) and every reduction uses the right axis |
| Spikes | 3 | both baselines use keepdims and broadcasting; the counts match the report |
| Cleaning | 2 | spikes become NaN in a copy; the raw data is unchanged |
| Drift | 2 | one lstsq call fits all four sensors; S3 is flagged |
| Wear and status | 2 | the vibration ratio flags S4; np.select rebuilds the status rule |
| No row loops | 2 | no for loop over rows or readings (loops over 4 sensor names for printing are fine) |
| Output | 1 | the report equals the expected report; the .npy file reloads |
| Total | 18 | 15 or more: you are ready for module 24 |
Stretch goals
Section titled “Stretch goals”- Add humidity to the report: does S3’s humidity drift too? Fit its slope with the same
lstsqcall by stacking the daily means of temperature and humidity side by side (shape(14, 8)). - Correct the drift: subtract
slope × dayfrom S3’s cleaned temperatures and show that its daily means are flat afterwards. - Print the timestamps of the 5 largest temperature spikes, with their sensor and size. Use
np.argsorton the flattened deviations andnp.unravel_index. - Fill the remaining gaps of the clean temperature cube with the time-of-day baseline (
np.where) and assert that no NaN remains. - Save all three cleaned measurements in one file with
np.savez_compressed("output/sensors_clean.npz", temperature=..., humidity=..., vibration=...)and compare the file size with the.npyfile.
Reference solution
Section titled “Reference solution”Try the project yourself first. Then compare your script with this one. Your names can differ; your report must not.
Reference solution
# sensor_health.py: a two-week health report for four sensors, NumPy only.from pathlib import Path
import numpy as np
np.set_printoptions(precision=3, suppress=True)SENSORS = np.array(["S1", "S2", "S3", "S4"])DAYS, SLOTS = 14, 144PATH = "data/sensors.csv"
# --- Load and check ------------------------------------------------------numeric = np.genfromtxt(PATH, delimiter=",", skip_header=1, usecols=(2, 3, 4))ids = np.loadtxt(PATH, delimiter=",", skiprows=1, usecols=1, dtype=str)status = np.loadtxt(PATH, delimiter=",", skiprows=1, usecols=5, dtype=str)assert (ids.reshape(-1, 4) == SENSORS).all(), "rows are not in S1-S4 order"temperature, humidity, vibration = numeric.T # three (8064,) columns
# --- Cubes and gaps: (day, slot, sensor) --------------------------------temp = temperature.reshape(DAYS, SLOTS, 4)vib = vibration.reshape(DAYS, SLOTS, 4)missing = np.isnan(numeric).reshape(-1, 4, 3).sum(axis=0) # (sensor, measure)
# --- Spikes ---------------------------------------------------------------time_of_day = np.nanmedian(temp, axis=0, keepdims=True) # (1, SLOTS, 4)temp_spike = (temp - time_of_day) > 5.0daily_vib = np.nanmedian(vib, axis=1, keepdims=True) # (DAYS, 1, 4)vib_spike = vib > 2.0 * daily_vibclean = np.where(temp_spike, np.nan, temp) # a new array; temp is unchangedmean_raw = np.nanmean(temp, axis=(0, 1))mean_clean = np.nanmean(clean, axis=(0, 1))
# --- Drift: one least-squares fit for all four sensors ----------------------daily_mean = np.nanmean(clean, axis=1) # (DAYS, 4)design = np.column_stack([np.ones(DAYS), np.arange(DAYS)]) # (DAYS, 2)coef = np.linalg.lstsq(design, daily_mean)[0] # (2, 4): intercepts, slopesslope = coef[1]
# --- Wear: last 3 days against the first 11 ----------------------------------day_median = np.nanmedian(vib, axis=1) # (DAYS, 4)ratio = np.median(day_median[11:], axis=0) / np.median(day_median[:11], axis=0)
# --- Status rule ------------------------------------------------------------rule = np.select( [ (vibration >= 11.2) | (temperature >= 42), (vibration >= 4.5) | (temperature >= 33), ], ["fail", "warn"], default="ok",)agree = int((rule == status).sum())
# --- Save -------------------------------------------------------------------Path("output").mkdir(exist_ok=True)out_path = Path("output") / "clean_temperature.npy"np.save(out_path, clean)reloaded = np.load(out_path)
# --- Report -----------------------------------------------------------------period = "2024-05-01 to 2024-05-14"print(f"Sensor health report: {period} ({DAYS} days x {SLOTS} slots x 4 sensors)")print("Missing temperature:", missing[:, 0])print("Missing humidity: ", missing[:, 1])print("Missing vibration: ", missing[:, 2])temp_counts, vib_counts = temp_spike.sum(axis=(0, 1)), vib_spike.sum(axis=(0, 1))print("Temperature spikes: ", temp_counts, f"(total {temp_counts.sum()})")print("Vibration spikes: ", vib_counts, f"(total {vib_counts.sum()})")print("Mean temp raw: ", mean_raw.round(2))print("Mean temp clean: ", mean_clean.round(2))print("Drift (degC/day): ", slope)print("Drifting sensors: ", SENSORS[slope > 0.1])print("Vibration ratio: ", ratio.round(2))print("Wearing sensors: ", SENSORS[ratio > 1.5])print(f"Status rule: {agree} of {len(status)} rows agree")print(f"Saved: {out_path.as_posix()} ({reloaded.nbytes:,} bytes of data)")
# --- Self-checks ------------------------------------------------------------assert temp.shape == (DAYS, SLOTS, 4) and temp_spike.sum() == 40assert np.isnan(temp).sum() == 22 # the raw cube still has only the real gapsassert np.array_equal(reloaded, clean, equal_nan=True)assert SENSORS[slope > 0.1].tolist() == ["S3"]assert SENSORS[ratio > 1.5].tolist() == ["S4"]Sensor health report: 2024-05-01 to 2024-05-14 (14 days x 144 slots x 4 sensors)Missing temperature: [6 4 6 6]Missing humidity: [11 8 5 5]Missing vibration: [10 3 10 7]Temperature spikes: [ 8 13 11 8] (total 40)Vibration spikes: [ 7 10 13 11] (total 41)Mean temp raw: [22.05 24.6 23.53 26.04]Mean temp clean: [22. 24.52 23.46 25.99]Drift (degC/day): [-0.001 0.004 0.352 0.001]Drifting sensors: ['S3']Vibration ratio: [1.01 1.01 1.01 2.17]Wearing sensors: ['S4']Status rule: 8063 of 8064 rows agreeSaved: output/clean_temperature.npy (64,512 bytes of data)Run it from the project folder:
python sensor_health.pyHow it works:
- Load and check.
genfromtxtturns the blanks into NaN;loadtxtis enough for the text columns, which have no blanks. Theassertcompares a(2016, 4)id matrix with the(4,)row of names by broadcasting. If a row were missing, it would fail instead of shifting data silently.numeric.Thas shape(3, 8064), so unpacking gives the three columns. - Gaps.
np.isnan(numeric)has shape(8064, 3). Reshaping it to(2016, 4, 3)puts the sensor on axis 1 and the measurement on axis 2; summing over axis 0 gives a(4, 3)table of gaps. - Temperature spikes. The median over the days gives the normal temperature of each sensor at each time of day. With
keepdims=Trueits shape(1, 144, 4)broadcasts against(14, 144, 4). The rule finds the 40 spikes of the data dictionary. - Vibration spikes. The daily median follows S4’s rising wear, so wear does not count as a spike. Twice the daily median finds 41 readings, the number of vibration spikes in the data dictionary.
- Cleaning.
np.wherebuilds a new array, sotempkeeps its spikes; the second self-check proves that the raw cube was not changed. A tupleaxis=(0, 1)reduces the days and slots together and leaves one mean per sensor. - Drift.
lstsqaccepts a matrix of targets: each column ofdaily_meanis fitted separately against the same design matrix, in one call. S3 drifts by 0.352 °C per day, the calibration drift of the data dictionary. The other slopes are close to 0. - Wear. S4’s median vibration over the last 3 days is 2.17 times its earlier level. The ratio is close to 1 for the other sensors.
- Status rule. One row disagrees: a
warnrow whose trigger value is now a blank, so the rule cannot see it. - Save.
.npystores the raw bytes plus the shape and dtype: 14 × 144 × 4 floats × 8 bytes = 64,512 bytes of data.np.array_equal(..., equal_nan=True)treats NaN as equal to NaN, which the default comparison does not.as_posix()prints the path with/on every system.
Alternative: you can keep everything in one 4-D cube, numeric.reshape(DAYS, SLOTS, 4, 3) (day, slot, sensor, measurement), and index the measurement on the last axis: cube[..., 0] is temperature. The ... (ellipsis) means “all the axes before”. It saves the separate reshapes, at the cost of one more axis to keep in your head.