Calculate energy from recorded power samples

This commit is contained in:
Steffen committed 2026-11-23 00:01:07 +01:00
1 parent 2117236366
commit b76897d8f8
4 files changed
+24 -13

No files matched your search

+1 -1
View File
@@ -90,7 +90,7 @@ Meter requests are excluded from the application's request-rate and latency summ
JMeter's overall console summary includes meter polls; use `run.json` and
`measured.csv` for the application-only figures.
Power integration uses trapezoids. Counter deltas provide a separate cross-check;
Energy from sampled power is the sum of the recorded in-window power values, each multiplied by the nominal polling interval. This assumes each reading represents that interval; actual polling timestamps may differ and sample coverage is reported. Counter deltas provide a separate cross-check;
the device's counter update granularity can make short runs report little or no
counter change despite nonzero power. Both boundary interpolation and meter accuracy
limit precision; this does not claim calibration. The plug measures what is connected
+9 -10
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env python3
"""Integrate timestamped external power readings over the exact measurement window."""
"""Sum timestamped external power readings at the nominal polling interval."""
import argparse, csv, datetime as dt, json
from pathlib import Path
p=argparse.ArgumentParser();p.add_argument('run');p.add_argument('power_csv');p.add_argument('--idle-watts',type=float);a=p.parse_args()
p=argparse.ArgumentParser();p.add_argument('run');p.add_argument('power_csv');p.add_argument('--idle-watts',type=float);p.add_argument('--interval-seconds',type=float,default=1);a=p.parse_args()
run=json.loads(Path(a.run).read_text());start=run['measurement_start_ms']/1000;end=run['measurement_end_ms']/1000
points=[]
with open(a.power_csv) as f:
@@ -14,14 +14,13 @@ with open(a.power_csv) as f:
points.append((instant.timestamp(),watts))
if len(points)<2 or any(b[0]<=a[0] for a,b in zip(points,points[1:])):p.error('Power timestamps must be strictly increasing')
if points[0][0]>start or points[-1][0]<end:p.error('Power samples must cover the entire measurement interval')
joules=0
for (t0,p0),(t1,p1) in zip(points,points[1:]):
lo=max(t0,start);hi=min(t1,end)
if hi<=lo:continue
plo=p0+(p1-p0)*(lo-t0)/(t1-t0);phi=p0+(p1-p0)*(hi-t0)/(t1-t0)
joules+=(plo+phi)/2*(hi-lo)
result={'duration_seconds':end-start,'joules':joules,'kWh':joules/3600000,'average_watts':joules/(end-start)}
if a.idle_watts is not None:result['joules_above_idle']=joules-a.idle_watts*(end-start)
if a.interval_seconds<=0:p.error('Interval must be positive')
measured=[power for timestamp,power in points if start<=timestamp<end]
if not measured:p.error('No power readings in measurement window')
coverage=len(measured)*a.interval_seconds
joules=sum(measured)*a.interval_seconds
result={'duration_seconds':end-start,'power_sample_count':len(measured),'nominal_sample_coverage_seconds':coverage,'method':'sum of recorded power readings multiplied by nominal interval','joules':joules,'kWh':joules/3600000,'average_watts':sum(measured)/len(measured)}
if a.idle_watts is not None:result['joules_above_idle']=joules-a.idle_watts*coverage
count=run.get('measured_http_samples',0)
if count:result['joules_per_http_request']=joules/count
print(json.dumps(result,indent=2))
+6 -2
View File
@@ -29,8 +29,12 @@ def summarize(raw,measured,start_ms,end_ms,interval_ms):
if a[0]<=time<=b[0]:return (time,*(a[i]+(b[i]-a[i])*(time-a[0])/(b[0]-a[0]) for i in range(1,5)))
raise ValueError('Missing boundary')
selected=[boundary(start_ms),*(p for p in points if start_ms<p[0]<end_ms),boundary(end_ms)]
joules=sum((a[1]+b[1])/2*(b[0]-a[0])/1000 for a,b in zip(selected,selected[1:]))
# Each recorded power reading represents one nominal polling interval.
# Do not interpolate power or invent readings at the window boundaries.
measured_points=[p for p in points if start_ms<=p[0]<end_ms]
if not measured_points:raise ValueError('No Shelly power readings inside the measured interval')
joules=sum(p[1] for p in measured_points)*(interval_ms/1000)
watt_hours=selected[-1][4]-selected[0][4]
with measured.open('w') as f:
w=csv.writer(f);w.writerow(['timestamp_ms','power_watts','voltage_volts','current_amps','energy_wh']);w.writerows(selected)
return {'measurement_seconds':(end_ms-start_ms)/1000,'samples_including_interpolated_boundaries':len(selected),'integrated_joules':joules,'integrated_kWh':joules/3600000,'average_watts':joules/((end_ms-start_ms)/1000),'counter_delta_Wh':watt_hours,'counter_joules':watt_hours*3600,'counter_kWh':watt_hours/1000,'boundary_method':'Linear interpolation between polls; timestamps approximate HTTP request midpoint'}
return {'measurement_seconds':(end_ms-start_ms)/1000,'samples_including_interpolated_boundaries':len(selected),'power_sample_count':len(measured_points),'nominal_sample_interval_ms':interval_ms,'nominal_sample_coverage_seconds':len(measured_points)*interval_ms/1000,'energy_method':'sum of recorded power readings multiplied by nominal polling interval; assumes each reading represents that interval','integrated_joules':joules,'integrated_kWh':joules/3600000,'average_watts':sum(p[1] for p in measured_points)/len(measured_points),'counter_delta_Wh':watt_hours,'counter_joules':watt_hours*3600,'counter_kWh':watt_hours/1000,'boundary_method':'Energy counter and exported plot boundaries interpolated; power sum uses only recorded in-window samples; timestamps approximate HTTP request midpoint'}
+8
View File
@@ -13,6 +13,14 @@ with tempfile.TemporaryDirectory(prefix='healthapp-shelly-test-') as name:
result=shelly.summarize(raw,root/'measured.csv',2500,17500,1000)
assert result['integrated_joules']==1500 and abs(result['counter_joules']-1500)<.0001
assert result['measurement_seconds']==15 and result['average_watts']==100
assert result['power_sample_count']==15 and result['nominal_sample_coverage_seconds']==15
# Variable power distinguishes a direct sample sum from trapezoidal integration.
with raw.open() as f: variable=list(csv.DictReader(f))
variable[3]['shelly_power_watts']='200'
with raw.open('w') as f:
w=csv.DictWriter(f,fieldnames=fields);w.writeheader();w.writerows(variable)
variable_result=shelly.summarize(raw,root/'variable.csv',2500,17500,1000)
assert variable_result['integrated_joules']==1600
for start,end in [(-1000,17500),(2500,25000)]:
try:shelly.summarize(raw,root/'bad.csv',start,end,1000)
except ValueError:pass