-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpredictor_temp.py
More file actions
2178 lines (1941 loc) 路 92.8 KB
/
Copy pathpredictor_temp.py
File metadata and controls
2178 lines (1941 loc) 路 92.8 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
from copy import Error
from utils import ReplayBuffer
from citylearn import CityLearn
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
class DataLoader:
"""Base Class"""
def __init__(self, action_space: list) -> None:
self.action_space = action_space
def upload_data(self) -> None:
"""Upload to memory"""
raise NotImplementedError
def load_data(self):
"""Optional: not directly called. Should be called within `upload_data` if used."""
raise NotImplementedError
def parse_data(self, data: dict, current_data: dict):
"""Parses `current_data` for optimization and loads into `data`"""
for key, value in current_data.items():
if key not in data:
data[key] = []
data[key].append(value)
return data
def convert_to_numpy(self, params: dict):
"""Converts dic[key] to nd.array"""
for key in params:
if key == "c_bat_init" or key == "c_Csto_init" or key == "c_Hsto_init":
params[key] = np.array(params[key][0])
else:
params[key] = np.array(params[key])
def get_dimensions(self, data: dict):
"""Prints shape of each param"""
for key in data.keys():
print(data[key].shape)
def get_building(self, data: dict, building_id: int):
"""Loads data (dict) from a particular building. 1-based indexing for building"""
assert building_id > 0, "building_id is 1-based indexing."
building_data = {}
for key in data.keys():
building_data[key] = np.array(data[key])[:, building_id - 1]
return building_data
def create_random_data(self, data: dict):
"""Synthetic data (Gaussian) generation"""
for key in data:
data[key] = np.clip(np.random.random(size=data[key].shape), 0, 1)
return data
# TODO: @Zhiyao - add in parameter/initialization for capacity as discussed.
class Predictor(DataLoader):
def __init__(self, action_space: list) -> None:
super().__init__(action_space)
self.building_ids = range(len(self.action_space)) # number of buildings
self.state_buffer = ReplayBuffer(buffer_size=365, batch_size=32)
self.action_buffer = ReplayBuffer(buffer_size=365, batch_size=32)
# define constants
self.true_val_h = [
10.68,
49.35,
1e-05,
1e-05,
60.12,
105.12,
85.44,
111.96,
102.24,
]
self.true_val_b = [140, 80, 50, 75, 50, 30, 40, 30, 35]
self.true_val_c = [
618.12,
227.37,
414.68,
383.565,
244.685,
96.87,
127.82,
165.45,
175.23,
]
self.CF_C = 0.006
self.CF_H = 0.008
self.CF_B = 0
# define regression model
self.regr = LinearRegression(
fit_intercept=False
) # , positive=True) # version error
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.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.5 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.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.parse_data(
replay_buffer.get_recent(), self.get_day_data(replay_buffer, timestep)
)
replay_buffer.add(data)
replay_buffer.total_it += 1
else:
data = self.full_parse_data({}, self.get_day_data(replay_buffer, timestep))
replay_buffer.add(data)
replay_buffer.total_it += 24 # this is incorrect.
return data
def full_parse_data(
self, data: dict, current_data: dict
): # override in child class
"""Parses `current_data` for optimization and loads into `data`. Everything is of shape 24, 9"""
TOTAL_PARAMS = 23
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."
)
for key, value in current_data.items():
if key not in data:
data[key] = []
if len(value.shape) == 1:
value = np.repeat(value, 24).reshape(24, len(self.building_ids))
data[key].append(value)
return data
# TODO: @Zhiyao - needs fixing -- done
def calculate_avg(self):
"""calculate hourly avg value of the day"""
buffer = self.state_buffer
daytype = {i: [] for i in self.building_ids}
elec_dem = {i: [] for i in self.building_ids}
solar_gen = {i: [] for i in self.building_ids}
elec_weekday = {i: np.zeros([24]) for i in self.building_ids}
elec_weekend1 = {i: np.zeros([24]) for i in self.building_ids}
elec_weekend2 = {i: np.zeros([24]) for i in self.building_ids}
solar_alldays = {i: np.zeros([24]) for i in self.building_ids}
weekend1, weekend2, weekday = 0, 0, 0
for i in range(-14, -1):
for uid in self.building_ids:
daytype[uid].append(np.array(buffer.get(i)["daytype"])[0, uid])
elec_dem[uid].append(np.array(buffer.get(i)["elec_dem"])[:, uid])
solar_gen[uid].append(np.array(buffer.get(i)["solar_gen"])[:, uid])
for i in range(len(elec_dem[0])):
for uid in self.building_ids:
solar_alldays[uid] += solar_gen[uid][i]
if daytype[0][i] in [7]:
weekend1 += 1
for uid in self.building_ids:
elec_weekend1[uid] += elec_dem[uid][i]
elif daytype[0][i] in [1, 8]:
weekend2 += 1
for uid in self.building_ids:
elec_weekend2[uid] += elec_dem[uid][i]
else:
weekday += 1
for uid in self.building_ids:
elec_weekday[uid] += elec_dem[uid][i]
for uid in self.building_ids:
self.solar_avg[uid] = solar_alldays[uid] / 13
self.elec_weekday_avg[uid] = elec_weekday[uid] / weekday
self.elec_weekend1_avg[uid] = elec_weekend1[uid] / weekend1
self.elec_weekend2_avg[uid] = elec_weekend1[uid] / weekend2
# 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
observation_data = {}
# get current day's buffer
data = replay_buffer.get(-2) 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)
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"] # 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"] # load previous C_max
if C_max is None:
C_max = np.max(C_bd, axis=0)
else:
H_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])
E_hpC_max = np.max(C_bd / COP_C, axis=0)
E_ehH_max = H_max / 0.9
C_p_bat = [np.round(self.capacity_b[uid], 2) for uid in self.building_ids]
c_bat_init = np.array(
self.state_buffer.get(-1)["soc_b"][-1]
) # -2 to -1 (confirm)--done
c_bat_init[c_bat_init == np.inf] = 0
C_p_Hsto = [np.round(self.H_qr_est[uid], 2) for uid in self.building_ids]
c_Hsto_init = np.array(
self.state_buffer.get(-1)["soc_h"][-1]
) # -2 to -1 (confirm)--done
c_Hsto_init[c_Hsto_init == np.inf] = 0
C_p_Csto = [np.round(self.C_qr_est[uid], 2) for uid in self.building_ids]
c_Csto_init = np.array(
self.state_buffer.get(-1)["soc_c"][-1]
) # -2 to -1 (confirm)--done
c_Csto_init[c_Csto_init == np.inf] = 0
print("C_p_bat", C_p_bat, "\nC_p_Hsto", C_p_Hsto, "\nC_p_Csto", C_p_Csto)
# add E-grid - default day-ahead
observation_data["E_grid"] = np.zeros((window, len(self.building_ids)))
observation_data["E_grid_prevhour"] = np.zeros((window, len(self.building_ids)))
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["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"]
return observation_data
def upload_data(self, state, action):
"""Uploads state and action_reward replay buffer"""
raise Error("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):
# 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):
# 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):
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):
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):
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"
"""buffer(-1) is the current day record, so buffer(-2) is for yesterday"""
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):
# assert (
# daystep % 24 == 0
# ), "only make day-ahead prediction at the first hour of the day"
"""changed for adaptive dispatch--make inference every hour"""
if timestep % 24 == 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)
solar_gen = {uid: np.zeros([window + 2]) for uid in self.building_ids}
elec_dem = {uid: np.zeros([window + 2]) 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:
if timestep % 24 in [0]:
solar_gen[uid][0] = (
pred_buffer.get(-2)["solar_gen"][-1][uid] - self.solar_avg[uid][23]
)
solar_gen[uid][1] = (
pred_buffer.get(-1)["solar_gen"][timestep % 24][uid]
- self.solar_avg[uid][0]
)
else:
solar_gen[uid][0] = (
pred_buffer.get(-1)["solar_gen"][(timestep - 1) % 24][uid]
- self.solar_avg[uid][(timestep - 1) % 24]
)
solar_gen[uid][1] = (
pred_buffer.get(-1)["solar_gen"][timestep % 24][uid]
- self.solar_avg[uid][timestep % 24]
)
daytype[uid] = pred_buffer.get(-1)["daytype"][0][uid]
if timestep % 24 in [0]:
if daytype[uid] in [7]:
elec_dem[uid][0] = (
pred_buffer.get(-2)["elec_dem"][-1][uid]
- self.elec_weekend1_avg[uid][23]
)
elec_dem[uid][1] = (
pred_buffer.get(-1)["elec_dem"][0][uid]
- self.elec_weekend1_avg[uid][0]
)
elif daytype[uid] in [1, 8]:
elec_dem[uid][0] = (
pred_buffer.get(-2)["elec_dem"][-1][uid]
- self.elec_weekend2_avg[uid][23]
)
elec_dem[uid][1] = (
pred_buffer.get(-1)["elec_dem"][0][uid]
- self.elec_weekend2_avg[uid][0]
)
else:
elec_dem[uid][0] = (
pred_buffer.get(-2)["elec_dem"][-1][uid]
- self.elec_weekday_avg[uid][23]
)
elec_dem[uid][1] = (
pred_buffer.get(-1)["elec_dem"][0][uid]
- self.elec_weekday_avg[uid][0]
)
else:
if daytype[uid] in [7]:
elec_dem[uid][0] = (
pred_buffer.get(-1)["elec_dem"][(timestep - 1) % 24][uid]
- self.elec_weekend1_avg[uid][(timestep - 1) % 24]
)
elec_dem[uid][1] = (
pred_buffer.get(-1)["elec_dem"][timestep % 24][uid]
- self.elec_weekend1_avg[uid][timestep % 24]
)
elif daytype[uid] in [1, 8]:
elec_dem[uid][0] = (
pred_buffer.get(-1)["elec_dem"][(timestep - 1) % 24][uid]
- self.elec_weekend2_avg[uid][(timestep - 1) % 24]
)
elec_dem[uid][1] = (
pred_buffer.get(-1)["elec_dem"][timestep % 24][uid]
- self.elec_weekend2_avg[uid][timestep % 24]
)
else:
elec_dem[uid][0] = (
pred_buffer.get(-1)["elec_dem"][(timestep - 1) % 24][uid]
- self.elec_weekday_avg[uid][(timestep - 1) % 24]
)
elec_dem[uid][1] = (
pred_buffer.get(-1)["elec_dem"][timestep % 24][uid]
- self.elec_weekday_avg[uid][timestep % 24]
)
# # daytype[uid] = pred_buffer.get_recent()["day"][0][uid]
# if daytype[uid] in [7]:
# elec_dem[uid][1] = (
# pred_buffer.get(-1)["non_shiftable_load"][0][uid]
# - self.elec_weekend1_avg[uid][0]
# )
# elif daytype[uid] in [1, 8]:
# elec_dem[uid][1] = (
# pred_buffer.get(-1)["non_shiftable_load"][0][uid]
# - self.elec_weekend2_avg[uid][0]
# )
# else:
# elec_dem[uid][1] = (
# pred_buffer.get(-1)["non_shiftable_load"][0][uid]
# - self.elec_weekday_avg[uid][0]
# )
for i in range(np.shape(input_solar[uid])[0]):
x_pred = [
[
solar_gen[uid][i],
solar_gen[uid][i + 1],
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 + 1 + timestep) % 24]
day_pred_solar[uid][i] = max(0, y_pred.item() + avg)
solar_gen[uid][i + 2] = y_pred.item()
day_pred_solar[uid] = np.append(
np.array([pred_buffer.get(-1)["solar_gen"][timestep % 24][uid]]),
day_pred_solar[uid][0 : window - 1],
)
for i in range(len(input_elec[uid])):
x_pred = [
[elec_dem[uid][i], elec_dem[uid][i + 1], input_elec[uid][i, 0]]
] # ignore humidity
y_pred = self.regr_elec[uid].predict(x_pred)
if daytype[uid] in [7]:
avg = self.elec_weekend1_avg[uid][(i + 1 + timestep) % 24]
elif daytype[uid] in [1, 8]:
avg = self.elec_weekend2_avg[uid][(i + 1 + timestep) % 24]
else:
avg = self.elec_weekday_avg[uid][(i + 1 + timestep) % 24]
day_pred_elec[uid][i] = max(0, y_pred.item() + avg)
elec_dem[uid][i + 2] = y_pred.item()
day_pred_elec[uid] = np.append(
np.array([pred_buffer.get(-1)["elec_dem"][timestep % 24][uid]]),
day_pred_elec[uid][: window - 1],
)
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"""
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, 0):
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_append1 = [
solar_gen[i - 2][uid] - self.solar_avg[uid][(i - 2) % 24],
solar_gen[i - 1][uid] - self.solar_avg[uid][(i - 1) % 24],
]
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_append1 + 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
"""
T = 24
window = T - timestep % 24
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
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
repeat_times = 0
time = 0
jump_out = False
while not jump_out:
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.true_val_c[uid] / cop_c)
* (next_c_soc - (1 - self.CF_C) * now_c_soc)
* 0.9
- (self.true_val_h[uid] / effi_h)
* (next_h_soc - (1 - self.CF_H) * now_h_soc)
- (next_b_soc - (1 - self.CF_B) * now_b_soc)
* self.true_val_b[uid]
/ 0.9
)
else:
next_state = self.state_buffer.get(-2)
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.true_val_c[uid] / cop_c)
* (next_c_soc - (1 - self.CF_C) * now_c_soc)
* 0.9
- (self.true_val_h[uid] / effi_h)
* (next_h_soc - (1 - self.CF_H) * now_h_soc)
- (next_b_soc - (1 - self.CF_B) * now_b_soc)
* self.true_val_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 (
# repeat_times == 0
# ): # can we calculate direct when now_action > 0?
# if uid in [2, 3]:
# c_load = max(0, y * cop_c)
# 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:
# if (
# abs(a_clip_c - now_action_c) > 0.001
# and now_action_c < 0
# ): # cooling get clipped
# c_load = abs(a_clip_c * self.true_val_c[uid])
# if (
# abs(a_clip_h - now_action_h) > 0.001
# and now_action_h < 0
# ): # heating get clipped
# h_load = a_clip_h * self.true_val_h[uid]
# else: # heating not clipped
# h_load = (y - c_load / cop_c) * effi_h
# est_h_load[uid][time] = h_load
# est_c_load[uid][time] = c_load
# c_hasest[uid][time], h_hasest[uid][time] = -1, -1
# elif (
# abs(a_clip_h > now_action_h) > 0.01 and a_clip_h < 0
# ): # h clipped but c not clipped
# h_load = abs(a_clip_h * self.true_val_h[uid])
# c_load = (y - h_load / effi_h) * cop_c
# c_hasest[uid][time], h_hasest[uid][time] = -1, -1
# est_h_load[uid][time] = h_load
# est_c_load[uid][time] = c_load
if uid in [2, 3]:
c_load = max(0, y * cop_c)
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:
prev_t_cop = self.cop_cal(prev_t_out)
now_t_cop = self.cop_cal(now_t_out)
next_t_cop = self.cop_cal(next_t_out)
# if (
# prev_t_cop != now_t_cop
# or prev_t_cop != next_t_cop
# or now_t_cop != next_t_cop
# ):
## get results of slope in regr model
c_load = h_load = max(1, y - (1 / now_t_cop + 1 / 0.9))
c_hasest[uid][time], h_hasest[uid][time] = 1, 1
# else: # COP remaining the same (zero)
# h_load = self.avg_h_load[uid][time]
# c_load = self.avg_c_load[uid][time]
# c_hasest[uid][time], h_hasest[uid][time] = 2, 2
# 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)
# if c_hasest[uid][time] not in [
# 0,
# 2,
# ]: # meaning that avg can be updated
if self.daystep >= 1:
self.avg_h_load[uid][time] = (
self.avg_h_load[uid][time] * 0.8 + h_load * 0.2
)
self.avg_c_load[uid][time] = (
self.avg_c_load[uid][time] * 0.8 + c_load * 0.2
)
else:
self.avg_h_load[uid][time] = h_load
self.avg_c_load[uid][time] = c_load