IMO Test 10 — Exit route allocation¶

Definition¶

Occupants must follow their assigned escape routes and reach the exits allocated to them.

The implementation reuses the existing RiMEA 10 scenario, consisting of a corridor with twelve adjacent rooms and 23 occupants.

Each starting distribution is associated with a predefined journey ending at an assigned exit.

Source: IMO MSC.1/Circ.1533, Annex 3, Test 10.

In [1]:
from datetime import datetime
print(f"Executed on {datetime.now().astimezone()}")
Executed on 2026-12-01 15:30:31.583299+00:00
In [2]:
import sys
from pathlib import Path
from types import SimpleNamespace

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from shapely import wkt

repository = Path.cwd().parents[1]
sys.path.insert(0, str(repository / "standards"))
sys.path.insert(0, str(repository / "standards" / "rimea"))
sys.path.insert(0, str(repository / "tests" / "vv"))
In [3]:
import numpy as np

# House style for the V&V figures (plain matplotlib; applied per figure via rc_context).
from matplotlib.colors import to_rgba
from matplotlib.lines import Line2D
from matplotlib.patches import Patch, PathPatch
from matplotlib.patches import Polygon as MplPolygon
from matplotlib.path import Path as MplPath

VV_BLUE, VV_ORANGE, VV_RED, VV_GREEN = "#0072B2", "#E69F00", "#D55E00", "#009E73"
VV_RC = {
    "figure.facecolor": "white", "axes.facecolor": "white", "figure.dpi": 150,
    "font.family": "DejaVu Sans", "font.size": 10,
    "axes.grid": True, "grid.color": "#e5e5e5", "grid.linewidth": 0.8, "axes.axisbelow": True,
    "axes.edgecolor": "lightgrey", "axes.labelcolor": "dimgrey",
    "axes.titlecolor": "#333333", "axes.titleweight": "normal", "axes.titlesize": 11,
    "axes.spines.left": False, "axes.spines.bottom": False,
    "axes.spines.top": False, "axes.spines.right": False,
    "xtick.color": "dimgrey", "ytick.color": "dimgrey",
    "xtick.major.size": 0, "ytick.major.size": 0,
    "legend.frameon": True, "legend.facecolor": "white", "legend.framealpha": 0.8,
    "legend.edgecolor": "lightgrey", "legend.labelcolor": "dimgrey", "legend.fontsize": 9,
}


def vv_polygon_patch(geom, **kwargs):
    """Matplotlib patch for a shapely (Multi)Polygon, holes included."""
    verts, codes = [], []
    for part in getattr(geom, "geoms", [geom]):
        for ring in [part.exterior, *part.interiors]:
            xy = np.asarray(ring.coords)
            verts.extend(xy)
            codes += [MplPath.MOVETO] + [MplPath.LINETO] * (len(xy) - 2) + [MplPath.CLOSEPOLY]
    return PathPatch(MplPath(verts, codes), **kwargs)


def vv_draw_scenario(ax, scenario, starts=True, pad=0.04):
    """Draw walkable area, exits and start areas of a loaded scenario; return legend handles."""
    ax.add_patch(vv_polygon_patch(scenario.walkable_polygon, facecolor="#eeeeee",
                                  edgecolor="dimgrey", linewidth=1.4, zorder=1))
    handles = [Patch(facecolor="#eeeeee", edgecolor="dimgrey", label="walkable area")]
    if starts:
        for dist in scenario.distributions.values():
            ax.add_patch(MplPolygon(dist["coordinates"], closed=True,
                                    facecolor=to_rgba(VV_BLUE, 0.15), edgecolor=VV_BLUE,
                                    linestyle="--", linewidth=1.2, hatch="..", zorder=2))
        handles.append(Patch(facecolor=to_rgba(VV_BLUE, 0.15), edgecolor=VV_BLUE,
                             linestyle="--", hatch="..", label="start area"))
    for ex in scenario.exits.values():
        ax.add_patch(MplPolygon(ex["coordinates"], closed=True,
                                facecolor=to_rgba(VV_RED, 0.35), edgecolor=VV_RED,
                                linewidth=1.2, hatch="///", zorder=3))
    if scenario.exits:
        handles.append(Patch(facecolor=to_rgba(VV_RED, 0.35), edgecolor=VV_RED,
                             hatch="///", label="exit"))
    minx, miny, maxx, maxy = scenario.walkable_polygon.bounds
    m = pad * max(maxx - minx, maxy - miny)
    ax.set_xlim(minx - m, maxx + m)
    ax.set_ylim(miny - m, maxy + m)
    ax.set_aspect("equal")
    ax.grid(False)
    ax.set_xlabel("x [m]")
    ax.set_ylabel("y [m]")
    return handles


def vv_agent_count(scenario):
    """Total number of agents placed by the scenario's start areas."""
    return sum(int(d.get("parameters", {}).get("number", 0)) for d in scenario.distributions.values())

Scenario¶

In [4]:
import pedpy

from jupedsim_scenarios import load_scenario, run_scenario

from imo.scenario_builders.imo10_route_allocation import (
    SCENARIO_ZIP,
    load_raw,
    distribution_to_exit,
    agent_to_distribution,
    agent_to_actual_exit,
)

raw = load_raw()
scenario = load_scenario(str(SCENARIO_ZIP))

journey_map = distribution_to_exit(raw)

print(scenario.summary())

exit_ids = sorted(scenario.exits)

palette = dict(zip(
    exit_ids,
    [VV_BLUE, VV_ORANGE, VV_GREEN, VV_RED],
))
Scenario: standards/rimea/scenario_files/Rimea-10.zip
  Model:         CollisionFreeSpeedModel
  Seed:          420
  Max time:      300s
  Exits:         2
  Distributions: 12
  Stages:        0
  Zones:         0
  Journeys:      0
  Agents:        ~23
    jps-distributions_0: 2 agents
    jps-distributions_1: 2 agents
    jps-distributions_2: 2 agents
    jps-distributions_3: 2 agents
    jps-distributions_4: 2 agents
    jps-distributions_5: 2 agents
    jps-distributions_6: 2 agents
    jps-distributions_7: 1 agents
    jps-distributions_8: 2 agents
    jps-distributions_9: 2 agents
    jps-distributions_10: 2 agents
    jps-distributions_11: 2 agents
In [5]:
with plt.rc_context(VV_RC):
    fig, ax = plt.subplots(figsize=(10, 6))

    handles = vv_draw_scenario(
        ax, scenario, starts=False
    )[:1]

    for dist_id, dist in scenario.distributions.items():
        target = journey_map.get(dist_id)

        if target is None:
            continue

        ax.add_patch(MplPolygon(
            dist["coordinates"],
            closed=True,
            facecolor=to_rgba(palette[target], 0.25),
            edgecolor=palette[target],
            linestyle="--",
            hatch="..",
            zorder=2,
        ))

    for exit_id, exit_def in scenario.exits.items():
        ax.add_patch(MplPolygon(
            exit_def["coordinates"],
            closed=True,
            facecolor=palette[exit_id],
            edgecolor=palette[exit_id],
            zorder=3,
        ))

        handles.append(Patch(
            facecolor=palette[exit_id],
            label=f"Assigned to {exit_id}",
        ))

    ax.set_title(
        "Starting rooms coloured by assigned exit"
    )

    ax.legend(
        handles=handles,
        loc="upper center",
        bbox_to_anchor=(0.5, -0.15),
        ncol=3,
    )

    plt.tight_layout()
    plt.show()
No description has been provided for this image

Simulation¶

In [6]:
result = run_scenario(scenario, seed=42)

try:
    total_agents = result.total_agents
    agents_remaining = result.agents_remaining

    trajectory = pedpy.TrajectoryData(
        result.trajectory_dataframe()[
            ["id", "frame", "x", "y"]
        ].copy(),
        frame_rate=result.frame_rate,
    )
finally:
    result.cleanup()

Route-assignment measurements¶

Each occupant's initial position identifies the corresponding starting distribution and assigned exit.

The actual exit is identified as the exit polygon closest to the occupant's final recorded position.

This follows the measurement procedure used in pytest.

In [7]:
agent_distribution = agent_to_distribution(
    trajectory, raw["distributions"]
)

expected_exit = {
    agent_id: journey_map[distribution_id]
    for agent_id, distribution_id
    in agent_distribution.items()
}

actual_exit = agent_to_actual_exit(
    trajectory, raw["exits"]
)

assert len(expected_exit) == total_agents
assert set(expected_exit) == set(actual_exit)

rows = [
    {
        "agent_id": agent_id,
        "expected_exit": expected_exit[agent_id],
        "actual_exit": actual_exit[agent_id],
        "matches": (
            expected_exit[agent_id]
            == actual_exit[agent_id]
        ),
    }
    for agent_id in sorted(expected_exit)
]

table = pd.DataFrame(rows)

print(table.to_string(index=False))
 agent_id expected_exit actual_exit  matches
        1   jps-exits_0 jps-exits_0     True
        2   jps-exits_0 jps-exits_0     True
        3   jps-exits_0 jps-exits_0     True
        4   jps-exits_0 jps-exits_0     True
        5   jps-exits_0 jps-exits_0     True
        6   jps-exits_0 jps-exits_0     True
        7   jps-exits_0 jps-exits_0     True
        8   jps-exits_0 jps-exits_0     True
        9   jps-exits_0 jps-exits_0     True
       10   jps-exits_0 jps-exits_0     True
       11   jps-exits_0 jps-exits_0     True
       12   jps-exits_0 jps-exits_0     True
       13   jps-exits_0 jps-exits_0     True
       14   jps-exits_0 jps-exits_0     True
       15   jps-exits_0 jps-exits_0     True
       16   jps-exits_1 jps-exits_1     True
       17   jps-exits_1 jps-exits_1     True
       18   jps-exits_1 jps-exits_1     True
       19   jps-exits_1 jps-exits_1     True
       20   jps-exits_1 jps-exits_1     True
       21   jps-exits_1 jps-exits_1     True
       22   jps-exits_1 jps-exits_1     True
       23   jps-exits_1 jps-exits_1     True

Results¶

In [8]:
with plt.rc_context(VV_RC):
    fig, ax = plt.subplots(figsize=(10, 6))

    vv_draw_scenario(ax, scenario, starts=False)

    for agent_id, sub in trajectory.data.sort_values(
        ["id", "frame"]
    ).groupby("id"):
        assigned = expected_exit[agent_id]

        ax.plot(
            sub.x,
            sub.y,
            color=palette[assigned],
            alpha=0.75,
            linewidth=1.2,
            zorder=4,
        )

    starts = trajectory.data.sort_values(
        ["id", "frame"]
    ).groupby("id").first()

    ax.scatter(
        starts.x,
        starts.y,
        color="black",
        s=12,
        zorder=5,
        label="Initial position",
    )

    handles = [
        Line2D(
            [0], [0],
            color=palette[exit_id],
            label=f"Assigned to {exit_id}",
        )
        for exit_id in exit_ids
    ]

    ax.legend(handles=handles)
    ax.set_title("Trajectories by assigned exit")

    plt.tight_layout()
    plt.show()
No description has been provided for this image
In [9]:
summary = table.groupby("expected_exit")["matches"].agg(
    ["sum", "count"]
)

summary["wrong"] = summary["count"] - summary["sum"]

with plt.rc_context(VV_RC):
    fig, ax = plt.subplots(figsize=(8, 4))

    y = np.arange(len(summary))

    ax.barh(
        y,
        summary["sum"],
        color=VV_GREEN,
        label="Correct exit",
    )

    ax.barh(
        y,
        summary["wrong"],
        left=summary["sum"],
        color=VV_RED,
        label="Incorrect exit",
    )

    ax.set_yticks(y, summary.index)

    ax.set(
        xlabel="Number of occupants",
        ylabel="Assigned exit",
        title="Exit allocation verification",
    )

    ax.legend()

    match_rate = table["matches"].mean()

    ax.text(
        0.98, 0.95,
        f"Match rate: {match_rate:.0%}",
        transform=ax.transAxes,
        ha="right",
        va="top",
        fontweight="bold",
    )

    plt.tight_layout()
    plt.show()
No description has been provided for this image

Acceptance criterion¶

All occupants must evacuate.

Every occupant must be accounted for and reach the exit assigned to their journey. The permitted number of incorrect exit assignments is zero.

In [10]:
mismatches = table[~table["matches"]]

print(f"Total occupants: {total_agents}")
print(f"Remaining occupants: {agents_remaining}")
print(f"Incorrect exit assignments: {len(mismatches)}")

assert agents_remaining == 0
assert len(expected_exit) == total_agents
assert set(expected_exit) == set(actual_exit)
assert mismatches.empty, mismatches

print("Acceptance criterion passed.")
Total occupants: 23
Remaining occupants: 0
Incorrect exit assignments: 0
Acceptance criterion passed.