Skip to content
GebleaAlexPublic

About

Consumption you can audit, from meter readings you cannot trust. Rollovers, resets, gaps and late readings turned into consumption per interval, with a quality flag and bounds on every value.

Topics

Resources

Contributing

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

metervee

CI Python 3.11+ License: MIT

Consumption you can audit, from meter readings you cannot trust.

A register that wraps, two missing readings and a garbled one, turned into consumption per quarter-hour with a quality and a range for each

metervee turns raw meter readings (electricity, water, gas, heat, any counter) into consumption per interval. It handles what real data does: registers that wrap, meters that reset or get replaced, wild values, duplicates, corrections, holes, and readings that arrive a day late. Every value comes with a quality flag and with bounds, and the library says what those bounds assume.

Who it is for: anyone who turns counter readings into consumption and has to stand behind the numbers. Smart meter and sub-metering data, IoT pulse counters, energy management and billing, ESG and carbon reporting, research on load data.

It is pure Python (its only dependency is tzdata, on Windows), with an optional compiled core in Rust. It is early: version 0.2, and the API may still change.

Quick start

pip install git+https://github.com/GebleaAlex/metervee

The picture above, as code (examples/quickstart.py):

from datetime import UTC, datetime, timedelta
from decimal import Decimal

from metervee import Engine, Grid, Meter, Reading, quantize

start = datetime(2026, 3, 2, 8, 0, tzinfo=UTC)
# What a four-digit register showed every 15 minutes. It wraps, two readings never
# arrived, and one came through garbled.
shown = ["9998.2", "9999.1", "0000.4", None, None, "0003.1", "7341.0", "0005.0"]
readings = [
    Reading("main", start + timedelta(minutes=15 * index), Decimal(value))
    for index, value in enumerate(shown)
    if value is not None
]

engine = Engine([Meter.with_digits("main", 4, unit="kWh", max_rate=Decimal(15))])
engine.add(readings)  # any order, any number of times

cells = engine.intervals("main", start, start + timedelta(minutes=105), Grid.parse("15min"))
for cell, kwh in zip(cells, quantize([cell.value for cell in cells], 2), strict=True):
    print(f"{cell.start:%H:%M}  {kwh} kWh  between {float(cell.lower):g} and {float(cell.upper):g}  {cell.quality}")
print("left out:", [str(reading.value) for reading in engine.rejected("main")])

It prints this (the notes on the right are added here):

08:00  0.90 kWh  between 0.9 and 0.9  measured
08:15  1.30 kWh  between 1.3 and 1.3  measured        <- 9999.1 to 0000.4: a rollover
08:30  0.90 kWh  between 0 and 2.7  estimated         <- two readings missing: the 2.7 kWh
08:45  0.90 kWh  between 0 and 2.7  estimated            total is exact, its timing is not
09:00  0.90 kWh  between 0 and 2.7  estimated
09:15  0.95 kWh  between 0 and 1.9  interpolated      <- 7341.0 cannot be right: left out
09:30  0.95 kWh  between 0 and 1.9  interpolated
left out: ['7341.0']

The two things to know first

What the qualities mean. Every cell has one, and a cell takes the weakest quality of what went into it.

Quality Has a value Meaning
measured yes Both ends are readings. Nothing was assumed.
interpolated yes A measured amount, split evenly over a short stretch between two readings.
estimated yes The same over a longer stretch: the total is exact, its timing is a guess.
suspect yes The readings do not prove it: more than the meter can do, or resting on a reading in doubt.
ambiguous no Several amounts fit the readings. Only the bounds are known.
missing no Nothing can be said: no readings, a reset, a replaced device.

lower and upper say how far off a value can be. For measured they are equal to it.

How to choose max_rate. It is the most a meter can record in one hour, in the unit you want out, and it is the only evidence the engine has for telling a rollover from a reset and a real jump from a typo. Use a physical limit, not a typical value: for electricity the main fuse (a 3 x 25 A supply cannot exceed about 17 kWh in an hour), for water the meter's maximum flow (Qmax, or Q4), for gas the meter's rated maximum. Too high and wrong readings pass as plausible; too low and real peaks are marked suspect. Without it, nothing is checked. A register that wraps needs it.

For a mechanical register, add resets=False: it cannot lose its count, so a drop is only ever a wrong reading.

Common jobs

Load a CSV, write rows back.

import csv
from metervee import intervals_to_rows, readings_from_rows

with open("readings.csv", newline="") as file:
    readings = readings_from_rows(
        csv.DictReader(file),
        names={"measured_at": "timestamp", "value": "reading"},  # your column names
        meter="main",  # or a "meter" column
        tz="Europe/Bucharest",  # for timestamps that carry no zone
        blank="skip",  # an empty value is a row to skip, not a withdrawal
    )
engine.add(readings)
rows = intervals_to_rows(engine.intervals("main", start, end, "15min"), places=3, tz="Europe/Bucharest")

Values read from text are exact. Floats are refused unless you pass floats="shortest". readings_from_columns(), intervals_to_columns() and engine.table() do the same with whole columns, which is what polars, pandas and pyarrow exchange.

Monthly totals, or any billing period.

from metervee import month_edges

edges = month_edges(start, end, "Europe/Bucharest")  # local midnight on the 1st of each month
for month in engine.totals("water", edges):
    print(month.start, month.value, month.lower, month.upper, month.quality)

engine.total("water", any_moment, any_later_moment)  # one range

A total is computed from the readings, not by adding up days, so a gap that lies wholly inside the month is known exactly and the bounds stay tight.

Find out why.

for line in engine.explain("main", start, end):
    print(line)
# 2026-03-02 08:15 to 2026-03-02 08:30 UTC (15 min): 1.3; measured, the register wrapped past its last digit
# 2026-03-02 09:15 to 2026-03-02 09:45 UTC (30 min): 1.9; measured, the difference between two readings
#   left out 7341.0 read at 2026-03-02 09:30 UTC: it contradicts the readings around it

engine.steps() gives the same as data: the consumption between each pair of readings, with its cause and the readings left out. engine.rejected() lists those readings.

Correct a reading, and still reproduce what you reported.

engine.add(Reading("main", moment, Decimal("104.2"), recorded_at=now))  # replaces the earlier one
engine.add(Reading.void("main", other_moment, recorded_at=now))  # withdraws one
engine.intervals("main", start, end, grid, as_of=last_month)  # exactly what it said then

Each reading has the moment it was measured and the moment it was recorded. Nothing is overwritten, so any past answer can be recomputed. This rests on recorded_at being the time the reading reached you; left out, it is taken to be the time of measurement. A full example with a late reading is in examples/walkthrough.py.

Other kinds of meter.

Meter("heat", kind="interval", period=timedelta(minutes=15), tolerance=timedelta(seconds=30))
VirtualMeter("floors", {"floor 1": 1, "floor 2": 1})
VirtualMeter("unmetered", {"main": 1, "floors": -1})
VirtualMeter("tenant A", {"main": "0.35"})

An interval meter reports what was used in the period before each reading; tolerance moves a reading that is close to the end of a period onto it. A virtual meter is a sum, difference or share of others, only as good as its weakest term, and a tree of them is reduced to the real meters behind it, so nothing is counted twice.

How it decides

Readings are a set that only grows, and every answer is a pure function of that set. The order in which readings arrive cannot matter, a correction never destroys what it corrects, and the same readings always give the same result to the last digit: all arithmetic is exact, never floating point.

A register that only counts up can still go down in the data. max_rate tells the cases apart:

The readings show And Result
an increase it fits max_rate measured
an increase it is more than max_rate allows kept, marked suspect
a decrease one wrap of the register explains it measured, cause rollover
a decrease one wrap explains it, but across an outage kept, marked suspect
a decrease not even a wrap fits, or the register does not wrap missing, cause reset
either the gap is long enough for several wraps ambiguous, with bounds
a decrease the register wraps and no max_rate is known ambiguous: it is not guessed
an increase the register wraps and no max_rate is known kept as a lower bound, suspect

Readings that cannot be right. A value the register cannot show is rejected. So is a reading that contradicts both of its neighbours while they agree with each other. When two readings side by side contradict each other, the readings around them decide: if the rest fits without one of the two, that one is rejected; if it fits without either, both are left out and the total survives, only its timing is lost; if it fits without neither, the register really broke there and nothing is touched. In anything less clear (at the edge of the data, or where a reset would explain it too) the readings stay in, and the steps that rest on them are marked suspect.

Bounds. Splitting 12 kWh evenly over four quarter-hours is an assumption. What is certain is that each quarter-hour got between 0 and 12. value is the estimate, lower and upper are the certainty.

Gaps. The energy of a gap is exact; only its timing is estimated: evenly, or with gaps="profile" by the meter's own usual shape for that time of day.

Time. Grids restart at local midnight and are measured in elapsed time, so the day clocks go forward has 23 hours and 92 quarter-hours, and the day they go back has 25 and 100.

The reasoning behind each of these, including the versions that turned out wrong, is in docs/design.md.

What the guarantees assume

The bounds contain the true consumption, and a measured value is the true one, as long as three things hold: the readings that were kept are correct, max_rate really is a maximum, and the device was not reset without it showing. metervee works to detect when they do not hold, and says so with a flag. These cases it cannot detect, because the readings are identical to innocent ones:

  • A wrong value between its neighbours. 1020, 1023, 1025 with the middle one mistyped as 1022.
  • A reset just before the register would have wrapped. It looks exactly like the wrap. In four years of real data, with resets simulated, this happened in 1 cell of 133,759.
  • A reset hidden in a gap that leaves no drop. If the register has climbed back above its old value by the next reading, nothing shows. A rollover across an outage is flagged for this reason; an ordinary increase across one is not.

One thing is not monotonic: more readings usually tighten the bounds, but on a register that wraps, a new reading can reveal that a rollover spans an outage, and that takes certainty away.

Evidence

Benchmark. Four years of a real household's consumption, minute by minute (the UCI data set, 1,394 days in 61 complete runs), are fed through a simulated four-digit meter read every 15 minutes. Then 5% of the readings are lost, 0.5% are replaced by random values and each run gets a device reset (one every 23 days on average). Scored against the real consumption, per 15-minute cell:

Pipeline Energy in trusted cells Net error in those cells Wrong cells shown as measured
sort, interpolate, diff, clip negatives 100.00% +7800.26% 8,309 of 133,759
metervee 99.49% +0.01% 1 of 133,759

The first pipeline is deliberately the simplest one; it trusts every cell. metervee declines to vouch for 0.51% of the energy, so a total over its trusted cells is that much short of the real one, and says so. The one wrong cell is the reset just before a wrap described above. Method, every scenario and the limits: benchmarks/README.md.

Tests. Besides ordinary tests, properties are checked on generated data: arrival order never changes a result; as_of equals an engine that only ever saw the past; a window computed from the readings around it equals the same window from the whole history; totals are conserved; with correct readings, the truth is inside the bounds and equals every measured value, also when the device wraps or resets; nothing wrong is vouched for when readings are slightly off; and the compiled core equals the Python reference. Two independent reviews found defects that the tests had missed; each has a regression test in tests/test_review_findings.py and tests/test_second_review.py.

Speed. Adding a reading and asking about a window of time do not depend on the length of the history, because what happens to a reading depends only on a few readings around it. python -m benchmarks.speed, on a laptop, one meter read every 15 minutes:

History Readings One day All cells, reference All cells, compiled Columns, compiled
30 days 2,706 2.5 ms 0.08 s 0.01 s 0.01 s
365 days 32,937 2.5 ms 1.03 s 0.20 s 0.16 s
3650 days 329,376 2.5 ms 11.51 s 2.09 s 1.74 s

Two kinds of question do look at the whole history: one with as_of, and the first one with gaps="profile" after a reading is added.

The compiled core (rust/) is a Rust port of reconstruction, allocation and rounding into columns, with the same exact arithmetic (128-bit integers while numbers fit, arbitrary precision when they do not). pip install ./rust builds it, and the engine then uses it for large inputs. Its results are equal to the reference, not close to it; engine.table() is where it pays most. metervee.accel.available() says whether it is installed.

What is not there yet

  • A meter exchange with known closing and opening readings. replaced_at makes the consumption across a swap unknown, even when both readings were taken.
  • Readings that arrive already marked as estimated by their source, and a data-quality report per meter.
  • Interval periods in local time. tolerance assumes periods end on whole multiples of the period counted in UTC: right for quarter-hours and hours, wrong for daily periods that end at local midnight. Interval readings stamped at the start of their period need shifting by you.
  • Better gap estimation. The profile cuts the error of an even split by about a fifth. What is left is bursts that no average can place.
  • Storage. Readings live in memory. (An engine can be pickled.)
  • A faster compiled core. It is several times faster than the reference, not orders of magnitude: most of what is left is building Python objects.
  • A wider benchmark. One household and one kind of load so far.

Related work

SaQC and Pecos flag suspicious values in sensor time series. metervee is about the step before and after that for meters specifically: getting from register readings to consumption, and keeping every correction reproducible.

Contributing: CONTRIBUTING.md. License: MIT.

About

Consumption you can audit, from meter readings you cannot trust. Rollovers, resets, gaps and late readings turned into consumption per interval, with a quality flag and bounds on every value.

Topics

Resources

Contributing

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages