### Visualize Simulation Setup Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/queues_waiting.ipynb Calls the plotting function to display the defined simulation areas and agent starting points. ```python plot_simulation_configuration( walkable_area, spawning_area, agent_start_positions, exit_area ) ``` -------------------------------- ### Install Python Dependencies and JuPedSim with Setuptools Source: https://github.com/pedestriandynamics/jupedsim/blob/master/README.md Install JuPedSim from source using setuptools. Requires a C++20 capable compiler and CMake >= 3.22. First, install Python dependencies, then install the package. ```bash cd jupedsim pip install -r requirements.txt pip install . ``` -------------------------------- ### Visualize Simulation Setup Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/double-bottleneck.ipynb Calls the plotting function to display the defined simulation areas and agent starting positions. ```python plot_simulation_configuration( walkable_area, spawning_area, pos_in_spawning_area, exit_area ) ``` -------------------------------- ### Visualizing Initial Simulation Setup Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/corner.ipynb Calls the plotting function to display the initial configuration of the simulation environment. ```python plot_simulation_configuration( walkable_area, spawning_area, pos_in_spawning_area, exit_area ) ``` -------------------------------- ### Install JuPedSim with pip Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/index.rst Install the JuPedSim package using pip from PyPi.org. This is the easiest way to get started with the library. ```bash pip install jupedsim ``` -------------------------------- ### Visualize Journey Setup Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/queues_waiting.ipynb Calls the helper function to plot the simulation configuration, showing the defined queues and the distributing waypoint. ```python plot_journey_details( walkable_area, spawning_area, agent_start_positions, exit_area, waiting_positions_gates, [waypoint_coords], [waypoint_dist], ) ``` -------------------------------- ### Plot simulation configuration Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/direct_steering.ipynb Visualizes the simulation setup, including the walkable area, spawning area, starting positions, exit area, and waypoints. This function helps in verifying the initial configuration. ```python def plot_simulation_configuration( walkable_area, spawning_area, starting_positions, exit_area ): axes = pedpy.plot_walkable_area(walkable_area=walkable_area) axes.fill(*exit_area.exterior.xy, color="indianred") axes.scatter(*zip(*starting_positions), s=1) axes.set_xlabel("x/m") axes.set_ylabel("y/m") axes.set_aspect("equal") for idx, waypoint in enumerate(waypoints): axes.plot(waypoint[0], waypoint[1], "ro") axes.annotate( f"WP {idx + 1}", (waypoint[0], waypoint[1]), textcoords="offset points", xytext=(10, -15), ha="center", ) circle = Circle( (waypoint[0], waypoint[1]), distance_to_waypoints, fc="red", ec="red", alpha=0.1, ) axes.add_patch(circle) plot_simulation_configuration( walkable_area, spawning_area, pos_in_spawning_area, exit_area ) ``` -------------------------------- ### Plot Simulation Configuration Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/model-comparison.ipynb Visualizes the simulation setup, including the walkable area, exit areas, and starting positions. Useful for verifying the environment and initial agent placement. ```python def plot_simulation_configuration(geometry, starting_positions, exit_areas): """Plot setup for visual inspection.""" walkable_area = pedpy.WalkableArea(geometry) axes = pedpy.plot_walkable_area(walkable_area=walkable_area) for exit_area in exit_areas: axes.fill(*exit_area.exterior.xy, color="indianred") axes.scatter(*zip(*starting_positions), label="Starting Position") axes.set_xlabel("x/m") axes.set_ylabel("y/m") axes.set_aspect("equal") axes.grid(True, alpha=0.3) ``` -------------------------------- ### WarpDriverModel Initialization and Agent Setup Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/pedestrian_models/warp_driver_model.md Demonstrates how to initialize the WarpDriverModel with global parameters and add agents with their specific settings. It also shows how to access and modify agent-level parameters at runtime. ```APIDOC ## Python API ### Initialization Initialize the `WarpDriverModel` with shared parameters for all agents. ```python import jupedsim as jps model = jps.WarpDriverModel( time_horizon=2.0, step_size=0.5, sigma=0.3, time_uncertainty=0.5, velocity_uncertainty_x=0.2, velocity_uncertainty_y=0.2, ) sim = jps.Simulation(model=model, geometry=area, dt=0.01) ``` ### Adding Agents Add agents to the simulation, specifying their individual parameters. ```python agent_id = sim.add_agent(jps.WarpDriverModelAgentParameters( position=(2.0, 2.0), orientation=(1.0, 0.0), journey_id=journey_id, stage_id=stage_id, desired_speed=1.2, radius=0.15, )) ``` ### Runtime State Access and Modification Access and modify agent model states during simulation runtime. ```python # Access state state = sim.agent(agent_id).model print(state.desired_speed) # Output: 1.2 print(state.radius) # Output: 0.15 # Modify state state.desired_speed = 0.8 state.radius = 0.2 ``` ``` -------------------------------- ### Plot Simulation Setup Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/single-file.ipynb Visualizes the exterior and interior boundaries, waypoints, agent positions, and their initial goals using matplotlib. ```python def plot_points_and_polygons( all_waypoints, choosen_waypoints, exterior, interior, positions ): __file__, ax = plt.subplots(ncols=1, nrows=1) ax.set_aspect("equal") x_exterior, y_exterior = Polygon(exterior).exterior.xy plt.plot(x_exterior, y_exterior, "-k", label="exterior") plt.fill(x_exterior, y_exterior, alpha=0.3) x_interior, y_interior = Polygon(interior).exterior.xy plt.plot(x_interior, y_interior, "--k", label="interior") plt.fill(x_interior, y_interior, alpha=0.3) x_awp, y_awp = Polygon(all_waypoints).exterior.xy plt.plot(x_awp, y_awp, "-r") plt.fill(x_awp, y_awp, alpha=0.3) plt.scatter(*zip(*all_waypoints), marker=".", label="waypoints") x_agents, y_agents = Polygon(positions).exterior.xy plt.plot(x_agents, y_agents, "ob", ms=8, label="agents") x_wp, y_wp = Polygon(choosen_waypoints).exterior.xy plt.plot(x_wp, y_wp, "xk", ms=5, label="first goals") plt.legend() plt.title(f"N={len(positions)}") plt.show() ``` -------------------------------- ### Visualize Simulation Setup Source: https://github.com/pedestriandynamics/jupedsim/blob/master/notebooks/queues_waiting.ipynb Calls the plotting function to display the defined simulation configuration. ```python plot_simulation_configuration( walkable_area, spawning_area, agent_start_positions, exit_area ) ``` -------------------------------- ### Setup Simulation for Narrow Bottleneck Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/double-bottleneck.ipynb Sets up a jupedsim simulation object for the narrow bottleneck scenario, configuring the geometry and trajectory writer. ```python trajectory_file_narrow = "double-botteleneck_narrow.sqlite" # output file simulation_narrow = jps.Simulation( model=jps.CollisionFreeSpeedModel(), geometry=area_narrow, trajectory_writer=jps.SqliteTrajectoryWriter( output_file=pathlib.Path(trajectory_file_narrow) ), ) exit_id = simulation_narrow.add_exit_stage(exit_area.exterior.coords[:-1]) journey = jps.JourneyDescription([exit_id]) journey_id = simulation_narrow.add_journey(journey) ``` -------------------------------- ### Plot Simulation Configuration Helper Function Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/queues_waiting.ipynb A helper function to visualize the simulation setup, including walkable areas, source/exit zones, agent start positions, queues, and distributing waypoints. ```python def plot_journey_details( walkable_area, source_area, agent_start_positions, exit_area, waiting_positions_queues, waypoints, dists, ): axes = plot_simulation_configuration( walkable_area, source_area, agent_start_positions, exit_area ) for queue_positions in waiting_positions_queues: axes.scatter(*zip(*queue_positions), s=1) for coords, dist in zip(waypoints, dists): circle = Circle(coords, dist, color="lightsteelblue") axes.add_patch(circle) axes.scatter(coords[0], coords[1], marker="x", color="black") ``` -------------------------------- ### Plot Simulation Setup Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/lane-formation.ipynb Visualizes the defined simulation environment, including the walkable area, measurement areas, and distribution polygons. ```python fig, ax = plt.subplots(nrows=1, ncols=1) ax.set_aspect("equal") pedpy.plot_measurement_setup( walkable_area=walkable_area, measurement_areas=[measurement_area], measurement_lines=[measurement_line_left, measurement_line_right], ml_color="red", ml_width=2, axes=ax, ) for id, polygon in enumerate( [distribution_polygon_left, distribution_polygon_right] ): x, y = polygon.exterior.xy plt.fill(x, y, alpha=0.1, color="gray") centroid = polygon.centroid plt.text( centroid.x, centroid.y, f"Start {id + 1}", ha="center", va="center", fontsize=10, ) ``` -------------------------------- ### Setup and Execute Simulation for Wide Bottleneck Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/double-bottleneck.ipynb Sets up and executes a jupedsim simulation for the wider bottleneck scenario, including adding agents and running the simulation. ```python trajectory_file_wide = "double-botteleneck_wide.sqlite" # output file simulation_wide = jps.Simulation( model=jps.CollisionFreeSpeedModel(), geometry=area_wide, trajectory_writer=jps.SqliteTrajectoryWriter( output_file=pathlib.Path(trajectory_file_wide) ), ) exit_id = simulation_wide.add_exit_stage(exit_area.exterior.coords[:-1]) journey = jps.JourneyDescription([exit_id]) journey_id = simulation_wide.add_journey(journey) for pos, v0 in zip(pos_in_spawning_area, v_distribution): simulation_wide.add_agent( jps.CollisionFreeSpeedModelAgentParameters( journey_id=journey_id, stage_id=exit_id, position=pos, desired_speed=v0, radius=0.15, ) ) while simulation_wide.agent_count() > 0: simulation_wide.iterate() simulation_wide._writer.close() ``` -------------------------------- ### Plot Simulation Configuration Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/double-bottleneck.ipynb A helper function to visualize the walkable area, spawning area, starting positions, and exit area of the simulation setup. ```python def plot_simulation_configuration( walkable_area, spawning_area, starting_positions, exit_area ): axes = pedpy.plot_walkable_area(walkable_area=walkable_area) axes.fill(*spawning_area.exterior.xy, color="lightgrey") axes.fill(*exit_area.exterior.xy, color="indianred") axes.scatter(*zip(*starting_positions), s=1) axes.set_xlabel("x/m") axes.set_ylabel("y/m") axes.set_aspect("equal") ``` -------------------------------- ### Setup Simulation with Uneven Distribution Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/queues_waiting.ipynb Configures a Jupedsim simulation with a specific trajectory file and adds waypoint and exit stages. This setup is used for scenarios with uneven agent distribution. ```python trajectory_file_uneven = "queues_waiting_uneven.sqlite" # output file simulation_uneven = jps.Simulation( model=jps.CollisionFreeSpeedModel(), geometry=geo, trajectory_writer=jps.SqliteTrajectoryWriter( output_file=pathlib.Path(trajectory_file_uneven) ), ) waypoint_for_distributing = simulation_uneven.add_waypoint_stage( waypoint_coords, waypoint_dist ) exit = simulation_uneven.add_exit_stage(exit_area.exterior.coords[:-1]) waypoints_gates = [ simulation_uneven.add_queue_stage(i) for i in waiting_positions_gates ] queue_gates = [simulation_uneven.get_stage(i) for i in waypoints_gates] journey_uneven = jps.JourneyDescription( [waypoint_for_distributing, exit] + waypoints_gates ) ``` -------------------------------- ### Setup jupedsim Simulation Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/queues_waiting.ipynb Initializes a jupedsim simulation object with a collision-free speed model, geometry, and trajectory writer. The output trajectory is saved to a SQLite file. ```python trajectory_file = "queues_waiting.sqlite" # output file simulation = jps.Simulation( model=jps.CollisionFreeSpeedModel(), geometry=geo, trajectory_writer=jps.SqliteTrajectoryWriter( output_file=pathlib.Path(trajectory_file) ), ) ``` -------------------------------- ### Plot Simulation Setup with Exit Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/getting_started.ipynb Visualize the complete simulation setup, including the walkable area and the defined exit, using PedPy's plot_measurement_setup function. The exit is shown in red. ```python import matplotlib.pyplot as plt from pedpy import MeasurementArea, WalkableArea, plot_measurement_setup # We will use PedPy's plotting functionality, but it has no concept of exits # hence we will show the exit as measurement area plot_measurement_setup( walkable_area=WalkableArea(geometry), measurement_areas=[MeasurementArea(exit_polygon)], ma_color="r", ma_line_color="r", ).set_aspect("equal") plt.show() ``` -------------------------------- ### Print JuPedSim Version Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/citation/citation.rst Run this Python code to display the installed version of JuPedSim. Ensure the jupedsim library is installed. ```python import jupedsim print(jupedsim.__version__) ``` -------------------------------- ### Define Spawning Area and Agent Start Positions Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/queues_waiting.ipynb Calculates agent starting positions within a defined spawning area at the bottom of the geometry. Requires `jps` and `shapely.geometry.Polygon`. ```python num_agents = 20 spawning_polygon = Polygon([(25, 45), (35, 45), (35, 54), (25, 54)]) spawning_area = intersection(spawning_polygon, geo) agent_start_positions = jps.distribute_by_number( polygon=spawning_area, number_of_agents=num_agents, distance_to_agents=0.4, distance_to_polygon=0.2, seed=123, ) exit_area = Polygon([(22, 76), (30, 76), (30, 74), (22, 74)]) ``` -------------------------------- ### Create Queues and Get Stage Handles Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/queues_waiting.ipynb Creates queue stages in the simulation based on defined waiting positions and retrieves handles for later use in controlling agent waiting. ```python waypoints_gates = [simulation.add_queue_stage(i) for i in waiting_positions_gates] queue_gates = [simulation.get_stage(i) for i in waypoints_gates] ``` -------------------------------- ### Plot Measurement Line Setup Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/getting_started.ipynb Visualizes the defined measurement line on the walkable area. Requires matplotlib and pedpy. ```python import pedpy pedpy.plot_measurement_setup( walkable_area=walkable_area, measurement_lines=[measurement_line], ml_color="red", ml_width=2, ).set_aspect("equal") plt.show() ``` -------------------------------- ### Plotting Simulation Configuration Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/corner.ipynb A helper function to visualize the walkable area, spawning area, agent starting positions, and exit area. ```python def plot_simulation_configuration( walkable_area, spawning_area, starting_positions, exit_area ): axes = pedpy.plot_walkable_area(walkable_area=walkable_area) axes.fill(*spawning_area.exterior.xy, color="lightgrey") axes.fill(*exit_area.exterior.xy, color="indianred") axes.scatter(*zip(*starting_positions)) axes.set_xlabel("x/m") axes.set_ylabel("y/m") axes.set_aspect("equal") ``` -------------------------------- ### Plot Simulation Configuration Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/queues_waiting.ipynb A helper function to visualize the walkable area, spawning area, starting positions, and exit area. Requires `pedpy`. ```python def plot_simulation_configuration( walkable_area, spawning_area, starting_positions, exit_area ): axes = pedpy.plot_walkable_area(walkable_area=walkable_area) axes.fill(*spawning_area.exterior.xy, color="lightgrey") axes.fill(*exit_area.exterior.xy, color="indianred") axes.scatter(*zip(*starting_positions), s=1) axes.set_xlabel("x/m") axes.set_ylabel("y/m") axes.set_aspect("equal") return axes ``` -------------------------------- ### Add Agents and Run Simulation Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/double-bottleneck.ipynb Defines agent desired speeds using a normal distribution and adds each agent to the simulation with their respective starting position and speed. The simulation runs until all agents have exited. ```python v_distribution = normal(1.34, 0.05, num_agents) for pos, v0 in zip(pos_in_spawning_area, v_distribution): simulation.add_agent( jps.CollisionFreeSpeedModelAgentParameters( journey_id=journey_id, stage_id=exit_id, position=pos, desired_speed=v0, radius=0.15, ) ) while simulation.agent_count() > 0: simulation.iterate() simulation._writer.close() ``` -------------------------------- ### Initialize Simulation Scenarios Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/lane-formation.ipynb Sets up multiple simulation instances with varying numbers of agents for different flow conditions. Each simulation is configured with a specific time step, collision model, walkable geometry, and trajectory writer. ```python simulations = {} COLUMNS = 9 number_agents = [ (6 * COLUMNS, 0 * COLUMNS), (5 * COLUMNS, 1 * COLUMNS), (4 * COLUMNS, 2 * COLUMNS), (3 * COLUMNS, 3 * COLUMNS), ] for number in number_agents: trajectory_file = f"trajectories_number_agents_{number}.sqlite" simulation = jps.Simulation( dt=0.05, model=jps.CollisionFreeSpeedModel( strength_neighbor_repulsion=2.6, range_neighbor_repulsion=0.1, range_geometry_repulsion=0.05, ), geometry=walkable_area.polygon, trajectory_writer=jps.SqliteTrajectoryWriter( output_file=pathlib.Path(trajectory_file), ), ) simulations[number] = simulation ``` -------------------------------- ### Define Scenario 5 Geometry and Initial Conditions Source: https://github.com/pedestriandynamics/jupedsim/blob/master/notebooks/model-comparison.ipynb Sets up the geometric environment, agent positions, desired speeds, and goals for the bottleneck simulation. ```python def create_geometry_scenario5(): # Outer boundary outer = [(-5, -5), (5, -5), (5, 5), (-5, 5)] # Inner holes (from the second polygon) hole1 = [(0.5, 0), (4.0, 0), (4.0, 1), (1.5, 1), (0.5, 2), (0.5, 0)] hole2 = [(-0.5, 0), (-4.0, 0), (-4.0, 1), (-1.5, 1), (-0.5, 2), (-0.5, 0)] # Create polygon with holes geometry = Polygon(shell=outer, holes=[hole1, hole2]) return geometry def define_positions_scenario5(): """Define initial positions and desired speeds.""" positions = [ (-4, -0.5), (-3.5, -2), (-2, -3.5), (0, -4), (2, -3.5), (3.5, -2), (4, -0.5), ] speeds = 7 * [1.0] return positions, speeds def define_goals_scenario5(): """Define 7 goals polygons.""" goals = 7 * [Polygon([(-0.3, 1.5), (0.3, 1.5), (0.3, 2.0), (-0.3, 2)])] return goals geometry = create_geometry_scenario5() positions, speeds = define_positions_scenario5() goals = define_goals_scenario5() plot_simulation_configuration(geometry, positions, goals) times_dict = {} ``` -------------------------------- ### Example CSV Trajectory Writer Implementation Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/concepts/custom_serialization.rst A complete example of a custom writer that outputs trajectory data to a CSV file. It handles file opening, writing headers, and writing iteration state based on the specified interval. ```python import csv from pathlib import Path from jupedsim.serialization import TrajectoryWriter from jupedsim.simulation import Simulation class CsvTrajectoryWriter(TrajectoryWriter): """Write trajectory data to a CSV file.""" def __init__(self, output_file: Path, every_nth_frame: int = 1) -> None: if every_nth_frame < 1: raise TrajectoryWriter.Exception("'every_nth_frame' must be > 0") self._output_file = output_file self._every_nth_frame = every_nth_frame self._file = None self._csv_writer = None def begin_writing(self, simulation: Simulation) -> None: self._file = open(self._output_file, "w", newline="") self._csv_writer = csv.writer(self._file) self._csv_writer.writerow( ["frame", "id", "pos_x", "pos_y", "ori_x", "ori_y"] ) def write_iteration_state(self, simulation: Simulation) -> None: iteration = simulation.iteration_count() if iteration % self._every_nth_frame != 0: return ``` -------------------------------- ### Initialize Jupedsim Simulation Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/model-comparison.ipynb Sets up a Jupedsim simulation with specified model, agent parameters, geometry, goals, initial positions, speeds, and trajectory file. Supports different agent parameter types. ```python import pathlib import jupedsim as jps import matplotlib.pyplot as plt import numpy as np import pedpy from jupedsim.internal.notebook_utils import animate, read_sqlite_file from shapely import Polygon from shapely.geometry import Point from shapely.ops import unary_union def initialize_simulation( model, agent_parameters, geometry, goals, positions, speeds, trajectory_file ): simulation = jps.Simulation( model=model, geometry=geometry, dt=0.01, trajectory_writer=jps.SqliteTrajectoryWriter( output_file=pathlib.Path(trajectory_file), every_nth_frame=5 ), ) exit_ids = [simulation.add_exit_stage(goal) for goal in goals] journey = jps.JourneyDescription(exit_ids) journey_id = simulation.add_journey(journey) centroids = [polygon.centroid.coords[0] for polygon in goals] orientations = [ (v := np.array(centroid) - np.array(position)) / np.linalg.norm(v) for centroid, position in zip(centroids, positions) ] for pos, v0, exit_id, orientation in zip( positions, speeds, exit_ids, orientations ): if agent_parameters == jps.AnticipationVelocityModelAgentParameters: simulation.add_agent( agent_parameters( journey_id=journey_id, stage_id=exit_id, desired_speed=v0, position=pos, anticipation_time=1, reaction_time=0.3, ) ) elif agent_parameters == jps.SocialForceModelAgentParameters: simulation.add_agent( agent_parameters( journey_id=journey_id, stage_id=exit_id, desiredSpeed=v0, position=pos, ) ) elif ( agent_parameters == jps.GeneralizedCentrifugalForceModelAgentParameters ): simulation.add_agent( agent_parameters( journey_id=journey_id, stage_id=exit_id, desired_speed=v0, position=pos, orientation=orientation, ) ) elif agent_parameters == jps.WarpDriverModelAgentParameters: simulation.add_agent( agent_parameters( journey_id=journey_id, stage_id=exit_id, desired_speed=v0, position=pos, orientation=orientation, ) ) else: simulation.add_agent( agent_parameters( journey_id=journey_id, stage_id=exit_id, position=pos, desired_speed=v0, ) ) return simulation ``` -------------------------------- ### Visualize Room Layout and Waypoints Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/routing.ipynb Visualizes the walkable area, obstacles, waypoints, exit, and starting zone using matplotlib. Waypoints are marked with 'ro' and annotated, with associated circles indicating their influence radius. The exit and starting zones are filled and labeled. ```python fig, ax = plt.subplots(nrows=1, ncols=1) ax.set_aspect("equal") pedpy.plot_walkable_area(walkable_area=walkable_area, axes=ax) for idx, (waypoint, distance) in enumerate(waypoints): ax.plot(waypoint[0], waypoint[1], "ro") ax.annotate( f"WP {idx + 1}", (waypoint[0], waypoint[1]), textcoords="offset points", xytext=(10, -15), ha="center", ) circle = Circle( (waypoint[0], waypoint[1]), distance, fc="red", ec="red", alpha=0.1 ) ax.add_patch(circle) x, y = Polygon(exit_polygon).exterior.xy plt.fill(x, y, alpha=0.1, color="orange") centroid = Polygon(exit_polygon).centroid plt.text(centroid.x, centroid.y, "Exit", ha="center", va="center", fontsize=8) x, y = distribution_polygon.exterior.xy plt.fill(x, y, alpha=0.1, color="blue") centroid = distribution_polygon.centroid plt.text(centroid.x, centroid.y, "Start", ha="center", va="center", fontsize=10) ``` -------------------------------- ### Initialize Simulation and Distribute Agents Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/lane-formation.ipynb Sets up simulation exits and journeys, then distributes agents into two groups using specified polygons and parameters. Agents are assigned collision-free speed models and directed towards specific exits. ```python right_wing = {} left_wing = {} for number, simulation in simulations.items(): exits = [ simulation.add_exit_stage(exit_polygon_left), simulation.add_exit_stage(exit_polygon_right), ] journeys = [ simulation.add_journey(jps.JourneyDescription([exit])) for exit in exits ] # first group positions = jps.distribute_by_number( polygon=distribution_polygon_right, number_of_agents=number[1], distance_to_agents=0.4, distance_to_polygon=0.7, seed=45131502, ) group1 = set( [ simulation.add_agent( jps.CollisionFreeSpeedModelAgentParameters( position=position, journey_id=journeys[0], stage_id=exits[0], ) ) for position in positions ] ) # second group positions = jps.distribute_by_number( polygon=distribution_polygon_left, number_of_agents=number[0], distance_to_agents=0.4, distance_to_polygon=0.7, seed=45131502, ) group2 = set( [ simulation.add_agent( jps.CollisionFreeSpeedModelAgentParameters( position=position, journey_id=journeys[1], stage_id=exits[1], ) ) for position in positions ] ) right_wing[number] = group1 left_wing[number] = group2 ``` -------------------------------- ### Import Required Packages for Jupedsim Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/queues_waiting.ipynb Imports necessary libraries for Jupedsim, pedpy, and plotting. Ensure these are installed before running. ```python import pathlib import jupedsim as jps import pedpy from matplotlib.patches import Circle from numpy.random import normal # normal distribution of free movement speed from shapely import Polygon, from_wkt, intersection ``` -------------------------------- ### Add and Manage a Queue Stage Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/concepts/routing.rst Demonstrates adding a queue with predefined waiting spots to the simulation, retrieving it, and releasing agents from the queue. ```python # add the queue to the simulation queue_id = simulation.add_queue_stage( [ (0, 0), (0, 5), (0, 10), (0, 15), (0, 20), ) # retrieve queue from the simulation queue = simulation.get_stage(queue_id) ... # notify that the first 2 agents can move to the next stage queue.pop(2) # notify that the first agent can move to the next stage queue.pop(1) ``` -------------------------------- ### Initialize and Run WD Simulation Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/model-comparison.ipynb Initializes and runs a simulation using the Warp Driver (WD) Model. Reads trajectory data and animates the simulation. ```python model = "WD" trajectory_file = f"{model}.sqlite" simulation = initialize_simulation( jps.WarpDriverModel(), jps.WarpDriverModelAgentParameters, geometry, goals, positions, speeds, trajectory_file, ) times_dict[model] = run_simulation(simulation, max_iterations=2000) trajectories, walkable_area = read_sqlite_file(trajectory_file) animate( trajectories, walkable_area, title_note=model, every_nth_frame=5, width=width, height=height, ) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/direct_steering.ipynb Imports required libraries for jupedsim, pedpy, matplotlib, and shapely. Ensure these libraries are installed before running. ```python import pathlib import random import jupedsim as jps import pedpy from matplotlib.patches import Circle from shapely import GeometryCollection, Point, Polygon ``` -------------------------------- ### Initialize Warp Driver Model and Simulation Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/pedestrian_models/warp_driver_model.md Set up model-level parameters for the Warp Driver Model and initialize the Jupedsim simulation. Model parameters include time horizon, step size, and uncertainty values. ```python import jupedsim as jps # Model-level parameters (shared by all agents) model = jps.WarpDriverModel( time_horizon=2.0, step_size=0.5, sigma=0.3, time_uncertainty=0.5, velocity_uncertainty_x=0.2, velocity_uncertainty_y=0.2, ) sim = jps.Simulation(model=model, geometry=area, dt=0.01) ``` -------------------------------- ### Configure Python Test Wrapper Source: https://github.com/pedestriandynamics/jupedsim/blob/master/CMakeLists.txt Sets up the input and output paths for the Python test wrapper script, choosing between Unix and Windows specific templates. ```cmake if(BUILD_TESTS) if(UNIX) set(pytest-wrapper-in ${CMAKE_SOURCE_DIR}/cmake_templates/run-pythontests.unix.in) set(pytest-wrapper-out ${CMAKE_BINARY_DIR}/run-pythontests) else() set(pytest-wrapper-in ${CMAKE_SOURCE_DIR}/cmake_templates/run-pythontests.windows.in) set(pytest-wrapper-out ${CMAKE_BINARY_DIR}/run-pythontests.cmd) endif() configure_file( ${pytest-wrapper-in} ${pytest-wrapper-out} @ONLY ) endif() ``` -------------------------------- ### Configure Performance Test Wrapper Source: https://github.com/pedestriandynamics/jupedsim/blob/master/CMakeLists.txt Sets up the input and output paths for the performance test wrapper script, specifically for Unix-like systems. ```cmake if(UNIX) set(performancetests-wrapper-in ${CMAKE_SOURCE_DIR}/cmake_templates/run-performancetests.unix.in) set(performancetests-wrapper-out ${CMAKE_BINARY_DIR}/run-performancetests) configure_file( ${performancetests-wrapper-in} ${performancetests-wrapper-out} @ONLY ) endif() ``` -------------------------------- ### Per-Iteration Timing Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/debugging/profiling_and_timing.rst Access sim.timer.iteration_duration_us to get the time spent in the last call to iterate(). This is useful for displaying live simulation throughput. ```python while sim.agent_count() > 0: sim.iterate() it_ms = sim.timer.iteration_duration_us / 1000 print(f"iteration {sim.iteration_count():5d} {it_ms:.2f} ms/it", end="\r") ``` -------------------------------- ### Initialize JuPedSim Simulation with Collision-Free Speed Model Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/getting_started.ipynb Sets up a JuPedSim simulation using the CollisionFreeSpeedModel, specifying geometry and an SQLite trajectory writer. Requires jupedsim and pathlib libraries. ```python import pathlib import jupedsim as jps trajectory_file = "bottleneck_cfsm.sqlite" simulation_cfsm = jps.Simulation( model=jps.CollisionFreeSpeedModel(), geometry=geometry, trajectory_writer=jps.SqliteTrajectoryWriter( output_file=pathlib.Path(trajectory_file) ), ) ``` -------------------------------- ### Add Agents to Simulation Source: https://github.com/pedestriandynamics/jupedsim/blob/master/notebooks/corner-SocialForce.ipynb Defines agent parameters, including normally distributed free movement speeds, and adds them to the simulation with their respective journeys and starting positions. ```python v_distribution = normal(1.34, 0.05, num_agents) for pos, v0 in zip(pos_in_spawning_area, v_distribution): simulation.add_agent( jps.SocialForceModelAgentParameters( journey_id=journey_id, stage_id=exit_id, position=pos ) ) while simulation.agent_count() > 0: simulation.iterate() simulation._writer.close() ``` -------------------------------- ### Initialize and Run SFM Simulation Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/model-comparison.ipynb Initializes and runs a simulation using the Social Force Model (SFM). Reads trajectory data and animates the simulation. ```python model = "SFM" trajectory_file = f"{model}.sqlite" simulation = initialize_simulation( jps.SocialForceModel(), jps.SocialForceModelAgentParameters, geometry, goals, positions, speeds, trajectory_file, ) times_dict[model] = run_simulation(simulation, max_iterations=2000) trajectories, walkable_area = read_sqlite_file(trajectory_file) animate( trajectories, walkable_area, title_note=model, every_nth_frame=5, width=width, height=height, ) ``` -------------------------------- ### Configure Simulation Scenarios with Varying Agent Percentages Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/routing.ipynb Sets up multiple simulation objects with a 'collision-free' model. Adjusts agent group sizes by iterating through percentage values and defines trajectory output files. ```python simulations = {} percentages = [0, 20, 40, 50, 60, 70, 100] total_agents = 100 for percentage in percentages: trajectory_file = f"trajectories_percentage_{percentage}.sqlite" simulation = jps.Simulation( dt=0.05, model=jps.CollisionFreeSpeedModel( strength_neighbor_repulsion=2.6, range_neighbor_repulsion=0.1, range_geometry_repulsion=0.05, ), geometry=walkable_area.polygon, trajectory_writer=jps.SqliteTrajectoryWriter( output_file=pathlib.Path(trajectory_file), ), ) simulations[percentage] = simulation ``` -------------------------------- ### Add Agents to the Simulation Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/getting_started.ipynb Adds agents to the simulation with specified parameters, including journey, stage, initial position, and radius. Reuses previously loaded start positions. ```python for position in start_positions: simulation_cfsm.add_agent( jps.CollisionFreeSpeedModelAgentParameters( journey_id=journey_id, stage_id=exit_id, position=position, radius=0.12, ) ) ``` -------------------------------- ### Run WD Simulation and Animation Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/model-comparison.ipynb Initializes and runs a simulation using the Warp Driver (WD) Model. It then reads the trajectory data and animates the simulation. ```python model = "WD" trajectory_file = f"{model}.sqlite" simulation = initialize_simulation( jps.WarpDriverModel(), jps.WarpDriverModelAgentParameters, geometry, goals, positions, speeds, trajectory_file, ) times_dict[model] = run_simulation(simulation, max_iterations=2000) trajectories, walkable_area = read_sqlite_file(trajectory_file) animate( trajectories, walkable_area, title_note=model, every_nth_frame=5, width=width, height=height, ) ``` -------------------------------- ### Build JuPedSim from Source with CMake and Make Source: https://github.com/pedestriandynamics/jupedsim/blob/master/README.md Compile JuPedSim from source manually. This involves installing Python dependencies, generating Makefiles with CMake, compiling, and sourcing the environment script. ```bash pip install -r jupedsim/requirements.txt mkdir jupedsim-build cd jupedsim-build git submodule update --init cmake ../jupedsim make -j source ./environment ``` -------------------------------- ### Visualize Simulation Environment Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/journey.ipynb Plots the defined simulation area, start zone, exit, switch point, and waypoints using Matplotlib. This visualizes the geometry and routing elements for clarity. ```python fig, ax = plt.subplots(nrows=1, ncols=1) ax.set_aspect("equal") pedpy.plot_walkable_area(walkable_area=walkable_area, axes=ax) x, y = distribution_polygon.exterior.xy plt.fill(x, y, alpha=0.1) plt.plot(x, y, color="white") centroid = distribution_polygon.centroid plt.text(centroid.x, centroid.y, "Start", ha="center", va="center", fontsize=10) x, y = Polygon(exit_polygon).exterior.xy plt.fill(x, y, alpha=0.1) plt.plot(x, y, color="white") centroid = Polygon(exit_polygon).centroid plt.text(centroid.x, centroid.y, "Exit", ha="center", va="center", fontsize=10) ax.plot(switch_point[0], switch_point[1], "bo") circle = Circle( (switch_point[0], switch_point[1]), distance_to_switch, fc="blue", ec="blue", alpha=0.1, ) ax.add_patch(circle) ax.annotate( "Switch", (switch_point[0], switch_point[1]), textcoords="offset points", xytext=(-5, -15), ha="center", ) for idx, waypoint in enumerate(waypoints): ax.plot(waypoint[0], waypoint[1], "ro") ax.annotate( f"WP {idx + 1}", (waypoint[0], waypoint[1]), textcoords="offset points", xytext=(10, -15), ha="center", ) circle = Circle( (waypoint[0], waypoint[1]), distance_to_waypoints, fc="red", ec="red", alpha=0.1, ) ax.add_patch(circle) ``` -------------------------------- ### Initialize JuPedSim Simulation Source: https://github.com/pedestriandynamics/jupedsim/blob/master/notebooks/corner-SocialForce.ipynb Creates a simulation object with the Social Force Model and configures a SQLite trajectory writer. ```python trajectory_file = "corner_SocialForces.sqlite" # output file simulation = jps.Simulation( model=jps.SocialForceModel(), geometry=area, trajectory_writer=jps.SqliteTrajectoryWriter( output_file=pathlib.Path(trajectory_file) ), ) ``` -------------------------------- ### Run WD Simulation Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/model-comparison.ipynb Initializes and runs the Warp Driver Model (WD) simulation. It then reads the trajectory data and animates the simulation. ```python model = "WD" trajectory_file = f"{model}.sqlite" simulation = initialize_simulation( jps.WarpDriverModel(), jps.WarpDriverModelAgentParameters, geometry, goals, positions, speeds, trajectory_file, ) times_dict[model] = run_simulation(simulation, max_iterations=5000) trajectories, walkable_area = read_sqlite_file(trajectory_file) animate( trajectories, walkable_area, title_note=model, every_nth_frame=5, width=width, height=height, ) ``` -------------------------------- ### Specify Agent Routing Details Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/motivation.ipynb Adds exit stages and defines a journey for agents to follow towards a specified exit. This guides agent movement within the simulation environment. ```python exit_id = simulation.add_exit_stage(areas["exit"]) journey_id = simulation.add_journey(jps.JourneyDescription([exit_id])) ``` -------------------------------- ### List of Transition Scenarios Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/journey.ipynb A list containing references to the defined transition strategy functions. ```python scenarios = [ shortest_path, least_targeted, round_robin, ] ``` -------------------------------- ### Built-in HDF5 Trajectory Writer Usage Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/concepts/custom_serialization.rst Demonstrates the usage of the built-in HDF5 trajectory writer, which is compatible with the Pedestrian Dynamics Data Archive (PDA) schema. Install 'h5py' for this functionality. ```python import jupedsim as jps from pathlib import Path writer = jps.Hdf5TrajectoryWriter( output_file=Path("traj.h5"), every_nth_frame=4, compression_level=1, ) sim = jps.Simulation( model=..., geometry=..., trajectory_writer=writer, dt=0.01, ) while sim.agent_count() > 0: sim.iterate() writer.close() ``` -------------------------------- ### Define Geometry, Positions, and Goals for Scenario 4 Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/model-comparison.ipynb Sets up the simulation environment including the walkable area, initial agent positions, desired speeds, and goal regions for the perpendicular crossing scenario. ```python def create_geometry_scenario4(): geometry = Polygon([(-6, -6), (6, -6), (6, 6), (-6, 6)]) return geometry def define_positions_scenario4(): """Define initial positions and desired speeds.""" positions = [(-2, 0), (0, -2)] speeds = [1.0, 0.99] return positions, speeds def define_goals_scenario4(): """Define goal polygons.""" goals = [ Polygon([(5, -2), (6, -2), (6, 2), (5, 2)]), Polygon([(-2, 5), (-2, 6), (2, 6), (2, 5)]), ] return goals geometry = create_geometry_scenario4() positions, speeds = define_positions_scenario4() goals = define_goals_scenario4() plot_simulation_configuration(geometry, positions, goals) times_dict = {} ``` -------------------------------- ### Define Room Layout and Agent Paths Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/routing.ipynb Defines the room's geometry, obstacles, exit, waypoints, and the starting distribution area using Shapely polygons and pedpy's WalkableArea. ```python complete_area = Polygon( [ (0, 0), (0, 20), (20, 20), (20, 0), ] ) obstacles = [ Polygon( [ (5, 0.0), (5, 16), (5.2, 16), (5.2, 0.0), ] ), Polygon([(15, 19), (15, 5), (7.2, 5), (7.2, 4.8), (15.2, 4.8), (15.2, 19)]), ] exit_polygon = [(19, 19), (20, 19), (20, 20), (19, 20)] waypoints = [([3, 19], 3), ([7, 19], 2), ([7, 2.5], 2), ([17.5, 2.5], 2)] distribution_polygon = Polygon([[0, 0], [5, 0], [5, 10], [0, 10]]) obstacle = shapely.union_all(obstacles) walkable_area = pedpy.WalkableArea(shapely.difference(complete_area, obstacle)) ``` -------------------------------- ### Manual Trace Event Spans Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/debugging/profiling_and_timing.rst Manually start and end trace events to profile specific code regions. Events nest correctly, closing the most recent event on the calling thread. ```python import jupedsim as jps jps.start_trace_event("agent-spawning") for pos in positions: sim.add_agent(...) jps.end_trace_event() ``` -------------------------------- ### Importing Required Packages Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/corner.ipynb Imports necessary libraries for simulation, including jupedsim, pedpy, and numpy for random speed distribution. ```python import pathlib import jupedsim as jps import pedpy from numpy.random import normal # normal distribution of free movement speed from shapely import Polygon ``` -------------------------------- ### TrajectoryWriter Interface Definition Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/concepts/custom_serialization.rst Subclass TrajectoryWriter and implement these three methods to create a custom writer. Use begin_writing for setup, write_iteration_state for frame data, and every_nth_frame to control the write interval. ```python from jupedsim.serialization import TrajectoryWriter from jupedsim.simulation import Simulation class MyCustomWriter(TrajectoryWriter): def begin_writing(self, simulation: Simulation) -> None: """Called once before the first iteration. Use this to write headers, metadata, or set up output files. """ ... def write_iteration_state(self, simulation: Simulation) -> None: """Called every iteration. Check the iteration count against every_nth_frame() to decide whether to actually write data. """ ... def every_nth_frame(self) -> int: """Return the write interval. 1 = write every frame, 5 = every 5th frame, etc. """ ... ``` -------------------------------- ### Initialize and Run AVM Simulation Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/model-comparison.ipynb Initializes and runs a simulation using the Anticipation Velocity Model (AVM). Reads trajectory data and animates the simulation. ```python model = "AVM" trajectory_file = f"{model}.sqlite" simulation = initialize_simulation( jps.AnticipationVelocityModel(), jps.AnticipationVelocityModelAgentParameters, geometry, goals, positions, speeds, trajectory_file, ) times_dict[model] = run_simulation(simulation, max_iterations=2000) trajectories, walkable_area = read_sqlite_file(trajectory_file) animate( trajectories, walkable_area, title_note=model, every_nth_frame=5, width=width, height=height, ) ``` -------------------------------- ### Configure Simulation Model and Exit Source: https://github.com/pedestriandynamics/jupedsim/blob/master/docs/source/notebooks/direct_steering.ipynb Sets up the simulation environment, including the agent interaction model, geometry, and trajectory writer. Define the exit stage for the simulation. ```python trajectory_file = "output.sqlite" # output file simulation = jps.Simulation( model=jps.GeneralizedCentrifugalForceModel( max_neighbor_repulsion_force=10, max_neighbor_interaction_distance=2, max_neighbor_interpolation_distance=0.1, strength_neighbor_repulsion=0.3, max_geometry_repulsion_force=3, ), geometry=area, trajectory_writer=jps.SqliteTrajectoryWriter( output_file=pathlib.Path(trajectory_file) ), ) exit_id = simulation.add_exit_stage(exit_area.exterior.coords[:-1]) ```