Add avoidance and intrusion number computation#279
Add avoidance and intrusion number computation#279schroedtert wants to merge 20 commits intomainfrom
Conversation
4ea73ee to
6bfa513
Compare
|
@chraibi can you take over and add the documentation for the functions? |
Due to Python operator precedence, v_i - v_j / ||v_i - v_j|| was computing v_i - (v_j / ||v_i - v_j||) instead of the intended (v_i - v_j) / ||v_i - v_j||. Split into two steps to make the order of operations explicit.
cos_alpha should be the dot product of the unit position difference (e_v) and the unit relative velocity (v_rel_hat). Previously, it was divided by (distance * v_rel_norm), which introduced a spurious 1/d factor since e_v was already a unit vector. Also rename v_rel_norm to delta_v_norm to clarify it is the magnitude of the actual relative velocity (used in the TTC denominator), not the norm of the unit vector.
Per Cordes2024 Eq. 1, the neighbor set N_i is restricted to agents within r_ij <= 3*r_soc. Without this filter, distant agents contribute small but accumulating spurious values to the intrusion number.
Also update the API docs section header from "Other" to "Dimensionless Numbers".
Module docstring with paper reference, and per-function docstrings with the mathematical definitions (Eqs. 1 and 2 from Cordes et al. 2024), parameter descriptions, and return types. Follows the existing rst/math style used in other PedPy modules.
- Intrusion: two-agent known distance, neighbor cutoff exclusion, three-agent sum, and MAX aggregation method - Avoidance: head-on collision with analytically known TTC, diverging agents with zero avoidance
Demonstrates compute_intrusion and compute_avoidance using the existing bottleneck demo data. Shows per-agent results and temporal evolution plots of the frame-averaged dimensionless numbers.
a5af5bb to
2e990de
Compare
- Use column constants (ID_COL, FRAME_COL, etc.) instead of string literals in _compute_individual_distances - Use inner join instead of outer join for self-merge (same DataFrame) - Make compute_individual_distances public (used across modules) - Guard division by zero: filter distance > l_min in intrusion, skip distance == 0 and delta_v_norm == 0 pairs in avoidance - Fix SettingWithCopyWarning: use .loc[] and .copy() - Simplify cos_alpha computation: use np.sum directly instead of converting to list and back - Compute v_rel_hat only for valid pairs (nonzero relative velocity) - Fix methods.rst section adornment level for Dimensionless Numbers
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| def compute_individual_distances(*, traj_data: TrajectoryData) -> pd.DataFrame: | ||
| """Compute pairwise distances between all pedestrians per frame. | ||
|
|
||
| Args: | ||
| traj_data: trajectory data | ||
|
|
||
| Returns: | ||
| DataFrame with columns 'id', 'frame', 'neighbor_id', and 'distance' | ||
| """ | ||
| neighbor_point_col = f"{POINT_COL}_{NEIGHBOR_ID_COL}" | ||
| points = traj_data.data[[ID_COL, FRAME_COL, POINT_COL]] | ||
| neighbor_points = points.rename( | ||
| columns={ | ||
| ID_COL: NEIGHBOR_ID_COL, | ||
| POINT_COL: neighbor_point_col, | ||
| } | ||
| ) | ||
| matrix = points.merge( | ||
| neighbor_points, | ||
| how="inner", | ||
| on=FRAME_COL, | ||
| ) | ||
| matrix = matrix[matrix[ID_COL] != matrix[NEIGHBOR_ID_COL]] | ||
| matrix[DISTANCE_COL] = np.linalg.norm( | ||
| shapely.get_coordinates(matrix[POINT_COL]) - shapely.get_coordinates(matrix[neighbor_point_col]), | ||
| axis=1, | ||
| ) | ||
|
|
||
| matrix = matrix.drop(columns=[POINT_COL, neighbor_point_col]) | ||
| return matrix.reset_index(drop=True) |
There was a problem hiding this comment.
compute_individual_distances builds a full Cartesian product of pedestrians per frame via merge, which is O(n²) rows and can become prohibitively slow/memory-intensive for typical crowd sizes. Consider adding an optional max-distance/cutoff parameter (or a separate compute_individual_distances_within_radius) and using a spatial index (e.g., Shapely STRtree.query/query_nearest) to only materialize pairs that can actually interact, rather than all pairs.
| def compute_individual_distances(*, traj_data: TrajectoryData) -> pd.DataFrame: | |
| """Compute pairwise distances between all pedestrians per frame. | |
| Args: | |
| traj_data: trajectory data | |
| Returns: | |
| DataFrame with columns 'id', 'frame', 'neighbor_id', and 'distance' | |
| """ | |
| neighbor_point_col = f"{POINT_COL}_{NEIGHBOR_ID_COL}" | |
| points = traj_data.data[[ID_COL, FRAME_COL, POINT_COL]] | |
| neighbor_points = points.rename( | |
| columns={ | |
| ID_COL: NEIGHBOR_ID_COL, | |
| POINT_COL: neighbor_point_col, | |
| } | |
| ) | |
| matrix = points.merge( | |
| neighbor_points, | |
| how="inner", | |
| on=FRAME_COL, | |
| ) | |
| matrix = matrix[matrix[ID_COL] != matrix[NEIGHBOR_ID_COL]] | |
| matrix[DISTANCE_COL] = np.linalg.norm( | |
| shapely.get_coordinates(matrix[POINT_COL]) - shapely.get_coordinates(matrix[neighbor_point_col]), | |
| axis=1, | |
| ) | |
| matrix = matrix.drop(columns=[POINT_COL, neighbor_point_col]) | |
| return matrix.reset_index(drop=True) | |
| def compute_individual_distances( | |
| *, | |
| traj_data: TrajectoryData, | |
| max_distance: Optional[float] = None, | |
| ) -> pd.DataFrame: | |
| """Compute pairwise distances between pedestrians per frame. | |
| Args: | |
| traj_data: trajectory data | |
| max_distance: optional cutoff radius. If provided, only pairs whose | |
| distance is smaller than or equal to this value are returned. | |
| Returns: | |
| DataFrame with columns 'id', 'frame', 'neighbor_id', and 'distance' | |
| """ | |
| if max_distance is not None and max_distance < 0: | |
| raise PedPyValueError("max_distance needs to be greater than or equal to 0.") | |
| records = [] | |
| points = traj_data.data[[ID_COL, FRAME_COL, POINT_COL]] | |
| for frame, frame_points in points.groupby(FRAME_COL, sort=False): | |
| frame_points = frame_points.reset_index(drop=True) | |
| ids = frame_points[ID_COL].to_numpy() | |
| geometries = frame_points[POINT_COL].to_list() | |
| coordinates = shapely.get_coordinates(geometries) | |
| if len(frame_points) < 2: | |
| continue | |
| if max_distance is None: | |
| for src_idx, dst_idx in itertools.permutations(range(len(frame_points)), 2): | |
| distance = float( | |
| np.linalg.norm(coordinates[src_idx] - coordinates[dst_idx]) | |
| ) | |
| records.append( | |
| { | |
| ID_COL: ids[src_idx], | |
| FRAME_COL: frame, | |
| NEIGHBOR_ID_COL: ids[dst_idx], | |
| DISTANCE_COL: distance, | |
| } | |
| ) | |
| continue | |
| tree = shapely.STRtree(geometries) | |
| geometry_to_index = {id(geometry): idx for idx, geometry in enumerate(geometries)} | |
| for src_idx, geometry in enumerate(geometries): | |
| candidate_indices = { | |
| geometry_to_index[id(candidate)] | |
| for candidate in tree.query(geometry.buffer(max_distance)) | |
| } | |
| candidate_indices.discard(src_idx) | |
| for dst_idx in candidate_indices: | |
| distance = float( | |
| np.linalg.norm(coordinates[src_idx] - coordinates[dst_idx]) | |
| ) | |
| if distance <= max_distance: | |
| records.append( | |
| { | |
| ID_COL: ids[src_idx], | |
| FRAME_COL: frame, | |
| NEIGHBOR_ID_COL: ids[dst_idx], | |
| DISTANCE_COL: distance, | |
| } | |
| ) | |
| return pd.DataFrame.from_records( | |
| records, | |
| columns=[ID_COL, FRAME_COL, NEIGHBOR_ID_COL, DISTANCE_COL], | |
| ).reset_index(drop=True) |
- Change radius default from 0.2 to 0.4 to match paper (ℓ_soc = 0.4m) - Export INTRUSION_COL and AVOIDANCE_COL from pedpy.__init__ - Document that agents at exactly l_min distance are excluded
Codecov Report✅ All modified and coverable lines are covered by tests. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
No description provided.