-
Notifications
You must be signed in to change notification settings - Fork 2
/
predictor_underest_v2.py
1925 lines (1725 loc) · 91.5 KB
/
predictor_underest_v2.py
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
from utils import ReplayBuffer, DataLoader
from collections import defaultdict
from citylearn import CityLearn
from copy import deepcopy
import numpy as np
import pandas as pd
import sys
from scipy import stats
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.linear_model import LinearRegression
import statsmodels.api as sm
import statsmodels.formula.api as smf
# TODO: @Zhiyao - add in parameter/initialization for capacity as discussed.
class Predictor(DataLoader):
"""
we have following functions:
def __init__(self, action_space: list) -> None: see lines for explanations of vars
def estimate_data(
self, replay_buffer: ReplayBuffer, timestep: int, is_adaptive: bool = False
): return prediction data to TD3 agent (both day ahead and adaptive)
def full_parse_data(
self, previous_data: dict, current_data: dict, window: int = 24
): merge current hour data in current day data in the buffer
def calculate_avg(self): calculate last 14-day solar gen/elec loads for updating predictor
def get_day_data(self, replay_buffer: ReplayBuffer, timestep: int): helper method for uploading data to memory for estimation
def upload_data(self, state, action): NOT IMPLEMENTED
def upload_state(self, state_list: list): upload state to state buffer
def upload_action(self, action_list: list): upload action to action buffer
def state_to_dic(self, state_list: list): convert type from list to dict with state names
def cop_cal(self, temp): calculate COP
def gather_input(self, timestep): gather predictions of today's params for elec/solar prediction
def infer_solar_electricity_load(self, timestep: int): make predictions for solar/elec
def reshape_array(self, pred_buffer: ReplayBuffer): update regression model for prediction w/ latest 14-day data to fit
def infer_load(self, timestep: int): Returns heating, cooling, solar and electricity loads
def infer_heating_cooling_estimate(self, timestep): infer previous day h/c loads and calculate moving average
--use average with peak scaling as day-ahead predictions
def select_action(self, timestep: int): interface w/ TD3.py to select actions in online exploration period
def get_params(self, timestep: int) -> dict: return estimated params from online exploration
def quantile_reg(self): quantile regression for h/c capacity estimation--convert to DataFrame
def quantile_reg_H(self, uid, quantiles, H_dataframe, climate_zone): quantile regression for H capacity
def quantile_reg_C(self, uid, quantiles, C_dataframe, climate_zone): quantile regression for C capacity
def estimate_h(self): choose actions for estimating h capacity
def estimate_c(self): choose actions for estimating c capacity
def estimate_bat(self): choose actions for estimating bat capacity
THIS IS HOW THE WHOLE CLASS RUNS:
when select_action in TD3.py is called
store state in state buffer
run select_action function (around line 1100) in predictor.py
store action from select_action
select_action runs as follows:
all the first, run estimate_bat (i manually set three whole windows (from 22h to 6h+1) as time limit to run this,
otherwise this loop will be forced over and continue to h/c capacity estimation)
if we have reliable values of bat capacity (1 datapoint) and nominal power (3 datapoints, finally choose the maximal one),
then we jump out from E estimation and enter H/C estimation
during H/C estimation, i set each whole window for H/C est alternately everyday,
i.e. if current window (22 to 6(+1)) is for H est, then the next (22 to 6(+1)) will be C est.
run estimate_h or estimate_c alternately in each window
if current timestep is RBC_THRESHOLD-1 (last step for online exploration), run quantile_reg()
in quantile_reg, we have following process:
convert ndarrays to pd.DataFrame since it is required by statsmodel.QuantileRegressor
run quantile_reg_H and quantile_reg_C for each building and choose a certain quantile (currently we use two-point quantile avg)
when we initialize the digital twin, we may call get_params for capacity and nominal power data
"""
def __init__(self, building_info: dict, action_space: list) -> None:
super().__init__(action_space)
self.building_ids = range(len(self.action_space)) # number of buildings
# initialize two buffers
self.state_buffer = ReplayBuffer(buffer_size=365, batch_size=32)
self.action_buffer = ReplayBuffer(buffer_size=365, batch_size=32)
# define constants
self.CF_C = 0.006
self.CF_H = 0.008
self.CF_B = 0
self.rbc_threshold = 336
self.annual_c_demand = {uid: 0 for uid in self.building_ids}
self.annual_h_demand = {uid: 0 for uid in self.building_ids}
for uid in self.building_ids:
self.annual_h_demand[uid] = building_info[f"Building_{str(uid+1)}"]['Annual_DHW_demand (kWh)']
self.annual_c_demand[uid] = building_info[f"Building_{str(uid+1)}"]['Annual_cooling_demand (kWh)']
self.a_c_high = [action_space[uid].high[0] for uid in self.building_ids]
self.a_h_high = [action_space[uid].high[1] for uid in self.building_ids]
# define regression model
self.regr = LinearRegression(fit_intercept=False) # , positive=True)
# average and peak values for load prediction
self.avg_h_load = {uid: np.zeros(24) for uid in self.building_ids}
self.avg_c_load = {uid: np.ones(24) for uid in self.building_ids}
self.daystep = 0 # this is for h/c loads estimation--not real daystep!
self.h_peak = {uid: np.zeros(24, dtype=int) for uid in self.building_ids}
self.c_peak = {uid: np.zeros(24, dtype=int) for uid in self.building_ids}
self.gamma = 0.2
self.avg_type = [
"solar_gen",
"elec_weekday",
"elec_weekend1",
"elec_weekend2",
] # weekend1: Sat, weekend2: Sun and holidays
self.solar_avg = {i: np.zeros(24) for i in self.building_ids}
self.elec_weekday_avg = {i: np.zeros(24) for i in self.building_ids}
self.elec_weekend1_avg = {i: np.zeros(24) for i in self.building_ids}
self.elec_weekend2_avg = {i: np.zeros(24) for i in self.building_ids}
self.c_weekday_avg = {i: np.zeros(24) for i in self.building_ids}
self.c_weekend1_avg = {i: np.zeros(24) for i in self.building_ids}
self.c_weekend2_avg = {i: np.zeros(24) for i in self.building_ids}
self.h_weekday_avg = {i: np.zeros(24) for i in self.building_ids}
self.h_weekend1_avg = {i: np.zeros(24) for i in self.building_ids}
self.h_weekend2_avg = {i: np.zeros(24) for i in self.building_ids}
self.regr_solar = {uid: LinearRegression() for uid in self.building_ids}
self.regr_elec = {uid: LinearRegression() for uid in self.building_ids}
# ----------below vars are for capacity estimation-------------
self.timestep = 0
# -----------thresholds-------------
self.tau_c = {uid: 0.2 for uid in self.building_ids}
self.tau_h = {uid: 0.2 for uid in self.building_ids}
self.tau_b = {uid: 0.6 for uid in self.building_ids}
self.tau_cplus = {uid: 0.1 for uid in self.building_ids}
self.tau_hplus = {uid: 0.1 for uid in self.building_ids}
self.action_c = {uid: 0.1 for uid in self.building_ids}
self.action_h = {uid: 0.1 for uid in self.building_ids}
# ------------indications of estimation procedure----------
self.prev_hour_est_b = {uid: False for uid in self.building_ids}
self.prev_hour_est_c = {uid: False for uid in self.building_ids}
self.prev_hour_est_h = {uid: False for uid in self.building_ids}
self.has_heating = {uid: True for uid in self.building_ids}
self.a_clip = {uid: None for uid in self.building_ids}
self.avail_ratio_est_c = {uid: False for uid in self.building_ids}
self.avail_ratio_est_h = {uid: False for uid in self.building_ids}
self.avail_nominal = {uid: False for uid in self.building_ids}
self.prev_hour_nom = {uid: False for uid in self.building_ids}
# ------------number of est points---------------
self.num_elec_points = {uid: 0 for uid in self.building_ids}
self.num_h_points = {uid: 0 for uid in self.building_ids}
self.num_c_points = {uid: 0 for uid in self.building_ids}
self.ratio_c_est = {uid: [] for uid in self.building_ids}
self.C_bd_est = {uid: [] for uid in self.building_ids}
self.ratio_h_est = {uid: [] for uid in self.building_ids}
self.H_bd_est = {uid: [] for uid in self.building_ids}
# ------------estimated values: for return---------
self.cap_c_est = {uid: [] for uid in self.building_ids}
self.cap_h_est = {uid: [] for uid in self.building_ids}
self.cap_b_est = {uid: [] for uid in self.building_ids}
self.effi_b = {uid: 0 for uid in self.building_ids}
self.effi_c = {uid: 0 for uid in self.building_ids}
self.effi_h = {uid: 0 for uid in self.building_ids}
self.nominal_b = {uid: [] for uid in self.building_ids}
self.ratio_c = {uid: 0 for uid in self.building_ids}
self.ratio_h = {uid: 0 for uid in self.building_ids}
# ---------------results of est------------------
self.nom_p_est = {uid: 0 for uid in self.building_ids}
self.capacity_b = {uid: 0 for uid in self.building_ids}
self.H_qr_est = {uid: 0 for uid in self.building_ids}
self.C_qr_est = {uid: 0 for uid in self.building_ids}
self.E_day = True
self.C_day = self.H_day = False
# TODO: @Zhiyao + @Qasim - this function has not tested. Depends on internal predictor to work.
def estimate_data(
self, replay_buffer: ReplayBuffer, timestep: int, is_adaptive: bool = False
):
"""Estimates data to be passed into Optimization model for 24hours into future."""
if is_adaptive:
# if hour start of day, `get_recent()` will automatically return an empty dictionary
data = self.full_parse_data(
deepcopy(replay_buffer.get_recent()),
self.get_day_data(replay_buffer, timestep),
24 - timestep % 24,
)
replay_buffer.add(data)
else:
data = self.full_parse_data(
deepcopy(replay_buffer.get_recent()),
self.get_day_data(replay_buffer, timestep),
)
replay_buffer.add(data, full_day=True)
return data
def full_parse_data(
self, previous_data: dict, current_data: dict, window: int = 24
):
"""Parses `current_data` for optimization and loads into `data`. Everything is of shape 24, 9"""
TOTAL_PARAMS = 21
assert (
len(current_data)
== TOTAL_PARAMS # actions + rewards + E_grid_collect. Section 1.3.1
), (
f"Invalid number of parameters, found: {len(current_data)}, expected: {TOTAL_PARAMS}. "
f"Can't run Predictor agent optimization.\n"
f"@Zhiyao, these parameters come from `get_day_data`. "
f"Count the number of keys returned in that function and make sure its equal to `current_data` parameter. "
f"Otherwise, there's a mismatch that the actor wont be able to run. 23 is set on previous version. "
f"Change this is you believe you'd need more parameters."
)
data = {}
for key, value in current_data.items():
value = np.array(value)
if len(value.shape) == 1:
value = np.repeat(value.reshape(1, -1), window, axis=0)
if np.shape(value) == (24, len(self.building_ids)):
data[key] = value
else:
# makes sure horizontal dimensions are 24
if previous_data and "action" not in key:
data[key] = np.concatenate(
(previous_data[key][: 24 - window], value), axis=0
)
else:
data[key] = np.pad(value, ((24 - window, 0), (0, 0)))
return data
# TODO: @Zhiyao - needs fixing -- done
def calculate_avg(self):
"""calculate hourly avg value of the day"""
# print("calculating avg")
buffer = self.state_buffer
daytype = {i: 0 for i in self.building_ids}
elec_dem = {i: [] for i in self.building_ids}
solar_gen = {i: [] for i in self.building_ids}
range_index = -13
for day in range(range_index, 0):
for uid in self.building_ids:
elec_dem[uid] = np.array(buffer.get(day-1)["elec_dem"])[:, uid]
solar_gen[uid] = np.array(buffer.get(day-1)["solar_gen"])[:, uid]
daytype[uid] = np.array(buffer.get(day-1)["daytype"])[0, uid]
if self.solar_avg[uid].all() != 0:
self.solar_avg[uid] = self.solar_avg[uid] * 0.5 + solar_gen[uid] * 0.5
else:
self.solar_avg[uid] = solar_gen[uid]
if daytype[uid] in [7]:
if self.elec_weekend1_avg[uid].all() != 0:
self.elec_weekend1_avg[uid] = self.elec_weekend1_avg[uid] * 0.5 + elec_dem[uid] * 0.5
else:
self.elec_weekend1_avg[uid] = elec_dem[uid]
elif daytype[uid] in [1, 8]:
if self.elec_weekend2_avg[uid].all() != 0:
self.elec_weekend2_avg[uid] = self.elec_weekend2_avg[uid] * 0.5 + elec_dem[uid] * 0.5
else:
self.elec_weekend2_avg[uid] = elec_dem[uid]
else:
if self.elec_weekday_avg[uid].all() != 0:
self.elec_weekday_avg[uid] = self.elec_weekday_avg[uid] * 0.5 + elec_dem[uid] * 0.5
else:
self.elec_weekday_avg[uid] = elec_dem[uid]
# TODO: @Zhiyao - make sure in the case of adaptive this returns (and is sent to actor.py --> see TD3.py (select_action)) data of dimensions (window, 9)
# >>> Now, in the case of adaptive, say we're on hour 10. So, we only need to make predictions from hour 10 - 24 (1-based indexing).
# >>> You should return of dimensions (24 - 10, 9) and NOT 24, 9. This is because we've already observed loads in the first 9 hours and nothing can be changed for that.
# >>> You should make use of observed state & action information in `infer_load` functions. That should make use of observed information in the current day.
# NOTE: I think this should work fine, but you may need to change `state_buffer.get(-1)`. If this confuses you, and EVERYTHING else is working properly, ping me ASAP
# >>> and I can fix it accordingly.
def get_day_data(self, replay_buffer: ReplayBuffer, timestep: int):
"""Helper method for uploading data to memory. This is for estimation only!!!"""
T = 24
window = T - timestep % 24
self.timestep = timestep
observation_data = {}
# get previous day's buffer
data = replay_buffer.get(-1) if len(replay_buffer) > 0 else None
# NOTE: @Zhiyao - dimensions should be of `window, num_buildings`
# get heating, cooling, electricity, and solar estimate
(
heating_estimate,
cooling_estimate,
solar_estimate,
electricity_estimate,
future_temp,
) = self.infer_load(timestep)
# get capacity and nominal power parameters
additional_parameters = self.get_params(timestep)
E_ns = np.array([electricity_estimate[key] for key in self.building_ids]).T
E_pv = np.array([solar_estimate[key] for key in self.building_ids]).T
H_bd = np.array([heating_estimate[key] for key in self.building_ids]).T
C_bd = np.array([cooling_estimate[key] for key in self.building_ids]).T
H_max = (
None if data is None else data["H_max"].max(axis=0)
) # load previous H_max
if H_max is None:
H_max = np.max(H_bd, axis=0)
else:
H_max = np.max([H_max, H_bd.max(axis=0)], axis=0) # global max
C_max = (
None if data is None else data["C_max"].max(axis=0)
) # load previous C_max
if C_max is None:
C_max = np.max(C_bd, axis=0)
else:
C_max = np.max([C_max, C_bd.max(axis=0)], axis=0) # global max
temp = np.array([future_temp[uid].flatten() for uid in self.building_ids]).T
COP_C = np.zeros((window, len(self.building_ids)))
for hour in range(window):
for bid in self.building_ids:
COP_C[hour, bid] = self.cop_cal(temp[hour, bid])
C_p_Csto = additional_parameters["C_p_Csto"]
C_p_Hsto = additional_parameters["C_p_Hsto"]
C_p_bat = additional_parameters["C_p_bat"]
E_hpC_max = np.array(C_p_Csto) * np.array(self.a_c_high) / 2
E_ehH_max = np.array(C_p_Hsto) * np.array(self.a_h_high) / 0.9
c_bat_init = np.array(self.state_buffer.get(-1)["soc_b"])[-1]
c_bat_init[c_bat_init == np.inf] = 0
c_Hsto_init = np.array(self.state_buffer.get(-1)["soc_h"])[-1]
c_Hsto_init[c_Hsto_init == np.inf] = 0
# nominal power
E_bat_max = additional_parameters["E_bat_max"]
c_Csto_init = np.array(self.state_buffer.get(-1)["soc_c"])[-1]
c_Csto_init[c_Csto_init == np.inf] = 0
# add E-grid - default day-ahead
egc = np.array(self.state_buffer.get(-1)["elec_cons"])
observation_data["E_grid"] = np.pad(egc, ((0, T - egc.shape[0]), (0, 0)))
observation_data["E_grid_prevhour"] = np.zeros((T, len(self.building_ids)))
# observation_data["E_grid_prevhour"][0] = np.array(
# self.state_buffer.get(-2)["elec_cons"]
# )[-1]
observation_data["E_grid_prevhour"][0] = egc[0]
for hour in range(1, timestep % 24 + 1):
observation_data["E_grid_prevhour"][hour] = observation_data["E_grid"][hour]
observation_data["E_ns"] = E_ns
observation_data["H_bd"] = H_bd
observation_data["C_bd"] = C_bd
observation_data["H_max"] = H_max
observation_data["C_max"] = C_max
observation_data["E_pv"] = E_pv
observation_data["E_hpC_max"] = E_hpC_max
observation_data["E_ehH_max"] = E_ehH_max
observation_data["COP_C"] = COP_C
observation_data["C_p_bat"] = C_p_bat
observation_data["c_bat_init"] = c_bat_init
observation_data["C_p_Hsto"] = C_p_Hsto
observation_data["c_Hsto_init"] = c_Hsto_init
observation_data["C_p_Csto"] = C_p_Csto
observation_data["c_Csto_init"] = c_Csto_init
observation_data["E_bat_max"] = E_bat_max
observation_data["action_H"] = self.action_buffer.get(-1)["action_H"]
observation_data["action_C"] = self.action_buffer.get(-1)["action_C"]
observation_data["action_bat"] = self.action_buffer.get(-1)["action_bat"]
# add reward \in R^9 (scalar value for each building)
# observation_data["reward"] = self.action_buffer.get(-1)["reward"]
# print("\nE_ns_B4 from get_day_data:\n", np.array(observation_data["E_ns"])[:, 3].flatten(),
# np.size(np.array(observation_data["E_ns"])[:, 3].flatten()))
return observation_data
def upload_data(self, state, action):
"""Uploads state and action_reward replay buffer"""
raise NotImplementedError(
"This function is not called, and should not be called anywhere"
)
# TODO: @Zhiyao - needs implementation. See comment below -- done
def upload_state(self, state_list: list):
"""upload state to state buffer"""
# print(
# "@Zhiyao, you'd need to implement `record_dic` functionality in here where you're only adding to `state_buffer`.\n"
# "From `record_dic`, extract state information."
# )
# raise NotImplementedError
state = self.state_buffer.get_recent()
state_bdg = self.state_to_dic(state_list)
parse_state = self.parse_data(state, state_bdg)
self.state_buffer.add(parse_state)
# TODO: @Zhiyao - needs implementation. See comment below -- done
def upload_action(self, action_list: list):
"""upload action to action buffer"""
# print(
# "@Zhiyao, you'd need to implement `record_dic` functionality in here where you're only adding to `action_buffer`\n"
# "From `record_dic`, extract action information."
# )
# raise NotImplementedError
action_bdg = self.action_reward_to_dic(action_list)
action = self.action_buffer.get_recent()
parse_action = self.parse_data(action, action_bdg)
self.action_buffer.add(parse_action)
# TODO: @Zhiyao - This needs significant modification. only make use of `next_state` which will come from ** main.py **
# >>> this should include state information required for both heating, cooling, solar, electricity, and if necessary capcity estimation.
# >>> make sure to use only 2 buffers, one for state and one for action. You can make use of state buffer for various purposes - heating, cooling, etc. estimation.
def state_to_dic(self, state_list: list):
"""convert type from list to dict with state names"""
state_bdg = {}
for uid in self.building_ids:
state = state_list[uid]
s = {
"month": state[0],
"day": state[1],
"hour": state[2],
"daylight_savings_status": state[3],
"t_out": state[4],
"t_out_pred_6h": state[5],
"t_out_pred_12h": state[6],
"t_out_pred_24h": state[7],
"rh_out": state[8],
"rh_out_pred_6h": state[9],
"rh_out_pred_12h": state[10],
"rh_out_pred_24h": state[11],
"diffuse_solar_rad": state[12],
"diffuse_solar_rad_pred_6h": state[13],
"diffuse_solar_rad_pred_12h": state[14],
"diffuse_solar_rad_pred_24h": state[15],
"direct_solar_rad": state[16],
"direct_solar_rad_pred_6h": state[17],
"direct_solar_rad_pred_12h": state[18],
"direct_solar_rad_pred_24h": state[19],
"t_in": state[20],
"avg_unmet_setpoint": state[21],
"rh_in": state[22],
"non_shiftable_load": state[23],
"solar_gen": state[24],
"cooling_storage_soc": state[25],
"dhw_storage_soc": state[26],
"electrical_storage_soc": state[27],
"net_electricity_consumption": state[28],
"carbon_intensity": state[29],
}
state_bdg[uid] = s
s_dic = {}
# heating/cooling generation
daytype = [state_bdg[i]["day"] for i in self.building_ids]
hour = [state_bdg[i]["hour"] for i in self.building_ids]
t_out = [state_bdg[i]["t_out"] for i in self.building_ids]
rh_out = [state_bdg[i]["rh_out"] for i in self.building_ids]
t_in = [state_bdg[i]["t_in"] for i in self.building_ids]
rh_in = [state_bdg[i]["rh_in"] for i in self.building_ids]
elec_dem = [state_bdg[i]["non_shiftable_load"] for i in self.building_ids]
solar_gen = [state_bdg[i]["solar_gen"] for i in self.building_ids]
soc_c = [state_bdg[i]["cooling_storage_soc"] for i in self.building_ids]
soc_h = [state_bdg[i]["dhw_storage_soc"] for i in self.building_ids]
soc_b = [state_bdg[i]["electrical_storage_soc"] for i in self.building_ids]
elec_cons = [
state_bdg[i]["net_electricity_consumption"] for i in self.building_ids
]
# solar/pv generation
diffuse_solar_rad = [
state_bdg[i]["diffuse_solar_rad"] for i in self.building_ids
]
direct_solar_rad = [state_bdg[i]["direct_solar_rad"] for i in self.building_ids]
diffuse_6h = [
state_bdg[i]["diffuse_solar_rad_pred_6h"] for i in self.building_ids
]
direct_6h = [
state_bdg[i]["direct_solar_rad_pred_6h"] for i in self.building_ids
]
diffuse_12h = [
state_bdg[i]["diffuse_solar_rad_pred_12h"] for i in self.building_ids
]
direct_12h = [
state_bdg[i]["direct_solar_rad_pred_12h"] for i in self.building_ids
]
diffuse_24h = [
state_bdg[i]["diffuse_solar_rad_pred_24h"] for i in self.building_ids
]
direct_24h = [
state_bdg[i]["direct_solar_rad_pred_24h"] for i in self.building_ids
]
t_out_6h = [state_bdg[i]["t_out_pred_6h"] for i in self.building_ids]
t_out_12h = [state_bdg[i]["t_out_pred_12h"] for i in self.building_ids]
t_out_24h = [state_bdg[i]["t_out_pred_24h"] for i in self.building_ids]
# heating/cooling generation
s_dic["daytype"] = daytype
s_dic["hour"] = hour
s_dic["t_out"] = t_out
s_dic["rh_out"] = rh_out
s_dic["t_in"] = t_in
s_dic["rh_in"] = rh_in
s_dic["elec_dem"] = elec_dem
s_dic["solar_gen"] = solar_gen
s_dic["soc_c"] = soc_c
s_dic["soc_h"] = soc_h
s_dic["soc_b"] = soc_b
s_dic["elec_cons"] = elec_cons
# solar/pv generation
s_dic["diffuse_solar_rad"] = diffuse_solar_rad
s_dic["direct_solar_rad"] = direct_solar_rad
s_dic["diffuse_6h"] = diffuse_6h
s_dic["direct_6h"] = direct_6h
s_dic["diffuse_12h"] = diffuse_12h
s_dic["direct_12h"] = direct_12h
s_dic["diffuse_24h"] = diffuse_24h
s_dic["direct_24h"] = direct_24h
s_dic["solar_gen"] = solar_gen
s_dic["t_out"] = t_out
s_dic["t_out_6h"] = t_out_6h
s_dic["t_out_12h"] = t_out_12h
s_dic["t_out_24h"] = t_out_24h
return s_dic
# TODO: @Zhiyao - no need to store reward. No RL happening. Plz remove functionality. -- done
def action_reward_to_dic(self, action):
"""convert type from list to dict with action names"""
a_dic = {}
a_c = [action[i][0] for i in self.building_ids]
a_h = [action[i][1] for i in self.building_ids]
a_b = [action[i][2] for i in self.building_ids]
a_dic["action_C"] = a_c
a_dic["action_H"] = a_h
a_dic["action_bat"] = a_b
return a_dic
def cop_cal(self, temp):
"""calculate COP"""
eta_tech = 0.22
target_c = 8
if temp == target_c:
cop_c = 20
else:
cop_c = eta_tech * (target_c + 273.15) / (temp - target_c)
if cop_c <= 0 or cop_c > 20:
cop_c = 20
return cop_c
def gather_input(self, timestep):
# assert daystep % 24 == 0, "only gather input at the beginning of the day"
"""gather predictions of today's params for elec/solar prediction"""
T = 24
window = T - timestep % 24
buffer = self.state_buffer.get(-2)
input_solar_full = {uid: np.zeros([24, 2]) for uid in self.building_ids}
input_elec_full = {uid: np.zeros([24, 1]) for uid in self.building_ids}
input_solar = {uid: np.zeros([window, 2]) for uid in self.building_ids}
input_elec = {uid: np.zeros([window, 1]) for uid in self.building_ids}
for uid in self.building_ids:
x_diffuse_6h = np.array(buffer["diffuse_6h"])[-6:, uid]
x_diffuse_12h = np.array(buffer["diffuse_12h"])[-6:, uid]
x_diffuse_24h = np.array(buffer["diffuse_24h"])[-12:, uid]
x_direct_6h = np.array(buffer["direct_6h"])[-6:, uid]
x_direct_12h = np.array(buffer["direct_12h"])[-6:, uid]
x_direct_24h = np.array(buffer["direct_24h"])[-12:, uid]
input_solar_full[uid][0:6, 0] = x_diffuse_6h
input_solar_full[uid][0:6, 1] = x_direct_6h
input_solar_full[uid][6:12, 0] = x_diffuse_12h
input_solar_full[uid][6:12, 1] = x_direct_12h
input_solar_full[uid][12:, 0] = x_diffuse_24h
input_solar_full[uid][12:, 1] = x_direct_24h
x_elec_6h = np.array(buffer["t_out_6h"])[-6:, uid]
x_elec_12h = np.array(buffer["t_out_12h"])[-6:, uid]
x_elec_24h = np.array(buffer["t_out_24h"])[-12:, uid]
input_elec_full[uid][0:6, 0] = x_elec_6h
input_elec_full[uid][6:12, 0] = x_elec_12h
input_elec_full[uid][12:, 0] = x_elec_24h
input_solar[uid][:, :] = input_solar_full[uid][timestep % 24 :, :]
input_elec[uid][:, :] = input_elec_full[uid][timestep % 24 :, :]
return input_solar, input_elec
def infer_solar_electricity_load(self, timestep: int):
"""changed for adaptive dispatch--make inference every hour"""
"""make predictions for solar/elec"""
if timestep % 24 in [0]:
self.calculate_avg() # make sure get_recent() returns in 24*9 shape
T = 24
window = T - timestep % 24
pred_buffer = self.state_buffer
# ---------------fitting regression model---------------
x_solar, y_solar, x_elec, y_elec = self.reshape_array(pred_buffer)
for uid in self.building_ids:
self.regr_solar[uid].fit(x_solar[uid], y_solar[uid])
# self.regr_elec[uid].fit(x_elec[uid], y_elec[uid])
# ------------------start prediction-------------------
input_solar, input_elec = self.gather_input(timestep) # input shape: (window)
solar_gen = {uid: np.zeros([T]) for uid in self.building_ids}
elec_dem = {uid: np.zeros([T]) for uid in self.building_ids}
daytype = {uid: 0 for uid in self.building_ids}
day_pred_solar = {uid: np.zeros([window]) for uid in self.building_ids}
day_pred_elec = {uid: np.zeros([window]) for uid in self.building_ids}
for uid in self.building_ids:
daytype[uid] = pred_buffer.get(-1)["daytype"][0][0]
"""now you are at hour 7, so far you have obsverd actual loads e1,...,e7.
and you want to predict for load for hours 8 to 24. the average load profile is a1,...,,a24.
so you first calculate the offset d= (e1+...+d7)/7 - (a1+...+a7)/7.
if d >0, it means the current day may have higher loads than average.
then for the prediction, yoou just predict a8+d,...,a_24+d"""
if daytype[uid] in [7]:
elec_dem = self.elec_weekend1_avg[uid]
elif daytype[uid] in [1, 8]:
elec_dem = self.elec_weekend2_avg[uid]
else:
elec_dem = self.elec_weekday_avg[uid]
solar_gen = self.solar_avg[uid]
if timestep % 24 == 0:
day_pred_elec[uid] = elec_dem
day_pred_solar[uid] = solar_gen
else:
today_e_load = np.array(pred_buffer.get(-1)["elec_dem"])
today_s_load = np.array(pred_buffer.get(-1)["solar_gen"])
day_hour = (timestep % 24)
if timestep % 24 in [1, 2, 3, 4, 5]:
offset_e1 = np.sum(today_e_load[-day_hour-1:, uid]) / (day_hour+1)
offset_e2 = np.sum(elec_dem[: day_hour+1]) / (day_hour+1)
offset_e = offset_e1 - offset_e2
day_pred_elec[uid] = elec_dem[day_hour:] + offset_e
# offset_s1 = np.sum(today_s_load[-day_hour-1:, uid]) / (day_hour+1)
# offset_s2 = np.sum(solar_gen[: day_hour+1]) / (day_hour+1)
# offset_s = offset_s1 - offset_s2
# day_pred_solar[uid] = solar_gen[day_hour:] + offset_s
else:
offset_e1 = np.sum(today_e_load[-5:, uid]) / 5
offset_e2 = np.sum(elec_dem[day_hour - 4: day_hour+1]) / 5
offset_e = offset_e1 - offset_e2
day_pred_elec[uid] = elec_dem[day_hour:] + offset_e
# offset_s1 = np.sum(today_s_load[-5:, uid]) / 5
# offset_s2 = np.sum(solar_gen[day_hour - 4: day_hour+1]) / 5
# offset_s = offset_s1 - offset_s2
# day_pred_solar[uid] = solar_gen[day_hour:] + offset_s
for t in range(len(day_pred_elec[uid])):
day_pred_elec[uid][t] = max(0, day_pred_elec[uid][t])
# day_pred_solar[uid][t] = max(0, day_pred_solar[uid][t])
for i in range(np.shape(input_solar[uid])[0]):
x_pred = [
[
input_solar[uid][i, 0],
input_solar[uid][i, 1],
]
]
y_pred = self.regr_solar[uid].predict(x_pred)
avg = self.solar_avg[uid][(i + timestep) % 24]
day_pred_solar[uid][i] = max(0, y_pred.item() + avg)
day_pred_solar[uid][0] = pred_buffer.get(-1)["solar_gen"][-1][uid]
day_pred_elec[uid][0] = pred_buffer.get(-1)["elec_dem"][-1][uid]
return day_pred_solar, day_pred_elec, input_elec
# reshape input for fitting the model
def reshape_array(self, pred_buffer: ReplayBuffer):
"""only reshape array at the beginning of the day"""
"""update regression model for prediction w/ latest 14-day data to fit"""
x_solar = {i: [] for i in self.building_ids}
y_solar = {i: [] for i in self.building_ids}
x_elec = {i: [] for i in self.building_ids}
y_elec = {i: [] for i in self.building_ids}
solar_gen = []
elec_dem = []
x_diffuse = []
x_direct = []
x_tout = []
daytype = []
for i in range(-14, -1):
solar_gen = pred_buffer.get(i)["solar_gen"]
# expect solar_gen to be [24*7, 9] vertically sequential
elec_dem = pred_buffer.get(i)["elec_dem"]
x_diffuse = pred_buffer.get(i)["diffuse_solar_rad"]
x_direct = pred_buffer.get(i)["direct_solar_rad"]
x_tout = pred_buffer.get(i)["t_out"]
daytype = pred_buffer.get(i)["daytype"]
for uid in self.building_ids:
for i in range(2, np.shape(solar_gen)[0] - 1):
x_append2 = [x_diffuse[i][uid], x_direct[i][uid]]
y = [solar_gen[i][uid] - self.solar_avg[uid][i % 24]]
x_solar[uid].append(x_append2)
y_solar[uid].append(y)
for i in range(2, np.shape(elec_dem)[0] - 1):
if daytype[i - 2][uid] in [7]:
x_temp1 = (
elec_dem[i - 2][uid]
- self.elec_weekend1_avg[uid][(i - 2) % 24]
)
elif daytype[i - 2][uid] in [1, 8]:
x_temp1 = (
elec_dem[i - 2][uid]
- self.elec_weekend2_avg[uid][(i - 2) % 24]
)
else:
x_temp1 = (
elec_dem[i - 2][uid]
- self.elec_weekday_avg[uid][(i - 2) % 24]
)
if daytype[i - 1][uid] in [7]:
x_temp2 = (
elec_dem[i - 1][uid]
- self.elec_weekend1_avg[uid][(i - 1) % 24]
)
elif daytype[i - 1][uid] in [1, 8]:
x_temp2 = (
elec_dem[i - 1][uid]
- self.elec_weekend2_avg[uid][(i - 1) % 24]
)
else:
x_temp2 = (
elec_dem[i - 1][uid]
- self.elec_weekday_avg[uid][(i - 1) % 24]
)
x_append1 = [x_temp1, x_temp2]
x_append2 = [x_tout[i][uid]]
if daytype[i][uid] in [7]:
y = elec_dem[i][uid] - self.elec_weekend1_avg[uid][i % 24]
elif daytype[i][uid] in [1, 8]:
y = elec_dem[i][uid] - self.elec_weekend2_avg[uid][i % 24]
else:
y = elec_dem[i][uid] - self.elec_weekday_avg[uid][i % 24]
x_elec[uid].append(x_append1 + x_append2)
# print("x_pred for elec: ", x_append1 + x_append2)
y_elec[uid].append([y])
return x_solar, y_solar, x_elec, y_elec
# TODO: @Zhiyao - need to add in capacity estimation
def infer_load(self, timestep: int):
"""Returns heating, cooling, solar and electricity loads"""
return [
*self.infer_heating_cooling_estimate(timestep),
*self.infer_solar_electricity_load(timestep),
]
# TODO: @Zhiyao - state_buffer is appended before calling action. So at start of day, we have already stored state data for hour 0.
# >>> We infer at start of day, not end of day (in case of day-ahead). In case of adaptive, the dimensions need to be 24 - t, where t [0, 23].
def infer_heating_cooling_estimate(self, timestep):
"""
Note: h&c should be inferred simultaneously
inferring all-day h&c loads according to three methods accordingly:
1. direct calculation and power balance equation (if either is clipped)
2. two-point regression estimation (if nearby (t-1 or t+1) loads are calculated directly)
3. main method regression estimation (at least two different COPs among consecutive three hours)
**assuming conduct inference at the beginning hour of the day(aft recording in buffer, bef executing actions)
**so that when we obtain from ReplayBuffer.get_recent(), we get day-long data.
:return: daily h&c load inference
"""
"""infer previous day h/c loads and calculate moving average--use average with peak scaling as day-ahead predictions"""
T = 24
window = T - timestep % 24
# hasest indicates whether every hour of the day has estimation.
# only when all 0 become 1 in has_est, the function runs over.
effi_h = 0.9
est_c_load = {uid: np.zeros(24) for uid in self.building_ids}
est_h_load = {uid: np.zeros(24) for uid in self.building_ids}
adaptive_c_load = {uid: np.zeros(window) for uid in self.building_ids}
adaptive_h_load = {uid: np.zeros(window) for uid in self.building_ids}
c_hasest = {
uid: np.zeros(24, dtype=np.int16) for uid in self.building_ids
} # -1:clipped, 0:non-est, 1:regression, 2: moving avg
h_hasest = {uid: np.zeros(24, dtype=np.int16) for uid in self.building_ids}
# hasest indicates whether every hour of the day has estimation.
# only when all 0 become 1 in has_est, the function runs over.
effi_h = 0.9
daytype = self.state_buffer.get(-1)["daytype"][0][0]
prev_daytype = self.state_buffer.get(-2)["daytype"][0][0]
for uid in self.building_ids:
# starting from t=0, need a loop to cycle time
# say at hour=t, check if the action of c/h is clipped
# if so, directly calculate h/c load and continue this loop
if timestep % 24 == 0:
for time in range(24):
now_state = self.state_buffer.get(-2)
now_c_soc = now_state["soc_c"][time][uid]
now_h_soc = now_state["soc_h"][time][uid]
now_b_soc = now_state["soc_b"][time][uid]
now_t_out = now_state["t_out"][time][uid]
now_solar = now_state["solar_gen"][time][uid]
now_elec_dem = now_state["elec_dem"][time][uid]
cop_c = self.cop_cal(now_t_out) # cop at t
now_action = self.action_buffer.get(-2)
now_action_c = now_action["action_C"][time][uid]
now_action_h = now_action["action_H"][time][uid]
now_action_b = now_action["action_bat"][time][uid]
if time != 0:
prev_state = now_state
prev_t_out = prev_state["t_out"][time - 1][
uid
] # when time=0, time-1=-1
else:
prev_state = self.state_buffer.get(-3)
prev_t_out = prev_state["t_out"][-1][uid]
if time != 23:
next_state = now_state
next_c_soc = next_state["soc_c"][time + 1][uid]
next_h_soc = next_state["soc_h"][time + 1][uid]
next_b_soc = next_state["soc_b"][time + 1][uid]
next_t_out = next_state["t_out"][time + 1][uid]
next_elec_con = next_state["elec_cons"][time + 1][uid]
y = (
now_solar
+ next_elec_con
- now_elec_dem
- (self.C_qr_est[uid] / cop_c)
* (next_c_soc - (1 - self.CF_C) * now_c_soc)
* 0.9
- (self.H_qr_est[uid] / effi_h)
* (next_h_soc - (1 - self.CF_H) * now_h_soc)
- (next_b_soc - (1 - self.CF_B) * now_b_soc)
* self.capacity_b[uid]
/ 0.9
)
else:
next_state = self.state_buffer.get(-1)
next_c_soc = next_state["soc_c"][0][uid]
next_h_soc = next_state["soc_h"][0][uid]
next_b_soc = next_state["soc_b"][0][uid]
next_t_out = next_state["t_out"][0][uid]
next_elec_con = next_state["elec_cons"][0][uid]
y = (
now_solar
+ next_elec_con
- now_elec_dem
- (self.C_qr_est[uid] / cop_c)
* (next_c_soc - (1 - self.CF_C) * now_c_soc)
* 0.9
- (self.H_qr_est[uid] / effi_h)
* (next_h_soc - (1 - self.CF_H) * now_h_soc)
- (next_b_soc - (1 - self.CF_B) * now_b_soc)
* self.capacity_b[uid]
/ 0.9
)
a_clip_c = next_c_soc - (1 - self.CF_C) * now_c_soc
a_clip_h = next_h_soc - (1 - self.CF_H) * now_h_soc
if self.has_heating[uid] is False:
c_load = max(0, y)
h_load = 0
est_h_load[uid][time] = h_load
est_c_load[uid][time] = c_load
c_hasest[uid][time], h_hasest[uid][time] = -1, -1
else:
## get results of slope in regr model
# c_load = max(0, y * cop_c)
# h_load = max(0, y * effi_h)
c_load = h_load = max(0, y - (1/cop_c + 1/effi_h))
c_hasest[uid][time], h_hasest[uid][time] = 1, 1
# save load est to buffer
est_h_load[uid][time] = np.round(h_load, 2)
est_c_load[uid][time] = np.round(c_load, 2)
# ----------record average-------------
if time == 23:
if prev_daytype in [7]:
self.c_weekend1_avg[uid] = (
self.c_weekend1_avg[uid] * 0.5 + est_c_load[uid] * 0.5
if self.c_weekend1_avg[uid].all() != 0
else est_c_load[uid]
)
self.h_weekend1_avg[uid] = (
self.h_weekend1_avg[uid] * 0.5 + est_h_load[uid] * 0.5
if self.h_weekend1_avg[uid].all() != 0
else est_h_load[uid]
)
elif prev_daytype in [1, 8]:
self.c_weekend2_avg[uid] = (
self.c_weekend2_avg[uid] * 0.5 + est_c_load[uid] * 0.5
if self.c_weekend2_avg[uid].all() != 0
else est_c_load[uid]
)
self.h_weekend2_avg[uid] = (
self.h_weekend2_avg[uid] * 0.5 + est_h_load[uid] * 0.5
if self.h_weekend2_avg[uid].all() != 0
else est_h_load[uid]
)
else:
self.c_weekday_avg[uid] = (
self.c_weekday_avg[uid] * 0.5 + est_c_load[uid] * 0.5
if self.c_weekday_avg[uid].all() != 0
else est_c_load[uid]
)
self.h_weekday_avg[uid] = (
self.h_weekday_avg[uid] * 0.5 + est_h_load[uid] * 0.5
if self.h_weekday_avg[uid].all() != 0
else est_h_load[uid]
)
# ------------use average-------------
if daytype in [7]:
est_h_load[uid] = self.h_weekend1_avg[uid]
est_c_load[uid] = self.c_weekend1_avg[uid]
elif daytype in [1, 8]:
est_h_load[uid] = self.h_weekend2_avg[uid]
est_c_load[uid] = self.c_weekend2_avg[uid]
else:
est_h_load[uid] = self.h_weekday_avg[uid]
est_c_load[uid] = self.c_weekday_avg[uid]
# ------------scaling maximal three hours--------------
index_sort_h = np.argsort(est_h_load[uid])
index_sort_c = np.argsort(est_c_load[uid])
for ind in range(-3, 0):
index_h = index_sort_h[ind]
index_c = index_sort_c[ind]
est_h_load[uid][index_h] = est_h_load[uid][index_h] * 1
est_c_load[uid][index_c] = est_c_load[uid][index_c] * 1
adaptive_h_load[uid] = est_h_load[uid][T - window:]
adaptive_c_load[uid] = est_c_load[uid][T - window:]
'''
time = timestep % 24
if timestep == 24 * 14:
self.calculate_avg_h_c()
else:
for uid in self.building_ids:
# starting from t=0, need a loop to cycle time
# say at hour=t, check if the action of c/h is clipped
# if so, directly calculate h/c load and continue this loop
# ------------compare w/ true action--------
if time in [0]:
prev_state = self.state_buffer.get(-2)
now_state = self.state_buffer.get(-2)
next_state = self.state_buffer.get(-1)
now_action = self.action_buffer.get(-2)
elif time in [1]:
prev_state = self.state_buffer.get(-2)
now_state = self.state_buffer.get(-1)
next_state = self.state_buffer.get(-1)
now_action = self.action_buffer.get(-1)
else:
prev_state = self.state_buffer.get(-1)
now_state = self.state_buffer.get(-1)
next_state = self.state_buffer.get(-1)
now_action = self.action_buffer.get(-1)
now_c_soc = now_state["soc_c"][time-1][uid]
now_h_soc = now_state["soc_h"][time-1][uid]
now_b_soc = now_state["soc_b"][time-1][uid]
now_t_out = now_state["t_out"][time-1][uid]
now_solar = now_state["solar_gen"][time-1][uid]
now_elec_dem = now_state["elec_dem"][time-1][uid]
daytype = now_state["daytype"][time-1][uid]
cop_c = self.cop_cal(now_t_out) # cop at t
now_action_c = now_action["action_C"][time-1][uid]
now_action_h = now_action["action_H"][time-1][uid]
now_action_b = now_action["action_bat"][time-1][uid]
prev_t_out = prev_state["t_out"][time-2][uid]
next_c_soc = next_state["soc_c"][time][uid]