-
Notifications
You must be signed in to change notification settings - Fork 171
/
building.py
2716 lines (2172 loc) · 131 KB
/
building.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
import logging
from typing import Any, List, Mapping, Tuple, Union
from gymnasium import spaces
import numpy as np
import pandas as pd
import torch
from citylearn.base import Environment, EpisodeTracker
from citylearn.data import CarbonIntensity, EnergySimulation, Pricing, TOLERANCE, Weather, ZERO_DIVISION_PLACEHOLDER
from citylearn.dynamics import Dynamics, LSTMDynamics
from citylearn.electric_vehicle_charger import Charger
from citylearn.energy_model import Battery, ElectricDevice, ElectricHeater, HeatPump, PV, StorageTank
from citylearn.occupant import LogisticRegressionOccupant, Occupant
from citylearn.power_outage import PowerOutage
from citylearn.preprocessing import Normalize, PeriodicNormalization
LOGGER = logging.getLogger()
logging.basicConfig(level=logging.INFO)
class Building(Environment):
r"""Base class for building.
Parameters
----------
energy_simulation : EnergySimulation
Temporal features, cooling, heating, dhw and plug loads, solar generation and indoor environment time series.
weather : Weather
Outdoor weather conditions and forecasts time sereis.
observation_metadata : dict
Mapping of active and inactive observations.
action_metadata : dict
Mapping od active and inactive actions.
episode_tracker: EpisodeTracker, optional
:py:class:`citylearn.base.EpisodeTracker` object used to keep track of current episode time steps
for reading observations from data files.
carbon_intensity : CarbonIntensity, optional
Carbon dioxide emission rate time series.
pricing : Pricing, optional
Energy pricing and forecasts time series.
dhw_storage : StorageTank, optional
Hot water storage object for domestic hot water.
cooling_storage : StorageTank, optional
Cold water storage object for space cooling.
heating_storage : StorageTank, optional
Hot water storage object for space heating.
electrical_storage : Battery, optional
Electric storage object for meeting electric loads.
dhw_device : Union[HeatPump, ElectricHeater], optional
Electric device for meeting hot domestic hot water demand and charging `dhw_storage`.
cooling_device : HeatPump, optional
Electric device for meeting space cooling demand and charging `cooling_storage`.
heating_device : Union[HeatPump, ElectricHeater], optional
Electric device for meeting space heating demand and charging `heating_storage`.
pv : PV, optional
PV object for offsetting electricity demand from grid.
name : str, optional
Unique building name.
observation_space_limit_delta: float, default: 0.0
+/- buffer for observation space limits after they have been dynamically calculated.
maximum_temperature_delta: float, default: 20.0
Expected maximum absolute temperature delta above and below indoor dry-bulb temperature in [C].
demand_observation_limit_factor: float, default: 1.15
Multiplier for maximum cooling/heating/dhw demand observations when setting observation limits.
simulate_power_outage: bool, default: False
Whether to allow time steps when the grid is unavailable and loads must be met using only the
building's downward flexibility resources.
stochastic_power_outage: bool, default: False
Whether to use a stochastic function to determine outage time steps otherwise,
:py:class:`citylearn.building.Building.energy_simulation.power_outage` time series is used.
stochastic_power_outage_model: PowerOutage, optional
Power outage model class used to generate stochastic power outage signals.
carbon_intensity : CarbonIntensity, optional
Carbon dioxide emission rate time series.
electric_vehicle_chargers : Charger, optional
Electric Vehicle Chargers associated with the building.
Other Parameters
----------------
**kwargs : Any
Other keyword arguments used to initialize super class.
"""
def __init__(
self, energy_simulation: EnergySimulation, weather: Weather, observation_metadata: Mapping[str, bool],
action_metadata: Mapping[str, bool], episode_tracker: EpisodeTracker,
carbon_intensity: CarbonIntensity = None,
pricing: Pricing = None, dhw_storage: StorageTank = None, cooling_storage: StorageTank = None,
heating_storage: StorageTank = None, electrical_storage: Battery = None,
dhw_device: Union[HeatPump, ElectricHeater] = None, cooling_device: HeatPump = None,
heating_device: Union[HeatPump, ElectricHeater] = None, pv: PV = None, name: str = None,
maximum_temperature_delta: float = None, observation_space_limit_delta: float = None,
demand_observation_limit_factor: float = None, simulate_power_outage: bool = None,
stochastic_power_outage: bool = None, stochastic_power_outage_model: PowerOutage = None,
electric_vehicle_chargers: List[Charger] = None, **kwargs: Any
):
self.name = name
self.dhw_storage = dhw_storage
self.cooling_storage = cooling_storage
self.heating_storage = heating_storage
self.electrical_storage = electrical_storage
self.dhw_device = dhw_device
self.cooling_device = cooling_device
self.heating_device = heating_device
self.__non_shiftable_load_device = ElectricDevice(0.0)
self.pv = pv
super().__init__(
seconds_per_time_step=kwargs.get('seconds_per_time_step'),
random_seed=kwargs.get('random_seed'),
episode_tracker=episode_tracker
)
self.stochastic_power_outage_model = stochastic_power_outage_model
self.electric_vehicle_chargers = electric_vehicle_chargers
self.energy_simulation = energy_simulation
self.weather = weather
self.carbon_intensity = carbon_intensity
self.pricing = pricing
self.observation_metadata = observation_metadata
self.action_metadata = action_metadata
self.observation_space_limit_delta = observation_space_limit_delta
self.maximum_temperature_delta = maximum_temperature_delta
self.demand_observation_limit_factor = demand_observation_limit_factor
self.simulate_power_outage = simulate_power_outage
self.stochastic_power_outage = stochastic_power_outage
self.non_periodic_normalized_observation_space_limits = None
self.periodic_normalized_observation_space_limits = None
self.observation_space = self.estimate_observation_space(include_all=False, normalize=False)
self.action_space = self.estimate_action_space()
@property
def energy_simulation(self) -> EnergySimulation:
"""Temporal features, cooling, heating, dhw and plug loads, solar generation and indoor environment time series."""
return self.__energy_simulation
@property
def weather(self) -> Weather:
"""Outdoor weather conditions and forecasts time series."""
return self.__weather
@property
def observation_metadata(self) -> Mapping[str, bool]:
"""Mapping of active and inactive observations."""
return self.__observation_metadata
@property
def action_metadata(self) -> Mapping[str, bool]:
"""Mapping od active and inactive actions."""
return self.__action_metadata
@property
def carbon_intensity(self) -> CarbonIntensity:
"""Carbon dioxide emission rate time series."""
return self.__carbon_intensity
@property
def pricing(self) -> Pricing:
"""Energy pricing and forecasts time series."""
return self.__pricing
@property
def dhw_storage(self) -> StorageTank:
"""Hot water storage object for domestic hot water."""
return self.__dhw_storage
@property
def cooling_storage(self) -> StorageTank:
"""Cold water storage object for space cooling."""
return self.__cooling_storage
@property
def heating_storage(self) -> StorageTank:
"""Hot water storage object for space heating."""
return self.__heating_storage
@property
def electrical_storage(self) -> Battery:
"""Electric storage object for meeting electric loads."""
return self.__electrical_storage
@property
def dhw_device(self) -> Union[HeatPump, ElectricHeater]:
"""Electric device for meeting hot domestic hot water demand and charging `dhw_storage`."""
return self.__dhw_device
@property
def cooling_device(self) -> HeatPump:
"""Electric device for meeting space cooling demand and charging `cooling_storage`."""
return self.__cooling_device
@property
def heating_device(self) -> Union[HeatPump, ElectricHeater]:
"""Electric device for meeting space heating demand and charging `heating_storage`."""
return self.__heating_device
@property
def non_shiftable_load_device(self) -> ElectricDevice:
"""Generic electric device for meeting non_shiftable_load."""
return self.__non_shiftable_load_device
@property
def pv(self) -> PV:
"""PV object for offsetting electricity demand from grid."""
return self.__pv
@property
def electric_vehicle_chargers(self) -> List[Charger]:
"""Electric Vehicle Chargers associated with the building for charging connected eletric vehicles."""
return self.__electric_vehicle_chargers
@property
def name(self) -> str:
"""Unique building name."""
return self.__name
@property
def observation_space_limit_delta(self) -> float:
"""+/- buffer for observation space limits after they have been dynamically calculated."""
return self.__observation_space_limit_delta
@property
def maximum_temperature_delta(self) -> float:
"""Expected maximum absolute temperature delta above and below indoor dry-bulb temperature in [C]."""
return self.__maximum_temperature_delta
@property
def demand_observation_limit_factor(self) -> float:
"""Multiplier for maximum cooling/heating/dhw demand observations when setting observation limits."""
return self.__demand_observation_limit_factor
@property
def simulate_power_outage(self) -> bool:
"""Whether to allow time steps when the grid is unavailable and loads must be met using only the
building's downward flexibility resources."""
return self.__simulate_power_outage
@property
def stochastic_power_outage(self) -> bool:
"""Whether to use a stochastic function to determine outage time steps otherwise,
:py:class:`citylearn.building.Building.energy_simulation.power_outage` time series is used."""
return self.__stochastic_power_outage
@property
def observation_space(self) -> spaces.Box:
"""Agent observation space."""
return self.__observation_space
@property
def action_space(self) -> spaces.Box:
"""Agent action spaces."""
return self.__action_space
@property
def active_observations(self) -> List[str]:
"""Observations in `observation_metadata` with True value i.e. obeservable."""
return [k for k, v in self.observation_metadata.items() if v]
@property
def active_actions(self) -> List[str]:
"""Actions in `action_metadata` with True value i.e.
indicates which storage systems are to be controlled during simulation."""
return [k for k, v in self.action_metadata.items() if v]
@property
def net_electricity_consumption_emission_without_storage_and_pv(self) -> np.ndarray:
"""Carbon dioxide emmission from `net_electricity_consumption_without_storage_pv` time series, in [kg_co2]."""
return (
self.carbon_intensity.carbon_intensity[
0:self.time_step + 1] * self.net_electricity_consumption_without_storage_and_pv
).clip(min=0)
@property
def net_electricity_consumption_cost_without_storage_and_pv(self) -> np.ndarray:
"""net_electricity_consumption_without_storage_and_pv` cost time series, in [$]."""
return self.pricing.electricity_pricing[
0:self.time_step + 1] * self.net_electricity_consumption_without_storage_and_pv
@property
def net_electricity_consumption_without_storage_and_pv(self) -> np.ndarray:
"""Net electricity consumption in the absence of flexibility provided by storage devices,
and self generation time series, in [kWh].
Notes
-----
net_electricity_consumption_without_storage_and_pv =
`net_electricity_consumption_without_storage` - `solar_generation`
"""
return self.net_electricity_consumption_without_storage - self.solar_generation
@property
def net_electricity_consumption_emission_without_storage(self) -> np.ndarray:
"""Carbon dioxide emmission from `net_electricity_consumption_without_storage` time series, in [kg_co2]."""
return (self.carbon_intensity.carbon_intensity[
0:self.time_step + 1] * self.net_electricity_consumption_without_storage).clip(min=0)
@property
def net_electricity_consumption_cost_without_storage(self) -> np.ndarray:
"""`net_electricity_consumption_without_storage` cost time series, in [$]."""
return self.pricing.electricity_pricing[0:self.time_step + 1] * self.net_electricity_consumption_without_storage
@property
def net_electricity_consumption_without_storage(self) -> np.ndarray:
"""net electricity consumption in the absence of flexibility provided by storage devices time series, in [kWh].
Notes
-----
net_electricity_consumption_without_storage = `net_electricity_consumption` - (`cooling_storage_electricity_consumption`
+ `heating_storage_electricity_consumption` + `dhw_storage_electricity_consumption` + `electrical_storage_electricity_consumption` + `charger_electricity_consumption`)
Regarding electric vehicles there is:
chargers_electricity_consumption -> Sum of the electricity consumption of all electric_vehicle_chargers in the building
So, the first one is subtracted from the net_electricity_consumption, obtaining the energy consumption as if the cars were not used at all.
However, if there are chargers and EVs, they need to charge per usual, so that consumption is added
This is what allows to check if the control mechanism affects the grid balancing scheme for EVs for example.
"""
return self.net_electricity_consumption - np.sum([
self.cooling_storage_electricity_consumption,
self.heating_storage_electricity_consumption,
self.dhw_storage_electricity_consumption,
self.electrical_storage_electricity_consumption,
self.__chargers_electricity_consumption
], axis=0)
@property
def net_electricity_consumption_emission(self) -> np.ndarray:
"""Carbon dioxide emmission from `net_electricity_consumption` time series, in [kg_co2]."""
return self.__net_electricity_consumption_emission[:self.time_step + 1]
@property
def net_electricity_consumption_cost(self) -> np.ndarray:
"""`net_electricity_consumption` cost time series, in [$]."""
return self.__net_electricity_consumption_cost[:self.time_step + 1]
@property
def net_electricity_consumption(self) -> np.ndarray:
"""Net electricity consumption time series, in [kWh]."""
return self.__net_electricity_consumption[:self.time_step + 1]
@property
def cooling_electricity_consumption(self) -> np.ndarray:
"""`cooling_device` net electricity consumption in meeting cooling demand and `cooling_storage` energy demand time series, in [kWh].
"""
return self.cooling_device.electricity_consumption[:self.time_step + 1]
@property
def heating_electricity_consumption(self) -> np.ndarray:
"""`heating_device` net electricity consumption in meeting heating demand and `heating_storage` energy demand time series, in [kWh].
"""
return self.heating_device.electricity_consumption[:self.time_step + 1]
@property
def dhw_electricity_consumption(self) -> np.ndarray:
"""`dhw_device` net electricity consumption in meeting domestic hot water and `dhw_storage` energy demand time series, in [kWh].
"""
return self.dhw_device.electricity_consumption[:self.time_step + 1]
@property
def non_shiftable_load_electricity_consumption(self) -> np.ndarray:
"""`non_shiftable_load_device` net electricity consumption in meeting `non_shiftable_load` energy demand time series, in [kWh].
"""
return self.non_shiftable_load_device.electricity_consumption[:self.time_step + 1]
@property
def cooling_storage_electricity_consumption(self) -> np.ndarray:
"""`cooling_storage` net electricity consumption time series, in [kWh].
Positive values indicate `cooling_device` electricity consumption to charge `cooling_storage` while negative values indicate avoided `cooling_device`
electricity consumption by discharging `cooling_storage` to meet `cooling_demand`.
"""
return self.cooling_device.get_input_power(self.cooling_storage.energy_balance[:self.time_step + 1],
self.weather.outdoor_dry_bulb_temperature[:self.time_step + 1],
False)
@property
def heating_storage_electricity_consumption(self) -> np.ndarray:
"""`heating_storage` net electricity consumption time series, in [kWh].
Positive values indicate `heating_device` electricity consumption to charge `heating_storage` while negative values indicate avoided `heating_device`
electricity consumption by discharging `heating_storage` to meet `heating_demand`.
"""
if isinstance(self.heating_device, HeatPump):
consumption = self.heating_device.get_input_power(self.heating_storage.energy_balance[:self.time_step + 1],
self.weather.outdoor_dry_bulb_temperature[
:self.time_step + 1], True)
else:
consumption = self.heating_device.get_input_power(self.heating_storage.energy_balance[:self.time_step + 1])
return consumption
@property
def dhw_storage_electricity_consumption(self) -> np.ndarray:
"""`dhw_storage` net electricity consumption time series, in [kWh].
Positive values indicate `dhw_device` electricity consumption to charge `dhw_storage` while negative values indicate avoided `dhw_device`
electricity consumption by discharging `dhw_storage` to meet `dhw_demand`.
"""
if isinstance(self.dhw_device, HeatPump):
consumption = self.dhw_device.get_input_power(self.dhw_storage.energy_balance[:self.time_step + 1],
self.weather.outdoor_dry_bulb_temperature[
:self.time_step + 1], True)
else:
consumption = self.dhw_device.get_input_power(self.dhw_storage.energy_balance[:self.time_step + 1])
return consumption
@property
def electrical_storage_electricity_consumption(self) -> np.ndarray:
"""Energy supply from grid and/or `PV` to `electrical_storage` time series, in [kWh]."""
return self.electrical_storage.electricity_consumption[:self.time_step + 1]
@property
def energy_from_cooling_device_to_cooling_storage(self) -> np.ndarray:
"""Energy supply from `cooling_device` to `cooling_storage` time series, in [kWh]."""
return self.cooling_storage.energy_balance.clip(min=0)[:self.time_step + 1]
@property
def energy_from_heating_device_to_heating_storage(self) -> np.ndarray:
"""Energy supply from `heating_device` to `heating_storage` time series, in [kWh]."""
return self.heating_storage.energy_balance.clip(min=0)[:self.time_step + 1]
@property
def energy_from_dhw_device_to_dhw_storage(self) -> np.ndarray:
"""Energy supply from `dhw_device` to `dhw_storage` time series, in [kWh]."""
return self.dhw_storage.energy_balance.clip(min=0)[:self.time_step + 1]
@property
def energy_to_electrical_storage(self) -> np.ndarray:
"""Energy supply from `electrical_device` to building time series, in [kWh]."""
return self.electrical_storage.energy_balance.clip(min=0)[:self.time_step + 1]
@property
def energy_from_cooling_device(self) -> np.ndarray:
"""Energy supply from `cooling_device` to building time series, in [kWh]."""
return self.__energy_from_cooling_device[:self.time_step + 1]
@property
def energy_from_heating_device(self) -> np.ndarray:
"""Energy supply from `heating_device` to building time series, in [kWh]."""
return self.__energy_from_heating_device[:self.time_step + 1]
@property
def energy_from_dhw_device(self) -> np.ndarray:
"""Energy supply from `dhw_device` to building time series, in [kWh]."""
return self.__energy_from_dhw_device[:self.time_step + 1]
@property
def energy_to_non_shiftable_load(self) -> np.ndarray:
"""Energy supply from grid, PV and battery to non shiftable loads, in [kWh]."""
return self.__energy_to_non_shiftable_load[:self.time_step + 1]
@property
def energy_from_cooling_storage(self) -> np.ndarray:
"""Energy supply from `cooling_storage` to building time series, in [kWh]."""
return self.cooling_storage.energy_balance.clip(max=0)[:self.time_step + 1] * -1
@property
def energy_from_heating_storage(self) -> np.ndarray:
"""Energy supply from `heating_storage` to building time series, in [kWh]."""
return self.heating_storage.energy_balance.clip(max=0)[:self.time_step + 1] * -1
@property
def energy_from_dhw_storage(self) -> np.ndarray:
"""Energy supply from `dhw_storage` to building time series, in [kWh]."""
return self.dhw_storage.energy_balance.clip(max=0)[:self.time_step + 1] * -1
@property
def energy_from_electrical_storage(self) -> np.ndarray:
"""Energy supply from `electrical_storage` to building time series, in [kWh]."""
return self.electrical_storage.energy_balance.clip(max=0)[:self.time_step + 1] * -1
@property
def indoor_dry_bulb_temperature(self) -> np.ndarray:
"""dry bulb temperature time series, in [C].
This is the temperature when cooling_device and heating_device are controlled.
"""
return self.energy_simulation.indoor_dry_bulb_temperature[0:self.time_step + 1]
@property
def indoor_dry_bulb_temperature_cooling_set_point(self) -> np.ndarray:
"""Dry bulb temperature cooling set point time series, in [C]."""
return self.energy_simulation.indoor_dry_bulb_temperature_cooling_set_point[0:self.time_step + 1]
@property
def indoor_dry_bulb_temperature_heating_set_point(self) -> np.ndarray:
"""Dry bulb temperature heating set point time series, in [C]."""
return self.energy_simulation.indoor_dry_bulb_temperature_heating_set_point[0:self.time_step + 1]
@property
def comfort_band(self) -> np.ndarray:
"""Occupant comfort band above the `indoor_dry_bulb_temperature_cooling_set_point` and below the `indoor_dry_bulb_temperature_heating_set_point`, in [C]."""
return self.energy_simulation.comfort_band[0:self.time_step + 1]
@property
def occupant_count(self) -> np.ndarray:
"""Building occupant count time series, in [people]."""
return self.energy_simulation.occupant_count[0:self.time_step + 1]
@property
def cooling_demand(self) -> np.ndarray:
"""Space cooling demand to be met by `cooling_device` and/or `cooling_storage` time series, in [kWh]."""
return self.energy_simulation.cooling_demand[0:self.time_step + 1]
@property
def heating_demand(self) -> np.ndarray:
"""Space heating demand to be met by `heating_device` and/or `heating_storage` time series, in [kWh]."""
return self.energy_simulation.heating_demand[0:self.time_step + 1]
@property
def dhw_demand(self) -> np.ndarray:
"""Domestic hot water demand to be met by `dhw_device` and/or `dhw_storage` time series, in [kWh]."""
return self.energy_simulation.dhw_demand[0:self.time_step + 1]
@property
def non_shiftable_load(self) -> np.ndarray:
"""Electricity load that must be met by the grid, or `PV` and/or `electrical_storage` if available time series, in [kWh]."""
return self.energy_simulation.non_shiftable_load[0:self.time_step + 1]
@property
def cooling_device_cop(self) -> np.ndarray:
"""Heat pump `cooling_device` coefficient of performance time series."""
return self.cooling_device.get_cop(self.weather.outdoor_dry_bulb_temperature, heating=False)[
0:self.time_step + 1]
@property
def heating_device_cop(self) -> np.ndarray:
"""Heat pump `heating_device` coefficient of performance or electric heater `heating_device` static technical efficiency time series."""
return self.heating_device.get_cop(self.weather.outdoor_dry_bulb_temperature, heating=True)[
0:self.time_step + 1] \
if isinstance(self.heating_device, HeatPump) else np.zeros(self.time_step + 1, dtype='float32')
@property
def dhw_device_cop(self) -> np.ndarray:
"""Heat pump `dhw_device` coefficient of performance or electric heater `dhw_device` static technical efficiency time series."""
return self.dhw_device.get_cop(self.weather.outdoor_dry_bulb_temperature, heating=True)[0:self.time_step + 1] \
if isinstance(self.dhw_device, HeatPump) else np.zeros(self.time_step + 1, dtype='float32')
@property
def solar_generation(self) -> np.ndarray:
"""`PV` solar generation (negative value) time series, in [kWh]."""
return self.__solar_generation[:self.time_step + 1]
@property
def power_outage_signal(self) -> np.ndarray:
"""Power outage signal time series, in [Yes/No]."""
return self.__power_outage_signal[:self.time_step + 1]
@property
def downward_electrical_flexibility(self) -> float:
"""Available distributed energy resource capacity to satisfy electric loads while considering power outage at current time step.
It is the sum of solar generation and any discharge from electrical storage, less electricity consumption by cooling, heating,
dhw and non-shfitable load devices as well as charging electrical storage. When there is no power outage, the returned value
is `np.inf`.
"""
capacity = abs(self.solar_generation[self.time_step]) - (
self.cooling_device.electricity_consumption[self.time_step]
+ self.heating_device.electricity_consumption[self.time_step]
+ self.dhw_device.electricity_consumption[self.time_step]
+ self.non_shiftable_load_device.electricity_consumption[self.time_step]
+ self.electrical_storage.electricity_consumption[self.time_step]
)
capacity = capacity if self.power_outage else np.inf
message = 'downward_electrical_flexibility must be >= 0.0!' \
f'time step:, {self.time_step}, outage:, {self.power_outage}, capacity:, {capacity},' \
f' solar:, {abs(self.solar_generation[self.time_step])},' \
f' cooling:, {self.cooling_device.electricity_consumption[self.time_step]},' \
f' heating:, {self.heating_device.electricity_consumption[self.time_step]},' \
f'dhw:, {self.dhw_device.electricity_consumption[self.time_step]},' \
f'non-shiftable:, {self.non_shiftable_load_device.electricity_consumption[self.time_step]},' \
f' battery:, {self.electrical_storage.electricity_consumption[self.time_step]}'
assert capacity >= 0.0 or abs(capacity) < TOLERANCE, message
capacity = max(0.0, capacity)
return capacity
@property
def power_outage(self) -> bool:
"""Whether there is power outage at current time step."""
return self.simulate_power_outage and bool(self.__power_outage_signal[self.time_step])
@property
def stochastic_power_outage_model(self) -> PowerOutage:
"""Power outage model class used to generate stochastic power outage signals."""
return self.__stochastic_power_outage_model
@energy_simulation.setter
def energy_simulation(self, energy_simulation: EnergySimulation):
self.__energy_simulation = energy_simulation
@weather.setter
def weather(self, weather: Weather):
self.__weather = weather
@observation_metadata.setter
def observation_metadata(self, observation_metadata: Mapping[str, bool]):
self.__observation_metadata = observation_metadata
@action_metadata.setter
def action_metadata(self, action_metadata: Mapping[str, bool]):
self.__action_metadata = action_metadata
@carbon_intensity.setter
def carbon_intensity(self, carbon_intensity: CarbonIntensity):
if carbon_intensity is None:
self.__carbon_intensity = CarbonIntensity(
np.zeros(self.episode_tracker.simulation_time_steps, dtype='float32'))
else:
self.__carbon_intensity = carbon_intensity
@pricing.setter
def pricing(self, pricing: Pricing):
if pricing is None:
self.__pricing = Pricing(
np.zeros(self.episode_tracker.simulation_time_steps, dtype='float32'),
np.zeros(self.episode_tracker.simulation_time_steps, dtype='float32'),
np.zeros(self.episode_tracker.simulation_time_steps, dtype='float32'),
np.zeros(self.episode_tracker.simulation_time_steps, dtype='float32'),
)
else:
self.__pricing = pricing
@dhw_storage.setter
def dhw_storage(self, dhw_storage: StorageTank):
self.__dhw_storage = StorageTank(0.0) if dhw_storage is None else dhw_storage
@cooling_storage.setter
def cooling_storage(self, cooling_storage: StorageTank):
self.__cooling_storage = StorageTank(0.0) if cooling_storage is None else cooling_storage
@heating_storage.setter
def heating_storage(self, heating_storage: StorageTank):
self.__heating_storage = StorageTank(0.0) if heating_storage is None else heating_storage
@electrical_storage.setter
def electrical_storage(self, electrical_storage: Battery):
self.__electrical_storage = Battery(0.0, 0.0) if electrical_storage is None else electrical_storage
@dhw_device.setter
def dhw_device(self, dhw_device: Union[HeatPump, ElectricHeater]):
self.__dhw_device = ElectricHeater(0.0) if dhw_device is None else dhw_device
@cooling_device.setter
def cooling_device(self, cooling_device: HeatPump):
self.__cooling_device = HeatPump(0.0) if cooling_device is None else cooling_device
@heating_device.setter
def heating_device(self, heating_device: Union[HeatPump, ElectricHeater]):
self.__heating_device = HeatPump(0.0) if heating_device is None else heating_device
@pv.setter
def pv(self, pv: PV):
self.__pv = PV(0.0) if pv is None else pv
@electric_vehicle_chargers.setter
def electric_vehicle_chargers(self, electric_vehicle_chargers: List[Charger]):
self.__electric_vehicle_chargers = electric_vehicle_chargers
@observation_space.setter
def observation_space(self, observation_space: spaces.Box):
self.__observation_space = observation_space
self.non_periodic_normalized_observation_space_limits = self.estimate_observation_space_limits(include_all=True,
periodic_normalization=False)
self.periodic_normalized_observation_space_limits = self.estimate_observation_space_limits(include_all=True,
periodic_normalization=True)
@action_space.setter
def action_space(self, action_space: spaces.Box):
self.__action_space = action_space
@name.setter
def name(self, name: str):
self.__name = self.uid if name is None else name
@observation_space_limit_delta.setter
def observation_space_limit_delta(self, observation_space_limit_delta: float):
self.__observation_space_limit_delta = 0.0 if observation_space_limit_delta is None else observation_space_limit_delta
if hasattr(self, 'observation_space') and self.observation_space is not None:
self.observation_space = self.estimate_observation_space(include_all=False, normalize=False)
else:
pass
@maximum_temperature_delta.setter
def maximum_temperature_delta(self, maximum_temperature_delta: float):
self.__maximum_temperature_delta = 20.0 if maximum_temperature_delta is None else maximum_temperature_delta
if hasattr(self, 'observation_space') and self.observation_space is not None:
self.observation_space = self.estimate_observation_space(include_all=False, normalize=False)
else:
pass
@demand_observation_limit_factor.setter
def demand_observation_limit_factor(self, demand_observation_limit_factor: float):
self.__demand_observation_limit_factor = 2.0 if demand_observation_limit_factor is None else demand_observation_limit_factor
if hasattr(self, 'observation_space') and self.observation_space is not None:
self.observation_space = self.estimate_observation_space(include_all=False, normalize=False)
else:
pass
@stochastic_power_outage_model.setter
def stochastic_power_outage_model(self, stochastic_power_outage_model: PowerOutage):
self.__stochastic_power_outage_model = PowerOutage() if stochastic_power_outage_model is None else stochastic_power_outage_model
@simulate_power_outage.setter
def simulate_power_outage(self, simulate_power_outage: bool):
self.__simulate_power_outage = False if simulate_power_outage is None else simulate_power_outage
@stochastic_power_outage.setter
def stochastic_power_outage(self, stochastic_power_outage: bool):
self.__stochastic_power_outage = False if stochastic_power_outage is None else stochastic_power_outage
@Environment.random_seed.setter
def random_seed(self, seed: int):
Environment.random_seed.fset(self, seed)
self.cooling_device.random_seed = self.random_seed
self.heating_device.random_seed = self.random_seed
self.dhw_device.random_seed = self.random_seed
self.cooling_storage.random_seed = self.random_seed
self.heating_storage.random_seed = self.random_seed
self.electrical_storage.random_seed = self.random_seed
self.pv.random_seed = self.random_seed
@Environment.episode_tracker.setter
def episode_tracker(self, episode_tracker: EpisodeTracker):
Environment.episode_tracker.fset(self, episode_tracker)
self.cooling_device.episode_tracker = self.episode_tracker
self.heating_device.episode_tracker = self.episode_tracker
self.dhw_device.episode_tracker = self.episode_tracker
self.cooling_storage.episode_tracker = self.episode_tracker
self.heating_storage.episode_tracker = self.episode_tracker
self.dhw_storage.episode_tracker = self.episode_tracker
self.electrical_storage.episode_tracker = self.episode_tracker
self.non_shiftable_load_device.episode_tracker = self.episode_tracker
self.pv.episode_tracker = self.episode_tracker
def get_metadata(self) -> Mapping[str, Any]:
n_years = max(1, (self.episode_tracker.episode_time_steps * self.seconds_per_time_step) / (8760 * 3600))
return {
**super().get_metadata(),
'name': self.name,
'observation_metadata': self.observation_metadata,
'action_metadata': self.action_metadata,
'maximum_temperature_delta': self.maximum_temperature_delta,
'cooling_device': self.cooling_device.get_metadata(),
'heating_device': self.heating_device.get_metadata(),
'dhw_device': self.dhw_device.get_metadata(),
'non_shiftable_load_device': self.non_shiftable_load_device.get_metadata(),
'cooling_storage': self.cooling_storage.get_metadata(),
'heating_storage': self.heating_storage.get_metadata(),
'dhw_storage': self.dhw_storage.get_metadata(),
'electrical_storage': self.electrical_storage.get_metadata(),
'pv': self.pv.get_metadata(),
'annual_cooling_demand_estimate': self.energy_simulation.cooling_demand.sum() / n_years,
'annual_heating_demand_estimate': self.energy_simulation.heating_demand.sum() / n_years,
'annual_dhw_demand_estimate': self.energy_simulation.dhw_demand.sum() / n_years,
'annual_non_shiftable_load_estimate': self.energy_simulation.non_shiftable_load.sum() / n_years,
'annual_solar_generation_estimate': self.pv.get_generation(
self.energy_simulation.solar_generation).sum() / n_years,
}
def observations(self, include_all: bool = None, normalize: bool = None, periodic_normalization: bool = None,
check_limits: bool = None) -> Mapping[str, float]:
r"""Observations at current time step.
Parameters
----------
include_all: bool, default: False,
Whether to estimate for all observations as listed in `observation_metadata` or only those that are active.
normalize : bool, default: False
Whether to apply min-max normalization bounded between [0, 1].
periodic_normalization: bool, default: False
Whether to apply sine-cosine normalization to cyclic observations including hour, day_type and month.
check_limits: bool, default: False
Whether to check if observations are within observation space and if not, will send output to log describing
out of bounds observations. Useful for agents that will fail if observations fall outside space e.g. RLlib agents.
Returns
-------
observation_space : spaces.Box
Observation low and high limits.
Notes
-----
Lower and upper bounds of net electricity consumption are rough estimates and may not be completely accurate hence,
scaling this observation-variable using these bounds may result in normalized values above 1 or below 0.
"""
normalize = False if normalize is None else normalize
periodic_normalization = False if periodic_normalization is None else periodic_normalization
include_all = False if include_all is None else include_all
check_limits = False if check_limits is None else check_limits
observations = {}
data = self._get_observations_data()
if include_all:
valid_observations = list(data.keys())
else:
valid_observations = self.active_observations
observations = {k: data[k] for k in valid_observations if k in data.keys()}
# Observations for electric_vehicle_chargers
# Connected is 1 and disconnected is 0
if self.electric_vehicle_chargers is not None:
for charger in self.electric_vehicle_chargers: # If present, itrerate to each charger
charger_id = charger.charger_id
charger_key_state = f'charger_{charger_id}_connected_state' # Observations names are composed from the charger unique ID
charger_key_incoming_state = f'charger_{charger_id}_incoming_state'
if charger.connected_electric_vehicle:
observations[
charger_key_state] = 1 # attributes the f'charger_{charger_id}_connected_state' the value of one (connected EV)
obs = charger.connected_electric_vehicle.observations(include_all, normalize, periodic_normalization)
for k, v in obs.items():
observations[
f'charger_{charger_id}_connected_{k}'] = v # for the connected EV several observations are added (according to the observations specified in Electric_Vehicle class
else: # otherwise, when not connected, 0 is given and observations are filled with -1
observations[charger_key_state] = 0
for o in self.observation_metadata:
if f'charger_{charger_id}_connected' in o and o != charger_key_state:
observations[o] = -0.1
# same logic for incoming EV, which states if an EV is routing towards the charger
if charger.incoming_electric_vehicle:
observations[charger_key_incoming_state] = 1
obs = charger.incoming_electric_vehicle.observations(include_all, normalize, periodic_normalization)
for k, v in obs.items():
observations[f'charger_{charger_id}_incoming_{k}'] = v
else:
observations[charger_key_incoming_state] = 0
for o in self.observation_metadata:
if f'charger_{charger_id}_incoming' in o and o != charger_key_incoming_state:
observations[o] = -0.1
unknown_observations = list(set(valid_observations).difference(observations.keys()))
assert len(unknown_observations) == 0, f'Unknown observations: {unknown_observations}'
non_periodic_low_limit, non_periodic_high_limit = self.non_periodic_normalized_observation_space_limits
periodic_low_limit, periodic_high_limit = self.periodic_normalized_observation_space_limits
periodic_observations = self.get_periodic_observation_metadata()
if check_limits:
for k in self.active_observations:
value = observations[k]
lower = non_periodic_low_limit[k]
upper = non_periodic_high_limit[k]
if not lower <= value <= upper:
report = {
'Building': self.name,
'episode': self.episode_tracker.episode,
'time_step': f'{self.time_step + 1}/{self.episode_tracker.episode_time_steps}',
'observation': k,
'value': value,
'lower': lower,
'upper': upper
}
LOGGER.debug(f'Observation outside space limit: {report}')
else:
pass
else:
pass
if periodic_normalization:
observations_copy = {k: v for k, v in observations.items()}
observations = {}
pn = PeriodicNormalization(x_max=0)
for k, v in observations_copy.items():
if k in periodic_observations:
pn.x_max = max(periodic_observations[k])
sin_x, cos_x = v * pn
observations[f'{k}_cos'] = cos_x
observations[f'{k}_sin'] = sin_x
else:
observations[k] = v
else:
pass
if normalize:
nm = Normalize(0.0, 1.0)
for k, v in observations.items():
nm.x_min = periodic_low_limit[k]
nm.x_max = periodic_high_limit[k]
observations[k] = v * nm
else:
pass
return observations
def _get_observations_data(self) -> Mapping[str, Union[float, int]]:
return {
**{
k.lstrip('_'): self.energy_simulation.__getattr__(k.lstrip('_'))[self.time_step]
for k, v in vars(self.energy_simulation).items() if isinstance(v, np.ndarray)
},
**{
k.lstrip('_'): self.weather.__getattr__(k.lstrip('_'))[self.time_step]
for k, v in vars(self.weather).items() if isinstance(v, np.ndarray)
},
**{
k.lstrip('_'): self.pricing.__getattr__(k.lstrip('_'))[self.time_step]
for k, v in vars(self.pricing).items() if isinstance(v, np.ndarray)
},
**{
k.lstrip('_'): self.carbon_intensity.__getattr__(k.lstrip('_'))[self.time_step]
for k, v in vars(self.carbon_intensity).items() if isinstance(v, np.ndarray)
},
'solar_generation':abs(self.solar_generation[self.time_step]),
**{
'cooling_storage_soc':self.cooling_storage.soc[self.time_step],
'heating_storage_soc':self.heating_storage.soc[self.time_step],
'dhw_storage_soc':self.dhw_storage.soc[self.time_step],
'electrical_storage_soc':self.electrical_storage.soc[self.time_step],
},
'cooling_demand': self.__energy_from_cooling_device[self.time_step] + abs(min(self.cooling_storage.energy_balance[self.time_step], 0.0)),
'heating_demand': self.__energy_from_heating_device[self.time_step] + abs(min(self.heating_storage.energy_balance[self.time_step], 0.0)),
'dhw_demand': self.__energy_from_dhw_device[self.time_step] + abs(min(self.dhw_storage.energy_balance[self.time_step], 0.0)),