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 and evaluate a reinforcement learning controller

This tutorial trains a Soft Actor-Critic (SAC) controller from Stable Baselines3 on a CityLearn energy community and compares it with the business-as-usual (BAU) operation on a compact scorecard. It covers the four steps of every CityLearn RL study:

  1. choose the dataset, the reward and separate training and evaluation windows;

  2. wrap the environment for the RL library;

  3. train the controller;

  4. evaluate it deterministically on unseen data and compare it with the BAU.

The training below is deliberately short, so that the notebook runs in a few minutes on a laptop CPU; the trained controller is therefore not expected to beat the BAU. Increase the training window and the number of episodes for a real study.

Install CityLearn with the rl extra, which adds PyTorch, and Stable Baselines3 2.4 or newer:

[ ]:
%pip install "citylearn[rl]" "stable-baselines3>=2.4"

1. Dataset, reward and windows

citylearn_challenge_2022_phase_all_plus_evs holds a year of hourly data for 17 buildings with PV, batteries and EV chargers. To keep the example fast, it uses three buildings and a single central agent, which controls all their batteries and chargers.

The reward is the learning signal, while the KPIs judge the finished episode. This dataset configures version 2 of Electric_Vehicles_Reward_Function, the default, which adds the grid-import reward of each building to the EV charging terms and penalises vehicles that leave far below their requested state of charge (see the reward function guide).

The controller trains on the first week and is evaluated on the second week, which it has not seen during training. Both environments simulate the same two weeks and each runs only its own week as its episode, because the observation limits that the normalisation uses come from the simulation window: two environments built on different windows would scale the same value differently.

[1]:
from citylearn.citylearn import CityLearnEnv

DATASET = 'citylearn_challenge_2022_phase_all_plus_evs'
BUILDINGS = ['Building_1', 'Building_4', 'Building_5']
TRAIN_WINDOW = (0, 167)       # first week, hourly time steps
EVALUATION_WINDOW = (168, 335)  # second week
SEED = 0


def make_env(window):
    # Both environments simulate the same two weeks, so the observation limits that
    # NormalizedObservationWrapper uses are the same; each one runs only its own week.
    return CityLearnEnv(
        DATASET,
        buildings=BUILDINGS,
        central_agent=True,
        simulation_start_time_step=TRAIN_WINDOW[0],
        simulation_end_time_step=EVALUATION_WINDOW[1],
        episode_time_steps=[list(window)],
        random_seed=SEED,
    )

2. Wrappers

Stable Baselines3 expects one flat observation vector and one flat action vector. NormalizedObservationWrapper scales the observations to [0, 1] and encodes cyclical features such as the hour with sine and cosine, and StableBaselines3Wrapper turns the central agent’s lists into the arrays the library expects.

[2]:
from citylearn.wrappers import NormalizedObservationWrapper, StableBaselines3Wrapper


def wrap(env):
    return StableBaselines3Wrapper(NormalizedObservationWrapper(env))


train_env = wrap(make_env(TRAIN_WINDOW))
print('observations:', train_env.observation_space.shape, 'actions:', train_env.action_space.shape)
2026-11-29 21:01:21,551 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:22,567 INFO util.py:155 -- Missing packages: ['ipywidgets']. Run `pip install -U ipywidgets`, then restart the notebook server for rich notebook output.
observations: (77,) actions: (7,)

3. Training

Each training episode covers the training window once. Three episodes are enough to check that the setup works; a study would train for hundreds.

[3]:
from stable_baselines3 import SAC

EPISODES = 3
episode_steps = train_env.unwrapped.time_steps - 1  # the last data row is only the terminal observation

model = SAC('MlpPolicy', train_env, learning_starts=episode_steps, seed=SEED, verbose=0)
model = model.learn(total_timesteps=EPISODES*episode_steps)

4. Evaluation and comparison with the BAU

The trained policy runs deterministically on the evaluation week. evaluate_v2() then returns the KPIs of the episode next to those of the native BAU reference, which CityLearn simulates on the same window. The scorecard selects a few district rows; the scorecard guide explains how to read them.

[4]:
eval_env = wrap(make_env(EVALUATION_WINDOW))
observations, _ = eval_env.reset()

while not eval_env.unwrapped.terminated:
    actions, _ = model.predict(observations, deterministic=True)
    observations, _, _, _, _ = eval_env.step(actions)

kpis = eval_env.unwrapped.evaluate_v2()
[5]:
selected = {
    'district_cost_total_control_eur': 'Cost, SAC (EUR)',
    'district_cost_total_business_as_usual_eur': 'Cost, BAU (EUR)',
    'district_energy_grid_total_import_control_kwh': 'Grid import, SAC (kWh)',
    'district_energy_grid_total_import_business_as_usual_kwh': 'Grid import, BAU (kWh)',
    'district_ev_performance_departure_min_acceptable_feasible_ratio': 'EVs leaving with enough charge (ratio)',
}
scorecard = kpis.loc[(kpis['level'] == 'district') & kpis['cost_function'].isin(selected), ['cost_function', 'value']]
scorecard = scorecard.assign(indicator=scorecard['cost_function'].map(selected)).set_index('indicator')['value']
scorecard.round(3)
[5]:
indicator
Cost, BAU (EUR)                           151.952
Cost, SAC (EUR)                            39.271
Grid import, BAU (kWh)                    984.952
Grid import, SAC (kWh)                    166.775
EVs leaving with enough charge (ratio)      0.000
Name: value, dtype: float64

Read the rows together. A controller can lower the cost and the grid import simply by charging the vehicles less, and the EV service row then shows how many vehicles left without the charge they needed. After this short training, that trade-off is typical: the SAC policy has not yet learned to charge the vehicles when energy is cheap, so the comparison with the BAU judges the whole service, not the cost alone.

Next steps

  • Train longer: widen TRAIN_WINDOW, raise EPISODES, and evaluate on several unseen windows.

  • Try another reward, for example reward_function='citylearn.reward_function.RewardFunction', and compare the scorecards of controllers trained with each.

  • Compare with the rule-based baselines of citylearn.agents.baseline on the same evaluation window (baselines guide).

  • Use the CLI to run the same training as a batch job (running simulations).