Apparent frequency of an undersampled signal
Here
Two loggers are fitted to the same compressor, and both read the power every 15 minutes. At the end of the day one reports 6.9 kWh and the other reports 9.6 kWh. Neither logger is faulty. They started at different seconds, and a compressor that runs for 8 minutes at a time can be missed completely between two readings. In the same building, a cold room report built from hourly averages shows no hour above 5.0 °C, although the air passed 5.0 °C on 676 occasions. This lesson shows what a logged value really means, how the sampling interval and the method of aggregation change the answer, and how to choose them so that the stored data can still answer the question. #DataLogging #Sampling #EnergyMetering
By the end of this lesson, you will be able to:
A site wants to know how much energy its refrigeration compressor uses in a day. The logger was set to one reading every 15 minutes, which is common in energy work. The total calculated from the log does not agree with the energy meter of the supplier, and it changes from one day to the next for no visible reason.
The logger stores the power at the moment of each reading, and the compressor runs for 6 to 10 minutes, then rests for 10 to 30 minutes. Whether a run is caught or missed depends on the second at which the logger started. The supplier’s meter adds energy continuously, so it does not have this problem.
So before any statistics, you must know what each stored value means, how far apart the values are, and how they were aggregated.
Every value in a log is one of three kinds. They can have the same column name and the same unit, so read the manual of the meter.
| Kind | What is stored | Good for | Weakness |
|---|---|---|---|
| Instantaneous | The value at the moment of the reading | Shape, states, peaks, limits | Sees nothing between readings |
| Interval average | The mean of the signal since the last reading | Energy, totals, load | Hides peaks and short events |
| Counter | A total that only increases (kWh, m³, starts) | Totals across any period, across gaps | Says nothing about the shape between readings |
Take one 15 minute interval in which a compressor is stopped at 0.014 kW, runs at 1.16 kW from minute 4.0 to minute 11.8, and is stopped again when the reading is taken.
The interval average is
Let
A compressor run of 6 minutes is seen at least once with
When a repeating signal is sampled too slowly, the readings do not look random: they show a slow, regular pattern that is not in the machine, called an alias. It is the wheel in a film that seems to turn slowly backwards, because the camera looks too seldom.
Let the signal repeat with period
Apparent frequency of an undersampled signal
Here
Take a square wave that is on for 3 minutes and off for 3 minutes, so
The readings repeat every 30 minutes. The log describes a machine that runs for 15 minutes and rests for 15 minutes.
The worst case is a sampling interval equal to the period: every reading falls at the same point of the cycle. A square wave of period 5 minutes read every 5 minutes gives “always on” or “always off”, depending on the second at which the logger started, while the true mean is one half.
Energy is power multiplied by time. From instantaneous readings
This is an estimate: it assumes that each reading describes its whole interval. That is good for a slow, smooth signal and poor for a machine that switches inside the interval, as the 0.0035 kWh above shows.
If each stored value is the average
Three routes to the energy of a period
A counter that reads 12,480.6 kWh at midnight and 12,611.9 kWh at the next midnight has measured
On a real site, check every difference of a counter before you use it. A counter can roll over to zero at its largest value, and some meters reset it after a power cut or a replacement. Either gives a negative difference, or one far too large. Mark that interval and take its energy from another source, never from the subtraction.
Suppose the logger on the compressor of data set D is silent from 09:00 to 11:00, and the meter continues to run. The last power reading before the gap is 1.166 kW, because the compressor was running, and the first reading after it is 0.013 kW. The true energy of the day is 8.081 kWh. If you add only the readings that exist, the total is 7.588 kWh, which is 6.1 percent low. If you draw a straight line across the gap, you add
Aggregation replaces many readings with one row for each hour or day. Each statistic in the row keeps a different part of the truth.
Some statistics can be combined again later and some cannot.
A mean hides anything shorter than its own interval. An hour with 54 minutes at 4.0 °C and 6 minutes at 7.0 °C has a mean of
A daily total depends on where the day begins. Store time in UTC, which has no clock changes, and calculate daily totals in the local time of the site. A site at UTC+3 that is aggregated by UTC days has “days” that run from 03:00 to 03:00 local time. For the compressor of data set D, the energy from 00:00 to 03:00 is 1.064 kWh, which is 13.2 percent of the day and would be given to the wrong date. Where clocks change for summer time, one local day in the year has 23 hours and one has 25. For a steady load, the 25 hour day uses about 4 percent more energy than its neighbours (25 hours divided by 24 is 1.042) and the 23 hour day about 4 percent less, with no change in the machine. A logger that stores local time without its offset writes one hour twice in autumn and skips one in spring; two readings with the same time stamp are the sign. Store UTC, convert once, and divide a daily total by the hours in that day when you compare days.
If readings are missing at random moments, the mean of the readings that remain is still a fair estimate. The sum is not: every missing interval removes its energy, so a sum with gaps is always too low. In the gap example, two missing hours in 24 removed 6.1 percent of the day’s energy.
Store the count of readings beside each aggregated value, and report the coverage: the readings that exist as a fraction of the readings expected. A daily total with a coverage of 91.7 percent is not a daily total.
True energy. The sum of the 8,640 readings multiplied by 10 s gives
Runs. With a threshold of 0.5 kW there are 52 runs. The on runs last 6.0 to 9.8 minutes, with a mean of 7.8 minutes. The off periods last 10.0 to 29.8 minutes, with a mean of 20.3 minutes. ✅
Cycle. The time from one start to the next lies from 16.0 to 38.7 minutes, with a mean of 28.0 minutes. ✅
What the rules predict. The shortest on run is 6.0 minutes. An interval of 1 or 5 minutes puts at least one reading in every run. An interval of 15 minutes is longer than every run, so some runs must fall between two readings. ✅
1 minute. Across the 6 phase offsets the estimate lies from 8.020 to 8.139 kWh. The error is
5 minutes. Across the 30 offsets the estimate lies from 7.563 to 8.660 kWh. The error is
15 minutes. Across the 90 offsets the estimate lies from 6.879 to 9.588 kWh.
The worst error is 18.6 percent, and only 44 of the 90 offsets are within 5 percent of the truth. ✅
Starts at 15 minutes. The 15 minute samples show 22 to 30 starts, where the machine made 52. About half of the runs were never seen. ✅
Energy. The interval averages give 8.081 kWh at 1 minute, at 5 minutes and at 15 minutes. The error is zero at every interval. ✅
Reason. When the averages are added and multiplied by the interval, every 10 s reading is counted exactly once, so the total is the same sum as in Step 1. ✅
What the averages lose. The largest 15 minute average is 0.753 kW, although the compressor draws 1.16 kW. Of the 15 minute averages, 76.0 percent lie from 0.03 to 1.00 kW, a range in which the machine never operates. At 5 minutes the share is 28.8 percent and at 1 minute it is 6.3 percent. ✅
Consequence. Averaged data give the right energy and a wrong picture of the states. A threshold applied to 15 minute averages cannot find the duty. ✅
Average the estimates over all offsets. Each 10 s reading belongs to exactly one phase offset. So the mean of the estimates from all offsets must equal the truth. ✅
Result. The mean of the 6, the 30 and the 90 estimates is 8.081 kWh in each case. Instantaneous sampling has no bias: it is not wrong in one direction. It is uncertain, and the uncertainty grows as the interval approaches the length of the runs. ✅
Compare with aliasing. This compressor’s cycle varies from 16.0 to 38.7 minutes, so the 15 minute readings give no clean false period. The same effect appears as an irregular error. ✅
Range of the hourly means. The 336 hourly means lie from 3.84 to 4.21 °C. ✅
Excursions that survive. The number of hourly means above 5.0 °C is 0. Of the 676 excursions in the one minute data, none survives. ✅
Reason. No hour holds more than 6 minutes above the limit, and the other 54 minutes or more keep the mean near 4 °C. ✅
What the mean does keep. The mean of the 336 hourly means is 4.013 °C, the same as the mean of the 20,160 readings, because every hour holds 60 readings. The hourly mean is a correct record of the average and no record at all of the limit. ✅
Maximum. The hourly maximum is above 5.0 °C in 332 of the 336 hours, and above 5.2 °C in 34 hours. The largest hourly maximum is 5.44 °C, the true maximum of the record. ✅
What the maximum hides. By the maximum, 98.8 percent of the hours passed the limit. The air was above the limit for 4.35 percent of the time. The maximum says that the limit was passed and says nothing about for how long. ✅
Minimum. The hourly minimum is below 3.0 °C in 316 of the 336 hours, and the smallest is 2.66 °C. It shows the bottom of the thermostat cycle in the same way. ✅
Count in each hour. Count the readings above 5.0 °C inside each hour before the raw data are discarded. The count lies from 0 to 6 minutes in an hour. ✅
Check by adding. The 336 hourly counts add to 877 minutes, exactly the count from the one minute data. A count is a sum, so it survives aggregation without loss. ✅
One spot reading an hour. If the logger had stored only one instantaneous reading in each hour, the fraction of readings above 5.0 °C would lie from 1.79 to 8.33 percent, depending on which minute of the hour was read. The true value is 4.35 percent. ✅
The script constructs the clean square wave and confirms the false period of 30 minutes. It then samples the compressor power at every interval and phase offset, forms the interval averages, compares the counter with power readings across a gap, and reduces the cold room record to hourly rows.
"""Sampling interval, aliasing, interval averages, counters and hourly aggregation."""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 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))
def repeat_period(x): """Smallest shift (in samples) after which the series repeats exactly.""" for lag in range(1, x.size // 2): if np.array_equal(x[lag:], x[:-lag]): return lag return None
# ---------- Part 1: aliasing with a clean square wave ----------t = np.arange(0, 6 * 3600, 10) # 6 hours in steps of 10 ssquare = ((t % 360) < 180).astype(float) # period 6 min, on for 3 minspot = square[::30] # one sample every 5 minprint("Aliasing: square wave of period 6 min sampled every 5 min")print(f" true period {repeat_period(square) * 10 / 60:.0f} min, " f"period seen in the samples {repeat_period(spot) * 5} min")print(f" first 13 samples: {' '.join(str(int(v)) for v in spot[:13])}")print(f" formula 1 / (1/5 - 1/6) = {1.0 / (1.0 / 5.0 - 1.0 / 6.0):.0f} min")same = ((t % 300) < 150).astype(float) # period 5 min, on for 2.5 minprint(f" period 5 min sampled every 5 min: mean of samples " f"{same[0::30].mean():.2f} at offset 0 s, {same[15::30].mean():.2f} at offset 150 s " f"(true mean {same.mean():.2f})")
# ---------- Part 2: compressor energy against sampling interval ----------STEP = 10.0p = compressor_power()truth = np.sum(p) * STEP / 3600.0 # kWh in the dayrunning = p > 0.5edge = np.diff(np.r_[0, running.astype(int), 0])begin, end = np.where(edge == 1)[0], np.where(edge == -1)[0]on_min, off_min = (end - begin) / 6.0, (begin[1:] - end[:-1]) / 6.0print("Compressor, one day")print(f" truth from 10 s readings: {truth:.3f} kWh, {begin.size} runs")print(f" on runs {on_min.min():.1f} to {on_min.max():.1f} min (mean {on_min.mean():.1f}), " f"off runs {off_min.min():.1f} to {off_min.max():.1f} min (mean {off_min.mean():.1f})")cycle = np.diff(begin) / 6.0print(f" cycle, start to start: {cycle.min():.1f} to {cycle.max():.1f} min " f"(mean {cycle.mean():.1f})")print(" instantaneous samples, every phase offset:")spread = {}for label, k in (("1 min", 6), ("5 min", 30), ("15 min", 90)): est = np.array([p[o::k].mean() * 24.0 for o in range(k)]) err = 100.0 * (est - truth) / truth starts = [count_runs(running[o::k]) for o in range(k)] spread[label] = est print(f" {label:>6}: {k:2d} offsets, energy {est.min():.3f} to {est.max():.3f} kWh, " f"error {err.min():+.1f} to {err.max():+.1f} %, " f"starts seen {min(starts)} to {max(starts)}") print(f" mean of the {k} estimates {est.mean():.3f} kWh, " f"within 5 % of the truth: {np.sum(np.abs(err) <= 5.0)} of {k}")print(" interval averages:")for label, k in (("1 min", 6), ("5 min", 30), ("15 min", 90)): avg = p.reshape(-1, k).mean(axis=1) middle = np.mean((avg > 0.03) & (avg < 1.00)) print(f" {label:>6}: energy {np.sum(avg) * k * STEP / 3600.0:.3f} kWh, " f"largest average {avg.max():.3f} kW, " f"{100.0 * middle:.1f} % of averages between 0.03 and 1.00 kW")
# ---------- Part 3: a counter against power samples across a gap ----------counter = np.cumsum(p) * STEP / 3600.0 # kWh since midnighta, b = 9 * 360, 11 * 360 # logger silent 09:00 to 11:00kept = np.ones(p.size, dtype=bool); kept[a:b] = Falsee_kept = np.sum(p[kept]) * STEP / 3600.0e_line = e_kept + 0.5 * (p[a - 1] + p[b]) * 2.0e_hold = e_kept + p[a - 1] * 2.0print("Gap from 09:00 to 11:00")print(f" power before the gap {p[a - 1]:.3f} kW, after the gap {p[b]:.3f} kW")for name, value in (("sum of the readings that exist", e_kept), ("straight line across the gap", e_line), ("last value held across the gap", e_hold)): print(f" {name}: {value:.3f} kWh ({100.0 * (value - truth) / truth:+.1f} %)")print(f" counter at 09:00 {counter[a - 1]:.3f} kWh, at 11:00 {counter[b - 1]:.3f} kWh, " f"energy in the gap {counter[b - 1] - counter[a - 1]:.3f} kWh")print(f" counter at 24:00 minus counter at 00:00: {counter[-1]:.3f} kWh")print(f" energy from 00:00 to 03:00: {counter[3 * 360 - 1]:.3f} kWh " f"({100.0 * counter[3 * 360 - 1] / truth:.1f} % of the day)")
# ---------- Part 4: cold room temperature aggregated to hours ----------temp = cold_room_minutes()hourly = temp.reshape(-1, 60)h_mean, h_min, h_max = hourly.mean(axis=1), hourly.min(axis=1), hourly.max(axis=1)h_above = (hourly > 5.0).sum(axis=1)above = temp > 5.0print("Cold room, 14 days")print(f" minute data: mean {temp.mean():.3f} degC, maximum {temp.max():.2f} degC, " f"{above.sum()} min above 5.0 degC ({100.0 * above.mean():.2f} %) " f"in {count_runs(above)} runs")print(f" hourly mean: {h_mean.size} values from {h_mean.min():.2f} to {h_mean.max():.2f} degC, " f"{np.sum(h_mean > 5.0)} above 5.0 degC, mean of them {h_mean.mean():.3f} degC")print(f" hourly maximum: {np.sum(h_max > 5.0)} of {h_max.size} hours above 5.0 degC, " f"{np.sum(h_max > 5.2)} above 5.2 degC, largest {h_max.max():.2f} degC")print(f" hourly minimum: {np.sum(h_min < 3.0)} of {h_min.size} hours below 3.0 degC, " f"smallest {h_min.min():.2f} degC")print(f" hourly minutes above 5.0 degC: 0 to {h_above.max()} in an hour, " f"total {h_above.sum()} min")frac = [100.0 * np.mean(temp[o::60] > 5.0) for o in range(60)]print(f" one spot reading an hour: {min(frac):.2f} to {max(frac):.2f} % above 5.0 degC, " f"by the minute chosen")
# ---------- Plot ----------fig, ax = plt.subplots(3, 1, figsize=(9, 9))window = slice(0, 4 * 360) # first 4 hoursminutes = np.arange(p.size) * STEP / 60.0ax[0].plot(minutes[window], p[window], linewidth=0.8, label="10 s readings")for offset, mark in ((0, "o"), (45, "s")): idx = np.arange(offset, 4 * 360, 90) ax[0].plot(minutes[idx], p[idx], mark, label=f"15 min samples, offset {offset * 10} s")ax[0].set_xlabel("time (min)"); ax[0].set_ylabel("power (kW)")ax[0].set_title("The same compressor, two 15 min sampling phases")ax[0].legend(loc="center right", fontsize=8)for pos, label in enumerate(("1 min", "5 min", "15 min")): ax[1].plot(np.full(spread[label].size, pos), spread[label], "_", markersize=14)ax[1].set_xticks([0, 1, 2]); ax[1].set_xticklabels(["1 min", "5 min", "15 min"])ax[1].set_xlim(-0.5, 2.5)ax[1].axhline(truth, color="tab:red", linewidth=0.8)ax[1].set_ylabel("energy estimate (kWh)")ax[1].set_title("Day's energy from instantaneous samples, all phase offsets")day2 = slice(24, 48)hrs = np.arange(24)ax[2].plot(np.arange(1440) / 60.0, temp[1440:2880], linewidth=0.5, color="0.6", label="1 min readings")ax[2].step(hrs, h_mean[day2], where="post", label="hourly mean")ax[2].step(hrs, h_max[day2], where="post", label="hourly maximum")ax[2].axhline(5.0, color="tab:red", linewidth=0.8)ax[2].set_xlabel("hour of day 2"); ax[2].set_ylabel("temperature (degC)")ax[2].set_title("Cold room: what the hourly mean hides")ax[2].legend(fontsize=8)fig.tight_layout()fig.savefig("sampling_and_aggregation.png", dpi=120)print("Saved sampling_and_aggregation.png")Expected output
Aliasing: square wave of period 6 min sampled every 5 min true period 6 min, period seen in the samples 30 min first 13 samples: 1 0 0 0 1 1 1 0 0 0 1 1 1 formula 1 / (1/5 - 1/6) = 30 min period 5 min sampled every 5 min: mean of samples 1.00 at offset 0 s, 0.00 at offset 150 s (true mean 0.50)Compressor, one day truth from 10 s readings: 8.081 kWh, 52 runs on runs 6.0 to 9.8 min (mean 7.8), off runs 10.0 to 29.8 min (mean 20.3) cycle, start to start: 16.0 to 38.7 min (mean 28.0) instantaneous samples, every phase offset: 1 min: 6 offsets, energy 8.020 to 8.139 kWh, error -0.8 to +0.7 %, starts seen 52 to 52 mean of the 6 estimates 8.081 kWh, within 5 % of the truth: 6 of 6 5 min: 30 offsets, energy 7.563 to 8.660 kWh, error -6.4 to +7.2 %, starts seen 52 to 52 mean of the 30 estimates 8.081 kWh, within 5 % of the truth: 25 of 30 15 min: 90 offsets, energy 6.879 to 9.588 kWh, error -14.9 to +18.6 %, starts seen 22 to 30 mean of the 90 estimates 8.081 kWh, within 5 % of the truth: 44 of 90 interval averages: 1 min: energy 8.081 kWh, largest average 1.185 kW, 6.3 % of averages between 0.03 and 1.00 kW 5 min: energy 8.081 kWh, largest average 1.166 kW, 28.8 % of averages between 0.03 and 1.00 kW 15 min: energy 8.081 kWh, largest average 0.753 kW, 76.0 % of averages between 0.03 and 1.00 kWGap from 09:00 to 11:00 power before the gap 1.166 kW, after the gap 0.013 kW sum of the readings that exist: 7.588 kWh (-6.1 %) straight line across the gap: 8.767 kWh (+8.5 %) last value held across the gap: 9.920 kWh (+22.8 %) counter at 09:00 3.138 kWh, at 11:00 3.630 kWh, energy in the gap 0.492 kWh counter at 24:00 minus counter at 00:00: 8.081 kWh energy from 00:00 to 03:00: 1.064 kWh (13.2 % of the day)Cold room, 14 days minute data: mean 4.013 degC, maximum 5.44 degC, 877 min above 5.0 degC (4.35 %) in 676 runs hourly mean: 336 values from 3.84 to 4.21 degC, 0 above 5.0 degC, mean of them 4.013 degC hourly maximum: 332 of 336 hours above 5.0 degC, 34 above 5.2 degC, largest 5.44 degC hourly minimum: 316 of 336 hours below 3.0 degC, smallest 2.66 degC hourly minutes above 5.0 degC: 0 to 6 in an hour, total 877 min one spot reading an hour: 1.79 to 8.33 % above 5.0 degC, by the minute chosenSaved sampling_and_aggregation.pngIn the top panel of the saved plot, two sets of 15 minute samples from the same four hours catch different runs. The middle panel shows the estimates spreading as the interval grows. In the bottom panel the hourly mean stays near 4 °C while the one minute readings touch the limit line in almost every cycle.
1. An energy counter reads 12,480.6 kWh at 00:00 and 12,611.9 kWh at 24:00. Find the energy of the day and the mean power.
2. A fan cycles with a period of 7 minutes. Its state is logged every 6 minutes. What period appears in the log? What is the longest interval that shows the true period?
3. A power log has one reading a minute. On one day 3 hours are missing. The readings that exist add to 41.2 kWh over 21 hours. The energy counter shows 49.0 kWh for the full day. Find the energy in the gap, the mean power in the gap, and the error of an estimate made by scaling the 21 hours to 24.
The gap holds
4. Change the script to sample the compressor of data set D every 30 minutes (one reading in every 180). Find the range of the energy estimate across the 180 phase offsets and the worst error.
Add ("30 min", 180) to the list of intervals. The estimate lies from 5.465 to 12.345 kWh, an error of
A compressor runs for 3 minutes and rests for 3 minutes, again and again. A logger stores its state once every 5 minutes. What does the log show?
The faint shape is the true power: an exact square wave of 1.16 kW and 0.014 kW, made for this figure. It is an illustration, not the lesson's data. Each dot is one instantaneous reading, and the stepped line holds it until the next reading. The solid bars under the plot are the same held readings alone: this is all that the log knows, and it is the machine that the log suggests. The phase is the moment of the first reading, as a percent of one interval: two loggers that start at different seconds have different phases. Energy from the samples is the mean of the readings multiplied by 3 hours. Energy from interval averages adds the true mean of every interval, so it is exact at any interval and any phase. The range across all phases uses 100 phases, from 0 to 99 percent. Below one minute the dots are not drawn.
Three questions. Each wrong choice is a mistake people really make, so read the note after you answer.
1. A fan cycles with a period of 10 minutes. Its state is logged every 8 minutes. What period appears in the log?
2. A load is on for 2.5 minutes and off for 2.5 minutes. Two loggers read its power every 5 minutes. One reports that the load was on all day. The other reports that it was off all day. Which logger is faulty?
3. A meter stores the average power of each 15 minute interval. In one interval the compressor is stopped at 0.014 kW, except for a run of 7.8 minutes at 1.16 kW. The stored value is 0.610 kW. What can you take from this value?
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.