#!/usr/bin/env python3 """Python 3, stdlib: python3 laghouat-batterie.py Laghouat_2022_final.csv Données: Mohammed Seghir, Mendeley Data v3, 10.17632/4jdt83yy43.3, CC BY 4.0. Requires laghouat-rejouer.py alongside this file. """ import csv import math import runpy import sys from collections import defaultdict from datetime import date, timedelta from pathlib import Path from statistics import mean DURATIONS = (1, 3, 7, 14) RULES = ("rapport","pesee","marge") HOURS = range(11,17) CUT = date(2022,5,19) TASK = 75 EPS = 1e-8 def simulate(days, cap, load, production, allow): """production(day, hour_index) and allow(day, state) are injected separately.""" state = 0.7*cap missing, done, accepted = [], [], [] for day in days: for i in range(24): net = state + (production(day,i) if i<6 else 0) - load missing.append(max(0,-net)) state = min(cap,max(0,net)) if i==6: on = bool(allow(day,state)) accepted.append(on) served = on and state+EPS>=TASK done.append(served) if served: state = max(0,state-TASK) assert 0<=state<=cap return missing,done,accepted,state def compare(days, previous, clean, actual, coeff, guard, cap, load, audit=False, rules=RULES): first = days[0][0] ratio = previous[6]/previous[4] a,b = coeff assert previous[0]==first-timedelta(days=1) result=[] for rule in rules: def estimate(d,i): factor=ratio if rule in ("rapport","rapport_marge") else max(0,a+b*d[3]) if rule in ("marge","rapport_marge"): factor *= (1-guard) return clean[d[0]][i]*factor # The decision sees the virtual ledger and contemporaneous clean-panel readings only. decisions=simulate(days,cap,load,estimate,lambda d,s:s+EPS>=TASK+17*load)[2] def observe(d,i): return actual[d[0]][i] def replay(flags): it=iter(flags) return simulate(days,cap,load,observe,lambda d,s:next(it)) missing,done,_,state=replay(decisions) avoidable=0 if audit: for i,yes in enumerate(decisions): if yes: continue alt=decisions.copy() alt[i]=True other_missing,other_done,_,_=replay(alt) # Individually safe: no new/worsened essential shortfall in any hour, # no loss of any originally delivered optional task, and task succeeds. avoidable+=bool(other_done[i] and all(x<=y+EPS for x,y in zip(other_missing,missing)) and all(not x or y for x,y in zip(done,other_done))) result.append((rule,sum(x>EPS for x in missing),sum(missing),sum(done), len(days)-sum(decisions),sum(decisions)-sum(done),avoidable,state)) return result def analyze(train, test, clean, actual, coeff, guard, cap, load, audit=False, rules=RULES): groups=defaultdict(list) output=[] seq=[train[-1]]+test for n in DURATIONS: for i in range(78): days=test[i:i+n] assert len(days)==n and all(row[1].date()=CUT] assert len(train)==90 and len(test)==91 a,b=coeff=ref["fit"](train[:60],4,True) residuals=[] for r in train[60:]: pred=r[4]*max(0,a+b*r[3]) residuals.append(max(0,1-r[6]/pred) if pred>0 else 0) guard=sorted(residuals)[math.ceil(.9*len(residuals))-1] clean,actual=defaultdict(list),defaultdict(list) for r in raw: t=r["time"] if t.hour in HOURS: clean[t.date()].append(r["P_clean_W"]) actual[t.date()].append(r["P_dusty_W"]) assert all(len(clean[r[0]])==6 and abs(sum(actual[r[0]])-r[6])0 for x in g)) # Variants fixed independently of test outcomes: one axis at a time. for cap,load in [(280,9),(480,9),(360,8),(360,10)]: g,_=analyze(train,test,clean,actual,coeff,guard,cap,load) print("variante 14 j",cap,load,[(k,round(mean(x[1] for x in g[14,k]),2), round(mean(x[3] for x in g[14,k]),2)) for k in RULES]) control,_=analyze(train,test,clean,actual,coeff,guard,360,9,True,("rapport_marge",)) g=control[14,"rapport_marge"] print("même marge, appliquée au rapport 14 j", *[round(mean(x[j] for x in g),3) for j in range(1,7)],sum(x[1]>0 for x in g)) with open("laghouat-batterie.csv","w",encoding="utf-8",newline="") as out: w=csv.writer(out) w.writerow(("debut","fin","jours","regle","heures_essentielles_partiellement_ou_totalement_manquees", "Wh_essentiels_manques","taches_servies","taches_refusees", "taches_autorisees_non_servies","refus_individuellement_evitables","charge_finale_Wh")) for r in rows: w.writerow((*r[:5],f"{r[5]:.5f}",*r[6:-1],f"{r[-1]:.5f}")) if __name__=="__main__": main()