{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"hide-input"
]
},
"outputs": [],
"source": [
"import pathlib\n",
"\n",
"import jupedsim as jps\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import pedpy\n",
"from shapely import Polygon\n",
"\n",
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Lane formation in bi-directional flow\n",
"\n",
"This notebook can be directly downloaded {download}`here <./lane-formation.ipynb>` to run it locally.\n",
"\n",
"Lane formation is a quantitative phenomenon, that is observed in bidirectional pedestrian flows. It involves pedestrians automatically forming a number of lanes with varying widths, where individuals within each lane move in the same direction. This self-organizing behavior of pedestrians can have a significant impact on overall evacuation time.\n",
"\n",
"In this example, we will replicate a simple experiment performed by [Feliciani et al 2016](https://doi.org/10.1103/PhysRevE.94.032304).\n",
"In their experiment, Feliciani et al observed bidirectional pedestrian flow in a corridor with two comparative lanes in each flow direction. Thereby, they changed the ratio of both groups of pedestrians Flow ratio is changed by changing each group size while maintaining comparable total flow and density.\n",
"\n",
"![](demo-data/lane_formation/lane_formation.png)\n",
"\n",
"The following is the implementation of the experiment setup in JuPedSim:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"length = 38\n",
"width = 3\n",
"area = [[0, 0], [length, 0], [length, width], [0, width]]\n",
"exit_polygon_left = [(0, 0), (1, 0), (1, width), (0, width)]\n",
"exit_polygon_right = [\n",
" (length - 1, 0),\n",
" (length, 0),\n",
" (length, width),\n",
" (length - 1, width),\n",
"]\n",
"distribution_polygon_left = Polygon([[0, 0], [12, 0], [12, width], [0, width]])\n",
"distribution_polygon_right = Polygon(\n",
" [[length - 12, 0], [length, 0], [length, width], [26, width]]\n",
")\n",
"measurement_area = pedpy.MeasurementArea([[14, 0], [24, 0], [24, 3], [14, 3]])\n",
"measurement_line_left = pedpy.MeasurementLine([[14, 0], [14, width]])\n",
"measurement_line_right = pedpy.MeasurementLine([[24, 0], [24, width]])\n",
"walkable_area = pedpy.WalkableArea(area)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax = plt.subplots(nrows=1, ncols=1)\n",
"ax.set_aspect(\"equal\")\n",
"pedpy.plot_measurement_setup(\n",
" walkable_area=walkable_area,\n",
" measurement_areas=[measurement_area],\n",
" measurement_lines=[measurement_line_left, measurement_line_right],\n",
" ml_color=\"red\",\n",
" ml_width=2,\n",
" axes=ax,\n",
")\n",
"for id, polygon in enumerate(\n",
" [distribution_polygon_left, distribution_polygon_right]\n",
"):\n",
" x, y = polygon.exterior.xy\n",
" plt.fill(x, y, alpha=0.1, color=\"gray\")\n",
" centroid = polygon.centroid\n",
" plt.text(\n",
" centroid.x,\n",
" centroid.y,\n",
" f\"Start {id+1}\",\n",
" ha=\"center\",\n",
" va=\"center\",\n",
" fontsize=10,\n",
" )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Definition of the simulation scenarios\n",
"\n",
"Since the main focus of the abovementioned experiment was on investigating the influence of the ratio, we will set up different scenarios to investigate the variation of the density in the measurement area with varying ratios.\n",
"\n",
"In order to compare the formation of lanes and evacuation times, we will replicate the setup used in the experiment. This involves creating a corridor with two lanes in each direction of flow. We will use different simulation scenarios by initializing various combinations of ratios and densities. These scenarios include unidirectional flow, unbalanced bidirectional flows, and a balanced bidirectional flow scenario.\n",
"\n",
"This replication study aims to investigate the impact of lane formation on evacuation time in different scenarios of bidirectional pedestrian flows.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"simulations = {}\n",
"COLUMNS = 9\n",
"number_agents = [\n",
" (6 * COLUMNS, 0 * COLUMNS),\n",
" (5 * COLUMNS, 1 * COLUMNS),\n",
" (4 * COLUMNS, 2 * COLUMNS),\n",
" (3 * COLUMNS, 3 * COLUMNS),\n",
"]\n",
"for number in number_agents:\n",
" trajectory_file = f\"trajectories_number_agents_{number}.sqlite\"\n",
" simulation = jps.Simulation(\n",
" dt=0.05,\n",
" model=jps.CollisionFreeSpeedModel(\n",
" strength_neighbor_repulsion=2.6,\n",
" range_neighbor_repulsion=0.1,\n",
" range_geometry_repulsion=0.05,\n",
" ),\n",
" geometry=walkable_area.polygon,\n",
" trajectory_writer=jps.SqliteTrajectoryWriter(\n",
" output_file=pathlib.Path(trajectory_file),\n",
" ),\n",
" )\n",
" simulations[number] = simulation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Initialisation of the simulation and distribution of agents\n",
"\n",
"The simulation will commence by assigning a specific number of pedestrian agents.\n",
"These agents will be distributed randomly across the corridor using two distinct distribution polygons, deviating from Feliciani's paper where participants were positioned on predetermined grid points.\n",
"\n",
"The simulation will then proceed with initializing the journeys of each agent.\n",
"Left-facing groups will opt to exit through the right door, while right-facing groups will choose to exit through the left door.\n",
"\n",
"For further analysis, it is essential to keep record of the identification numbers of agents belonging to different groups throughout their distribution process.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"right_wing = {}\n",
"left_wing = {}\n",
"for number, simulation in simulations.items():\n",
" exits = [\n",
" simulation.add_exit_stage(exit_polygon_left),\n",
" simulation.add_exit_stage(exit_polygon_right),\n",
" ]\n",
" journeys = [\n",
" simulation.add_journey(jps.JourneyDescription([exit])) for exit in exits\n",
" ]\n",
"\n",
" # first group\n",
" positions = jps.distribute_by_number(\n",
" polygon=distribution_polygon_right,\n",
" number_of_agents=number[1],\n",
" distance_to_agents=0.4,\n",
" distance_to_polygon=0.7,\n",
" seed=45131502,\n",
" )\n",
" group1 = set(\n",
" [\n",
" simulation.add_agent(\n",
" jps.CollisionFreeSpeedModelAgentParameters(\n",
" position=position,\n",
" journey_id=journeys[0],\n",
" stage_id=exits[0],\n",
" )\n",
" )\n",
" for position in positions\n",
" ]\n",
" )\n",
"\n",
" # second group\n",
" positions = jps.distribute_by_number(\n",
" polygon=distribution_polygon_left,\n",
" number_of_agents=number[0],\n",
" distance_to_agents=0.4,\n",
" distance_to_polygon=0.7,\n",
" seed=45131502,\n",
" )\n",
"\n",
" group2 = set(\n",
" [\n",
" simulation.add_agent(\n",
" jps.CollisionFreeSpeedModelAgentParameters(\n",
" position=position,\n",
" journey_id=journeys[1],\n",
" stage_id=exits[1],\n",
" )\n",
" )\n",
" for position in positions\n",
" ]\n",
" )\n",
"\n",
" right_wing[number] = group1\n",
" left_wing[number] = group2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Running simulations\n",
"\n",
"Now we will run series of simulations, for different ratio values (here defined by numbers of agents in both groups).\n",
"\n",
"For each simulation, it runs the simulation until either all agents have finished or a maximum iteration count is reached.\n",
"\n",
"Once a simulation completes, its results are saved to a uniquely named file.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"trajectory_files = {}\n",
"for number, simulation in simulations.items():\n",
" while simulation.agent_count() > 0 and simulation.iteration_count() < 3000:\n",
" simulation.iterate()\n",
"\n",
" trajectory_file = f\"trajectories_number_agents_{number}.sqlite\"\n",
" trajectory_files[number] = trajectory_file"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Visualisation of the simulation results\n",
"\n",
"Here we visualize the movement of the agents in every simulation along with plots of the trajectories.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from jupedsim.internal.notebook_utils import animate, read_sqlite_file\n",
"\n",
"agent_trajectories = {}\n",
"for number in number_agents:\n",
" trajectory_file = trajectory_files[number]\n",
" agent_trajectories[number], walkable_area = read_sqlite_file(\n",
" trajectory_file\n",
" )\n",
" animate(\n",
" agent_trajectories[number],\n",
" walkable_area,\n",
" every_nth_frame=5,\n",
" width=1200,\n",
" height=400,\n",
" title_note=f\"Ratio: {min(number)/sum(number):0.2f}\",\n",
" ).show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, axes = plt.subplots(\n",
" nrows=len(number_agents), ncols=1, height_ratios=[5, 5, 5, 5]\n",
")\n",
"axes = np.atleast_1d(axes)\n",
"colors = [\"red\", \"blue\"]\n",
"for ax, number in zip(axes, number_agents):\n",
" trajectories = agent_trajectories[number].data\n",
" for ig, group in enumerate([left_wing[number], right_wing[number]]):\n",
" traj = pedpy.TrajectoryData(\n",
" trajectories[trajectories[\"id\"].isin(group)],\n",
" frame_rate=agent_trajectories[number].frame_rate,\n",
" )\n",
" pedpy.plot_trajectories(\n",
" traj=traj,\n",
" walkable_area=walkable_area,\n",
" axes=ax,\n",
" traj_color=colors[ig],\n",
" traj_width=0.3,\n",
" traj_start_marker=\".\",\n",
" )\n",
" ax.set_title(f\"Ratio: {min(number)/sum(number):.2f}\")\n",
"plt.tight_layout()\n",
"fig.set_size_inches((10, 12))\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Voronoi-based measurements\n",
"\n",
"Although the same total number of agents is simulated in all scenarios, the density in the middle of the corridor (within the measurement area) can still vary depending on the ratio of the distribution of agents within the simulation.\n",
"\n",
"Therefore, here will will be calculating the density within the measurement are using the Voronoi method.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import warnings\n",
"\n",
"warnings.filterwarnings(\"ignore\")\n",
"\n",
"individual = {}\n",
"density_voronoi = {}\n",
"\n",
"for number in number_agents:\n",
" individual[number] = pedpy.compute_individual_voronoi_polygons(\n",
" traj_data=agent_trajectories[number], walkable_area=walkable_area\n",
" )\n",
" density_voronoi[number], intersecting = pedpy.compute_voronoi_density(\n",
" individual_voronoi_data=individual[number],\n",
" measurement_area=measurement_area,\n",
" )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Density\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"density_voronoi_ = {}\n",
"\n",
"for number in number_agents:\n",
" individual[number] = pedpy.compute_individual_voronoi_polygons(\n",
" traj_data=agent_trajectories[number], walkable_area=walkable_area\n",
" )\n",
" density_voronoi[number], intersecting = pedpy.compute_voronoi_density(\n",
" individual_voronoi_data=individual[number],\n",
" measurement_area=measurement_area,\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig0, ax0 = plt.subplots(nrows=1, ncols=1)\n",
"labels = []\n",
"colors = plt.rcParams[\"axes.prop_cycle\"].by_key()[\"color\"]\n",
"for i, number in enumerate(number_agents):\n",
" pedpy.plot_density(\n",
" density=density_voronoi[number], axes=ax0, color=colors[i]\n",
" )\n",
" labels.append(f\"Ratio: {min(number)/sum(number):.3f}\")\n",
"\n",
"ax0.legend(labels)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Speed\n",
"\n",
"For the speed time series we will differenciate between the two groups."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"hide-input"
]
},
"outputs": [],
"source": [
"speed_r = {}\n",
"speed_l = {}\n",
"mean_speed_r = {}\n",
"mean_speed_l = {}\n",
"for number in number_agents:\n",
" traj = agent_trajectories[number]\n",
" fps = agent_trajectories[number].frame_rate\n",
" df = traj.data\n",
" group1 = left_wing[number]\n",
" group2 = right_wing[number]\n",
" df_r = df[df[\"id\"].isin(group2)]\n",
" df_l = df[df[\"id\"].isin(group1)]\n",
"\n",
" if not df_r.empty:\n",
" df_r = pedpy.TrajectoryData(df_r, fps)\n",
" speed_r[number] = pedpy.compute_individual_speed(\n",
" frame_step=5,\n",
" movement_direction=[-1, 0],\n",
" traj_data=df_r,\n",
" compute_velocity=True,\n",
" speed_calculation=pedpy.SpeedCalculation.BORDER_SINGLE_SIDED,\n",
" )\n",
" mean_speed_r[number] = pedpy.compute_mean_speed_per_frame(\n",
" traj_data=df_r,\n",
" measurement_area=measurement_area,\n",
" individual_speed=speed_r[number],\n",
" )\n",
"\n",
" if not df_l.empty:\n",
" df_l = pedpy.TrajectoryData(df_l, fps)\n",
" speed_l[number] = pedpy.compute_individual_speed(\n",
" frame_step=5,\n",
" movement_direction=[1, 0],\n",
" traj_data=df_l,\n",
" compute_velocity=True,\n",
" speed_calculation=pedpy.SpeedCalculation.BORDER_SINGLE_SIDED,\n",
" )\n",
" mean_speed_l[number] = pedpy.compute_mean_speed_per_frame(\n",
" traj_data=df_l,\n",
" measurement_area=measurement_area,\n",
" individual_speed=speed_l[number],\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"hide-input"
]
},
"outputs": [],
"source": [
"fig0, ((ax1, ax2), (ax3, ax4)) = plt.subplots(\n",
" nrows=2, ncols=2, figsize=(10, 10)\n",
")\n",
"axes = [ax1, ax2, ax3, ax4]\n",
"\n",
"for ax, number in zip(axes, number_agents):\n",
" if number in mean_speed_r:\n",
" pedpy.plot_speed(\n",
" speed=mean_speed_r[number],\n",
" axes=ax,\n",
" title=f\"Mean speed. Ratio: {min(number)/sum(number):.3f}\",\n",
" color=pedpy.PEDPY_BLUE,\n",
" )\n",
"\n",
" if number in mean_speed_l:\n",
" pedpy.plot_speed(\n",
" speed=mean_speed_l[number],\n",
" title=f\"Mean speed. Ratio: {min(number)/sum(number):.3f}\",\n",
" axes=ax,\n",
" color=pedpy.PEDPY_RED,\n",
" )\n",
" ax.legend([\"Left group\", \"Right group\"])\n",
"\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Evacuation time vs Ratios\n",
"\n",
"From the observed increase of the density with increasing ratio, we expect that the evacuation time will increase as well. Again, due to the poor handling of conflicts in narrow space, the agents from both groups tend to clog in the middle of the corridor.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"hide-input"
]
},
"outputs": [],
"source": [
"evac_times = {}\n",
"for i, number in enumerate(number_agents):\n",
" trajectories = agent_trajectories[number].data\n",
" fps = agent_trajectories[number].frame_rate\n",
" evac_time = trajectories[\"frame\"].max() / fps\n",
" ratio = min(number) / sum(number)\n",
" evac_times[ratio] = evac_time\n",
"\n",
"plt.plot(list(evac_times.keys()), list(evac_times.values()), \"o--\", ms=12)\n",
"plt.xlabel(\"Ratio\")\n",
"plt.ylabel(\"Evactime [s]\")\n",
"plt.grid()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Discussion of results\n",
"\n",
"As we might expect, the is highest for balanced ratio, which is an indicator of high number of unsolved conflicts.\n",
"\n",
"This is expected because the used model is known for not handling lane simulations very well dure to poor conflict resolution. See [Xu2021](https://doi.org/10.1016/j.trc.2021.103464), where a simplified collision-free velocity model that anticipates collisions is presented. This updated model diminishes gridlock events and offers a more accurate depiction of pedestrian movements compared to the previous version.\n",
"\n",
"The following result show mainly that a **balanced ratio** lead in the simulation to **higher densities** and more conflicts that remain mainly unsolved. This in turns is reflected in **higher evacuation times**.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Download\n",
"\n",
"This notebook can be directly downloaded {download}`here <./lane-formation.ipynb>` to run it locally."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.5"
}
},
"nbformat": 4,
"nbformat_minor": 4
}