This is the documentation of CityLearn 3.8.3. Use the version selector or Other versions in the left sidebar to switch to an earlier release or to the development documentation (dev).

Open In Colab

Train a controller with RLlib

This tutorial trains Proximal Policy Optimization (PPO) controllers from Ray RLlib on a CityLearn energy community with the wrappers RLlibSingleAgentWrapper (one central agent) and RLlibMultiAgentEnv (one agent per building), and runs the trained policies through evaluate_v2(). For the Stable Baselines3 workflow, see Train and evaluate a reinforcement learning controller.

Versions and installation. The notebook is tested with Ray 2.60.0 (new API stack, which pins gymnasium 1.2.2) on Python 3.12; Ray 2.60 supports Python 3.10 to 3.14. Ray releases pin their own gymnasium version, so install Ray in a separate environment if you need another gymnasium. Older Ray releases, such as 2.10, use the old API stack and have no wheels for Python 3.12 or newer. The Ray 2.60 wrapper updates (RLlibMultiAgentEnv agents / possible_agents and deterministic agent-ID action ordering) are in CityLearn 3.7.0 and later, which the cell below installs from PyPI. The training is deliberately tiny (two iterations over one day) and only shows the workflow; the policies are not expected to beat the business-as-usual operation.

[ ]:
%pip install "citylearn[rl]>=3.7.0" "ray[rllib]"

Environment configuration

The wrappers take an env_config dictionary with the CityLearnEnv arguments in env_kwargs and an optional list of wrappers. Normalizing and clipping the observations keeps them inside the observation space.

[1]:
import numpy as np
import ray
import torch
from ray.rllib.algorithms.ppo import PPOConfig
from ray.rllib.core.columns import Columns
from ray.rllib.utils.spaces.space_utils import clip_action, unsquash_action

from citylearn.wrappers import (
    ClippedObservationWrapper, NormalizedObservationWrapper, RLlibMultiAgentEnv, RLlibSingleAgentWrapper,
)

ray.init(num_cpus=1, include_dashboard=False, logging_level='ERROR')

env_config = {
    'env_kwargs': {
        'schema': 'citylearn_challenge_2023_phase_2_local_evaluation',
        'simulation_start_time_step': 0,
        'simulation_end_time_step': 23,  # one day of hourly time steps
        'random_seed': 0,
    },
    'wrappers': [NormalizedObservationWrapper, ClippedObservationWrapper],
}
ITERATIONS = 2
2026-11-29 21:01:29,751 INFO util.py:155 -- Missing packages: ['ipywidgets']. Run `pip install -U ipywidgets`, then restart the notebook server for rich notebook output.
2026-11-29 21:01:30,971 INFO util.py:155 -- Missing packages: ['ipywidgets']. Run `pip install -U ipywidgets`, then restart the notebook server for rich notebook output.

Single agent

RLlibSingleAgentWrapper sets central_agent=True, so one policy controls every building. num_env_runners=0 samples in the training process, which keeps the example local.

[2]:
config = (
    PPOConfig()
    .environment(RLlibSingleAgentWrapper, env_config=env_config)
    .env_runners(num_env_runners=0)
    .training(train_batch_size_per_learner=48, minibatch_size=24, num_epochs=1)
)
algo = config.build_algo()

for _ in range(ITERATIONS):
    result = algo.train()

print('environment steps sampled:', result['num_env_steps_sampled_lifetime'])
2026-11-29 21:01:33,307 WARNING algorithm_config.py:5160 -- You are running PPO on the new API stack! This is the new default behavior for this algorithm. If you don't want to use the new API stack, set `config.api_stack(enable_rl_module_and_learner=False,enable_env_runner_and_connector_v2=False)`. For a detailed migration guide, see here: https://docs.ray.io/en/master/rllib/new-api-stack-migration-guide.html
environment steps sampled: 96.0

RLlib’s new API stack removed compute_single_action. Inference goes through the policy’s RLModule: the module returns the parameters of the action distribution, and the deterministic action is the distribution’s mode. Because RLlib trains with normalize_actions=True by default, unsquash_action rescales (and clips) the policy output from [-1, 1] to action_space bounds—for example mapping 0.0 to 0.5 on a [0, 1] cooling_device action—matching RLlib’s NormalizeAndClipActions connector during training.

[3]:
def deterministic_action(module, observation, action_space, *, normalize_actions=True):
    batch = {Columns.OBS: torch.as_tensor(np.asarray(observation, dtype='float32'))[None]}

    with torch.no_grad():
        logits = module.forward_inference(batch)[Columns.ACTION_DIST_INPUTS]

    raw_action = module.get_inference_action_dist_cls().from_logits(logits).to_deterministic().sample()[0].numpy()

    if normalize_actions:
        return unsquash_action(raw_action, action_space)

    return clip_action(raw_action, action_space)


def evaluate(env, actions):
    observations, _ = env.reset()

    while not env.unwrapped.terminated:
        observations, *_ = env.step(actions(observations))

    kpis = env.unwrapped.evaluate_v2()
    kpis = kpis.pivot(index='cost_function', columns='name', values='value').round(3)
    return kpis.dropna(how='all')


single_env = RLlibSingleAgentWrapper(env_config)
module = algo.get_module()
evaluate(
    single_env,
    lambda o: deterministic_action(
        module, o, single_env.action_space, normalize_actions=config.normalize_actions,
    ),
)
[3]:
name Building_1 Building_2 Building_3 District
cost_function
building_battery_health_capacity_fade_business_as_usual_ratio 0.0 0.000 0.000 NaN
building_battery_health_capacity_fade_delta_to_business_as_usual_ratio -0.0 0.000 -0.000 NaN
building_battery_health_capacity_fade_ratio 0.0 0.000 0.000 NaN
building_battery_health_equivalent_full_cycles_business_as_usual_count 0.7 0.197 0.705 NaN
building_battery_health_equivalent_full_cycles_count 0.0 0.457 0.119 NaN
... ... ... ... ...
district_thermal_service_audit_served_service_energy_kwh NaN NaN NaN 236.152
district_thermal_service_audit_thermal_coverage_ratio NaN NaN NaN 1.000
district_thermal_service_audit_unknown_outage_intervals_count NaN NaN NaN 0.000
district_thermal_service_audit_unserved_service_energy_kwh NaN NaN NaN 0.000
district_thermal_service_audit_unserved_service_ratio NaN NaN NaN 0.000

953 rows × 4 columns

Multiple agents

RLlibMultiAgentEnv sets central_agent=False and exposes one agent per building, named agent_0, agent_1, … in possible_agents. The policy mapping below gives every building its own policy.

[4]:
multi_env = RLlibMultiAgentEnv(env_config)
agent_ids = list(multi_env.possible_agents)

multi_config = (
    PPOConfig()
    .environment(RLlibMultiAgentEnv, env_config=env_config)
    .multi_agent(policies=set(agent_ids), policy_mapping_fn=lambda agent_id, *args, **kwargs: agent_id)
    .env_runners(num_env_runners=0)
    .training(train_batch_size_per_learner=48, minibatch_size=24, num_epochs=1)
)
multi_algo = multi_config.build_algo()

for _ in range(ITERATIONS):
    multi_algo.train()

modules = {agent_id: multi_algo.get_module(agent_id) for agent_id in agent_ids}
evaluate(
    multi_env,
    lambda observations: {
        agent_id: deterministic_action(
            modules[agent_id],
            observations[agent_id],
            multi_env.action_space[agent_id],
            normalize_actions=multi_config.normalize_actions,
        )
        for agent_id in agent_ids
    },
)
[4]:
name Building_1 Building_2 Building_3 District
cost_function
building_battery_health_capacity_fade_business_as_usual_ratio 0.0 0.000 0.000 NaN
building_battery_health_capacity_fade_delta_to_business_as_usual_ratio -0.0 0.000 -0.000 NaN
building_battery_health_capacity_fade_ratio 0.0 0.000 0.000 NaN
building_battery_health_equivalent_full_cycles_business_as_usual_count 0.7 0.197 0.705 NaN
building_battery_health_equivalent_full_cycles_count 0.0 0.417 0.213 NaN
... ... ... ... ...
district_thermal_service_audit_served_service_energy_kwh NaN NaN NaN 227.788
district_thermal_service_audit_thermal_coverage_ratio NaN NaN NaN 1.000
district_thermal_service_audit_unknown_outage_intervals_count NaN NaN NaN 0.000
district_thermal_service_audit_unserved_service_energy_kwh NaN NaN NaN 0.000
district_thermal_service_audit_unserved_service_ratio NaN NaN NaN 0.000

955 rows × 4 columns

[5]:
algo.stop()
multi_algo.stop()
ray.shutdown()

Next steps

  • Train for more iterations on a longer window, and evaluate on a window the policies have not seen.

  • Use .env_runners(num_env_runners=N) for parallel sampling, and SACConfig for an off-policy algorithm.

  • Compare the result with the business-as-usual operation, as in the Stable Baselines3 tutorial.