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

+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))