IMO Test 8 — Counterflow¶
Definition¶
Counterflow through a corridor is expected to increase evacuation time compared with one-way movement.
The implementation compares two rooms connected by a narrow corridor. The one-way scenario contains 20 occupants, while the counterflow scenario contains 20 occupants travelling in each direction.
The population size therefore also differs between the two configurations.
Source: IMO MSC.1/Circ.1533, Annex 3, Test 8.
In [1]:
from datetime import datetime
print(f"Executed on {datetime.now().astimezone()}")
Executed on 2026-12-01 15:30:21.722586+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]:
from vv_helpers import run_vv_scenario
from imo.scenario_builders.imo08_counterflow import (
build_scenario,
)
cases = {
"One-way": build_scenario(False),
"Counterflow": build_scenario(True),
}
In [5]:
with plt.rc_context(VV_RC):
fig, axes = plt.subplots(2, 1, figsize=(10, 7))
for ax, (name, config) in zip(axes, cases.items()):
scenario = SimpleNamespace(
walkable_polygon=wkt.loads(
config["walkable_area_wkt"]
),
distributions=config["distributions"],
exits=config["exits"],
)
handles = vv_draw_scenario(ax, scenario)
ax.annotate(
"", xy=(19, 5.3), xytext=(11, 5.3),
arrowprops={
"arrowstyle": "->",
"color": VV_BLUE,
"lw": 2.5,
},
)
if name == "Counterflow":
ax.annotate(
"", xy=(11, 4.7), xytext=(19, 4.7),
arrowprops={
"arrowstyle": "->",
"color": VV_ORANGE,
"lw": 2.5,
},
)
ax.set_title(
f"{name}: {vv_agent_count(scenario)} occupants"
)
axes[-1].legend(
handles=handles,
loc="upper center",
bbox_to_anchor=(0.5, -0.25),
ncol=3,
)
plt.tight_layout()
plt.show()
Simulation¶
In [6]:
metrics = {}
trajectories = {}
for name, config in cases.items():
metrics[name], trajectories[name] = (
run_vv_scenario(**config)
)
print(name)
print(metrics[name])
One-way
{'success': True, 'status': 'completed', 'message': 'All agents evacuated before reaching the maximum simulation time.', 'evacuation_time': 27.47, 'total_agents': 20, 'agents_evacuated': 20, 'agents_remaining': 0, 'all_evacuated': True, 'frame_rate': 10.0, 'dt': 0.01, 'seed': 42, 'walkable_polygon': <POLYGON ((0 0, 10 0, 10 4, 20 4, 20 0, 30 0, 30 10, 20 10, 20 6, 10 6, 10 1...>}
Counterflow
{'success': True, 'status': 'completed', 'message': 'All agents evacuated before reaching the maximum simulation time.', 'evacuation_time': 40.26, 'total_agents': 40, 'agents_evacuated': 40, 'agents_remaining': 0, 'all_evacuated': True, 'frame_rate': 10.0, 'dt': 0.01, 'seed': 42, 'walkable_polygon': <POLYGON ((0 0, 10 0, 10 4, 20 4, 20 0, 30 0, 30 10, 20 10, 20 6, 10 6, 10 1...>}
Results¶
In [7]:
with plt.rc_context(VV_RC):
fig, axes = plt.subplots(2, 1, figsize=(10, 7))
for ax, (name, config) in zip(axes, cases.items()):
scenario = SimpleNamespace(
walkable_polygon=wkt.loads(
config["walkable_area_wkt"]
),
distributions=config["distributions"],
exits=config["exits"],
)
vv_draw_scenario(ax, scenario)
df = trajectories[name].data
for _, sub in df.sort_values(
["id", "frame"]
).groupby("id"):
color = (
VV_BLUE if sub.iloc[0]["x"] < 15
else VV_ORANGE
)
ax.plot(
sub.x, sub.y,
color=color, alpha=0.5,
linewidth=0.8, zorder=4,
)
ax.set_title(name)
plt.tight_layout()
plt.show()
In [8]:
names = list(metrics)
times = [
metrics[name]["evacuation_time"]
for name in names
]
with plt.rc_context(VV_RC):
fig, ax = plt.subplots(figsize=(7, 4))
bars = ax.bar(
names, times,
color=[VV_BLUE, VV_ORANGE],
width=0.55,
)
ax.bar_label(
bars,
labels=[f"{t:.2f} s" for t in times],
padding=4,
)
ax.set(
ylabel="Evacuation time [s]",
title="One-way versus counterflow evacuation",
ylim=(0, max(times) * 1.2),
)
plt.tight_layout()
plt.show()
Acceptance criterion¶
All occupants must evacuate in both scenarios.
The counterflow evacuation time must be strictly greater than the one-way evacuation time.
In [9]:
one_way = metrics["One-way"]
counterflow = metrics["Counterflow"]
assert one_way["agents_remaining"] == 0
assert counterflow["agents_remaining"] == 0
assert (
counterflow["evacuation_time"]
> one_way["evacuation_time"]
), metrics
print("Acceptance criterion passed.")
Acceptance criterion passed.