diff --git a/pedpy/__init__.py b/pedpy/__init__.py index 6dd82288..d9acec74 100644 --- a/pedpy/__init__.py +++ b/pedpy/__init__.py @@ -12,6 +12,7 @@ from .column_identifier import ( ACC_COL, + ALIGNMENT_COL, A_X_COL, A_Y_COL, COUNT_COL, @@ -119,6 +120,8 @@ ) from .methods.spatial_analysis import compute_pair_distribution_function from .methods.speed_calculator import ( + compute_alignment_parameter, + compute_arithmetic_voronoi_speed, compute_individual_speed, compute_line_speed, compute_mean_speed_per_frame, @@ -205,6 +208,8 @@ "compute_speed_profile", "get_grid_cells", "SpeedCalculation", + "compute_alignment_parameter", + "compute_arithmetic_voronoi_speed", "compute_individual_speed", "compute_line_speed", "compute_mean_speed_per_frame", @@ -258,6 +263,7 @@ "FLOW_COL", "MEAN_SPEED_COL", "ACC_COL", + "ALIGNMENT_COL", "A_X_COL", "A_Y_COL", "FIRST_FRAME_COL", diff --git a/pedpy/column_identifier.py b/pedpy/column_identifier.py index bde0ee2f..36435daa 100644 --- a/pedpy/column_identifier.py +++ b/pedpy/column_identifier.py @@ -24,6 +24,7 @@ ACC_COL: Final = "acceleration" A_X_COL: Final = "a_x" A_Y_COL: Final = "a_y" +ALIGNMENT_COL: Final = "alignment" FIRST_FRAME_COL: Final = "entering_frame" MID_FRAME_COL: Final = "mid_frame" diff --git a/pedpy/methods/speed_calculator.py b/pedpy/methods/speed_calculator.py index 4f269360..3e67f732 100644 --- a/pedpy/methods/speed_calculator.py +++ b/pedpy/methods/speed_calculator.py @@ -1,6 +1,6 @@ """Module containing functions to compute velocities.""" -from typing import Optional +from typing import Final, Optional, Union import numpy as np import numpy.typing as npt @@ -8,8 +8,11 @@ import shapely from pedpy.column_identifier import ( + ALIGNMENT_COL, FRAME_COL, ID_COL, + INTERSECTION_COL, + POINT_COL, POLYGON_COL, SPECIES_COL, SPEED_COL, @@ -17,10 +20,12 @@ SPEED_SP2_COL, V_X_COL, V_Y_COL, + X_COL, + Y_COL, ) from pedpy.data.geometry import MeasurementArea, MeasurementLine from pedpy.data.trajectory_data import TrajectoryData -from pedpy.errors import InputError, SpeedError +from pedpy.errors import InputError, PedPyValueError, SpeedError from pedpy.methods.method_utils import ( DataValidationStatus, SpeedCalculation, @@ -32,6 +37,9 @@ is_species_valid, ) +_INTERSECTION_AREA_THRESHOLD: Final = 1e-16 +_VECTOR_NORM_THRESHOLD: Final = 1e-12 + def compute_individual_speed( *, @@ -338,6 +346,216 @@ def compute_voronoi_speed( return pd.DataFrame(df_voronoi_speed) +def compute_arithmetic_voronoi_speed( + *, + traj_data: TrajectoryData, + individual_speed: pd.DataFrame, + individual_voronoi_intersection: pd.DataFrame, + measurement_area: Optional[MeasurementArea] = None, +) -> pd.DataFrame: + r"""Compute the arithmetic Voronoi speed per frame in a measurement area. + + Calculates the unweighted arithmetic mean speed :math:`v_{arithmetic}(t)` + over all pedestrians :math:`P_M(t)` whose Voronoi cell :math:`V_i(t)` + intersects the measurement area :math:`M` with positive area + (:math:`A(V_i(t) \cap M) > 0`): + + .. math:: + + v_{arithmetic}(t) = \frac{1}{|P_M(t)|} \sum_{i \in P_M(t)} v_i(t). + + Frames in which no Voronoi cell intersects the measurement area receive a + speed of ``0.0``. + + Args: + traj_data (TrajectoryData): trajectory data + individual_speed (pandas.DataFrame): individual speed data from + :func:`~speed_calculator.compute_individual_speed` + individual_voronoi_intersection (pandas.DataFrame): intersections of + individual Voronoi cells with the measurement area from + :func:`~method_utils.compute_intersecting_polygons` (or Voronoi + polygon data when ``measurement_area`` is also passed) + measurement_area (MeasurementArea, optional): measurement area used to + compute intersections when ``individual_voronoi_intersection`` + contains ``polygon`` instead of ``intersection`` + + Returns: + DataFrame containing the columns ``frame`` and ``speed`` in m/s + """ + _check_trajectory_data(traj_data) + if len(individual_speed.index) < len(individual_voronoi_intersection.index): + raise SpeedError( + f"Can not compute the arithmetic Voronoi speed, as there are less speed " + f"data (rows={len(individual_speed)}) than Voronoi intersection " + f"data (rows={len(individual_voronoi_intersection.index)}). This " + f"means a person occupies space but has no speed at some frames. " + f"To resolve this either edit your Voronoi intersection data, " + f"s.th. it only contains the data that is also contained in the " + f"speed data. Or use a different speed border method when " + f"computing the individual speed." + ) + + df_voronoi = individual_voronoi_intersection.merge( + individual_speed, + on=[ID_COL, FRAME_COL], + ) + + if INTERSECTION_COL in df_voronoi.columns: + intersections = df_voronoi[INTERSECTION_COL] + elif POLYGON_COL in df_voronoi.columns and measurement_area is not None: + intersections = shapely.intersection(df_voronoi[POLYGON_COL], measurement_area.polygon) + else: + raise InputError( + f"Expected column '{INTERSECTION_COL}' in 'individual_voronoi_intersection' " + f"(or '{POLYGON_COL}' together with 'measurement_area')." + ) + + intersecting = df_voronoi[shapely.area(intersections) > _INTERSECTION_AREA_THRESHOLD] + df_arithmetic_speed = intersecting.groupby(by=FRAME_COL)[SPEED_COL].mean() + df_arithmetic_speed = df_arithmetic_speed.reindex( + list(range(traj_data.data.frame.min(), traj_data.data.frame.max() + 1)), + fill_value=0.0, + ) + df_arithmetic_speed = df_arithmetic_speed.reset_index() + df_arithmetic_speed.columns = [FRAME_COL, SPEED_COL] + return pd.DataFrame(df_arithmetic_speed) + + +def _resolve_desired_unit_vectors( + combined: pd.DataFrame, + target_point: Optional[npt.ArrayLike], + desired_direction: Optional[Union[npt.ArrayLike, pd.DataFrame]], +) -> npt.NDArray[np.float64]: + """Compute per-row unit desired direction vectors ``(u_x, u_y)``.""" + if (target_point is None) == (desired_direction is None): + raise PedPyValueError("Provide exactly one of 'target_point' or 'desired_direction'.") + + if target_point is not None: + target = np.asarray(target_point, dtype=np.float64) + if target.shape != (2,): + raise PedPyValueError(f"'target_point' must have shape (2,), got {target.shape}.") + raw_u = target[None, :] - combined[[X_COL, Y_COL]].to_numpy(dtype=np.float64) + elif isinstance(desired_direction, pd.DataFrame): + if not {"u_x", "u_y"}.issubset(desired_direction.columns): + raise PedPyValueError("DataFrame 'desired_direction' must contain 'u_x' and 'u_y' columns.") + join_cols = [col for col in (ID_COL, FRAME_COL) if col in desired_direction.columns] + if not join_cols: + raise PedPyValueError( + f"DataFrame 'desired_direction' must contain '{ID_COL}' (and optionally '{FRAME_COL}')." + ) + aligned = combined[[ID_COL, FRAME_COL]].merge( + desired_direction[[*join_cols, "u_x", "u_y"]], + on=join_cols, + how="left", + ) + raw_u = aligned[["u_x", "u_y"]].to_numpy(dtype=np.float64) + else: + vec = np.asarray(desired_direction, dtype=np.float64) + if vec.shape != (2,): + raise PedPyValueError(f"'desired_direction' must have shape (2,), got {vec.shape}.") + vec_norm = float(np.linalg.norm(vec)) + if vec_norm <= _VECTOR_NORM_THRESHOLD: + raise PedPyValueError("'desired_direction' must be a non-zero 2D vector.") + return np.broadcast_to(vec / vec_norm, (len(combined), 2)).copy() + + norms = np.linalg.norm(raw_u, axis=1, keepdims=True) + return np.divide(raw_u, norms, out=np.zeros_like(raw_u), where=norms > _VECTOR_NORM_THRESHOLD) + + +def compute_alignment_parameter( + *, + traj_data: TrajectoryData, + individual_speed: pd.DataFrame, + target_point: Optional[npt.ArrayLike] = None, + desired_direction: Optional[Union[npt.ArrayLike, pd.DataFrame]] = None, + measurement_area: Optional[MeasurementArea] = None, +) -> pd.DataFrame: + r"""Compute the per-frame alignment parameter :math:`\phi_d(t)`. + + Quantifies how closely pedestrian velocities align with their desired + direction of motion (e.g. toward an exit door or along a corridor), + following Feliciani et al. (2020), *Scientific Reports*, 10, 15947 + (``doi:10.1038/s41598-020-72733-w``): + + .. math:: + + \phi_d(t) = \frac{1}{N(t)} \sum_{n=1}^{N(t)} + \frac{\vec{v}_t^n \cdot \vec{u}_t^n}{\|\vec{v}_t^n\|}, + + where :math:`\vec{v}_t^n` is the velocity vector of pedestrian :math:`n` at + frame :math:`t`, :math:`\vec{u}_t^n` is their unit desired direction of + motion, and :math:`N(t)` is the number of pedestrians considered at frame + :math:`t`. Values near ``+1`` indicate organized movement toward the + desired target/direction, ``0`` indicates perpendicular/azimuthal motion + (or stationary pedestrians), and ``-1`` indicates motion in the opposite + direction. + + Args: + traj_data (TrajectoryData): trajectory data + individual_speed (pandas.DataFrame): individual velocity data from + :func:`~speed_calculator.compute_individual_speed` computed with + ``compute_velocity=True`` + target_point (array-like, optional): 2D coordinates ``(x, y)`` of a + target point (such as an exit center) toward which each + pedestrian's desired unit vector points. Mutually exclusive with + ``desired_direction``. + desired_direction (array-like or pandas.DataFrame, optional): either a + constant 2D direction vector ``(u_x, u_y)`` or a DataFrame mapping + ``id`` (and optionally ``frame``) to ``u_x`` and ``u_y``. Mutually + exclusive with ``target_point``. + measurement_area (MeasurementArea, optional): if provided, restricts + the evaluation to pedestrians inside ``measurement_area`` + + Returns: + DataFrame containing the columns ``frame`` and ``alignment`` + """ + _check_trajectory_data(traj_data) + if not {ID_COL, FRAME_COL, V_X_COL, V_Y_COL}.issubset(individual_speed.columns): + raise SpeedError( + "Required velocity columns ('v_x', 'v_y') are missing from 'individual_speed'. " + "Compute individual speed with `compute_velocity=True`." + ) + + if measurement_area is not None and len(individual_speed.index) < len(traj_data.data.index): + raise SpeedError( + f"Can not compute the alignment parameter inside a measurement area, as " + f"there are less speed data (rows={len(individual_speed)}) than trajectory " + f"data (rows={len(traj_data.data.index)})." + ) + + combined = traj_data.data.merge( + individual_speed[[ID_COL, FRAME_COL, V_X_COL, V_Y_COL]], + on=[ID_COL, FRAME_COL], + ) + if measurement_area is not None: + combined = combined[shapely.within(combined[POINT_COL], measurement_area.polygon)].copy() + + unit_u = _resolve_desired_unit_vectors( + combined=combined, + target_point=target_point, + desired_direction=desired_direction, + ) + velocities = combined[[V_X_COL, V_Y_COL]].to_numpy(dtype=np.float64) + v_norms = np.linalg.norm(velocities, axis=1) + dots = np.sum(velocities * unit_u, axis=1) + combined = combined.copy() + combined[ALIGNMENT_COL] = np.divide( + dots, + v_norms, + out=np.zeros_like(dots), + where=v_norms > _VECTOR_NORM_THRESHOLD, + ) + + df_alignment = combined.groupby(by=FRAME_COL)[ALIGNMENT_COL].mean() + df_alignment = df_alignment.reindex( + list(range(traj_data.data.frame.min(), traj_data.data.frame.max() + 1)), + fill_value=0.0, + ) + df_alignment = df_alignment.reset_index() + df_alignment.columns = [FRAME_COL, ALIGNMENT_COL] + return pd.DataFrame(df_alignment) + + def compute_passing_speed(*, frames_in_area: pd.DataFrame, frame_rate: float, distance: float) -> pd.DataFrame: r"""Compute the individual speed of the pedestrian who pass the area. diff --git a/tests/unit_tests/methods/test_speed_calculator.py b/tests/unit_tests/methods/test_speed_calculator.py index d5cd5037..6f4a6c24 100644 --- a/tests/unit_tests/methods/test_speed_calculator.py +++ b/tests/unit_tests/methods/test_speed_calculator.py @@ -7,7 +7,7 @@ from pedpy.column_identifier import * from pedpy.data.geometry import MeasurementArea, MeasurementLine, WalkableArea from pedpy.data.trajectory_data import TrajectoryData -from pedpy.errors import InputError, SpeedError +from pedpy.errors import InputError, PedPyValueError, SpeedError from pedpy.methods.method_utils import ( Cutoff, SpeedCalculation, @@ -15,6 +15,8 @@ compute_intersecting_polygons, ) from pedpy.methods.speed_calculator import ( + compute_alignment_parameter, + compute_arithmetic_voronoi_speed, compute_individual_speed, compute_line_speed, compute_mean_speed_per_frame, @@ -389,3 +391,156 @@ def test_compute_line_speed_missing_velocity_columns(example_data): individual_voronoi_polygons=voronoi, measurement_line=line, ) + + +def test_compute_arithmetic_voronoi_speed_unweighted_mean_and_empty_frames(): + traj_df = pd.DataFrame( + { + ID_COL: [1, 2, 3, 1], + FRAME_COL: [0, 0, 0, 1], + X_COL: [0.5, 3.5, 9.0, 9.0], + Y_COL: [1.0, 1.0, 1.0, 1.0], + } + ) + traj_data = TrajectoryData(data=traj_df, frame_rate=1.0) + measurement_area = MeasurementArea([(0.0, 0.0), (4.0, 0.0), (4.0, 2.0), (0.0, 2.0)]) + + # Ped 1 covers 3/4 of M (x in [0, 3]), Ped 2 covers 1/4 of M (x in [3, 4]), Ped 3 is outside M + poly_1 = Polygon([(0.0, 0.0), (3.0, 0.0), (3.0, 2.0), (0.0, 2.0)]) + poly_2 = Polygon([(3.0, 0.0), (5.0, 0.0), (5.0, 2.0), (3.0, 2.0)]) + poly_out = Polygon([(8.0, 0.0), (10.0, 0.0), (10.0, 2.0), (8.0, 2.0)]) + + voronoi_df = pd.DataFrame( + { + ID_COL: [1, 2, 3, 1], + FRAME_COL: [0, 0, 0, 1], + POLYGON_COL: [poly_1, poly_2, poly_out, poly_out], + } + ) + intersection_df = compute_intersecting_polygons( + individual_voronoi_data=voronoi_df, + measurement_area=measurement_area, + ) + speed_df = pd.DataFrame( + { + ID_COL: [1, 2, 3, 1], + FRAME_COL: [0, 0, 0, 1], + SPEED_COL: [1.0, 3.0, 10.0, 2.0], + } + ) + + voronoi_speed = compute_voronoi_speed( + traj_data=traj_data, + individual_speed=speed_df, + individual_voronoi_intersection=intersection_df, + measurement_area=measurement_area, + ) + arithmetic_speed = compute_arithmetic_voronoi_speed( + traj_data=traj_data, + individual_speed=speed_df, + individual_voronoi_intersection=intersection_df, + ) + arithmetic_from_polys = compute_arithmetic_voronoi_speed( + traj_data=traj_data, + individual_speed=speed_df, + individual_voronoi_intersection=voronoi_df, + measurement_area=measurement_area, + ) + + # Area-weighted Voronoi speed at frame 0: 0.75 * 1.0 + 0.25 * 3.0 = 1.5 + assert np.isclose(voronoi_speed.loc[voronoi_speed[FRAME_COL] == 0, SPEED_COL].iloc[0], 1.5) + # Unweighted arithmetic Voronoi speed at frame 0: (1.0 + 3.0) / 2 = 2.0; frame 1 empty -> 0.0 + assert np.allclose(arithmetic_speed[SPEED_COL].to_numpy(), [2.0, 0.0]) + pd.testing.assert_frame_equal(arithmetic_speed, arithmetic_from_polys) + + with pytest.raises(SpeedError, match="arithmetic Voronoi speed"): + compute_arithmetic_voronoi_speed( + traj_data=traj_data, + individual_speed=speed_df.iloc[:2], + individual_voronoi_intersection=intersection_df, + ) + + +def test_compute_alignment_parameter_target_and_directions(): + # Target door at (10, 0): + # Frame 0: Ped 1 at (0, 0) moves +x toward door (+1.0), Ped 2 at (0, 2) moves +x + # Frame 1: Ped 1 at (1, 0) moves -x away from door (-1.0), Ped 2 at (0, 2) stationary (0.0) + # Frame 2: Ped 1 at (0, 0) moves +y perpendicular to door (0.0) + traj_df = pd.DataFrame( + { + ID_COL: [1, 2, 1, 2, 1], + FRAME_COL: [0, 0, 1, 1, 2], + X_COL: [0.0, 0.0, 1.0, 0.0, 0.0], + Y_COL: [0.0, 0.0, 0.0, 2.0, 0.0], + } + ) + traj_data = TrajectoryData(data=traj_df, frame_rate=1.0) + speed_df = pd.DataFrame( + { + ID_COL: [1, 2, 1, 2, 1], + FRAME_COL: [0, 0, 1, 1, 2], + SPEED_COL: [2.0, 1.0, 2.0, 0.0, 1.5], + V_X_COL: [2.0, 1.0, -2.0, 0.0, 0.0], + V_Y_COL: [0.0, 0.0, 0.0, 0.0, 1.5], + } + ) + + res_target = compute_alignment_parameter( + traj_data=traj_data, + individual_speed=speed_df, + target_point=(10.0, 0.0), + ) + assert list(res_target.columns) == [FRAME_COL, ALIGNMENT_COL] + assert np.allclose(res_target[ALIGNMENT_COL].to_numpy(), [1.0, -0.5, 0.0]) + + # Constant desired direction (2, 0) (non-unit vector normalized internally) + res_dir = compute_alignment_parameter( + traj_data=traj_data, + individual_speed=speed_df, + desired_direction=(2.0, 0.0), + ) + assert np.allclose(res_dir[ALIGNMENT_COL].to_numpy(), [1.0, -0.5, 0.0]) + + # Per-pedestrian desired direction DataFrame + dir_df = pd.DataFrame({ID_COL: [1, 2], "u_x": [1.0, -1.0], "u_y": [0.0, 0.0]}) + res_df_dir = compute_alignment_parameter( + traj_data=traj_data, + individual_speed=speed_df, + desired_direction=dir_df, + ) + # Frame 0: Ped 1 has +1, Ped 2 has -1 -> mean 0.0 + assert np.allclose(res_df_dir[ALIGNMENT_COL].to_numpy(), [0.0, -0.5, 0.0]) + + # Measurement area filtering (only around y == 2, so Frame 0 and 2 have 0 peds -> 0.0) + ma = MeasurementArea([(-1.0, 1.5), (2.0, 1.5), (2.0, 3.0), (-1.0, 3.0)]) + res_ma = compute_alignment_parameter( + traj_data=traj_data, + individual_speed=speed_df, + desired_direction=(1.0, 0.0), + measurement_area=ma, + ) + assert np.allclose(res_ma[ALIGNMENT_COL].to_numpy(), [0.0, 0.0, 0.0]) + + +def test_compute_alignment_parameter_validation_errors(): + traj_df = pd.DataFrame({ID_COL: [1], FRAME_COL: [0], X_COL: [0.0], Y_COL: [0.0]}) + traj_data = TrajectoryData(data=traj_df, frame_rate=1.0) + speed_no_vel = pd.DataFrame({ID_COL: [1], FRAME_COL: [0], SPEED_COL: [1.0]}) + speed_vel = pd.DataFrame({ID_COL: [1], FRAME_COL: [0], SPEED_COL: [1.0], V_X_COL: [1.0], V_Y_COL: [0.0]}) + + with pytest.raises(SpeedError, match="compute_velocity=True"): + compute_alignment_parameter( + traj_data=traj_data, + individual_speed=speed_no_vel, + desired_direction=(1.0, 0.0), + ) + + with pytest.raises(PedPyValueError, match="exactly one"): + compute_alignment_parameter(traj_data=traj_data, individual_speed=speed_vel) + + with pytest.raises(PedPyValueError, match="non-zero"): + compute_alignment_parameter( + traj_data=traj_data, + individual_speed=speed_vel, + desired_direction=(0.0, 0.0), + )