Repository navigation
Expand file tree
/
Copy pathfetch.py
More file actions
3385 lines (3010 loc) · 189 KB
/
Copy pathfetch.py
File metadata and controls
3385 lines (3010 loc) · 189 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -----------------------------------------------------------------------------
# Predbat Home Battery System
# Copyright Trefor Southwell 2026 - All Rights Reserved
# This application maybe used for personal use only and not for commercial use
# -----------------------------------------------------------------------------
# fmt off
# pylint: disable=consider-using-f-string
# pylint: disable=line-too-long
# pylint: disable=attribute-defined-outside-init
# pyright: reportAttributeAccessIssue=false
"""Data fetching module for energy rates, consumption, and forecasts.
Orchestrates loading of import/export energy rates from multiple sources
(Octopus, Energi Data Service, manual config), historical load and PV data,
battery temperature, and other sensor inputs. Converts all data to per-minute
dictionaries for use by the prediction engine.
"""
from datetime import datetime, timedelta
from utils import minutes_to_time, str2time, dp1, dp2, dp3, dp4, time_string_to_stamp, minute_data, get_now_from_cumulative, MinuteArray
from const import (
MINUTE_WATT,
PREDICT_STEP,
TIME_FORMAT,
PREDBAT_MODE_OPTIONS,
PREDBAT_MODE_CONTROL_SOC,
PREDBAT_MODE_CONTROL_CHARGEDISCHARGE,
PREDBAT_MODE_CONTROL_CHARGE,
PREDBAT_MODE_MONITOR,
LOAD_FORECAST_HISTORY_MAX_DAYS,
PREDBAT_MAX_CARS,
CAR_CHARGING_LIMIT_UNCAPPED,
CLOUD_WINDOW_MINUTES,
CLOUD_ARRAY_MARGIN,
PV_ARRAY_KWP_UNKNOWN,
)
from predbat_metrics import metrics
from futurerate import FutureRate
from axle import fetch_axle_sessions, load_axle_slot, fetch_axle_active
import copy
class Fetch:
"""Data fetching mixin for loading energy rates, consumption, and forecasts.
Orchestrates loading of import/export rates from multiple sources,
historical load/PV data, battery temperature, car charging energy,
and other sensor inputs. Converts all data to per-minute dictionaries.
"""
def get_cloud_factor(self, minutes_now, pv_data, pv_data10):
"""
Work out approximated cloud factor
"""
pv_total = 0
pv_total10 = 0
for minute in range(self.forecast_minutes):
pv_total += pv_data.get(minute + minutes_now, 0.0)
pv_total10 += pv_data10.get(minute + minutes_now, 0.0)
pv_factor = None
if pv_total > 0 and (pv_total > pv_total10):
pv_diff = pv_total - pv_total10
pv_factor = dp2(pv_diff / pv_total) / 2.0
pv_factor = min(pv_factor, 1.0)
if self.metric_cloud_enable:
pv_factor_round = pv_factor
if pv_factor_round:
pv_factor_round = dp1(pv_factor_round)
self.log("PV Forecast {}kWh and 10% Forecast {}kWh; PV cloud factor {}".format(dp1(pv_total), dp1(pv_total10), pv_factor_round))
return pv_factor
else:
return None
def get_cloud_duty(self, minutes_now, pv_data, pv_data10, pv_data90):
"""Work out how many steps of each conservation window the envelope model spends raised.
Peaks reach the p90 ceiling and troughs reach the p10 floor together only when the up:down
step ratio matches the band's own asymmetry, (p50-p10):(p90-p50). Solcast's downside is
typically about twice its upside, so a fixed 1:1 alternation - all the pairwise model could
express - always under-reaches on one side.
Returns (n_up, n_down), or None when there is no upside band to reach for: a forecast source
that publishes no p90 falls back to a copy of the p50, and the caller must keep the legacy
proportional model rather than silently losing the cloud model altogether.
"""
up_gap = 0.0
down_gap = 0.0
for minute in range(self.forecast_minutes):
nominal = pv_data.get(minute + minutes_now, 0.0)
up_gap += max(pv_data90.get(minute + minutes_now, 0.0) - nominal, 0.0)
down_gap += max(nominal - pv_data10.get(minute + minutes_now, 0.0), 0.0)
if up_gap <= 0:
return None
period = CLOUD_WINDOW_MINUTES // PREDICT_STEP
ratio = down_gap / up_gap
# Clamped to leave at least one step on each side - a window that is all up or all down has
# nothing to trade against and would leave the borrow outstanding.
n_up = int(min(max(round(period * ratio / (1.0 + ratio)), 1), period - 1))
return (n_up, period - n_up)
def resolve_pv_array_kwp(self, detected_kwp):
"""Settle the DC array size the p90 cloud ceiling is capped against.
Forecast Solar and Open-Meteo declare kwp per array and fetch_pv_forecast already totals it,
so most setups need no configuration. Solcast and the HA integrations publish no array size
and arrive as the PV_ARRAY_KWP_UNKNOWN sentinel, leaving the cap inert - correct, since an
invented figure would be worse than none. apps.yaml wins over both: declared figures are
routinely understated, users entering the inverter rating or one string of two.
"""
configured = self.get_arg("pv_array_kwp", 0.0)
if configured and configured > 0:
self.pv_array_kwp = float(configured)
elif detected_kwp and 0 < detected_kwp < PV_ARRAY_KWP_UNKNOWN:
self.pv_array_kwp = float(detected_kwp)
else:
self.pv_array_kwp = 0.0
return self.pv_array_kwp
def get_pv90_cloud_ceiling(self, minutes_now, pv_data, pv_data90):
"""Build the per-minute ceiling the p90 series modulates toward.
p50 reaches for p90 and p10 reaches for p50, but p90 has no next percentile above it, so its
upside is extrapolated by continuing the band one width further. Leaving p90 unmodulated
instead is not neutral: it makes p90 the one smooth scenario, handing it an efficiency
bonus the other two do not get and biasing every comparison between them.
The extrapolation is capped at the DC array size times CLOUD_ARRAY_MARGIN, since a very wide
band can otherwise reach past anything the array could physically produce. The cap can never
pull the ceiling below p90 itself - that would invert the upside scenario into a downside
one, which is the same failure mode load_scaling90 is clamped against.
"""
array_kwp = getattr(self, "pv_array_kwp", 0) or 0
cap = (array_kwp * CLOUD_ARRAY_MARGIN / 60.0) if array_kwp > 0 else None
ceiling = {}
for minute in range(self.forecast_minutes):
minute_absolute = minute + minutes_now
upside = pv_data90.get(minute_absolute, 0.0)
extended = upside + max(upside - pv_data.get(minute_absolute, 0.0), 0.0)
if cap is not None:
extended = max(min(extended, cap), upside)
ceiling[minute_absolute] = extended
return ceiling
def filtered_today(self, time_data, resetmidnight=False, stamp=None):
"""
Grab figure for today (midnight)
"""
if stamp is None:
stamp = self.midnight_utc + timedelta(days=1)
stamp_minus = stamp - timedelta(minutes=PREDICT_STEP)
if resetmidnight:
stamp = stamp_minus
tomorrow_value = time_data.get(stamp.strftime(TIME_FORMAT), time_data.get(stamp_minus.strftime(TIME_FORMAT), None))
return tomorrow_value
def filtered_times(self, time_data):
"""
Filter out duplicate values in time series data
"""
prev = None
new_data = {}
keys = list(time_data.keys())
for id in range(len(keys)):
stamp = keys[id]
value = time_data[stamp]
next_value = time_data[keys[id + 1]] if id + 1 < len(keys) else None
if prev is None or value != prev or next_value != value:
new_data[stamp] = value
prev = value
id += 1
return new_data
def inday_yesterday_weight(self, minutes_now):
"""
Weight the previous day's in-day load adjustment carries at a point in the day: full weight for the
first three hours (too little of today has happened to measure a divergence), then decaying linearly
to zero by midnight as today's own measurement takes over.
"""
if minutes_now < 180:
return 1.0
return (24 * 60 - minutes_now) / (24 * 60)
def inday_adjustment_at(self, minute_absolute, scale_today):
"""
In-day load adjustment factor to apply at a given minute from midnight today.
Today keeps the factor in full. Tomorrow it decays on exactly the curve load_today_comparison() will
use when it seeds tomorrow's factor from today's final value, so the plan agrees with what Predbat
will actually apply a few hours later - resetting to 1.0 at midnight instead left tonight's overnight
charge sized against a forecast Predbat was about to correct (batpred#4732). Beyond tomorrow there is
no measurement left to carry and the factor is neutral.
"""
day_offset = minute_absolute // (24 * 60)
if day_offset <= 0:
return scale_today
if day_offset > 1:
return 1.0
return 1.0 + (scale_today - 1.0) * self.inday_yesterday_weight(minute_absolute % (24 * 60))
def step_data_history(
self,
item,
minutes_now,
forward,
step=PREDICT_STEP,
scale_today=1.0,
scale_fixed=1.0,
type_load=False,
load_forecast=None,
cloud_factor=None,
cloud_ceiling=None,
cloud_duty=None,
load_scaling_dynamic=None,
base_offset=None,
flip=False,
load_adjust=None,
load_baseline=None,
):
"""
Create cached step data for historical array
"""
if load_baseline is None:
load_baseline = {}
if load_adjust is None:
load_adjust = {}
if load_forecast is None:
load_forecast = {}
values = {}
cloud_diff = 0
for minute in range(0, self.forecast_minutes + self.plan_interval_minutes, step):
value = 0
minute_absolute = minute + minutes_now
scaling_dynamic = 1.0
if load_scaling_dynamic:
scaling_dynamic = load_scaling_dynamic.get(minute_absolute, scaling_dynamic)
# Carry the in-day adjustment over midnight on the decay curve load_today_comparison() will
# apply tomorrow, rather than resetting it to 1.0 (batpred#4732)
scale_slot = self.inday_adjustment_at(minute_absolute, scale_today)
if type_load and not forward:
if self.load_forecast_only:
load_yesterday, load_yesterday_raw = (0, 0)
else:
load_yesterday, load_yesterday_raw = self.get_filtered_load_minute(item, minute, historical=True, step=step)
value += load_yesterday
else:
for offset in range(step):
if forward:
value += item.get(minute + minutes_now + offset, 0.0)
else:
if base_offset:
value += self.get_historical_base(item, minute + offset, base_offset)
else:
value += self.get_historical(item, minute + offset)
# Extra load adding in (e.g. heat pump)
load_extra = 0
if load_forecast:
for _offset in range(step):
load_extra += self.get_from_incrementing(load_forecast, minute_absolute, backwards=False)
if load_adjust:
load_extra += load_adjust.get(minute_absolute, 0) * step / float(self.plan_interval_minutes) # The kWh figure is for the plan interval period, so divide by plan_interval_minutes and times by step
load_extra = max(load_extra, -value) # Don't allow going to negative load values
values[minute] = dp4((value + load_extra) * scaling_dynamic * scale_slot * scale_fixed)
# Apply dynamic baseline
if minute_absolute in load_baseline:
values[minute] = max(values[minute], load_baseline[minute_absolute])
# Envelope-driven divergence model. Where the legacy model below swings by a fraction of
# the local value, this one swings toward a real per-minute ceiling - the next forecast
# percentile up - so the amplitude follows what the forecaster actually said about
# uncertainty at that time of day rather than one horizon-wide scalar.
#
# Conservation is per CLOUD_WINDOW_MINUTES rather than per adjacent pair. That is the whole
# point of the window: a pair can only trade 1:1, so a trough can never fall further than
# the peak beside it rose, and with an asymmetric p10/p50/p90 band the peak is the narrow
# side. Six steps to a window allow an uneven duty cycle (n_up up, n_down down), which lets
# peaks reach the ceiling while troughs still fall far enough to change the plan.
if cloud_ceiling and cloud_duty:
n_up, n_down = cloud_duty
period = n_up + n_down
# flip offsets the pattern by n_up so a flipped series lowers exactly where the plain
# one raises - the antiphase the legacy model got from a 1:1 alternation, generalised
# to an uneven duty cycle.
phase = n_up if flip else 0
for window_start in range(0, self.forecast_minutes, CLOUD_WINDOW_MINUTES):
offsets = [minute for minute in range(window_start, min(window_start + CLOUD_WINDOW_MINUTES, self.forecast_minutes), step)]
ups = [minute for minute in offsets if (((minute + minutes_now) // step) + phase) % period < n_up]
downs = [minute for minute in offsets if minute not in ups]
if not ups or not downs:
continue
window_total = sum(values[minute] for minute in offsets)
headroom = {minute: max(sum(cloud_ceiling.get(minute + minutes_now + offset, 0.0) for offset in range(step)) - values[minute], 0.0) for minute in ups}
want = sum(headroom.values())
# Each down step can give back at most what it holds, so the window can never be
# driven negative and never has to leave a borrow outstanding.
room = sum(max(values[minute] - (load_baseline.get(minute + minutes_now, 0.0) if load_baseline else 0.0), 0.0) for minute in downs)
borrow = min(want, room)
if borrow <= 0:
continue
for minute in ups:
values[minute] = dp4(values[minute] + headroom[minute] * borrow / want)
for minute in downs:
floor = load_baseline.get(minute + minutes_now, 0.0) if load_baseline else 0.0
values[minute] = dp4(values[minute] - borrow * max(values[minute] - floor, 0.0) / room)
# dp4 on each step leaves up to half a milliwatt-hour per step unaccounted for.
# Push that residual onto the roomiest down step, which recovers the window total on
# any window holding meaningful energy - the scenarios are compared against each
# other, so a systematic drift in one of them is a bias in the plan, not a rounding
# detail. It is not guaranteed: the correction is floored at zero, so a window whose
# roomiest down step holds less than the residual keeps the remainder. In practice
# that is confined to near-empty dawn and dusk windows and measures around 0.001 kWh
# over a 48 hour horizon.
drift = sum(values[minute] for minute in offsets) - window_total
if drift:
roomiest = max(downs, key=lambda minute: values[minute])
values[roomiest] = dp4(max(values[roomiest] - drift, 0.0))
# Simple divergence model that raises and lowers alternate steps so the planner stops
# assuming PV exactly blankets load. It is approximately - not exactly - total-preserving:
# a raised step borrows, and the following step repays only what its own value can cover
# (`min(cloud_diff, values[minute])`), so a borrow larger than the step that follows it is
# not fully given back. Repaying exactly needs the outstanding debt tracked separately from
# the next borrow, which is a rewrite of the model rather than a tweak here.
if cloud_factor and cloud_factor > 0:
last_minute = self.forecast_minutes - step
for minute in range(0, self.forecast_minutes, step):
# The inner parentheses matter: a conditional expression binds looser than "+", so
# "int(...) + 1 if flip else 0" is "(int(...) + 1) if flip else 0" - which is a
# constant 0 whenever flip is False, leaving every non-flipped caller unmodulated.
# flip only means anything as an antiphase to a modulated base, so it is the offset
# that is conditional, not the whole expression.
#
# Keyed off the minutes_now parameter, not self.minutes_now: every other minute in
# this function comes from the parameter, and output.py already calls it with 0.
# That also keeps the result a pure function of the inputs, which the replay and
# test paths rely on for determinism.
cloud_on = (int((minute + minutes_now) / step) + (1 if flip else 0)) % 2
if cloud_on > 0:
# Don't borrow on the final step - the fill loop above runs a plan interval
# past forecast_minutes, so values.get(minute + step) finds a real bucket that
# this loop will never reach to repay, leaking that borrow into the total.
if minute < last_minute:
cloud_diff += min(values[minute] * cloud_factor, values.get(minute + step, 0) * cloud_factor)
values[minute] += cloud_diff
else:
# The dynamic load baseline is a floor, applied in the fill loop above. The
# subtract has to respect it or the modulation walks straight back through it -
# only ever an issue since the load arrays started being modulated at all.
floor = load_baseline.get(minute + minutes_now, 0.0) if load_baseline else 0.0
subtract = min(cloud_diff, max(values[minute] - floor, 0.0))
values[minute] -= subtract
cloud_diff = 0
values[minute] = dp4(values[minute])
return values
def get_filtered_load_window(self, data, indices, step):
"""
Compute the car-charging/iBoost-filtered load for a single window given its list of backwards minute
indices. Returns (filtered_load, raw_load) for that one window (no base-load applied).
"""
raw = 0.0
subtract_energy = 0.0
for idx in indices:
raw += self.get_from_incrementing(data, idx)
if self.car_charging_hold and self.car_charging_energy:
subtract_energy += self.get_from_incrementing(self.car_charging_energy, idx)
if self.iboost_energy_subtract and self.iboost_energy_today:
subtract_energy += self.get_from_incrementing(self.iboost_energy_today, idx)
load = max(0.0, raw - subtract_energy)
if self.car_charging_hold and (not self.car_charging_energy) and (load >= (self.car_charging_threshold * step)):
# Car charging hold - ignore car charging in this window based on the threshold
load = max(load - (self.car_charging_rate[0] * step / 60.0), 0)
return load, raw
def get_filtered_load_minute(self, data, minute_previous, historical, step=1, base_in_raw=True):
"""
Gets a previous load minute after filtering for car charging.
For historical (days_previous) data the car-charging hold and car/iBoost subtraction are applied to
each previous day individually and only then weighted-averaged, so a single day's car charging is not
diluted below the hold threshold by averaging it with the other (lower-load) days first.
base_in_raw controls whether the base-load top-up is reflected in the returned raw value. Set it to
False to keep the raw value at the true measured load so callers can detect genuine zero/gap buckets.
"""
if historical:
total = 0.0
total_raw = 0.0
total_weight = 0.0
for point, days in enumerate(self.days_previous):
use_days = max(min(days, self.load_minutes_age), 1)
weight = self.days_previous_weight[point]
full_days = 24 * 60 * (use_days - 1)
indices = [24 * 60 - (minute_previous + offset) + full_days for offset in range(step)]
day_load, day_raw = self.get_filtered_load_window(data, indices, step)
total += day_load * weight
total_raw += day_raw * weight
total_weight += weight
if total_weight > 0:
load_yesterday = total / total_weight
load_yesterday_raw = total_raw / total_weight
else:
load_yesterday = 0.0
load_yesterday_raw = 0.0
else:
indices = [minute_previous + offset for offset in range(step)]
load_yesterday, load_yesterday_raw = self.get_filtered_load_window(data, indices, step)
# Apply base load
base_load = self.base_load * step / 60.0
if load_yesterday < base_load:
add_to_base = base_load - load_yesterday
load_yesterday += add_to_base
if base_in_raw:
load_yesterday_raw += add_to_base
return load_yesterday, load_yesterday_raw
def fill_load_from_power(self, load_minutes, load_power_data):
"""
This function helps to deal with load sensors which don't increment very often leading to poor quality load data
For example if its in kWh units then it might take many hours to increment.
Predbat actually wants a much more real time estimate, but integrating power sensors alone leads to drift over time.
Strategy: Divide data into 30-minute periods. For each period:
1. Calculate total load consumed (difference between start and end of period)
2. Integrate power data over that period
3. Scale power data to match the total load
4. Generate smooth minute-by-minute load curve
Since data goes backwards in time (minute 0 is now, higher minutes are further in past),
the load value DECREASES as we go forward in time (backwards through minutes).
"""
if not load_power_data:
self.log("Warn: No power data provided to fill_load_from_power")
return load_minutes
# Create a copy to avoid modifying the original
new_load_minutes = load_minutes.copy()
# Find all the minutes we have load data for.
# Deliberately do NOT extend max_minute using load_power_data.keys() even if the power
# sensor has older history than the load sensor. Any minutes beyond the load data range
# have no cumulative energy readings and would all default to 0, which the zero-period
# detection incorrectly treats as a full-day data gap every run.
max_minute = max(load_minutes.keys()) if load_minutes else 0
# Determine gap size threshold for zero-load detection
# This uses the same threshold as the gap filling logic
gap_size = max(self.get_arg("load_filter_threshold", self.plan_interval_minutes), 5)
# Preprocessing: Fill periods of zero load where power data exists
# Find zero-load periods by looking for consecutive minutes with the same value (or 0)
zero_periods = []
period_start = None
last_value = None
for minute in range(0, max_minute + 1):
current_value = new_load_minutes.get(minute, 0)
# Check if this is a zero or constant period
if minute == 0:
last_value = current_value
if current_value == 0 or current_value == new_load_minutes.get(minute + 1, 0):
period_start = minute
else:
# If value is same as previous and same as next, it's a flat period
next_value = new_load_minutes.get(minute + 1, current_value)
if current_value == last_value and current_value == next_value:
if period_start is None:
period_start = minute
else:
# End of constant period
if period_start is not None and period_start < minute:
period_length = minute - period_start
# Only consider it zero load if it exceeds the gap_size threshold
if period_length >= gap_size:
# Check if there's power data in this period
has_power = any(load_power_data.get(m, 0) > 0 for m in range(period_start, minute))
if has_power and (last_value == 0 or last_value == new_load_minutes.get(minute, 0)):
zero_periods.append((period_start, minute - 1, last_value))
period_start = None
last_value = current_value
# Check final period
if period_start is not None and period_start < max_minute:
period_length = max_minute - period_start + 1
# Only consider it zero load if it exceeds the gap_size threshold
if period_length >= gap_size:
has_power = any(load_power_data.get(m, 0) > 0 for m in range(period_start, max_minute + 1))
if has_power and last_value == 0:
zero_periods.append((period_start, max_minute, last_value))
# Fill zero periods with integrated power data
if zero_periods:
self.log("Warn: Found {} periods of zero load with power data, filling using power integration".format(len(zero_periods)))
# Print the first 5 periods for debugging
for _i, (period_start, period_end, base_value) in enumerate(zero_periods[:5]):
start_timestamp = self.now_utc - timedelta(minutes=period_start)
self.log("Zero load period starting at {} ({} minutes) for {} minutes with base value {}".format(start_timestamp.strftime(TIME_FORMAT), period_start, period_end - period_start + 1, base_value))
for period_start, period_end, _base_value in zero_periods:
# Integrate power data over this period
# First calculate total energy consumed in this period
total_energy = 0
for minute in range(period_start, period_end + 1):
power = load_power_data.get(minute, 0)
total_energy += power / 60.0 / 1000.0
amount_to_fill = 0
for minute in range(period_end, period_start, -1):
power = max(load_power_data.get(minute, 0), 0)
energy = power / 60.0 / 1000.0
amount_to_fill += energy
new_load_minutes[minute] = new_load_minutes.get(minute, 0) + amount_to_fill
# Fill to start
for minute in range(period_start, -1, -1):
new_load_minutes[minute] = new_load_minutes.get(minute, 0) + amount_to_fill
# Process in 30-minute periods
period_length = 30
num_periods = (max_minute + period_length) // period_length
self.log("Processing {} 30-minute periods for power integration".format(num_periods))
for period_idx in range(num_periods):
period_start = period_idx * period_length
period_end = min(period_start + period_length - 1, max_minute)
# Get load at start and end of period (going backwards in time)
# period_start is more recent (higher cumulative value)
# period_end is further in past (lower cumulative value)
load_at_start = new_load_minutes.get(period_start, 0)
load_at_end = new_load_minutes.get(period_end + 1, new_load_minutes.get(period_end, 0))
# Total energy consumed in this period (going backwards means decrement)
load_total = load_at_start - load_at_end
# Integrate power data over this period (convert W to kWh)
integrated_energy = 0.0
power_count = 0
for minute in range(period_start, period_end + 1):
power = max(load_power_data.get(minute, 0), 0)
if power > 0:
power_count += 1
# Convert watts to kWh per minute: W * (1 hour / 60 minutes) / 1000
integrated_energy += power / 60.0 / 1000.0
# If we have both power data and load consumption, scale the power integration
if integrated_energy > 0 and load_total > 0:
# Calculate scaling factor to match load total
scale_factor = load_total / integrated_energy
# Apply scaled power integration to create smooth load curve
# Start from the highest value (at period_start = most recent)
# and decrement going backwards in time
running_total = load_at_start
for minute in range(period_start, period_end + 1):
new_load_minutes[minute] = dp4(running_total)
power = max(load_power_data.get(minute, 0), 0)
energy_decrement = (power / 60.0 / 1000.0) * scale_factor
running_total -= energy_decrement
elif load_total > 0:
# No power data but we have load consumption
# Distribute the load evenly across the period
energy_per_minute = load_total / (period_end - period_start + 1)
running_total = load_at_start
for minute in range(period_start, period_end + 1):
new_load_minutes[minute] = dp4(running_total)
running_total -= energy_per_minute
return new_load_minutes
def previous_days_modal_filter(self, data):
"""
Look at the data from previous days and discard the best case one
"""
total_points = len(self.days_previous)
sum_days = []
sum_days_id = {}
min_sum = 99999999
min_sum_day = 0
sum_all_days = {}
days_list = self.days_previous.copy()
# Sort days list in numerical order with highest number day first
days_list.sort(reverse=True)
max_days = min(max(days_list), self.load_minutes_age) if self.load_minutes_age > 0 else max(days_list)
for days in range(1, max_days + 1):
sum_day = 0
full_days = 24 * 60 * (days - 1)
for minute in range(0, 24 * 60, PREDICT_STEP):
minute_previous = 24 * 60 - minute + full_days - 1
load_yesterday, load_yesterday_raw = self.get_filtered_load_minute(data, minute_previous, historical=False, step=PREDICT_STEP)
sum_day += load_yesterday
if days in days_list:
sum_days.append(dp2(sum_day))
sum_days_id[days] = sum_day
if sum_day < min_sum:
min_sum_day = days
min_sum = dp2(sum_day)
sum_all_days[days] = dp2(sum_day)
# Work out the average non-zero day
average_non_zero_day = 0
average_non_zero_count = 0
for day_sum in sum_all_days.values():
# Sensible threshold to ignore zero days
if day_sum > 2.5:
average_non_zero_day += day_sum
average_non_zero_count += 1
if average_non_zero_count > 0:
average_non_zero_day /= average_non_zero_count
else:
average_non_zero_day = 24 # Assume a nominal 24kWh day if no data
# log the unsorted list of days and load kWh, easier to read and ensures correct 'lowest day' is reported
self.log("Historical load totals for days {} are {}kWh, minimum value {}kWh".format(self.days_previous.copy(), sum_days, min_sum))
if self.load_filter_modal and total_points >= 3 and (min_sum_day > 0):
self.log("Modal filter enabled - Discarding day {} as it is the lowest of the {} datapoints".format(min_sum_day, len(days_list)))
min_sum_day_idx = days_list.index(min_sum_day)
del days_list[min_sum_day_idx]
# Remove day 'min_sum_day' from self.days_previous
min_sum_day_idx = self.days_previous.index(min_sum_day)
del self.days_previous[min_sum_day_idx]
del self.days_previous_weight[min_sum_day_idx]
# Fill all the gaps including days we don't use
gap_size = max(self.get_arg("load_filter_threshold", self.plan_interval_minutes), 5)
gap_minutes = 0
gap_start_minute_previous = None
gap_list = []
num_gaps = 0
max_minute = max(max_days * 24 * 60, max(data.keys()) if data else 0)
# Find all the gaps
for minute_previous in range(0, max_minute, PREDICT_STEP):
if data.get(minute_previous, 0) == data.get(minute_previous + PREDICT_STEP, 0):
gap_minutes += PREDICT_STEP
if gap_start_minute_previous is None:
gap_start_minute_previous = minute_previous
else:
if gap_minutes >= gap_size:
num_gaps += gap_minutes
gap_list.append((gap_start_minute_previous, gap_minutes))
gap_minutes = 0
gap_start_minute_previous = None
if gap_minutes >= gap_size:
num_gaps += gap_minutes
gap_list.append((gap_start_minute_previous, gap_minutes))
# Work out total number of gap_minutes
if num_gaps > 0:
self.log("Warn: Found {} gaps in load_today totalling {} minutes to fill using average data".format(len(gap_list), num_gaps))
# Print the first 5 gaps for debugging
for _i, (gap_start, gap_length) in enumerate(gap_list[:5]):
gap_start_timestamp = self.now_utc - timedelta(minutes=gap_start)
self.log("Gap starting at {} ({} minutes) for {} minutes".format(gap_start_timestamp.strftime(TIME_FORMAT), gap_start, gap_length))
# Do the filling
len_data = len(data) if isinstance(data, MinuteArray) else 99999999
for gap in gap_list:
gap_start_minute_previous = gap[0]
gap_minutes = gap[1]
gap_end_minute_previous = gap_start_minute_previous + gap_minutes
total_to_add = 0
# Fill the gap region by stepping backward through time (decrementing minute_previous)
# gap_start_minute_previous is the highest index (earliest in gap)
# We fill from there down to the end of the gap
minute_previous = min(gap_end_minute_previous, len_data - 1)
gap_day = None
while minute_previous > gap_start_minute_previous and minute_previous >= 0:
# Change of day?
new_gap_day = max(minute_previous // (24 * 60), 1)
if gap_day is None or (new_gap_day != gap_day):
gap_day = new_gap_day
average_day = sum_all_days.get(gap_day, average_non_zero_day)
if average_day <= 2.5:
average_day = average_non_zero_day
per_minute_increment = average_day / (24 * 60)
gap_day = new_gap_day
data[minute_previous] = dp4(data.get(minute_previous, 0) + total_to_add)
minute_previous -= 1
total_to_add += per_minute_increment
# Now ensure the sensor is incrementing all the way to 0
while minute_previous >= 0:
data[minute_previous] = dp4(data.get(minute_previous, 0) + total_to_add)
minute_previous -= 1
return data
def get_historical_base(self, data, minute, base_minutes):
"""
Get historical data from base minute ago
"""
# No data?
if not data:
return 0
minute_previous = base_minutes - minute
return self.get_from_incrementing(data, minute_previous)
def get_historical(self, data, minute):
"""
Get historical data across N previous days in days_previous array based on current minute
"""
total = 0
total_weight = 0
this_point = 0
# No data?
if not data:
return 0
for days in self.days_previous:
use_days = max(min(days, self.load_minutes_age), 1)
weight = self.days_previous_weight[this_point]
full_days = 24 * 60 * (use_days - 1)
minute_previous = 24 * 60 - minute + full_days
value = self.get_from_incrementing(data, minute_previous)
total += value * weight
total_weight += weight
this_point += 1
# Zero data?
if total_weight == 0:
return 0
else:
return total / total_weight
def get_from_incrementing(self, data, index, backwards=True):
"""
Get a single value from an incrementing series e.g. kWh today -> kWh this minute
"""
while index < 0:
index += 24 * 60
if backwards:
return max(data.get(index, 0) - data.get(index + 1, 0), 0)
else:
return max(data.get(index + 1, 0) - data.get(index, 0), 0)
def minute_data_import_export(self, max_days_previous, now_utc, key, scale=1.0, required_unit=None, increment=True, smoothing=True, pad=True, required=True):
"""
Download one or more entities for import/export data
:param required: Set False when the data only improves the result rather than being needed for it,
e.g. the rate history the ML load model adds as a training feature. A missing
history is then reported once as information instead of as a fetch failure, as
Home Assistant legitimately has no history for entities its recorder isn't storing.
"""
if "." not in key:
entity_ids = self.get_arg(key, indirect=False)
else:
entity_ids = key
if isinstance(entity_ids, str):
entity_ids = [entity_ids]
if entity_ids is None:
self.log("Error: No entity IDs provided for {}".format(key))
entity_ids = []
import_today = {}
for entity_id in entity_ids:
# Ignore invalid entity IDs, they might be fixed values
if (not entity_id) or ("." not in entity_id):
continue
try:
history = self.get_history_wrapper(entity_id=entity_id, days=max_days_previous, required=required)
except (ValueError, TypeError) as exc:
self.log("Warn: No history data found for {} : {}".format(entity_id, exc))
history = []
if history and len(history) > 0 and len(history[0]) > 0:
item = history[0][0]
try:
last_updated_time = str2time(item["last_updated"])
except (ValueError, TypeError):
last_updated_time = now_utc
age_days = max_days_previous
age = now_utc - last_updated_time
if age_days is None:
age_days = age.days
else:
age_days = min(age_days, age.days)
import_today, _ = minute_data(
history[0],
max_days_previous if pad else age_days,
now_utc,
"state",
"last_updated",
backwards=True,
smoothing=smoothing,
scale=scale,
clean_increment=increment,
accumulate=import_today,
required_unit=required_unit,
can_modify_history=True, # history is not accessed after this point, so minute_data can freely modify it
)
else:
if not required:
# Optional data - Home Assistant simply has no history for this entity, which is
# normal when its recorder isn't configured to store it, so don't cry wolf
self.log("Info: No history available for {}, continuing without it".format(entity_id))
elif history is None:
# Only record as a failure if it was None (not just empty but failure)
self.log("Warn: Failure to fetch history for {}".format(entity_id))
self.record_status("Warn: Failure to fetch history from {}".format(entity_id), had_errors=True)
else:
self.log("Warn: Unable to fetch history for {}".format(entity_id))
if import_today and smoothing:
size = (max_days_previous * 24 * 60 + 2) if pad else (max(import_today.keys()) + 2)
return MinuteArray(import_today, size)
return import_today
def minute_data_load(self, now_utc, entity_name, max_days_previous, load_scaling=1.0, required_unit=None, interpolate=False, pad=True, clean_increment=True):
"""
Download one or more entities for load data
"""
if "." not in entity_name:
entity_ids = self.get_arg(entity_name, indirect=False)
else:
entity_ids = entity_name
if isinstance(entity_ids, str):
entity_ids = [entity_ids]
if entity_ids is None:
self.log("Error: No entity IDs provided for {}".format(entity_name))
entity_ids = []
load_minutes = {}
age_days = None
for entity_id in entity_ids:
if (not entity_id) or ("." not in entity_id):
# Invalid entity ID, might be a fixed value
continue
try:
history = self.get_history_wrapper(entity_id=entity_id, days=max_days_previous)
except (ValueError, TypeError):
history = []
if isinstance(history, list) and history and history[0]:
item = history[0][0]
try:
last_updated_time = str2time(item["last_updated"])
except (ValueError, TypeError):
last_updated_time = now_utc
age = now_utc - last_updated_time
if age_days is None:
age_days = age.days
else:
age_days = min(age_days, age.days)
load_minutes, _ = minute_data(
history[0],
max_days_previous if pad else age_days,
now_utc,
"state",
"last_updated",
backwards=True,
smoothing=True,
scale=load_scaling,
clean_increment=clean_increment,
accumulate=load_minutes,
required_unit=required_unit,
interpolate=interpolate,
can_modify_history=True, # history is not accessed after this point, so minute_data can freely modify it
)
else:
if history is None:
# Only record as a failure if it was None (not just empty but failure)
self.log("Warn: Failure to fetch history for {}".format(entity_id))
self.record_status("Warn: Failure to fetch history from {}".format(entity_id), had_errors=True)
else:
self.log("Warn: Unable to fetch history for {}".format(entity_id))
if age_days is None:
age_days = 0
if load_minutes:
size = (max_days_previous * 24 * 60 + 2) if pad else (max(load_minutes.keys()) + 2)
load_minutes = MinuteArray(load_minutes, size)
return load_minutes, age_days
def fetch_pv_forecast_and_dawn(self):
"""
Fetch the PV forecast, compute the dawn light/dark split from it, and publish the dawn
binary_sensor - as one call so the ordering that #4699 regressed on (the split must be
computed from a freshly-fetched forecast, not the empty dict fetch_sensor_data() resets it
to at the top of each cycle) can't drift apart again. Published unconditionally regardless
of whether import rates currently exist, so the sensor never goes stale.
Returns:
pv_light_dark: dict as returned by calc_pv_light_dark(), also stored on self.pv_light_dark.
"""
self.pv_forecast_minute, self.pv_forecast_minute10, self.pv_forecast_minute90 = self.fetch_pv_forecast()
# Stored on self, not just local, so it can be used elsewhere rather than only by the
# window split below.
pv_light_dark = self.pv_light_dark = self.calc_pv_light_dark()
# "on" past dawn, "off" before it or when unclassified (no PV forecast) - based on the PV
# forecast crossing low_power_pv_threshold_w, not the same as PV actually producing right
# now, see calc_dawn's docstring. Independent of combine_charge_slots/set_charge_low_power.
self.dashboard_item(
"binary_sensor." + self.prefix + "_dawn",
state="on" if pv_light_dark.get(self.minutes_now) == 1 else "off",
attributes={"friendly_name": "Predbat is past dawn (light, not dark, by PV forecast)", "icon": "mdi:weather-sunset-up"},
)
return pv_light_dark
def combine_active_keep(self):
"""
Combine the SOC keep floors (alerts, manual_soc) and ceilings (manual_soc_max) into all_active_keep/all_active_keep_max.
"""
# Combine keep from alerts and manual SOC into all_active_keep
self.all_active_keep = self.alert_active_keep.copy()
if self.manual_soc_keep:
for minute, soc_value in self.manual_soc_keep.items():
if minute in self.all_active_keep:
self.all_active_keep[minute] = max(self.all_active_keep[minute], soc_value)
else:
self.all_active_keep[minute] = soc_value
# Manual SOC max is a ceiling rather than a floor - combine separately, taking the
# tightest (lowest) ceiling if more than one source ever applies to the same minute.
self.all_active_keep_max = {}
if self.manual_soc_max_keep:
for minute, soc_value in self.manual_soc_max_keep.items():
if minute in self.all_active_keep_max:
self.all_active_keep_max[minute] = min(self.all_active_keep_max[minute], soc_value)
else:
self.all_active_keep_max[minute] = soc_value
# A ceiling below the floor at the same minute is a contradiction (e.g. a leftover manual_soc
# override never cleared) - the floor wins as the safety-relevant constraint, so drop the
# conflicting ceiling rather than hand the optimiser two penalties pulling opposite ways.
for minute in list(self.all_active_keep_max.keys()):
floor_value = self.all_active_keep.get(minute, 0)
if floor_value > self.all_active_keep_max[minute]:
self.log("Warn: manual_soc_max target {}% at minute {} is below the manual_soc/alert floor {}% for the same minute - ignoring the ceiling there".format(self.all_active_keep_max[minute], minute, floor_value))
del self.all_active_keep_max[minute]
def fetch_sensor_data(self, save=True):
"""
Fetch all the data, e.g. energy rates, load, PV predictions, car plan etc.
"""
prev_octopus_slots = self.octopus_slots.copy()
prev_octopus_saving_slots = self.octopus_saving_slots.copy()
prev_octopus_free_slots = self.octopus_free_slots.copy()
prev_axle_sessions = self.axle_sessions.copy()
import_rates = {}
self.rate_import_replicated = {}
export_rates = {}
self.rate_export_replicated = {}
self.rate_slots = []
self.io_adjusted = {}
self.low_rates = []
self.high_export_rates = []
self.octopus_slots = [[] for _ in range(self.num_cars)]
self.cost_today_sofar = 0
self.carbon_today_sofar = 0
self.import_today = {}
self.export_today = {}
self.battery_temperature_history = {}
self.battery_temperature_prediction = {}
self.pv_today = {}
self.load_minutes = {}
self.load_minutes_age = 0
self.load_forecast = {}
self.load_forecast_array = []
self.pv_forecast_minute = {}
self.pv_forecast_minute10 = {}
self.pv_forecast_minute90 = {}
self.pv_light_dark = {}
# See Plan.refresh_pv_forecast_minute90(): both series are re-fetched together below, so no
# earlier pair of signatures may be held against them