Skip to content

Add avoidance and intrusion number computation#279

Open
schroedtert wants to merge 20 commits intomainfrom
avoidance-intrusion
Open

Add avoidance and intrusion number computation#279
schroedtert wants to merge 20 commits intomainfrom
avoidance-intrusion

Conversation

@schroedtert
Copy link
Copy Markdown
Collaborator

No description provided.

@schroedtert schroedtert force-pushed the avoidance-intrusion branch from 4ea73ee to 6bfa513 Compare March 25, 2024 14:10
@schroedtert
Copy link
Copy Markdown
Collaborator Author

@chraibi can you take over and add the documentation for the functions?

@schroedtert schroedtert added this to the v1.4.0 milestone Feb 22, 2025
@chraibi chraibi removed this from the v1.4.0 milestone Sep 1, 2025
schroedtert and others added 13 commits April 7, 2026 20:41
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.
@chraibi chraibi force-pushed the avoidance-intrusion branch from a5af5bb to 2e990de Compare April 7, 2026 18:44
@chraibi chraibi marked this pull request as ready for review April 7, 2026 19:52
Copilot AI review requested due to automatic review settings April 7, 2026 19:52

This comment was marked as outdated.

@chraibi chraibi requested review from ThoChat April 7, 2026 20:07
- 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
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +1300 to +1329
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)
Copy link

Copilot AI Apr 9, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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)

Copilot uses AI. Check for mistakes.
- 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
Copy link
Copy Markdown

codecov bot commented Apr 9, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 86.52%. Comparing base (7299724) to head (6bf6cda).
⚠️ Report is 3 commits behind head on main.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants