Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions notebooks/user_guide.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -1985,6 +1985,38 @@
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### Filling border frames\n",
"\n",
"When using `SpeedCalculation.BORDER_EXCLUDE` or `SpeedCalculation.BORDER_ADAPTIVE`, border frames where the calculation window is incomplete are dropped by default (`BorderFillMethod.NONE`).\n",
"To keep a 1:1 row alignment with `traj.data`, pass `border_fill=BorderFillMethod.NAN` (inserts `NaN` at dropped border frames) or `border_fill=BorderFillMethod.LAST_VALUE` (forward-/backward-fills from the nearest valid value of the same pedestrian).\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from pedpy import BorderFillMethod\n",
"\n",
"individual_speed_nan = compute_individual_speed(\n",
" traj_data=traj,\n",
" frame_step=frame_step,\n",
" speed_calculation=SpeedCalculation.BORDER_EXCLUDE,\n",
" border_fill=BorderFillMethod.NAN,\n",
")\n",
"individual_speed_last = compute_individual_speed(\n",
" traj_data=traj,\n",
" frame_step=frame_step,\n",
" speed_calculation=SpeedCalculation.BORDER_EXCLUDE,\n",
" border_fill=BorderFillMethod.LAST_VALUE,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
Expand Down Expand Up @@ -2782,6 +2814,27 @@
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Just like `compute_individual_speed`, `compute_individual_acceleration` accepts `border_fill` (`BorderFillMethod.NAN` or `BorderFillMethod.LAST_VALUE`) so the output DataFrame preserves the full length of `traj.data`:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"individual_acceleration_last = compute_individual_acceleration(\n",
" traj_data=traj,\n",
" frame_step=frame_step,\n",
" acceleration_calculation=AccelerationCalculation.BORDER_EXCLUDE,\n",
" border_fill=BorderFillMethod.LAST_VALUE,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
Expand Down
2 changes: 2 additions & 0 deletions pedpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@
)
from .methods.method_utils import (
AccelerationCalculation,
BorderFillMethod,
Cutoff,
SpeedCalculation,
compute_frame_range_in_area,
Expand Down Expand Up @@ -205,6 +206,7 @@
"compute_speed_profile",
"get_grid_cells",
"SpeedCalculation",
"BorderFillMethod",
"compute_individual_speed",
"compute_line_speed",
"compute_mean_speed_per_frame",
Expand Down
27 changes: 25 additions & 2 deletions pedpy/methods/acceleration_calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@
from pedpy.column_identifier import ACC_COL, A_X_COL, A_Y_COL, FRAME_COL, ID_COL
from pedpy.data.geometry import MeasurementArea
from pedpy.data.trajectory_data import TrajectoryData
from pedpy.errors import AccelerationError
from pedpy.errors import AccelerationError, PedPyValueError
from pedpy.methods.method_utils import (
AccelerationCalculation,
BorderFillMethod,
_apply_border_fill,
_check_trajectory_data,
_compute_individual_movement_acceleration,
)
Expand All @@ -25,6 +27,7 @@ def compute_individual_acceleration(
movement_direction: Optional[npt.NDArray[np.float64]] = None,
compute_acceleration_components: bool = False,
acceleration_calculation: AccelerationCalculation = AccelerationCalculation.BORDER_EXCLUDE,
border_fill: BorderFillMethod = BorderFillMethod.NONE,
) -> pd.DataFrame:
r"""Compute the individual acceleration for each pedestrian.

Expand Down Expand Up @@ -97,6 +100,16 @@ def compute_individual_acceleration(
If :code:`compute_acceleration_components` is `True` also
:math:`\Delta\bar{X}` is returned.

**Filling border frames:**

When border frames cannot be computed (e.g. with
:attr:`~method_utils.AccelerationCalculation.BORDER_EXCLUDE`), they are
dropped by default (:attr:`~method_utils.BorderFillMethod.NONE`). Setting
``border_fill`` to :attr:`~method_utils.BorderFillMethod.NAN` or
:attr:`~method_utils.BorderFillMethod.LAST_VALUE` preserves a 1:1 row
alignment with ``traj_data.data`` by inserting ``NaN`` or forward-/backward-
filling from the nearest valid value of the same pedestrian.

Args:
traj_data (TrajectoryData): trajectory data
frame_step (int): gives the size of time interval for calculating the
Expand All @@ -109,13 +122,19 @@ def compute_individual_acceleration(
acceleration_calculation (method_utils.AccelerationCalculation): method
used to compute the acceleration at the borders of the individual
trajectories
border_fill (method_utils.BorderFillMethod): strategy used to fill
dropped border frames so the output has the same length as
``traj_data.data`` (default: ``BorderFillMethod.NONE``)

Returns:
DataFrame containing the columns 'id', 'frame', and 'acceleration' in
:math:`m/s^2`, 'a_x' and 'a_y' with the acceleration components
in x and y direction if :code:`compute_acceleration_components` is True
"""
_check_trajectory_data(traj_data)
if not isinstance(border_fill, BorderFillMethod):
raise PedPyValueError(f"border fill method not accepted: {border_fill!r}")

df_movement = _compute_individual_movement_acceleration(
traj_data=traj_data,
frame_step=frame_step,
Expand All @@ -129,7 +148,11 @@ def compute_individual_acceleration(
compute_acceleration_components=compute_acceleration_components,
)

return df_acceleration
return _apply_border_fill(
result_df=df_acceleration,
traj_data=traj_data,
border_fill=border_fill,
)


def compute_mean_acceleration_per_frame(
Expand Down
60 changes: 60 additions & 0 deletions pedpy/methods/method_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,22 @@ class AccelerationCalculation(Enum): # pylint: disable=too-few-public-methods
BORDER_EXCLUDE = auto()


class BorderFillMethod(Enum): # pylint: disable=too-few-public-methods
"""Strategy used to fill dropped border frames in individual calculations.

Attributes:
NONE: Drop border frames where the calculation window is incomplete
(default).
NAN: Keep border frames and fill computed columns with ``NaN``.
LAST_VALUE: Keep border frames and forward-/backward-fill computed
columns from the nearest valid value of the same pedestrian.
"""

NONE = auto()
NAN = auto()
LAST_VALUE = auto()


class DataValidationStatus(Enum): # pylint: disable=too-few-public-methods
"""Identifies the result of a return value."""

Expand Down Expand Up @@ -1044,6 +1060,50 @@ def _compute_movement_acceleration_exclude_border(
].dropna()


def _apply_border_fill(
*,
result_df: pd.DataFrame,
traj_data: TrajectoryData,
border_fill: BorderFillMethod,
) -> pd.DataFrame:
"""Align per-frame individual results to ``traj_data`` using ``border_fill``.

Args:
result_df (pd.DataFrame): Computed per-frame individual DataFrame
containing ``ID_COL``, ``FRAME_COL``, and value columns.
traj_data (TrajectoryData): Input trajectory data defining the full
``(id, frame)`` sequence and row order.
border_fill (BorderFillMethod): Strategy for filling missing border
frames.

Returns:
DataFrame aligned to ``traj_data.data`` when ``border_fill`` is not
``BorderFillMethod.NONE``, otherwise ``result_df`` unchanged.
"""
if not isinstance(border_fill, BorderFillMethod):
raise PedPyValueError(f"border fill method not accepted: {border_fill!r}")

if border_fill == BorderFillMethod.NONE:
return result_df

value_cols = [col for col in result_df.columns if col not in (ID_COL, FRAME_COL)]
order_col = "_pedpy_row_order"

base_df = traj_data.data[[ID_COL, FRAME_COL]].copy()
base_df[order_col] = np.arange(len(base_df))

merged = base_df.merge(result_df, on=[ID_COL, FRAME_COL], how="left")

if border_fill == BorderFillMethod.LAST_VALUE and not merged.empty and value_cols:
merged = merged.sort_values(by=[ID_COL, FRAME_COL])
merged[value_cols] = merged.groupby(ID_COL)[value_cols].ffill()
merged[value_cols] = merged.groupby(ID_COL)[value_cols].bfill()

merged = merged.sort_values(by=order_col).drop(columns=[order_col])
merged.index = traj_data.data.index
return merged[[ID_COL, FRAME_COL, *value_cols]]


def _get_continuous_parts_in_area(*, traj_data: TrajectoryData, measurement_area: MeasurementArea) -> pd.DataFrame:
"""Compute the time-continuous parts of each pedestrian in the area.

Expand Down
31 changes: 30 additions & 1 deletion pedpy/methods/speed_calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@
)
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 (
BorderFillMethod,
DataValidationStatus,
SpeedCalculation,
_apply_border_fill,
_apply_lambda_for_intersecting_frames,
_check_trajectory_data,
_compute_individual_movement,
Expand All @@ -40,6 +42,7 @@ def compute_individual_speed(
movement_direction: Optional[npt.NDArray[np.float64]] = None,
compute_velocity: bool = False,
speed_calculation: SpeedCalculation = SpeedCalculation.BORDER_EXCLUDE,
border_fill: BorderFillMethod = BorderFillMethod.NONE,
) -> pd.DataFrame:
r"""Compute the individual speed for each pedestrian.

Expand Down Expand Up @@ -167,6 +170,19 @@ def compute_individual_speed(

If :code:`compute_velocity` is `True` also :math:`\bar{X}` is returned.

**Filling border frames:**

When using :attr:`~method_utils.SpeedCalculation.BORDER_EXCLUDE` or
:attr:`~method_utils.SpeedCalculation.BORDER_ADAPTIVE`, border frames where
the window cannot be formed are dropped by default
(:attr:`~method_utils.BorderFillMethod.NONE`). Setting ``border_fill`` to
:attr:`~method_utils.BorderFillMethod.NAN` or
:attr:`~method_utils.BorderFillMethod.LAST_VALUE` preserves a 1:1 row
alignment with ``traj_data.data`` by inserting ``NaN`` or forward-/backward-
filling from the nearest valid value of the same pedestrian. ``border_fill``
has no effect when :attr:`~method_utils.SpeedCalculation.BORDER_SINGLE_SIDED`
is used.

Args:
traj_data (TrajectoryData): trajectory data
frame_step (int): gives the size of time interval for calculating the
Expand All @@ -177,13 +193,19 @@ def compute_individual_speed(
compute_velocity (bool): compute the x and y components of the velocity
speed_calculation (method_utils.SpeedCalculation): method used to
compute the speed at the borders of the individual trajectories
border_fill (method_utils.BorderFillMethod): strategy used to fill
dropped border frames so the output has the same length as
``traj_data.data`` (default: ``BorderFillMethod.NONE``)

Returns:
DataFrame containing the columns 'id', 'frame', and 'speed' in m/s,
'v_x' and 'v_y' with the speed components in x and y direction if
:code:`compute_velocity` is True
"""
_check_trajectory_data(traj_data)
if not isinstance(border_fill, BorderFillMethod):
raise PedPyValueError(f"border fill method not accepted: {border_fill!r}")

df_movement = _compute_individual_movement(
traj_data=traj_data,
frame_step=frame_step,
Expand All @@ -196,6 +218,13 @@ def compute_individual_speed(
compute_velocity=compute_velocity,
)

if speed_calculation != SpeedCalculation.BORDER_SINGLE_SIDED:
df_speed = _apply_border_fill(
result_df=df_speed,
traj_data=traj_data,
border_fill=border_fill,
)

return df_speed


Expand Down
22 changes: 12 additions & 10 deletions pedpy/plotting/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -631,16 +631,18 @@ def _plot_violin_xy(
y_label = kwargs.pop("y_label", "")

axes.set_title(title)
violin_parts = axes.violinplot(
data,
showmeans=True,
showextrema=True,
showmedians=True,
**kwargs,
)
for parts in violin_parts["bodies"]: # type: ignore[attr-defined]
parts.set_facecolor(facecolor)
parts.set_edgecolor(edgecolor)
clean_data = data.dropna()
if not clean_data.empty:
violin_parts = axes.violinplot(
clean_data,
showmeans=True,
showextrema=True,
showmedians=True,
**kwargs,
)
for parts in violin_parts["bodies"]: # type: ignore[attr-defined]
parts.set_facecolor(facecolor)
parts.set_edgecolor(edgecolor)

axes.set_xlabel(x_label)
axes.set_ylabel(y_label)
Expand Down
Loading
Loading