Skip to content

API reference

Environment

frads_gym.FradsEnv(render_mode=None, output_dir=None, config_file=None, run_annual=False, cleanup=True, run_period=None, treat_weather_as_actual=False, weather_files_path=None, run_periods=None, number_of_timesteps_per_hour=1, reward_function=None, logging=False, enable_radiance=True, truncate_on='none', staggered_start=False, env_id=0, n_envs=1, normalizer_state_dir=None, weekday_from_ep=False, sync_first_action=False, truncate_month_only=False)

Bases: Env

Gymnasium environment for facade control with EnergyPlus and Radiance (via frads).

EnergyPlus runs in a background thread and hands control to the environment at every zone timestep: step(action) sets the glazing state of each controlled window, lets EnergyPlus and Radiance advance one timestep and returns the observations defined in the configuration.

Observations and actions come from the configuration (see the configuration reference): every active entry with an observation_space becomes a key of the Dict observation space, and every entry with actuate_cfs_state adds one dimension in [low, high] to the Box action space, in config order. facade_state_mapping maps each action value to a glazing state.

Only one environment can run per process (EnergyPlus callbacks reach the simulation through a process-wide context, and the environment changes the working directory to output_dir). Run several environments with a subprocess vector env such as stable-baselines3's SubprocVecEnv.

Create the environment; the configuration and arguments are checked first.

Parameters:

Name Type Description Default
render_mode str | None

None, "raw_obs" (print the raw observation every step) or "raw_time" (print the simulation time every step).

None
output_dir str

Directory for EnergyPlus output, Radiance matrices and environment_log.csv. Required. The process changes its working directory to it.

None
config_file str | dict

Path to a JSON configuration file or the configuration as a dict. Relative paths in a dict resolve against its config_dir key.

None
run_annual bool

Simulate the whole year (January 1 to December 31) regardless of the months and days in run_period.

False
cleanup bool

Remove eplusout, Temp, Octrees and Matrices in output_dir before starting.

True
run_period dict | None

{"begin_year", "begin_month", "begin_day", "end_year", "end_month", "end_day"}, any subset; applied to the first RunPeriod of the model. Missing years default to 2002.

None
treat_weather_as_actual bool

Set the RunPeriod flag "Treat Weather as Actual".

False
weather_files_path list[str]

List of EPW files. Required. Each full reset (a new EnergyPlus run) uses the next file in turn.

None
run_periods list[dict] | None

One run period per weather file, used instead of run_period.

None
number_of_timesteps_per_hour int

EnergyPlus timesteps per hour (a divisor of 60); one step() per timestep.

1
reward_function callable

Callable (obs, action, next_obs, info) -> float. Required. obs and next_obs are the processed observations; info holds the raw values as raw_current_<key> and raw_next_<key>.

None
logging bool

Append every step to environment_log.csv in output_dir.

False
enable_radiance bool

Compute daylight and glare with Radiance. Without it only EnergyPlus runs; entries that need Radiance must then be inactive.

True
truncate_on str

"none", "day" or "month": end an episode (truncated=True) when the simulation date passes into a new day or month. EnergyPlus keeps running and the next reset() continues from there.

'none'
staggered_start bool

Shift the start month of run_periods by env_id and by the number of resets, so parallel environments see different seasons.

False
env_id int

Index of this environment among n_envs parallel ones (for staggering).

0
n_envs int

Number of parallel environments.

1
normalizer_state_dir str | None

Directory with normalizer_state_<city_id>.pkl files to restore the dynamic observation normalisation from an earlier run.

None
weekday_from_ep bool

Take the weekday of the observation from the EnergyPlus run-period calendar instead of from the weather-file date.

False
sync_first_action bool

reset() returns the first observation without letting EnergyPlus advance, so the first action acts on the transition that observation starts.

False
truncate_month_only bool

With truncate_on="month", ignore year changes that are not month changes.

False

Raises:

Type Description
ConfigError

The configuration or an argument is invalid; the message lists every problem.

RuntimeError

The configuration needs features that the installed frads lacks.

reset(seed=None, options=None)

Reset the environment and return the initial observation.

step(action)

Apply an action for one EnergyPlus timestep and return the result.

Parameters:

Name Type Description Default
action ndarray

One value per actuate_cfs_state entry, in config order; each is mapped to a glazing state through facade_state_mapping.

required

Returns:

Name Type Description
observation dict

Processed observation after the timestep.

reward float

Value of reward_function.

terminated bool

Always False; episodes end by truncation.

truncated bool

True at the end of the run period, at a day or month boundary (truncate_on) or after a step timeout.

info dict

Raw values as raw_current_<key> and raw_next_<key> and more.

close()

Clean up resources when environment is no longer needed.

save_normalizer_state(path)

Pickle current observation-normalizer state to path.

Persists the stateful trackers that accumulate obs statistics
  • _ema_trackers — EMA mean/var/count (used by ema_zscore)
  • stat_trackers — Welford for static z-score
  • observation_history — sample list for static min-max
  • observation_history_dynamic — sliding window for dyn-norm
  • _obs_welford_trackers — Welford used inside dyn-normaliser
  • _ema_quantile_trackers — EMQ P5/P95 (used by ema_minmax)

Static-config-only modes (raw, static_minmax with fixed bounds from JSON) don't rely on any of these; loading into them is a no-op.

load_normalizer_state(path)

Load observation-normalizer state from a pickle produced by :meth:save_normalizer_state. Overwrites any existing tracker state.

Raises:

Type Description
FileNotFoundError

if path does not exist.

ValueError

if the state-file schema version is incompatible.

OSError / UnpicklingError

on corrupt files (propagated).

Wrappers

frads_gym.wrappers.ActionRepeatWrapper(env, repeat)

Bases: Wrapper

Repeat the agent's action for repeat consecutive base-env steps.

Parameters:

Name Type Description Default
env Env

Base environment (or an already-wrapped env) exposing the standard Gymnasium step/reset API.

required
repeat int

Number of consecutive base-env steps per decision. repeat=1 is a no-op (one base-env step per decision).

required

frads_gym.wrappers.ActiveHoursWrapper(env, check_solar=True, check_occupancy=False, mode='or', solar_keys=None, occupancy_key='occupant_count_1', inactive_action=None)

Bases: Wrapper

Skip inactive timesteps, exposing only active transitions to the agent.

Parameters:

Name Type Description Default
env Env

Base FradsEnv (or wrapped FradsEnv).

required
check_solar bool

If True, require GHI > 0 for a timestep to be active.

True
check_occupancy bool

If True, require occupant_count > 0 to be active.

False
mode str

"or" — active if either condition is met (default). "and" — active only if both conditions are met.

'or'
solar_keys Optional[List[str]]

Info-dict keys (without raw_next_ prefix) summed for the GHI check. Default: DNI + DHI.

None
occupancy_key str

Info-dict key (without raw_next_ prefix) for the occupancy check.

'occupant_count_1'
inactive_action Optional[float]

Action applied during fast-forwarded (inactive) timesteps. None (default) keeps the legacy behaviour: hold the agent's last action (zeros before the first agent step). A float is broadcast to the full action shape, e.g. 0.0 = the first state of facade_state_mapping for every window.

None

frads_gym.wrappers.SolarForecastWrapper(env, forecast_horizon=8, add_to_obs=True, ghi_max=1200.0, epw_path=None)

Bases: Wrapper

Add solar irradiance forecast to observations and info.

Parameters:

Name Type Description Default
env Env

Base environment (must have Dict observation space).

required
forecast_horizon int

Number of future timesteps to forecast. Default 8 = 2 hours at 15-min timesteps.

8
add_to_obs bool

If True, add solar_forecast to the observation space (Box, shape=(forecast_horizon,), normalised to [0, 1]).

True
ghi_max float

Normalisation ceiling for GHI [W/m²]. Default 1200.

1200.0
epw_path Optional[str]

Path to EPW file. If None, extracted from the unwrapped environment at reset time.

None

frads_gym.wrappers.TemporalHistoryWrapper(env, max_time_steps=48, flatten_keys=None, padding='zero')

Bases: ObservationWrapper

Stack the last max_time_steps observations into the Dict obs space.

Adds two keys

obs_history: (max_time_steps, flat_obs_dim) float32 temporal_mask: (max_time_steps,) float32, 1=valid 0=pad

Configuration checks

frads_gym.validation

Checks of the configuration and the FradsEnv arguments.

Mistakes fail when the environment is created, with every problem listed at once, instead of surfacing as silent zeros or a hang somewhere in a simulation.

ConfigError

Bases: ValueError

An invalid frads-gym configuration or FradsEnv argument.

validate_config(config)

Raise ConfigError listing every problem of a frads-gym configuration dict.

validate_env_args(*, config_file, output_dir, reward_function, weather_files_path, number_of_timesteps_per_hour, truncate_on, run_period, run_periods, staggered_start, env_id, n_envs)

Raise ConfigError listing every problem of the FradsEnv constructor arguments.