23. Logging unusued variables
Until version v3.3.2 of Sinergym, all variables monitored using the LoggerWrapper had to be present in the observation space. This presents a drawback when we want to monitor certain aspects of the simulation that are not used in the optimization process (in other words, that are not present in the environment’s observation space), it would be impossible.
Including extra variables that are not directly part of the observation space requires certain internal changes that break the minimalist structure of the classes that make up the tool.
This notebook explains the correct way to do it, which is available from Sinergym v3.3.3. It involves the use of ReduceObservationWrapper in combination with LoggerWrapper.
The idea is to define all the variables we want, whether they are part of the final observation space or not, and monitor everything with the LoggerWrapper, to later add a layer that removes the desired variables from the observation space (when they would already be monitored, which is our goal).
[2]:
import gymnasium as gym
import numpy as np
import sinergym
from sinergym.utils.wrappers import (
LoggerWrapper,
NormalizeAction,
NormalizeObservation,
ReduceObservationWrapper)
# Creating environment and applying wrappers for normalization and logging
env = gym.make('Eplus-5zone-hot-continuous-stochastic-v1')
env = NormalizeAction(env)
env = NormalizeObservation(env)
env = LoggerWrapper(env)
print('###########################################################################')
print('Old observation space shape: ',env.observation_space.shape[0])
print('Old observation variables: ',env.get_wrapper_attr('observation_variables'))
print('###########################################################################')
env = ReduceObservationWrapper(env, obs_reduction=['outdoor_temperature','outdoor_humidity','air_temperature'])
print('###########################################################################')
print('Wrapped observation space shape: ',env.observation_space.shape[0])
print('Wrapped observation variables: ',env.get_wrapper_attr('observation_variables'))
print('###########################################################################')
#==============================================================================================#
[ENVIRONMENT] (INFO) : Creating Gymnasium environment... [5zone-hot-continuous-stochastic-v1]
#==============================================================================================#
[MODELING] (INFO) : Experiment working directory created [/workspaces/sinergym/examples/Eplus-env-5zone-hot-continuous-stochastic-v1-res2]
[MODELING] (INFO) : Model Config is correct.
[MODELING] (INFO) : Updated building model with whole Output:Variable available names
[MODELING] (INFO) : Updated building model with whole Output:Meter available names
[MODELING] (INFO) : runperiod established: {'start_day': 1, 'start_month': 1, 'start_year': 1991, 'end_day': 31, 'end_month': 12, 'end_year': 1991, 'start_weekday': 0, 'n_steps_per_hour': 4}
[MODELING] (INFO) : Episode length (seconds): 31536000.0
[MODELING] (INFO) : timestep size (seconds): 900.0
[MODELING] (INFO) : timesteps per episode: 35040
[REWARD] (INFO) : Reward function initialized.
[ENVIRONMENT] (INFO) : Environment 5zone-hot-continuous-stochastic-v1 created successfully.
[WRAPPER NormalizeAction] (INFO) : New normalized action Space: Box(-1.0, 1.0, (2,), float32)
[WRAPPER NormalizeAction] (INFO) : Wrapper initialized
[WRAPPER NormalizeObservation] (INFO) : Wrapper initialized.
[WRAPPER LoggerWrapper] (INFO) : Wrapper initialized.
###########################################################################
Old observation space shape: 17
Old observation variables: ['month', 'day_of_month', 'hour', 'outdoor_temperature', 'outdoor_humidity', 'wind_speed', 'wind_direction', 'diffuse_solar_radiation', 'direct_solar_radiation', 'htg_setpoint', 'clg_setpoint', 'air_temperature', 'air_humidity', 'people_occupant', 'co2_emission', 'HVAC_electricity_demand_rate', 'total_electricity_HVAC']
###########################################################################
[WRAPPER ReduceObservationWrapper] (INFO) : Wrapper initialized.
###########################################################################
Wrapped observation space shape: 14
Wrapped observation variables: ['month', 'day_of_month', 'hour', 'wind_speed', 'wind_direction', 'diffuse_solar_radiation', 'direct_solar_radiation', 'htg_setpoint', 'clg_setpoint', 'air_humidity', 'people_occupant', 'co2_emission', 'HVAC_electricity_demand_rate', 'total_electricity_HVAC']
###########################################################################
The order of the wrappers is important. By applying normalization first, for example, we ensure that this transformation is subsequently monitored. As we apply the Logger before reducing the observation space, we also record these variables before they are removed from the observations. If we left the logger for the end, these variables would not be recorded. This can be verified by reviewing the generated monitor.csv
files.
Let’s review the info dictionary to see these normalized variables that are no longer in obs
:
[4]:
obs, info = env.reset()
print('###########################################################################')
print('Reset observation length: ',len(obs))
print('Removed variables info: ',info['removed_observation'])
print('###########################################################################')
a = env.action_space.sample()
obs, _, _, _, info = env.step(a)
print('###########################################################################')
print('Reset observation length: ',len(obs))
print('Removed variables info: ',info['removed_observation'])
print('###########################################################################')
[WRAPPER LoggerWrapper] (INFO) : End of episode detected, recording summary (progress.csv) if logger is active
/usr/local/lib/python3.10/dist-packages/numpy/core/fromnumeric.py:3504: RuntimeWarning: Mean of empty slice.
return _methods._mean(a, axis=axis, dtype=dtype,
/usr/local/lib/python3.10/dist-packages/numpy/core/_methods.py:129: RuntimeWarning: invalid value encountered in scalar divide
ret = ret.dtype.type(ret / rcount)
#----------------------------------------------------------------------------------------------#
[ENVIRONMENT] (INFO) : Starting a new episode... [5zone-hot-continuous-stochastic-v1] [Episode 2]
#----------------------------------------------------------------------------------------------#
[MODELING] (INFO) : Episode directory created [/workspaces/sinergym/examples/Eplus-env-5zone-hot-continuous-stochastic-v1-res2/Eplus-env-sub_run2]
[MODELING] (INFO) : Weather file USA_AZ_Davis-Monthan.AFB.722745_TMY3.epw used.
[MODELING] (INFO) : Adapting weather to building model. [USA_AZ_Davis-Monthan.AFB.722745_TMY3.epw]
[ENVIRONMENT] (INFO) : Saving episode output path... [/workspaces/sinergym/examples/Eplus-env-5zone-hot-continuous-stochastic-v1-res2/Eplus-env-sub_run2/output]
[SIMULATOR] (INFO) : Running EnergyPlus with args: ['-w', '/workspaces/sinergym/examples/Eplus-env-5zone-hot-continuous-stochastic-v1-res2/Eplus-env-sub_run2/USA_AZ_Davis-Monthan.AFB.722745_TMY3_Random_1.0_0.0_0.001.epw', '-d', '/workspaces/sinergym/examples/Eplus-env-5zone-hot-continuous-stochastic-v1-res2/Eplus-env-sub_run2/output', '/workspaces/sinergym/examples/Eplus-env-5zone-hot-continuous-stochastic-v1-res2/Eplus-env-sub_run2/5ZoneAutoDXVAV.epJSON']
[ENVIRONMENT] (INFO) : Episode 2 started.
[WRAPPER NormalizeObservation] (INFO) : Saving normalization calibration data... [5zone-hot-continuous-stochastic-v1]
[WRAPPER LoggerWrapper] (INFO) : Creating monitor.csv for current episode (episode 2) if logger is active
/usr/local/lib/python3.10/dist-packages/opyplus/weather_data/weather_data.py:493: FutureWarning: the 'line_terminator'' keyword is deprecated, use 'lineterminator' instead.
epw_content = self._headers_to_epw(use_datetimes=use_datetimes) + df.to_csv(
/usr/local/lib/python3.10/dist-packages/gymnasium/core.py:311: UserWarning: WARN: env.name to get variables from other wrappers is deprecated and will be removed in v1.0, to get this variable you can do `env.unwrapped.name` for environment variables or `env.get_wrapper_attr('name')` that will search the reminding wrappers.
logger.warn(
/usr/local/lib/python3.10/dist-packages/gymnasium/spaces/box.py:240: UserWarning: WARN: Casting input x to numpy array.
gym.logger.warn("Casting input x to numpy array.")
###########################################################################
Reset observation length: 14
Removed variables info: {'outdoor_temperature': 0.9948461020148158, 'outdoor_humidity': -0.9935016762419474, 'air_temperature': -0.6942300884545833}
###########################################################################
[SIMULATOR] (INFO) : handlers are ready.
[SIMULATOR] (INFO) : System is ready.
###########################################################################
Reset observation length: 14
Removed variables info: {'outdoor_temperature': -0.09010209798427844, 'outdoor_humidity': 0.7044684403339807, 'air_temperature': 0.8821502704407667}
###########################################################################
Note that even if we remove a variable that is used in the reward function, as this value is used in the core of the environment (before any wrapper), it works perfectly.
[5]:
env.close()
[WRAPPER LoggerWrapper] (INFO) : End of episode, recording summary (progress.csv) if logger is active
[ENVIRONMENT] (INFO) : Environment closed. [5zone-hot-continuous-stochastic-v1]
[WRAPPER NormalizeObservation] (INFO) : Saving normalization calibration data... [5zone-hot-continuous-stochastic-v1]
Progress: |***************************************************************************************************| 99%