From b71cf04bb1bea9c074ca5aa3c2e976b4a6f77e92 Mon Sep 17 00:00:00 2001 From: Mark Colley <39366189+M-Colley@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:50:34 +0000 Subject: [PATCH] feat: add single-file 1D density and optimize profile grid intersections --- pedpy/__init__.py | 4 + pedpy/methods/density_calculator.py | 230 +++++++++++++++++- pedpy/methods/profile_calculator.py | 160 ++++++++++-- .../methods/test_density_calculator.py | 86 ++++++- .../methods/test_profile_calculator.py | 66 +++++ .../test_trajectory_data_type_check.py | 6 +- 6 files changed, 521 insertions(+), 31 deletions(-) diff --git a/pedpy/__init__.py b/pedpy/__init__.py index 6dd82288..8f164ba1 100644 --- a/pedpy/__init__.py +++ b/pedpy/__init__.py @@ -81,9 +81,11 @@ compute_voronoi_acceleration, ) from .methods.density_calculator import ( + SingleFileMethod, compute_classic_density, compute_line_density, compute_passing_density, + compute_single_file_density, compute_voronoi_density, ) from .methods.flow_calculator import ( @@ -176,9 +178,11 @@ "load_walkable_area_from_crowdit", "load_trajectory_from_crowdit", "load_trajectory_from_pathfinder_csv", + "SingleFileMethod", "compute_classic_density", "compute_line_density", "compute_passing_density", + "compute_single_file_density", "compute_voronoi_density", "compute_flow", "compute_line_flow", diff --git a/pedpy/methods/density_calculator.py b/pedpy/methods/density_calculator.py index 35a36455..cb37abb6 100644 --- a/pedpy/methods/density_calculator.py +++ b/pedpy/methods/density_calculator.py @@ -1,8 +1,10 @@ """Module containing functions to compute densities.""" -from typing import Tuple +from enum import Enum, auto +from typing import Final, Optional, Tuple, Union import numpy as np +import numpy.typing as npt import pandas as pd import shapely @@ -13,11 +15,14 @@ DENSITY_SP2_COL, FRAME_COL, ID_COL, + POINT_COL, POLYGON_COL, + X_COL, + Y_COL, ) from pedpy.data.geometry import MeasurementArea, MeasurementLine from pedpy.data.trajectory_data import TrajectoryData -from pedpy.errors import InputError +from pedpy.errors import InputError, PedPyTypeError, PedPyValueError from pedpy.methods.method_utils import ( _apply_lambda_for_intersecting_frames, _check_trajectory_data, @@ -290,3 +295,224 @@ def compute_line_density( result[DENSITY_COL] = result[DENSITY_SP1_COL].fillna(0) + result[DENSITY_SP2_COL].fillna(0) return result + + +_MIN_SPACING_THRESHOLD: Final = 1e-12 +_HALF_FACTOR: Final = 0.5 + + +class SingleFileMethod(Enum): # pylint: disable=too-few-public-methods + r"""1D individual density definition for single-file trajectories. + + Attributes: + VORONOI: 1D Voronoi cell width :math:`d_k = (s_{k+1} - s_{k-1}) / 2`, + yielding individual density :math:`\rho_k = 1 / d_k`. + HEADWAY: Forward headway :math:`h_k = s_{k+1} - s_{k}`, yielding + individual density :math:`\rho_k = 1 / h_k`. + """ + + VORONOI = auto() + HEADWAY = auto() + + +def _project_single_file_positions( + df: pd.DataFrame, + centerline: Optional[shapely.LineString], + axis: str, + closed: bool, + track_length: Optional[float], +) -> Tuple[npt.NDArray[np.float64], Optional[float]]: + """Project pedestrian positions onto a 1D coordinate and resolve loop length.""" + if centerline is not None: + if not isinstance(centerline, shapely.LineString): + raise PedPyTypeError( + f"Expected 'centerline' to be a shapely.LineString, got {type(centerline).__name__!r} instead." + ) + s_coords = np.asarray(shapely.line_locate_point(centerline, df[POINT_COL].to_numpy()), dtype=np.float64) + resolved_length = track_length if track_length is not None else (float(centerline.length) if closed else None) + else: + if axis not in (X_COL, Y_COL): + raise PedPyValueError(f"'axis' must be '{X_COL}' or '{Y_COL}', got {axis!r}.") + s_coords = df[axis].to_numpy(dtype=np.float64) + resolved_length = track_length + + if closed: + if resolved_length is None or resolved_length <= 0.0: + raise PedPyValueError("A positive 'track_length' (or non-empty 'centerline') is required when closed=True.") + s_coords = np.mod(s_coords, resolved_length) + + return s_coords, resolved_length + + +def _compute_single_file_frame_cells( + s_sorted: npt.NDArray[np.float64], + closed: bool, + loop_length: Optional[float], + method: SingleFileMethod, +) -> Tuple[npt.NDArray[np.float64], npt.NDArray[np.float64], npt.NDArray[np.float64]]: + """Compute ``(spacing, left_edge, right_edge)`` for sorted 1D coordinates.""" + n_peds = len(s_sorted) + spacing = np.full(n_peds, np.nan, dtype=np.float64) + left_edge = np.full(n_peds, np.nan, dtype=np.float64) + right_edge = np.full(n_peds, np.nan, dtype=np.float64) + + if n_peds < 2: + return spacing, left_edge, right_edge + + if closed: + assert loop_length is not None + forward_gaps = np.empty(n_peds, dtype=np.float64) + forward_gaps[:-1] = s_sorted[1:] - s_sorted[:-1] + forward_gaps[-1] = (s_sorted[0] + loop_length) - s_sorted[-1] + backward_gaps = np.roll(forward_gaps, 1) + + if method == SingleFileMethod.HEADWAY: + spacing = forward_gaps + left_edge = s_sorted + right_edge = s_sorted + forward_gaps + else: + spacing = _HALF_FACTOR * (backward_gaps + forward_gaps) + left_edge = s_sorted - _HALF_FACTOR * backward_gaps + right_edge = s_sorted + _HALF_FACTOR * forward_gaps + return spacing, left_edge, right_edge + + if method == SingleFileMethod.HEADWAY: + spacing[:-1] = s_sorted[1:] - s_sorted[:-1] + left_edge[:-1] = s_sorted[:-1] + right_edge[:-1] = s_sorted[1:] + elif n_peds >= 3: + midpoints = _HALF_FACTOR * (s_sorted[:-1] + s_sorted[1:]) + left_edge[1:-1] = midpoints[:-1] + right_edge[1:-1] = midpoints[1:] + spacing[1:-1] = right_edge[1:-1] - left_edge[1:-1] + + return spacing, left_edge, right_edge + + +def _interval_overlap_length( + left_edge: npt.NDArray[np.float64], + right_edge: npt.NDArray[np.float64], + s_min: float, + s_max: float, + closed: bool, + loop_length: Optional[float], +) -> npt.NDArray[np.float64]: + """Compute 1D overlap of ``[left_edge, right_edge]`` with ``[s_min, s_max]``.""" + valid = np.isfinite(left_edge) & np.isfinite(right_edge) + overlap = np.zeros_like(left_edge, dtype=np.float64) + if not np.any(valid): + return overlap + + l_v = left_edge[valid] + r_v = right_edge[valid] + seg_overlap = np.maximum(0.0, np.minimum(r_v, s_max) - np.maximum(l_v, s_min)) + if closed and loop_length is not None: + seg_overlap += np.maximum(0.0, np.minimum(r_v + loop_length, s_max) - np.maximum(l_v + loop_length, s_min)) + seg_overlap += np.maximum(0.0, np.minimum(r_v - loop_length, s_max) - np.maximum(l_v - loop_length, s_min)) + overlap[valid] = seg_overlap + return overlap + + +def compute_single_file_density( + *, + traj_data: TrajectoryData, + centerline: Optional[shapely.LineString] = None, + axis: str = X_COL, + closed: bool = False, + track_length: Optional[float] = None, + method: SingleFileMethod = SingleFileMethod.VORONOI, + measurement_interval: Optional[Tuple[float, float]] = None, +) -> Union[pd.DataFrame, Tuple[pd.DataFrame, pd.DataFrame]]: + r"""Compute 1D individual (and optional interval) densities for single-file trajectories. + + Projects pedestrian positions onto a 1D coordinate :math:`s_k(t)` (either + arc length along ``centerline`` or coordinate ``axis``) and evaluates + individual 1D densities in :math:`1/\mathrm{m}`: + + - :attr:`SingleFileMethod.VORONOI`: 1D Voronoi cell width + :math:`d_k = (s_{k+1} - s_{k-1}) / 2` and :math:`\rho_k = 1 / d_k`. + - :attr:`SingleFileMethod.HEADWAY`: forward headway + :math:`h_k = s_{k+1} - s_k` and :math:`\rho_k = 1 / h_k`. + + When ``closed=True`` (e.g. oval or circular single-file tracks of + circumference ``track_length``), wrap-around neighbors are used so every + pedestrian receives a finite cell width summing to ``track_length``. + + Args: + traj_data (TrajectoryData): Trajectory data to analyze. + centerline (shapely.LineString, optional): Optional 1D reference path + onto which pedestrian positions are projected via arc length. + axis (str): Coordinate column (``"x"`` or ``"y"``) used when + ``centerline`` is ``None`` (default: ``"x"``). + closed (bool): Treat the 1D domain as periodic with circumference + ``track_length`` (default: ``False``). + track_length (float, optional): Periodic track circumference in meters + when ``closed=True`` (defaults to ``centerline.length`` when + ``centerline`` is provided). + method (SingleFileMethod): 1D cell definition (default: + ``SingleFileMethod.VORONOI``). + measurement_interval (Tuple[float, float], optional): Optional 1D + measurement section ``(s_min, s_max)``. When provided, returns a + 2-tuple ``(frame_density_df, individual_df)`` analogous to + :func:`compute_voronoi_density`. + + Returns: + DataFrame with columns ``id``, ``frame``, ``arc_length``, ``spacing``, + and ``density`` (in :math:`1/\mathrm{m}`) when ``measurement_interval`` + is ``None``; otherwise ``(frame_density_df, individual_df)``. + """ + _check_trajectory_data(traj_data) + if not isinstance(method, SingleFileMethod): + raise PedPyValueError(f"Unsupported single-file density method: {method!r}.") + if measurement_interval is not None and measurement_interval[1] <= measurement_interval[0]: + raise PedPyValueError("'measurement_interval' must satisfy s_max > s_min.") + + work_df = traj_data.data[[ID_COL, FRAME_COL, X_COL, Y_COL, POINT_COL]].copy() + work_df["_orig_order"] = np.arange(len(work_df)) + s_coords, resolved_length = _project_single_file_positions(work_df, centerline, axis, closed, track_length) + work_df["arc_length"] = s_coords + + per_frame_chunks: list[pd.DataFrame] = [] + frame_densities: dict[int, float] = {} + + for frame_val, group in work_df.groupby(FRAME_COL): + sorted_group = group.sort_values(by=["arc_length", ID_COL]).copy() + s_sorted = sorted_group["arc_length"].to_numpy(dtype=np.float64) + spacing, left_e, right_e = _compute_single_file_frame_cells(s_sorted, closed, resolved_length, method) + density = np.where( + np.isfinite(spacing) & (spacing > _MIN_SPACING_THRESHOLD), + np.divide(1.0, spacing, out=np.full_like(spacing, np.nan), where=spacing > _MIN_SPACING_THRESHOLD), + np.nan, + ) + sorted_group["spacing"] = spacing + sorted_group[DENSITY_COL] = density + per_frame_chunks.append(sorted_group) + + if measurement_interval is not None: + s_min, s_max = float(measurement_interval[0]), float(measurement_interval[1]) + interval_len = s_max - s_min + if method == SingleFileMethod.VORONOI: + overlaps = _interval_overlap_length(left_e, right_e, s_min, s_max, closed, resolved_length) + valid = (overlaps > 0.0) & np.isfinite(spacing) & (spacing > _MIN_SPACING_THRESHOLD) + frame_densities[int(frame_val)] = float(np.sum(overlaps[valid] / spacing[valid]) / interval_len) + else: + in_sec = (s_sorted >= s_min) & (s_sorted <= s_max) + frame_densities[int(frame_val)] = float(np.count_nonzero(in_sec) / interval_len) + + if per_frame_chunks: + combined = pd.concat(per_frame_chunks, ignore_index=True).sort_values("_orig_order") + else: + combined = pd.DataFrame(columns=[ID_COL, FRAME_COL, "arc_length", "spacing", DENSITY_COL]) + individual_df = combined[[ID_COL, FRAME_COL, "arc_length", "spacing", DENSITY_COL]].reset_index(drop=True) + + if measurement_interval is None: + return individual_df + + if traj_data.data.empty: + return pd.DataFrame(columns=[FRAME_COL, DENSITY_COL]), individual_df + + full_frames = list(range(int(traj_data.data[FRAME_COL].min()), int(traj_data.data[FRAME_COL].max()) + 1)) + frame_series = pd.Series(frame_densities, dtype=float).reindex(full_frames, fill_value=0.0) + frame_df = frame_series.reset_index() + frame_df.columns = [FRAME_COL, DENSITY_COL] + return frame_df, individual_df diff --git a/pedpy/methods/profile_calculator.py b/pedpy/methods/profile_calculator.py index e1ee2911..681ace78 100644 --- a/pedpy/methods/profile_calculator.py +++ b/pedpy/methods/profile_calculator.py @@ -259,6 +259,15 @@ def compute_profiles( # noqa: D417 density_profiles: list[npt.NDArray[np.float64]] = [] speed_profiles: list[npt.NDArray[np.float64]] = [] + active_indices: Optional[npt.NDArray[np.intp]] = None + active_cells: Optional[npt.NDArray[shapely.Polygon]] = None + cell_tree: Optional[shapely.STRtree] = None + if needs_intersection: + active_indices, cell_tree, active_cells = _prepare_active_grid_tree( + grid_cells=grid_cells, + walkable_area=walkable_area, + ) + for _, frame_data in data.groupby(FRAME_COL): # Precompute intersection once; shared by density and speed when both # need it, avoiding a redundant shapely intersection call per frame. @@ -267,6 +276,9 @@ def compute_profiles( # noqa: D417 grid_intersections_area_frame = _compute_frame_grid_intersection( frame_data=frame_data, grid_cells=grid_cells, + active_indices=active_indices, + cell_tree=cell_tree, + active_cells=active_cells, ) density = _compute_density_for_frame( @@ -395,12 +407,30 @@ def compute_density_profile( if density_method == DensityMethod.GAUSSIAN and gaussian_width is None: raise PedPyValueError("Computing a Gaussian density profile needs a parameter 'gaussian_width'.") + active_indices: Optional[npt.NDArray[np.intp]] = None + active_cells: Optional[npt.NDArray[shapely.Polygon]] = None + cell_tree: Optional[shapely.STRtree] = None + if density_method == DensityMethod.VORONOI: + active_indices, cell_tree, active_cells = _prepare_active_grid_tree( + grid_cells=grid_cells, + walkable_area=walkable_area, + ) + density_profiles = [] for _, frame_data in data_grouped_by_frame: + grid_intersections_area_frame = None + if density_method == DensityMethod.VORONOI: + grid_intersections_area_frame = _compute_frame_grid_intersection( + frame_data=frame_data, + grid_cells=grid_cells, + active_indices=active_indices, + cell_tree=cell_tree, + active_cells=active_cells, + ) density = _compute_density_for_frame( frame_data=frame_data, density_method=density_method, - grid_intersections_area_frame=None, + grid_intersections_area_frame=grid_intersections_area_frame, grid_cells=grid_cells, bounds=bounds, x_center=x_center, @@ -700,11 +730,23 @@ def compute_speed_profile( if speed_method == SpeedMethod.GAUSSIAN and gaussian_width is None: raise PedPyValueError("Computing a Gaussian speed profile needs a parameter 'gaussian_width'.") + needs_on_the_fly = grid_intersections_area is None and speed_method in ( + SpeedMethod.VORONOI, + SpeedMethod.ARITHMETIC, + ) + active_indices: Optional[npt.NDArray[np.intp]] = None + active_cells: Optional[npt.NDArray[shapely.Polygon]] = None + cell_tree: Optional[shapely.STRtree] = None + if needs_on_the_fly: + active_indices, cell_tree, active_cells = _prepare_active_grid_tree( + grid_cells=grid_cells, + walkable_area=walkable_area, + ) + speed_profiles = [] for frame, frame_data in data_grouped_by_frame: # Resolve the frame-level intersection from the global matrix when the - # caller pre-computed it; otherwise pass None and let the helper - # compute it on-the-fly. + # caller pre-computed it; otherwise compute using the pre-filtered STRtree. grid_intersections_area_frame = None if grid_intersections_area is not None and speed_method in ( SpeedMethod.VORONOI, @@ -714,6 +756,14 @@ def compute_speed_profile( :, data_grouped_by_frame.indices[frame], ] + elif needs_on_the_fly: + grid_intersections_area_frame = _compute_frame_grid_intersection( + frame_data=frame_data, + grid_cells=grid_cells, + active_indices=active_indices, + cell_tree=cell_tree, + active_cells=active_cells, + ) speed = _compute_speed_for_frame( frame_data=frame_data, @@ -1070,6 +1120,7 @@ def compute_grid_cell_polygon_intersection_area( *, data: pd.DataFrame, grid_cells: npt.NDArray[shapely.Polygon], + walkable_area: Optional[WalkableArea] = None, ) -> Tuple[ npt.NDArray[np.float64], pd.DataFrame, @@ -1100,6 +1151,8 @@ def compute_grid_cell_polygon_intersection_area( :func:`~method_utils.compute_individual_voronoi_polygons`) grid_cells: Grid cells used for computing the profiles, e.g., result from :func:`get_grid_cells` + walkable_area (WalkableArea, optional): If provided, grid cells outside + ``walkable_area`` are skipped prior to polygon intersection checks. Returns: Tuple containing first the grid cell-polygon intersection areas, and @@ -1112,6 +1165,7 @@ def compute_grid_cell_polygon_intersection_area( ) = _compute_grid_polygon_intersection( data=data, grid_cells=grid_cells, + walkable_area=walkable_area, ) return ( grid_intersections_area, @@ -1119,48 +1173,104 @@ def compute_grid_cell_polygon_intersection_area( ) +def _prepare_active_grid_tree( + *, + grid_cells: npt.NDArray[shapely.Polygon], + walkable_area: Optional[WalkableArea] = None, +) -> Tuple[npt.NDArray[np.intp], shapely.STRtree, npt.NDArray[shapely.Polygon]]: + """Filter grid cells overlapping ``walkable_area`` and build an ``STRtree``.""" + cells_array = np.asarray(grid_cells) + if walkable_area is not None: + poly = walkable_area.polygon + shapely.prepare(poly) + active_mask = shapely.intersects(poly, cells_array) & ~shapely.touches(poly, cells_array) + active_indices = np.flatnonzero(active_mask) + else: + active_indices = np.arange(len(cells_array), dtype=np.intp) + + active_cells = cells_array[active_indices] + return active_indices, shapely.STRtree(active_cells), active_cells + + def _compute_frame_grid_intersection( *, frame_data: pd.DataFrame, grid_cells: npt.NDArray[shapely.Polygon], + active_indices: Optional[npt.NDArray[np.intp]] = None, + cell_tree: Optional[shapely.STRtree] = None, + active_cells: Optional[npt.NDArray[shapely.Polygon]] = None, ) -> npt.NDArray[np.float64]: """Compute grid cell-polygon intersection areas for a single frame. + Uses a spatial index (:class:`shapely.STRtree`) over active grid cells so + cells outside ``walkable_area`` and non-overlapping cell-polygon pairs are + never intersected. + Args: frame_data: DataFrame for a single frame containing a 'polygon' column. grid_cells: Grid cells used for computing the profiles. + active_indices: Optional indices of ``grid_cells`` overlapping + ``walkable_area``. + cell_tree: Optional pre-built ``STRtree`` over ``active_cells``. + active_cells: Optional subset of ``grid_cells`` indexed by ``cell_tree``. Returns: Intersection areas with shape (num_grid_cells, num_pedestrians_in_frame). """ - return shapely.area( - shapely.intersection( - np.asarray(grid_cells)[:, np.newaxis], - np.asarray(frame_data.polygon)[np.newaxis, :], + cells_array = np.asarray(grid_cells) + ped_polys = np.asarray(frame_data.polygon) + result = np.zeros((len(cells_array), len(ped_polys)), dtype=np.float64) + if len(cells_array) == 0 or len(ped_polys) == 0: + return result + + if active_indices is None or cell_tree is None or active_cells is None: + active_indices, cell_tree, active_cells = _prepare_active_grid_tree(grid_cells=cells_array) + + if len(active_cells) == 0: + return result + + ped_idx, local_cell_idx = cell_tree.query(ped_polys, predicate="intersects") + if len(ped_idx) > 0: + areas = shapely.area( + shapely.intersection( + active_cells[local_cell_idx], + ped_polys[ped_idx], + ) ) - ) + result[active_indices[local_cell_idx], ped_idx] = areas + + return result def _compute_grid_polygon_intersection( *, data: pd.DataFrame, grid_cells: npt.NDArray[shapely.Polygon], + walkable_area: Optional[WalkableArea] = None, ) -> Tuple[npt.NDArray[np.float64], pd.DataFrame]: internal_data = data.copy(deep=True) internal_data = internal_data.sort_values(by=FRAME_COL) internal_data = internal_data.reset_index(drop=True) - # Process frame-by-frame to avoid materializing a - # (num_grid_cells x num_total_rows) array of Shapely geometries, - # which causes excessive memory usage for large datasets. - # Preallocate the output array and fill it frame-by-frame to avoid - # doubling peak memory usage from concatenation. num_rows = len(internal_data) - grid_intersections_area = np.empty((len(grid_cells), num_rows), dtype=np.float64) + grid_intersections_area = np.zeros((len(grid_cells), num_rows), dtype=np.float64) + if num_rows == 0 or len(grid_cells) == 0: + return grid_intersections_area, internal_data + + active_indices, cell_tree, active_cells = _prepare_active_grid_tree( + grid_cells=grid_cells, + walkable_area=walkable_area, + ) col_offset = 0 for _, frame_data in internal_data.groupby(FRAME_COL): - frame_result = _compute_frame_grid_intersection(frame_data=frame_data, grid_cells=grid_cells) + frame_result = _compute_frame_grid_intersection( + frame_data=frame_data, + grid_cells=grid_cells, + active_indices=active_indices, + cell_tree=cell_tree, + active_cells=active_cells, + ) frame_size = frame_result.shape[1] grid_intersections_area[:, col_offset : col_offset + frame_size] = frame_result col_offset += frame_size @@ -1249,19 +1359,17 @@ def get_grid_cells( -grid_size, ) - grid_cells = [] - for j in range(len(y_coords) - 1): - for i in range(len(x_coords) - 1): - grid_cell = shapely.box( - x_coords[i], - y_coords[j], - x_coords[i + 1], - y_coords[j + 1], - ) - grid_cells.append(grid_cell) + xx_min, yy_max = np.meshgrid(x_coords[:-1], y_coords[:-1]) + xx_max, yy_min = np.meshgrid(x_coords[1:], y_coords[1:]) + grid_cells = shapely.box( + xx_min.ravel(), + yy_min.ravel(), + xx_max.ravel(), + yy_max.ravel(), + ) return ( - np.array(grid_cells), + np.asarray(grid_cells), len(y_coords) - 1, len(x_coords) - 1, ) diff --git a/tests/unit_tests/methods/test_density_calculator.py b/tests/unit_tests/methods/test_density_calculator.py index 8b05b6b7..06557cf1 100644 --- a/tests/unit_tests/methods/test_density_calculator.py +++ b/tests/unit_tests/methods/test_density_calculator.py @@ -1,18 +1,20 @@ import numpy as np import pandas as pd import pytest -from shapely import Polygon +from shapely import LineString, Polygon from shapely.geometry import Point from tests.utils.utils import get_trajectory, get_trajectory_data from pedpy.column_identifier import * from pedpy.data.geometry import MeasurementArea, MeasurementLine from pedpy.data.trajectory_data import TrajectoryData -from pedpy.errors import InputError +from pedpy.errors import InputError, PedPyTypeError, PedPyValueError from pedpy.methods.density_calculator import ( + SingleFileMethod, _get_num_peds_per_frame, compute_classic_density, compute_line_density, + compute_single_file_density, ) @@ -148,3 +150,83 @@ def test_compute_line_density_invalid_species(example_data): measurement_line=line, species=invalid_species, ) + + +def test_compute_single_file_density_open_line_voronoi_and_headway(): + # Positions at x = 0, 2, 5, 9 -> interior Voronoi widths: (5-0)/2=2.5, (9-2)/2=3.5 + traj_df = pd.DataFrame( + { + ID_COL: [10, 20, 30, 40], + FRAME_COL: [0, 0, 0, 0], + X_COL: [0.0, 2.0, 5.0, 9.0], + Y_COL: [0.0, 0.0, 0.0, 0.0], + } + ) + traj = TrajectoryData(data=traj_df, frame_rate=10.0) + + voronoi_df = compute_single_file_density( + traj_data=traj, + axis=X_COL, + closed=False, + method=SingleFileMethod.VORONOI, + ) + assert np.isnan(voronoi_df.iloc[0][DENSITY_COL]) + assert np.isnan(voronoi_df.iloc[3][DENSITY_COL]) + assert np.isclose(voronoi_df.iloc[1]["spacing"], 2.5) + assert np.isclose(voronoi_df.iloc[1][DENSITY_COL], 1.0 / 2.5) + assert np.isclose(voronoi_df.iloc[2]["spacing"], 3.5) + assert np.isclose(voronoi_df.iloc[2][DENSITY_COL], 1.0 / 3.5) + + headway_df = compute_single_file_density( + traj_data=traj, + axis=X_COL, + closed=False, + method=SingleFileMethod.HEADWAY, + ) + assert np.allclose(headway_df.iloc[:3]["spacing"], [2.0, 3.0, 4.0]) + assert np.allclose(headway_df.iloc[:3][DENSITY_COL], [0.5, 1.0 / 3.0, 0.25]) + assert np.isnan(headway_df.iloc[3][DENSITY_COL]) + + +def test_compute_single_file_density_closed_loop_and_centerline_interval(): + # Closed square centerline of perimeter 16 m with 4 evenly spaced pedestrians (spacing = 4 m, density = 0.25 1/m) + ring = LineString([(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0), (0.0, 0.0)]) + traj_df = pd.DataFrame( + { + ID_COL: [1, 2, 3, 4], + FRAME_COL: [0, 0, 0, 0], + X_COL: [1.0, 4.0, 3.0, 0.0], + Y_COL: [0.0, 1.0, 4.0, 3.0], + } + ) + traj = TrajectoryData(data=traj_df, frame_rate=10.0) + + frame_df, ind_df = compute_single_file_density( + traj_data=traj, + centerline=ring, + closed=True, + method=SingleFileMethod.VORONOI, + measurement_interval=(0.0, 8.0), + ) + + assert np.isclose(ind_df["spacing"].sum(), 16.0) + assert np.allclose(ind_df["spacing"], 4.0) + assert np.allclose(ind_df[DENSITY_COL], 0.25) + assert np.allclose(frame_df[DENSITY_COL], [0.25]) + + +def test_compute_single_file_density_validation_errors(): + traj_df = pd.DataFrame({ID_COL: [1, 2], FRAME_COL: [0, 0], X_COL: [0.0, 1.0], Y_COL: [0.0, 0.0]}) + traj = TrajectoryData(data=traj_df, frame_rate=1.0) + + with pytest.raises(PedPyValueError, match="axis"): + compute_single_file_density(traj_data=traj, axis="z") + + with pytest.raises(PedPyValueError, match="track_length"): + compute_single_file_density(traj_data=traj, closed=True) + + with pytest.raises(PedPyTypeError, match="LineString"): + compute_single_file_density(traj_data=traj, centerline="not_a_line") # type: ignore[arg-type] + + with pytest.raises(PedPyValueError, match="measurement_interval"): + compute_single_file_density(traj_data=traj, measurement_interval=(5.0, 2.0)) diff --git a/tests/unit_tests/methods/test_profile_calculator.py b/tests/unit_tests/methods/test_profile_calculator.py index 0664a6ac..fd54de25 100644 --- a/tests/unit_tests/methods/test_profile_calculator.py +++ b/tests/unit_tests/methods/test_profile_calculator.py @@ -562,3 +562,69 @@ def test_speed_dispatch_calls_correct_impl_per_frame(mocker, speed_method, spy_t gaussian_width=1.0, # ignored unless GAUSSIAN ) assert spy.call_count == n_frames + + +def test_l_shaped_walkable_area_skips_outside_grid_cells(): + # L-shaped geometry inside 4x4 bounding box (area = 7 out of 16 cells) + l_shape = WalkableArea( + [ + (0.0, 0.0), + (4.0, 0.0), + (4.0, 1.0), + (1.0, 1.0), + (1.0, 4.0), + (0.0, 4.0), + ] + ) + grid_cells, rows, cols = get_grid_cells(walkable_area=l_shape, grid_size=1.0) + assert (rows, cols) == (4, 4) + + active_indices, _, active_cells = _profile_calc_module._prepare_active_grid_tree( + grid_cells=grid_cells, + walkable_area=l_shape, + ) + # Only the 7 cells overlapping the L-shape are indexed (9 outside cells skipped) + assert len(active_cells) == 7 + assert len(active_indices) == 7 + + data = pd.DataFrame( + { + ID_COL: [1, 2], + FRAME_COL: [0, 0], + "x": [0.5, 2.5], + "y": [2.5, 0.5], + "speed": [1.2, 1.8], + "polygon": [ + shapely.box(0.0, 1.0, 1.0, 4.0), + shapely.box(1.0, 0.0, 4.0, 1.0), + ], + } + ) + + density_profiles, speed_profiles = compute_profiles( + data=data, + walkable_area=l_shape, + grid_size=1.0, + density_method=DensityMethod.VORONOI, + speed_method=SpeedMethod.VORONOI, + ) + assert density_profiles[0].shape == (4, 4) + assert speed_profiles[0].shape == (4, 4) + + # Top-right 3x3 block (rows 0..2, cols 1..3) is completely outside the L-shape -> strictly 0.0 + np.testing.assert_allclose(density_profiles[0][:3, 1:], 0.0) + np.testing.assert_allclose(speed_profiles[0][:3, 1:], 0.0) + + # Compare against dense brute-force shapely intersection + dense_areas = shapely.area( + shapely.intersection( + np.asarray(grid_cells)[:, np.newaxis], + np.asarray(data["polygon"])[np.newaxis, :], + ) + ) + sparse_areas, _ = compute_grid_cell_polygon_intersection_area( + data=data, + grid_cells=grid_cells, + walkable_area=l_shape, + ) + np.testing.assert_allclose(sparse_areas, dense_areas) diff --git a/tests/unit_tests/methods/test_trajectory_data_type_check.py b/tests/unit_tests/methods/test_trajectory_data_type_check.py index 662d68ad..2fe3b70b 100644 --- a/tests/unit_tests/methods/test_trajectory_data_type_check.py +++ b/tests/unit_tests/methods/test_trajectory_data_type_check.py @@ -9,7 +9,10 @@ compute_mean_acceleration_per_frame, compute_voronoi_acceleration, ) -from pedpy.methods.density_calculator import compute_classic_density +from pedpy.methods.density_calculator import ( + compute_classic_density, + compute_single_file_density, +) from pedpy.methods.flow_calculator import compute_n_t from pedpy.methods.method_utils import ( compute_crossing_frames, @@ -69,6 +72,7 @@ pytest.param( compute_classic_density, dict(traj_data=_BAD, measurement_area=None), id="compute_classic_density" ), + pytest.param(compute_single_file_density, dict(traj_data=_BAD), id="compute_single_file_density"), pytest.param(compute_n_t, dict(traj_data=_BAD, measurement_line=None), id="compute_n_t"), pytest.param(is_trajectory_valid, dict(traj_data=_BAD, walkable_area=None), id="is_trajectory_valid"), pytest.param(get_invalid_trajectory, dict(traj_data=_BAD, walkable_area=None), id="get_invalid_trajectory"),