minergym aims to make it easy to create a gymnasium-compatible environment from
an energyplus building file.
import sys
# minergym must have access to the energyplus python api.
sys.path.append("/usr/local/energyplus-24.1")
import numpy as np
import gymnasium.spaces as spaces
import typing
# Exports EnergyPlusSimulation
import minergym.simulation as simulation
# automatically generates observation_template objects
import minergym.config as config
# points to building files shipped with the library
import minergym.data.building as building
# points to weather files
import minergym.data.weather as weather
# extracts information from epJSON files
from minergym.ontology import Ontology
# wraps a simulation into a gym environment
import minergym.environment as environment
building_file = building.crawlspace
weather_file = weather.honolulu
obs_template = {}
ont = Ontology.from_json(building_file)
config.auto_add_time(ont, obs_template)
config.auto_add_temperature(ont, obs_template)
actuators = config.auto_get_actuators(ont)
print(f"{obs_template=}") # Look at what those are!
print(f"{actuators=}")
def make_energyplus() -> simulation.EnergyPlusSimulation:
# For a simulation to run, we need a building file,
# a weather file, an observation template and the dict
# of actuators we want to control.
return simulation.EnergyPlusSimulation(
building_file,
weather_file,
obs_template,
actuators,
)
def reward_function(obs) -> float:
"""Calculate a reward term from a "raw observation"."""
zone_blacklist = [
"environment",
"attic",
"Breezeway",
"crawlspace",
]
def penalty(min, x, max):
if x < min:
return min - x
elif max < x:
return x - max
else:
return 0.0
def zone_sum(obs, min, max):
s = 0.0
for i, v in obs["temperature"].items():
if i in zone_blacklist:
continue
s += penalty(min, v, max)
return s
reward = 0.0
# Temperature reward
if 7 <= obs["time"]["current_time"] <= 19:
reward -= zone_sum(obs, 20, 23)
else:
reward -= zone_sum(obs, 15, 30)
return reward
def to_list(obs):
"""Extract from a raw observation the values we are interested in"""
pre_obs = (
# temperatures
[v for zone, v in obs["temperature"].items()] +
# temps
[obs["time"]["current_time"]]
)
return pre_obs
def observation_transform(obs):
"""Extract from a raw observation the values we are interested in. Turn
it into an array"""
obs = np.array(to_list(obs))
return obs
observation_mock = to_list(obs_template)
observation_space = spaces.Box(
np.array([0.0] * len(observation_mock)),
np.array([30.0] * len(observation_mock)),
)
action_space = spaces.Box(
np.array([0.0, 0.0]),
np.array([30.0, 30.0]),
)
def action_transform(act):
"""The heating setpoint acts as some kind of "lower temperature bound" on
the environment. The policy will produce, instead of a cooling setpoint,
cooling - heating. This means the raw actions will always be consistent
(heating < cooling).
"""
return {
"heating_sch": act[0],
"cooling_sch": act[0] + act[1],
}
gymenv = environment.EnergyPlusEnvironment[typing.Any, typing.Any](
make_energyplus,
reward_function,
observation_space,
observation_transform,
action_space,
action_transform,
)
# Voila!
obs, info = gymenv.reset()- Upgrade & convert your idf file
- Use
$ENERGYPLUS_PATH/PreProcess/IDFVersionUpdater/Transition-*-to-*to upgrade it up to the version of your energyplus installation’s version, which should be at least24.1. - Run
$ENERGYPLUS_PATH/bin/ExpandObjectson it. - convert it to the
epJSONformat using$ENERGYPLUS_PATH/bin/ConvertInputFormat.
- Use
- Use the
minergym.ontology.Ontology.from_jsonfunction to parse the building file. It gives you an rdf representation of every entity which will be useful for the procedures inconfigto generate an observation template. - Use the
minergym.configmodule to create an observation template (use theauto_add_*functions on an empty dict) and useauto_get_actuatorsto list the actuators you want to control. - Look at the
observation_templatedict all theauto_add_*procedure have filled. At each time step, the simulation will fill replace eachSomethingHolewith the value of the corresponding variable/meter. - With the path to the
building.epJSONfile, the path to theweather.epwfile, the observation template and the dict of actuators, create aminergym.simulation.EnergyPlusSimulationobject,startit to make sure the simulation is launching correctly. - Once the simulation runs, we need a couple more components to wrap it in a
gym environment:
- A well-defined observation space.
- A function to transform an
observation_template-shaped object into a point of the observation space. - A well-defined action space.
- A function to transform a point of the action space into a dict-of-actuator-values-shaped object.
- A reward function computed from an
observation_template-shaped object.
- With those components, you can create a
minergym.environmnet.EnergyPlusEnvironmentobject. - Do a couple of
env.step(env.action_space.sample())iterations to make sure your functions work correctly.
- People usually install EnergyPlus by putting it at an arbitrary location. If
that is the case, python won’t be able to find the
pyenergyplus.apimodule. To fix that, putimport sys;sys.path.append("<path to energyplus>")somewhere at the very beginning of your main script, or add the path to energyplus in yourPYTHONPATHenvironment variable. - The
config.auto_get_actuatorsfunction will give you more actuators than necessary. This won’t hurt the simulation, but you might want youraction_transformfunction to only consider some of them. You will have to run a bunch ofsim.step({"some_actuator": 12.345})experiments until you find which one is the correct cooling setpoint, heating setpoint, et cetera. - When you give the simulation a heating setpoint higher than the cooling
setpoint in the same zones, the simulation will crash. Because
minergymisn’t able to make sense of which actuator means what, you will have to ensure this constraint is not violated yourself. - Because each new simulation has to go through a couple of warmup phases,
calling
.reset()(resp.start()) on aEnergyPlusEnvironment(resp.EnergyPlusSimulation) will take a couple of seconds. When doing reinforcement learning, it might be a good idea to ge longer episodes. TheEnergyPlusSimulationconstructor has amax_stepfield to control this. - For a
MeterHoleto work, the corresponding meter usually has to be added (if it is not already there) to theepJSONbuilding file. For instance, to use theElectricity:HVACmeter in an environment we had to add it to the list of meters incrawlspace.epJSON. Here is what you would add to the toplevel json object:"Output:Meter": { "Electricity:HVAC": { "key_name": "*", "reporting_frequency": "Timestep" } }