eprllib 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. eprllib/__init__.py +0 -0
  2. eprllib/agents/__init__.py +0 -0
  3. eprllib/agents/conventional.py +143 -0
  4. eprllib/agents/holon_config.py +35 -0
  5. eprllib/agents/user.py +40 -0
  6. eprllib/env/VENT_ep_gym_env.py +178 -0
  7. eprllib/env/VENT_ep_gym_env_test.py +178 -0
  8. eprllib/env/VENT_ep_runner.py +413 -0
  9. eprllib/env/VENT_ep_runner_test.py +386 -0
  10. eprllib/env/__init__.py +1 -0
  11. eprllib/env/marl_ep_gym_env.py +174 -0
  12. eprllib/env/marl_ep_runner.py +373 -0
  13. eprllib/epjson/AirflowNetwork3zVent.epJSON +1816 -0
  14. eprllib/epjson/prot_1(comfort).epJSON +1565 -0
  15. eprllib/epjson/prot_1(natural).epJSON +2028 -0
  16. eprllib/epjson/prot_1.epJSON +1546 -0
  17. eprllib/epjson/prot_2.epJSON +1556 -0
  18. eprllib/epjson/prot_3_ceiling.epJSON +4485 -0
  19. eprllib/epw/GEF/GEF_Lujan_de_cuyo-hour-A1B-2030.epw +8768 -0
  20. eprllib/epw/GEF/GEF_Lujan_de_cuyo-hour-A1B-2050.epw +8768 -0
  21. eprllib/epw/GEF/GEF_Lujan_de_cuyo-hour-A1B-2100.epw +8768 -0
  22. eprllib/epw/GEF/GEF_Lujan_de_cuyo-hour-A2-2030.epw +8768 -0
  23. eprllib/epw/GEF/GEF_Lujan_de_cuyo-hour-A2-2050.epw +8768 -0
  24. eprllib/epw/GEF/GEF_Lujan_de_cuyo-hour-A2-2100.epw +8768 -0
  25. eprllib/epw/GEF/GEF_Lujan_de_cuyo-hour-B1-2030.epw +8768 -0
  26. eprllib/epw/GEF/GEF_Lujan_de_cuyo-hour-B1-2100.epw +8768 -0
  27. eprllib/epw/GEF/GEF_Lujan_de_cuyo-hour-H1.epw +8768 -0
  28. eprllib/epw/GEF/GEF_Lujan_de_cuyo-hour-H2.epw +8768 -0
  29. eprllib/epw/GEF/GEF_Lujan_de_cuyo-hour-H3.epw +8768 -0
  30. eprllib/epw/GEF/GEF_Lujan_de_cuyo-hour-H4.epw +8768 -0
  31. eprllib/epw/GEF/GEF_Lujan_de_cuyo-mon-A1B-2030.txt +75 -0
  32. eprllib/epw/GEF/GEF_Lujan_de_cuyo-mon-A1B-2050.txt +75 -0
  33. eprllib/epw/GEF/GEF_Lujan_de_cuyo-mon-A1B-2100.txt +75 -0
  34. eprllib/epw/GEF/GEF_Lujan_de_cuyo-mon-A2-2030.txt +75 -0
  35. eprllib/epw/GEF/GEF_Lujan_de_cuyo-mon-A2-2050.txt +75 -0
  36. eprllib/epw/GEF/GEF_Lujan_de_cuyo-mon-A2-2100.txt +75 -0
  37. eprllib/epw/GEF/GEF_Lujan_de_cuyo-mon-B1-2030.txt +75 -0
  38. eprllib/epw/GEF/GEF_Lujan_de_cuyo-mon-B1-2100.txt +75 -0
  39. eprllib/epw/GEF/GEF_Lujan_de_cuyo-mon-H1.txt +75 -0
  40. eprllib/epw/GEF/GEF_Lujan_de_cuyo-mon-H2.txt +76 -0
  41. eprllib/epw/GEF/GEF_Lujan_de_cuyo-mon-H3.txt +76 -0
  42. eprllib/epw/GEF/GEF_Lujan_de_cuyo-mon-H4.txt +75 -0
  43. eprllib/postprocess/VENT_init_conventional.py +157 -0
  44. eprllib/postprocess/VENT_init_conventional_test.py +157 -0
  45. eprllib/postprocess/VENT_init_evaluation.py +147 -0
  46. eprllib/postprocess/__init__.py +1 -0
  47. eprllib/postprocess/marl_init_conventional.py +165 -0
  48. eprllib/postprocess/marl_init_evaluation.py +158 -0
  49. eprllib/postprocess/marl_init_noventilation.py +159 -0
  50. eprllib/postprocess/marl_results_evaluation.ipynb +1580 -0
  51. eprllib/postprocess/neural_networ_analysis.ipynb +81 -0
  52. eprllib/postprocess/results_evaluation.ipynb +1588 -0
  53. eprllib/postprocess/results_evaluation_test.ipynb +1593 -0
  54. eprllib/postprocess/test_results_evaluation.ipynb +1617 -0
  55. eprllib/preprocess/__init__.py +1 -0
  56. eprllib/preprocess/conventional_experience.py +141 -0
  57. eprllib/tools/__init__.py +0 -0
  58. eprllib/tools/devices_space_action.py +53 -0
  59. eprllib/tools/ep_episode_config.py +381 -0
  60. eprllib/tools/rewards.py +28 -0
  61. eprllib/tools/weather_utils.py +143 -0
  62. eprllib-0.0.1.dist-info/METADATA +116 -0
  63. eprllib-0.0.1.dist-info/RECORD +64 -0
  64. eprllib-0.0.1.dist-info/WHEEL +4 -0
eprllib/__init__.py ADDED
File without changes
File without changes
@@ -0,0 +1,143 @@
1
+ """Here are contained all the conventional agents that are present in a dwelling. Each of them
2
+ presents actions to do in different devices.
3
+ """
4
+ from typing import Dict, Any
5
+
6
+ class Conventional:
7
+
8
+ def __init__(
9
+ self,
10
+ config: Dict[str,Any] = {'SP_temp': 24, 'dT_up': 2, 'dT_dn':2}
11
+ ):
12
+ """This agent perform conventional actions in an EnergyPlus model based on fixed rules
13
+ that take into account the basics variables as temperature, radiation, humidity and others.
14
+
15
+ Args:
16
+ config (Dict[str,Any]): as minimum, this config dictionary must to have:
17
+ 'SP_temp': float, # set point temperature of comfort
18
+ 'dT_up': float, # upper limit for the comfort range relative with respect to the SP_temp. Must be always a possitive number.
19
+ 'dT_dn': float, # lower limit for the comfort range relative with respect to the SP_temp. Must be always a possitive number.
20
+
21
+ Example:
22
+ ```
23
+ >>> from conventional import Conventional
24
+ >>> agent = Conventional({'SP_temp': 24, 'dT_up': 2, 'dT_dn':2})
25
+ >>> shade_action = agent.window_shade(Ti=32, Bw=450, action_p=1)
26
+ ```
27
+ """
28
+ self.config = config
29
+
30
+ def window_shade(self, Ti: float, Bw:float,action_p:int):
31
+ """Esta función permite la operación binaria (completamente cerrada [On] o completamente
32
+ abierta [Off]) de una persiana a partir de reglas fijas.
33
+
34
+ Args:
35
+ observacion (dict): El diccionario debe contener en su observación al menos los siguientes
36
+ elementos:
37
+ 'Ti' es la temperatura interior
38
+ 'Bw' es la radiación solar directa que existe en el plano de la ventana
39
+ 'action_p' es el estado actual de la persiana
40
+
41
+ Returns:
42
+ int: Regresa la acción a ser aplicada al elemento en EnergyPlus (0 si abre y 1 si cierra).
43
+ Devuelve -1 si hay un error.
44
+ """
45
+ # Se obtiene la configuración
46
+ SP_temp = self.config['SP_temp']
47
+ dT_up = self.config['dT_up']
48
+ dT_dn = self.config['dT_dn']
49
+
50
+ #Control de la persiana
51
+ if Ti >= (SP_temp + dT_up) and Bw == 0:
52
+ action_p = 0 #Abrir la persiana
53
+ elif Ti >= (SP_temp + dT_up) and Bw > 0:
54
+ action_p = 1 #Cerrar la persiana
55
+
56
+ elif Ti <= (SP_temp - dT_dn) and Bw == 0:
57
+ action_p = 1
58
+ elif Ti <= (SP_temp - dT_dn) and Bw > 0:
59
+ action_p = 0
60
+
61
+ elif Ti < (SP_temp + dT_up) and Ti > (SP_temp - dT_dn):
62
+ action_p = action_p
63
+
64
+ else:
65
+ print("Control de la persiana fallido")
66
+ action_p = -1
67
+
68
+ return action_p
69
+
70
+ def air_conditioner(self, Ti:float, action_aa:int):
71
+ """Esta función permite la operación binaria (encendido [On] o apagado [Off]) de un equipo
72
+ de aire acondicionado a partir de reglas fijas.
73
+
74
+ Args:
75
+ observacion (dict): El diccionario debe contener en su observación al menos los siguientes
76
+ elementos:
77
+ 'Ti' es la temperatura interior
78
+ 'action_aa' es el estado actual de operación del aire acondicionado
79
+
80
+ Returns:
81
+ int: Regresa la acción a ser aplicada al elemento en EnergyPlus (0 si apaga y 1 si prende).
82
+ Devuelve -1 si hay un error.
83
+ """
84
+ # Se obtiene la configuración
85
+ SP_temp = self.config['SP_temp']
86
+ dT_up = self.config['dT_up']
87
+ dT_dn = self.config['dT_dn']
88
+
89
+ if Ti >= (SP_temp + dT_up):
90
+ action_aa = 1
91
+
92
+ elif Ti <= (SP_temp - dT_dn):
93
+ action_aa = 0
94
+
95
+ elif Ti < (SP_temp + dT_up) and Ti > (SP_temp - dT_dn):
96
+ action_aa = action_aa
97
+
98
+ else:
99
+ print("Control de Aire Acondicionado Fallido")
100
+ action_aa = -1
101
+
102
+ return action_aa
103
+
104
+ def window_opening(self, Ti: float, To: float, action_v: int):
105
+ """Esta función permite la operación binaria (encendido [On] o apagado [Off]) de
106
+ una ventana a partir de reglas fijas.
107
+
108
+ Args:
109
+ observacion (dict): El diccionario debe contener en su observación al menos los siguientes
110
+ elementos:
111
+ 'Ti' es la temperatura interior
112
+ 'To' es la temperatura exterior
113
+ 'action_v' es el estado actual de la ventana
114
+
115
+ Returns:
116
+ int: Regresa la acción a ser aplicada al elemento en EnergyPlus (0 si cierra y 1 si abre).
117
+ Devuelve -1 si hay un error.
118
+ """
119
+ # Se obtiene la configuración
120
+ SP_temp = self.config['SP_temp']
121
+ dT_up = self.config['dT_up']
122
+ dT_dn = self.config['dT_dn']
123
+
124
+ if Ti >= (SP_temp + dT_up):
125
+ if Ti > To:
126
+ action_v = 1
127
+ else:
128
+ action_v = 0
129
+
130
+ elif Ti <= (SP_temp - dT_dn):
131
+ if Ti > To:
132
+ action_v = 0
133
+ else:
134
+ action_v = 1
135
+
136
+ elif Ti < (SP_temp + dT_up) and Ti > (SP_temp - dT_dn):
137
+ action_v = action_v
138
+
139
+ else:
140
+ print("Control de Ventana Fallido")
141
+ action_v = -1
142
+
143
+ return action_v
@@ -0,0 +1,35 @@
1
+ import gymnasium as gym
2
+
3
+ class Holon:
4
+ def __init__(self, config: dict):
5
+ self.observation_space: gym.Space = config['observation_space']
6
+ self.action_space: gym.Space = config['action_space']
7
+ self._holonparts: dict = config['holonparts']
8
+ self._superholons: dict = config['superholons']
9
+ self._authoritylist: dict = config['authoritylist']
10
+
11
+ def holonparts(self) -> dict:
12
+ return self._holonparts
13
+
14
+ def superholons(self) -> dict:
15
+ return self._superholons
16
+
17
+ def authoritylist(self) -> dict:
18
+ return self._authoritylist
19
+
20
+ def addParts(self, **kargs: dict) -> None:
21
+ for arg in kargs:
22
+ self._holonparts.append(arg)
23
+
24
+ def removeParts(self):
25
+ return
26
+ def requestStructure(self):
27
+ return
28
+ def changeAuthorities(self):
29
+ return
30
+ def requestAuthorities(self):
31
+ return
32
+ def requestStatus(self):
33
+ return
34
+ def close(self):
35
+ return
eprllib/agents/user.py ADDED
@@ -0,0 +1,40 @@
1
+
2
+
3
+ class User:
4
+
5
+ def __init__(
6
+ self,
7
+ config: dict,
8
+ ):
9
+ self.config = config
10
+
11
+ def action(self):
12
+ return
13
+
14
+ def precense_schedule(self):
15
+ """Perform and precense schedule for the user in the house.
16
+ """
17
+ return
18
+
19
+ def temperature_schedule(self, hora:int):
20
+ """Esta función establece las temperaturas del termostato de una vivienda según la hora del
21
+ día.
22
+
23
+ Args:
24
+ obs (dict): El diccionario debe contener en su observación al menos los siguientes
25
+ elementos:
26
+ 'hora' es la hora del día de 0 a 23
27
+
28
+ Returns:
29
+ int: Temperatura de calefacción
30
+ int: Temperatura de refrigeración
31
+ """
32
+ if hora <= 7 or hora >= 23:
33
+ Theat = 17
34
+ Tchill = 28
35
+
36
+ elif hora > 7 and hora < 23:
37
+ Theat = 20
38
+ Tchill = 25
39
+
40
+ return Theat, Tchill
@@ -0,0 +1,178 @@
1
+ """# ENERGYPLUS RLLIB ENVIRONMENT
2
+
3
+ This script define the environment of EnergyPlus implemented in RLlib. To works need to define the
4
+ EnergyPlus Runner.
5
+ """
6
+ import gymnasium as gym
7
+ # Used to define the environment base and the size of action and observation spaces.
8
+ from queue import Empty, Full, Queue
9
+ # Used to separate the execution in two threads and comunicate EnergyPlus with this environment.
10
+ from typing import Any, Dict, Optional
11
+ # To specify the types of variables espected.
12
+ from env.VENT_ep_runner import EnergyPlusRunner
13
+ # The EnergyPlus Runner.
14
+
15
+ class EnergyPlusEnv_v0(gym.Env):
16
+ def __init__(
17
+ self,
18
+ env_config: Dict[str, Any]
19
+ ):
20
+ """Environment of a building that run with EnergyPlus Runner.
21
+
22
+ Args:
23
+ env_config (Dict[str, Any]): _description_
24
+ 'action_space'
25
+ 'observation_space'
26
+ """
27
+ super().__init__()
28
+ # super init of the base class gym.Env.
29
+ self.env_config = env_config
30
+ # asigning the configuration of the environment.
31
+ self.episode = -1
32
+ # variable for the registry of the episode number.
33
+ self.action_space = self.env_config['action_space']
34
+ # asignation of the action space.
35
+ self.observation_space = self.env_config['observation_space']
36
+ # asignation of the observation space.
37
+ self.last_obs = {}
38
+ self.last_infos = {}
39
+ # dict to save the last observation in the environment.
40
+ self.energyplus_runner: Optional[EnergyPlusRunner] = None
41
+ # variable where the EnergyPlus Runner object will be save.
42
+ self.obs_queue: Optional[Queue] = None
43
+ # queue for observation communication between threads.
44
+ self.act_queue: Optional[Queue] = None
45
+ # queue for actions communication between threads.
46
+ self.infos_queue: Optional[Queue] = None
47
+ # queue for cooling metric communication between threads.
48
+
49
+ self.truncate_flag = False
50
+
51
+ def reset(
52
+ self, *,
53
+ seed: Optional[int] = None,
54
+ options: Optional[Dict[str, Any]] = None
55
+ ):
56
+ self.episode += 1
57
+ # Increment the counting of episodes in 1.
58
+ self.timestep = 0
59
+
60
+ if not self.truncate_flag:
61
+ # This flag is implemented in cases when the episode would be truncated.
62
+ if self.energyplus_runner is not None and self.energyplus_runner.simulation_complete:
63
+ # Condition implemented to restart a new epsiode when simulation is completed and EnergyPlus Runner is already inicialized.
64
+ self.energyplus_runner.stop()
65
+
66
+ # If the EnergyPlus Runner is not inicialized is a new simulation run.
67
+ self.obs_queue = Queue(maxsize=1)
68
+ self.act_queue = Queue(maxsize=1)
69
+ self.infos_queue = Queue(maxsize=1)
70
+ # Define the queues for flow control between threads in a max size of 1 because EnergyPlus
71
+ # time step will be processed at a time.
72
+
73
+
74
+ self.energyplus_runner = EnergyPlusRunner(
75
+ # Start EnergyPlusRunner whith the following configuration.
76
+ episode=self.episode,
77
+ env_config=self.env_config,
78
+ obs_queue=self.obs_queue,
79
+ act_queue=self.act_queue,
80
+ infos_queue=self.infos_queue
81
+ )
82
+
83
+ self.energyplus_runner.start()
84
+ # Divide the thread in two in this point.
85
+ self.energyplus_runner.obs_event.wait()
86
+ # Wait untill an observation is made.
87
+ obs = self.obs_queue.get()
88
+ # Get the observation.
89
+ self.energyplus_runner.infos_event.wait()
90
+ # Wait untill an cooling metric read is made.
91
+ infos = self.infos_queue.get()
92
+ # Get the cooling metric read. It is not used here, but yes in the step method and it is necesary
93
+ # to liberate the space in teh queue.
94
+
95
+ self.last_obs = obs
96
+ self.last_infos = infos
97
+ # Save the observation as a last observation.
98
+
99
+ else:
100
+ obs = self.last_obs
101
+ infos = self.last_infos
102
+ self.truncate_flag = False
103
+
104
+ return obs, infos
105
+
106
+ def step(self, action):
107
+ self.timestep += 1
108
+ terminated = False
109
+ truncated = False
110
+ # terminated variable is used to determine the end of a episode. Is stablished as False until the
111
+ # environment present a terminal state.
112
+ timeout = 40
113
+ # timeout is set to 4s to handle end of simulation cases, which happens async
114
+ # and materializes by worker thread waiting on this queue (EnergyPlus callback
115
+ # not consuming yet/anymore).timeout value can be increased if E+ timestep takes longer.
116
+ if self.energyplus_runner.simulation_complete:
117
+ # simulation_complete is likely to happen after last env step()
118
+ # is called, hence leading to waiting on queue for a timeout.
119
+ if self.energyplus_runner.failed():
120
+ # check for simulation errors.
121
+ raise Exception("Faulty episode")
122
+ terminated = True
123
+ # if the simulation is complete, the episode is ended.
124
+ obs = self.last_obs
125
+ infos = self.last_infos
126
+ # we use the last observation as a observation for the timestep.
127
+
128
+ else:
129
+ # if the simulation is not complete, enqueue action (received by EnergyPlus through
130
+ # dedicated callback) and then wait to get next observation.
131
+ try:
132
+ self.act_queue.put(action,timeout=timeout)
133
+ self.energyplus_runner.act_event.set()
134
+ # Send the action to the EnergyPlus Runner flow.
135
+ self.energyplus_runner.obs_event.wait(timeout=timeout)
136
+ obs = self.obs_queue.get(timeout=timeout)
137
+
138
+ self.energyplus_runner.infos_event.wait(timeout=timeout)
139
+ infos = self.infos_queue.get(timeout=timeout)
140
+ # Get the return observation after the action is applied.
141
+ self.last_infos = infos
142
+ # Upgrade last observation.
143
+
144
+ except (Full, Empty):
145
+ terminated = True
146
+ # Set the terminated variable into True to finish the episode.
147
+ obs = self.last_obs
148
+ infos = self.last_infos
149
+ # We use the last observation as a observation for the timestep.
150
+
151
+ if self.energyplus_runner.failed():
152
+ # Raise an exception if the episode is faulty.
153
+ truncated = True
154
+ raise Exception("Faulty episode")
155
+
156
+ # Transform energy variables in Joule to kWh
157
+
158
+ reward = -((22-infos['Ti'])**2)
159
+ # Calculate the reward in the timestep
160
+
161
+ #truncated = self.timestep_cut(6*24*5, terminated)
162
+
163
+ return obs, reward, terminated, truncated, infos
164
+
165
+ def close(self):
166
+ if self.energyplus_runner is not None:
167
+ self.energyplus_runner.stop()
168
+
169
+ def render(self, mode="human"):
170
+ pass
171
+
172
+ def timestep_cut(self, num_timestep: int, terminated: bool):
173
+ if self.timestep >= num_timestep and not terminated:
174
+ self.truncate_flag = True
175
+ return True
176
+ else:
177
+ self.truncate_flag = False
178
+ return False
@@ -0,0 +1,178 @@
1
+ """# ENERGYPLUS RLLIB ENVIRONMENT
2
+
3
+ This script define the environment of EnergyPlus implemented in RLlib. To works need to define the
4
+ EnergyPlus Runner.
5
+ """
6
+ import gymnasium as gym
7
+ # Used to define the environment base and the size of action and observation spaces.
8
+ from queue import Empty, Full, Queue
9
+ # Used to separate the execution in two threads and comunicate EnergyPlus with this environment.
10
+ from typing import Any, Dict, Optional
11
+ # To specify the types of variables espected.
12
+ from env.VENT_ep_runner_test import EnergyPlusRunner
13
+ # The EnergyPlus Runner.
14
+
15
+ class EnergyPlusEnv_v0(gym.Env):
16
+ def __init__(
17
+ self,
18
+ env_config: Dict[str, Any]
19
+ ):
20
+ """Environment of a building that run with EnergyPlus Runner.
21
+
22
+ Args:
23
+ env_config (Dict[str, Any]): _description_
24
+ 'action_space'
25
+ 'observation_space'
26
+ """
27
+ super().__init__()
28
+ # super init of the base class gym.Env.
29
+ self.env_config = env_config
30
+ # asigning the configuration of the environment.
31
+ self.episode = -1
32
+ # variable for the registry of the episode number.
33
+ self.action_space = self.env_config['action_space']
34
+ # asignation of the action space.
35
+ self.observation_space = self.env_config['observation_space']
36
+ # asignation of the observation space.
37
+ self.last_obs = {}
38
+ self.last_infos = {}
39
+ # dict to save the last observation in the environment.
40
+ self.energyplus_runner: Optional[EnergyPlusRunner] = None
41
+ # variable where the EnergyPlus Runner object will be save.
42
+ self.obs_queue: Optional[Queue] = None
43
+ # queue for observation communication between threads.
44
+ self.act_queue: Optional[Queue] = None
45
+ # queue for actions communication between threads.
46
+ self.infos_queue: Optional[Queue] = None
47
+ # queue for cooling metric communication between threads.
48
+
49
+ self.truncate_flag = False
50
+
51
+ def reset(
52
+ self, *,
53
+ seed: Optional[int] = None,
54
+ options: Optional[Dict[str, Any]] = None
55
+ ):
56
+ self.episode += 1
57
+ # Increment the counting of episodes in 1.
58
+ self.timestep = 0
59
+
60
+ if not self.truncate_flag:
61
+ # This flag is implemented in cases when the episode would be truncated.
62
+ if self.energyplus_runner is not None and self.energyplus_runner.simulation_complete:
63
+ # Condition implemented to restart a new epsiode when simulation is completed and EnergyPlus Runner is already inicialized.
64
+ self.energyplus_runner.stop()
65
+
66
+ # If the EnergyPlus Runner is not inicialized is a new simulation run.
67
+ self.obs_queue = Queue(maxsize=1)
68
+ self.act_queue = Queue(maxsize=1)
69
+ self.infos_queue = Queue(maxsize=1)
70
+ # Define the queues for flow control between threads in a max size of 1 because EnergyPlus
71
+ # time step will be processed at a time.
72
+
73
+
74
+ self.energyplus_runner = EnergyPlusRunner(
75
+ # Start EnergyPlusRunner whith the following configuration.
76
+ episode=self.episode,
77
+ env_config=self.env_config,
78
+ obs_queue=self.obs_queue,
79
+ act_queue=self.act_queue,
80
+ infos_queue=self.infos_queue
81
+ )
82
+
83
+ self.energyplus_runner.start()
84
+ # Divide the thread in two in this point.
85
+ self.energyplus_runner.obs_event.wait()
86
+ # Wait untill an observation is made.
87
+ obs = self.obs_queue.get()
88
+ # Get the observation.
89
+ self.energyplus_runner.infos_event.wait()
90
+ # Wait untill an cooling metric read is made.
91
+ infos = self.infos_queue.get()
92
+ # Get the cooling metric read. It is not used here, but yes in the step method and it is necesary
93
+ # to liberate the space in teh queue.
94
+
95
+ self.last_obs = obs
96
+ self.last_infos = infos
97
+ # Save the observation as a last observation.
98
+
99
+ else:
100
+ obs = self.last_obs
101
+ infos = self.last_infos
102
+ self.truncate_flag = False
103
+
104
+ return obs, infos
105
+
106
+ def step(self, action):
107
+ self.timestep += 1
108
+ terminated = False
109
+ truncated = False
110
+ # terminated variable is used to determine the end of a episode. Is stablished as False until the
111
+ # environment present a terminal state.
112
+ timeout = 40
113
+ # timeout is set to 4s to handle end of simulation cases, which happens async
114
+ # and materializes by worker thread waiting on this queue (EnergyPlus callback
115
+ # not consuming yet/anymore).timeout value can be increased if E+ timestep takes longer.
116
+ if self.energyplus_runner.simulation_complete:
117
+ # simulation_complete is likely to happen after last env step()
118
+ # is called, hence leading to waiting on queue for a timeout.
119
+ if self.energyplus_runner.failed():
120
+ # check for simulation errors.
121
+ raise Exception("Faulty episode")
122
+ terminated = True
123
+ # if the simulation is complete, the episode is ended.
124
+ obs = self.last_obs
125
+ infos = self.last_infos
126
+ # we use the last observation as a observation for the timestep.
127
+
128
+ else:
129
+ # if the simulation is not complete, enqueue action (received by EnergyPlus through
130
+ # dedicated callback) and then wait to get next observation.
131
+ try:
132
+ self.act_queue.put(action,timeout=timeout)
133
+ self.energyplus_runner.act_event.set()
134
+ # Send the action to the EnergyPlus Runner flow.
135
+ self.energyplus_runner.obs_event.wait(timeout=timeout)
136
+ obs = self.obs_queue.get(timeout=timeout)
137
+
138
+ self.energyplus_runner.infos_event.wait(timeout=timeout)
139
+ infos = self.infos_queue.get(timeout=timeout)
140
+ # Get the return observation after the action is applied.
141
+ self.last_infos = infos
142
+ # Upgrade last observation.
143
+
144
+ except (Full, Empty):
145
+ terminated = True
146
+ # Set the terminated variable into True to finish the episode.
147
+ obs = self.last_obs
148
+ infos = self.last_infos
149
+ # We use the last observation as a observation for the timestep.
150
+
151
+ if self.energyplus_runner.failed():
152
+ # Raise an exception if the episode is faulty.
153
+ truncated = True
154
+ raise Exception("Faulty episode")
155
+
156
+ # Transform energy variables in Joule to kWh
157
+
158
+ reward = -((22-infos['Ti'])**2)
159
+ # Calculate the reward in the timestep
160
+
161
+ #truncated = self.timestep_cut(6*24*5, terminated)
162
+
163
+ return obs, reward, terminated, truncated, infos
164
+
165
+ def close(self):
166
+ if self.energyplus_runner is not None:
167
+ self.energyplus_runner.stop()
168
+
169
+ def render(self, mode="human"):
170
+ pass
171
+
172
+ def timestep_cut(self, num_timestep: int, terminated: bool):
173
+ if self.timestep >= num_timestep and not terminated:
174
+ self.truncate_flag = True
175
+ return True
176
+ else:
177
+ self.truncate_flag = False
178
+ return False