Mean of a two-state signal
The mean is a weighted mixture of the two states. It equals neither of them unless the duty is 0 or 1.
A report says “the average power of the compressor was 0.34 kW”, and a technician sizes a backup supply for 0.34 kW. The compressor never draws 0.34 kW. It draws 1.16 kW or almost nothing, and the backup supply trips at the first start. Another report says “the average room temperature was 4.0 °C” about a room whose stock must never pass 5.0 °C, and the average is silent about the hour that matters. This lesson shows how to describe a set of readings so that the description is true: the centre, the spread, the shape, and the time spent beyond a limit. #EngineeringStatistics #SensorData #Histogram
By the end of this lesson, you will be able to:
A small refrigeration compressor is fitted with a power meter, and a logger stores one reading every 10 seconds. After one day the site holds 8,640 numbers. The owner asks three plain questions. How much energy did the compressor use? For what part of the day did it run? What power does the supply have to deliver?
One number cannot answer all three. The compressor has two states: it draws about 1.16 kW when it runs, and its electronics draw about 14 W when it is stopped. The average of the day is a mixture of the two, a power at which the machine never operates, and yet exactly the number that gives the energy bill.
So the first skill with any log is to look at how the readings are distributed, and then to choose the number that matches the question.
A log is a list of
The sample mean
For the tank, the sum is 36.0 and
Sort the readings from smallest to largest. The median is the middle value: half of the readings are below it and half are above it. The sorted tank readings are
The fifth of the nine is the middle one, so the median is
A percentile extends the same idea. The 95th percentile is the value that 95 percent of the readings are at or below. The median is the 50th percentile. The 25th and 75th percentiles are called the lower and upper quartiles.
To find the percentile
The range is the largest reading minus the smallest:
The interquartile range is the upper quartile minus the lower quartile. It is the width of the middle half of the readings. For the tank it is
The sample standard deviation
For the tank, the squared distances from 4.0 add to 0.12, so
Now suppose a tenth reading arrives, and it is 40.0 °C: a loose connector, not a hot tank.
| Measure | Nine readings | With the reading of 40.0 |
|---|---|---|
| Mean | 4.0 °C | 7.6 °C |
| Median | 4.0 °C | 4.0 °C |
| Standard deviation | 0.122 °C | 11.4 °C |
| Interquartile range | 0.2 °C | 0.175 °C |
One bad reading in ten moved the mean by 3.6 °C and made the standard deviation almost 100 times larger, while the median and the interquartile range hardly moved. A measure that one or two extreme readings cannot move far is called robust: the median and the interquartile range are robust; the mean, the range and the standard deviation are not.
A histogram divides the range of the readings into intervals of equal width, called bins, and counts the readings in each bin. It shows the shape of the data, which no single number shows. The most common value, the top of a peak, is called a mode.
The bin width is a choice. Wide bins hide the shape and narrow bins show only noise. Start with 20 to 50 bins across the range, then try half and double that width.
Three shapes cover most sensor logs.
When the histogram has two peaks, describe the two states one at a time. Let
Mean of a two-state signal
The mean is a weighted mixture of the two states. It equals neither of them unless the duty is 0 or 1.
For example, a duty of 0.25 with 2.0 kW running and 0.02 kW stopped gives
The standard deviation of a two-peaked signal describes neither peak: it measures the distance of the readings from a mean where there are no readings. It is close to the distance between the peaks multiplied by
To separate the states, call every reading above a threshold power “running”, and choose the threshold from the histogram: in the empty gap between the peaks, far from both. Anywhere in the gap gives the same duty; a threshold inside a peak cuts that peak in two and gives a wrong duty.
Energy is power multiplied by time, added over the readings. If each reading stands for the same time step
Energy from power readings
Energy equals mean power multiplied by duration. This is exact, for any shape of histogram.
A machine with a mean power of 0.515 kW for 24 hours uses
Many requirements are written as limits: the room must not pass 5.0 °C, the pressure must stay above 2.0 bar. For a limit
If 1,512 of 43,200 readings are above the limit, the fraction is
The fraction does not say whether the time above the limit was one long event or many short ones. For that, find each unbroken run of readings above the limit and report the number of runs and the length of the longest.
Mean. The 8,640 readings add to 2,909.1 kW.
The mean power is 0.337 kW. ✅
Median. The middle of the sorted readings is 0.0141 kW, which is the standby power. The mean is 24 times the median. A difference this large is the first sign that the data are not one peak. ✅
Look for readings near the mean. The smallest reading is 0.0120 kW and the largest is 1.2338 kW. The number of readings from 0.03 kW to 1.00 kW is 0. Not one reading in the day is near 0.337 kW. ✅
Count in bins of 0.01 kW. The bin from 0.01 to 0.02 kW holds 6,205 readings. This is the lower mode, the stopped state. ✅
Upper mode. Above 1 kW the fullest bin is from 1.15 to 1.16 kW, with 482 readings. This is the upper mode, the running state. Its peak is wider than one bin because the running power varies a little. ✅
The gap. There is no reading from 0.0195 kW to 1.0952 kW. The histogram is two narrow peaks with an empty space of more than 1 kW between them. ✅
Spread of the whole set. The standard deviation is 0.516 kW. The lower quartile is 0.0129 kW and the upper quartile is 1.1355 kW, so the interquartile range is 1.123 kW. ✅
What the spread means here. Neither number describes a state. One quartile lies in each peak, so the interquartile range is only the distance between the peaks. The standard deviation of 0.516 kW is 26 times the spread inside the running peak, which Step 3 finds. ✅
Choose the threshold. The gap runs from 0.02 kW to 1.10 kW. A threshold of 0.50 kW is far from both peaks. ✅
Duty. The number of readings above 0.50 kW is 2,435.
The compressor ran for 28.2 percent of the day, which is
Test the threshold. Thresholds of 0.10 kW and 1.00 kW give the same 28.18 percent, because both are in the gap. A threshold of 1.14 kW, which is inside the running peak, gives 23.68 percent. That answer is wrong by 4.5 points, and nothing in the result warns you. ✅
Each state alone. The 2,435 running readings have a mean of 1.1601 kW and a standard deviation of 0.0200 kW. The 6,205 stopped readings have a mean of 0.0136 kW and a standard deviation of 0.0012 kW. The supply must deliver 1.16 kW, not 0.337 kW, and more than that for the moment of each start, which a 10 second reading does not show. ✅
Starts. A start is a reading above the threshold that follows a reading below it. There are 52 starts in 24 hours, which is 2.17 starts per hour. ✅
Sum of power multiplied by time. Each reading stands for 10 s, which is
The compressor used 8.08 kWh in the day. ✅
Mean power multiplied by duration.
The mean gives the same energy, as the theory said. ✅
What the median would give.
Check a second way, state by state. Running:
Rebuild the mean from the two states.
The mixture formula returns the mean of Step 1. ✅
Check it against the meter. The two calculations above agree because they use the same readings, so they cannot find a wrong reading. Most power meters also keep their own energy register. Read it at the start and the end of the day: the difference should be close to 8.08 kWh, within a few percent (the readings miss the short surge at each start). A larger difference means a scale error, a wrong current transformer ratio in the logger, or missing readings. ✅
Mean and median. The mean is
Range. The smallest reading is
Percentiles. The 5th percentile is
Spread. The standard deviation is
The daily means. The 14 daily means lie from
Above 5.0 °C. The number of readings above
The air was above the limit for 4.35 percent of the time. ✅
In hours. 877 minutes is 14.6 hours in 14 days, or 62.6 minutes in an average day. ✅
Above 5.2 °C. The number of readings above
Check with a percentile. If 4.35 percent of the readings are above 5.0, then the 95.65th percentile must be 5.0. The script gives
Count the runs. The 877 minutes above
Longest run. The longest unbroken run above
Explain the pattern. The thermostat starts the compressor only when the air reaches
Move the limit by 0.1 °C. A probe that reads 0.1 °C low reports 4.9 °C when the air is at 5.0 °C, so the real time above 5.0 °C is the logged time above 4.9 °C: 1,589 minutes, 7.88 percent. A probe that reads 0.1 °C high makes the room look worse than it is: the real time is the logged time above 5.1 °C, 246 minutes, 1.22 percent. ✅
What it means. An error of only 0.1 °C changes the answer from 4.35 percent to anything between 1.22 and 7.88 percent, because most readings sit close to the limit. Before you report the time above a limit, compare the probe with a reference thermometer in the same place (or in an ice and water bath, which is 0.0 °C), and state the probe error with the result. ✅
The script generates both data sets and prints every number used in the two applications. It saves one plot with the two histograms.
"""Describe two sensor logs: compressor power (two peaks) and cold room temperature."""import numpy as npimport matplotlib.pyplot as plt
def compressor_power(seed=41, seconds=86400, step=10): """Data set D: compressor electrical power in kW, one reading every 10 s.""" rng = np.random.default_rng(seed) n = seconds // step; p = np.empty(n); on = False; left = 0 for i in range(n): if left <= 0: on = not on left = rng.integers(36, 60) if on else rng.integers(60, 180) # in steps of 10 s p[i] = (1.16 + rng.normal(0, 0.02)) if on else (0.012 + abs(rng.normal(0, 0.002))) left -= 1 return p # kW
def cold_room_minutes(seed=11, days=14): """Data set A: cold room air temperature in degC, one reading a minute.""" rng = np.random.default_rng(seed) n = days * 1440 t = np.empty(n); temp = 4.0; on = False; out = [] for i in range(n): minute = i % 1440 # door openings are more likely in working hours door = (480 <= minute < 1020) and (rng.random() < 0.035) if temp >= 5.0: on = True if temp <= 3.0: on = False temp += (-0.30 if on else 0.10) + (0.35 if door else 0.0) t[i] = temp + rng.normal(0.0, 0.05) # sensor noise, 0.05 degC return t
def longest_run(flags): """Length of the longest unbroken run of True values.""" best = run = 0 for f in flags: run = run + 1 if f else 0 best = max(best, run) return best
def count_runs(flags): """Number of separate runs of True values.""" f = np.asarray(flags, dtype=int) return int(f[0] + np.sum(np.diff(f) == 1))
# ---------- Part 1: compressor power, data set D ----------STEP = 10.0 # s between readingsp = compressor_power()n = p.sizehours = n * STEP / 3600.0q5, q25, q50, q75, q95 = np.percentile(p, [5, 25, 50, 75, 95])print("Compressor power, one day at 10 s")print(f" readings {n}, minimum {p.min():.4f} kW, maximum {p.max():.4f} kW")print(f" mean {p.mean():.4f} kW, median {q50:.4f} kW, " f"standard deviation {p.std(ddof=1):.4f} kW")print(f" 25th percentile {q25:.4f} kW, 75th percentile {q75:.4f} kW, " f"interquartile range {q75 - q25:.4f} kW")print(f" readings from 0.03 to 1.00 kW: {np.sum((p > 0.03) & (p < 1.00))}")
counts, edges = np.histogram(p, bins=np.arange(0.0, 1.2501, 0.01))low_bin = int(np.argmax(counts[:60]))high_bin = 60 + int(np.argmax(counts[60:]))print(f" lower mode: bin {edges[low_bin]:.2f} to {edges[low_bin + 1]:.2f} kW " f"with {counts[low_bin]} readings")print(f" upper mode: bin {edges[high_bin]:.2f} to {edges[high_bin + 1]:.2f} kW " f"with {counts[high_bin]} readings")print(f" gap: no reading from {p[p < 0.5].max():.4f} to {p[p > 0.5].min():.4f} kW")
for threshold in (0.10, 0.50, 1.00, 1.14): print(f" duty with threshold {threshold:.2f} kW: " f"{100.0 * np.mean(p > threshold):.2f} %")
running = p > 0.50duty = running.mean()p_run, p_stop = p[running].mean(), p[~running].mean()print(f" running: {running.sum()} readings, {running.sum() * STEP / 3600.0:.3f} h, " f"mean {p_run:.4f} kW, standard deviation {p[running].std(ddof=1):.4f} kW")print(f" stopped: {(~running).sum()} readings, mean {p_stop:.4f} kW, " f"standard deviation {p[~running].std(ddof=1):.4f} kW")print(f" starts {count_runs(running)}, " f"starts per hour {count_runs(running) / hours:.2f}")energy_sum = np.sum(p) * STEP / 3600.0energy_mean = p.mean() * hourse_run = p[running].sum() * STEP / 3600.0e_stop = p[~running].sum() * STEP / 3600.0print(f" energy, sum of power x time: {energy_sum:.3f} kWh")print(f" energy, mean power x 24 h: {energy_mean:.3f} kWh")print(f" energy, running {e_run:.3f} kWh + standby {e_stop:.3f} kWh " f"= {e_run + e_stop:.3f} kWh")print(f" mean rebuilt from the two states: " f"{duty * p_run + (1.0 - duty) * p_stop:.4f} kW")print(f" energy if the median is used: {q50 * hours:.3f} kWh")
# ---------- Part 2: cold room temperature, data set A ----------temp = cold_room_minutes()m = temp.sizet5, t25, t50, t75, t95 = np.percentile(temp, [5, 25, 50, 75, 95])print("Cold room temperature, 14 days at 1 min")print(f" readings {m}, minimum {temp.min():.2f} degC, maximum {temp.max():.2f} degC")print(f" mean {temp.mean():.3f} degC, median {t50:.3f} degC, " f"standard deviation {temp.std(ddof=1):.3f} degC")print(f" 5th percentile {t5:.2f} degC, 95th percentile {t95:.2f} degC, " f"interquartile range {t75 - t25:.2f} degC")for limit in (5.0, 5.2): above = temp > limit print(f" above {limit:.1f} degC: {above.sum()} min = {100.0 * above.mean():.2f} % " f"of the time, in {count_runs(above)} runs, longest {longest_run(above)} min")above5 = temp > 5.0print(f" above 5.0 degC: {above5.sum() / 60.0:.1f} h in 14 days, " f"{above5.sum() / 14.0:.1f} min a day")print(f" check: the {100.0 * (1.0 - above5.mean()):.2f}th percentile is " f"{np.percentile(temp, 100.0 * (1.0 - above5.mean())):.3f} degC")daily = temp.reshape(14, 1440).mean(axis=1)print(f" daily means from {daily.min():.2f} to {daily.max():.2f} degC")
# ---------- Plot ----------fig, ax = plt.subplots(1, 2, figsize=(10, 4))ax[0].hist(p, bins=np.arange(0.0, 1.2501, 0.02), color="tab:blue")ax[0].axvline(p.mean(), color="tab:red", label=f"mean {p.mean():.3f} kW")ax[0].axvline(q50, color="black", linestyle="--", label=f"median {q50:.3f} kW")ax[0].set_xlabel("power (kW)")ax[0].set_ylabel("number of readings")ax[0].set_title("Compressor power: two peaks")ax[0].legend()ax[1].hist(temp, bins=np.arange(2.6, 5.5001, 0.1), color="tab:blue")ax[1].axvline(5.0, color="tab:red", label="limit 5.0 degC")ax[1].axvline(temp.mean(), color="black", linestyle="--", label=f"mean {temp.mean():.2f} degC")ax[1].set_xlabel("air temperature (degC)")ax[1].set_ylabel("number of readings")ax[1].set_title("Cold room temperature")ax[1].legend()fig.tight_layout()fig.savefig("describing_sensor_data.png", dpi=120)print("Saved describing_sensor_data.png")Expected output
Compressor power, one day at 10 s readings 8640, minimum 0.0120 kW, maximum 1.2338 kW mean 0.3367 kW, median 0.0141 kW, standard deviation 0.5159 kW 25th percentile 0.0129 kW, 75th percentile 1.1355 kW, interquartile range 1.1227 kW readings from 0.03 to 1.00 kW: 0 lower mode: bin 0.01 to 0.02 kW with 6205 readings upper mode: bin 1.15 to 1.16 kW with 482 readings gap: no reading from 0.0195 to 1.0952 kW duty with threshold 0.10 kW: 28.18 % duty with threshold 0.50 kW: 28.18 % duty with threshold 1.00 kW: 28.18 % duty with threshold 1.14 kW: 23.68 % running: 2435 readings, 6.764 h, mean 1.1601 kW, standard deviation 0.0200 kW stopped: 6205 readings, mean 0.0136 kW, standard deviation 0.0012 kW starts 52, starts per hour 2.17 energy, sum of power x time: 8.081 kWh energy, mean power x 24 h: 8.081 kWh energy, running 7.847 kWh + standby 0.234 kWh = 8.081 kWh mean rebuilt from the two states: 0.3367 kW energy if the median is used: 0.338 kWhCold room temperature, 14 days at 1 min readings 20160, minimum 2.66 degC, maximum 5.44 degC mean 4.013 degC, median 4.015 degC, standard deviation 0.620 degC 5th percentile 3.04 degC, 95th percentile 4.98 degC, interquartile range 1.04 degC above 5.0 degC: 877 min = 4.35 % of the time, in 676 runs, longest 3 min above 5.2 degC: 38 min = 0.19 % of the time, in 36 runs, longest 2 min above 5.0 degC: 14.6 h in 14 days, 62.6 min a day check: the 95.65th percentile is 5.000 degC daily means from 4.00 to 4.06 degCSaved describing_sensor_data.pngIn the left plot the mean line stands alone in the empty space between the two peaks. In the right plot the thin tail beyond the limit line is the 877 minutes.
1. A pressure sensor gives seven readings in bar: 3.9, 4.1, 4.0, 4.2, 3.8, 4.0, 9.5. Find the mean and the median. Which describes the typical pressure?
The sum is 33.5, so the mean is
2. Eight pump start times in seconds are 12, 15, 11, 14, 13, 40, 12, 13. Find the quartiles, the interquartile range, the mean and the standard deviation. Use the position rule
Sorted: 11, 12, 12, 13, 13, 14, 15, 40. The 25th percentile has
3. A heater draws 2.0 kW when on and 0.02 kW when off. Its mean power over one day is 0.515 kW. Find the duty and the energy for the day.
From
4. A vaccine store is logged every minute for 30 days. The mean is 5.1 °C. Of the 43,200 readings, 1,512 are above 8.0 °C. The requirement is “not above 8.0 °C for more than 2 percent of the time”. Is the requirement met? What else must be reported?
5. Change the script to study the lower limit of the cold room. For data set A, find the number of minutes below 3.0 °C, the percentage of the time, and the longest run below 3.0 °C.
Replace temp > limit with temp < 3.0. There are 735 minutes below 3.0 °C, which is
A report says: the average power of the compressor was 0.337 kW. The compressor is an on-off machine. For how much of the day did it draw between 0.3 and 0.4 kW?
Three questions. Each wrong choice is a mistake people really make, so read the note after you answer.
1. A pump runs for 40 percent of the time at 1.5 kW. When it is stopped, its controller draws 0.05 kW. What is the energy for 24 hours?
2. A compressor draws 1.16 kW when it runs and 0.014 kW when it is stopped. Its duty rises from 45 percent to 55 percent. What happens to the mean and to the median?
3. The lesson's compressor has a mean of 0.337 kW and a standard deviation of 0.516 kW. What does the standard deviation tell you?
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.