diff --git a/notebooks/user_guide.ipynb b/notebooks/user_guide.ipynb index c2d77b5d..1f237ed1 100644 --- a/notebooks/user_guide.ipynb +++ b/notebooks/user_guide.ipynb @@ -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": {}, @@ -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": {}, diff --git a/pedpy/__init__.py b/pedpy/__init__.py index 6dd82288..eb091c7c 100644 --- a/pedpy/__init__.py +++ b/pedpy/__init__.py @@ -93,6 +93,7 @@ ) from .methods.method_utils import ( AccelerationCalculation, + BorderFillMethod, Cutoff, SpeedCalculation, compute_frame_range_in_area, @@ -205,6 +206,7 @@ "compute_speed_profile", "get_grid_cells", "SpeedCalculation", + "BorderFillMethod", "compute_individual_speed", "compute_line_speed", "compute_mean_speed_per_frame", diff --git a/pedpy/methods/acceleration_calculator.py b/pedpy/methods/acceleration_calculator.py index fee9ed47..18a16349 100644 --- a/pedpy/methods/acceleration_calculator.py +++ b/pedpy/methods/acceleration_calculator.py @@ -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, ) @@ -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. @@ -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 @@ -109,6 +122,9 @@ 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 @@ -116,6 +132,9 @@ def compute_individual_acceleration( 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, @@ -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( diff --git a/pedpy/methods/method_utils.py b/pedpy/methods/method_utils.py index 76bb0464..87135e8e 100644 --- a/pedpy/methods/method_utils.py +++ b/pedpy/methods/method_utils.py @@ -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.""" @@ -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. diff --git a/pedpy/methods/speed_calculator.py b/pedpy/methods/speed_calculator.py index 4f269360..9876e28a 100644 --- a/pedpy/methods/speed_calculator.py +++ b/pedpy/methods/speed_calculator.py @@ -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, @@ -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. @@ -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 @@ -177,6 +193,9 @@ 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, @@ -184,6 +203,9 @@ def compute_individual_speed( :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, @@ -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 diff --git a/pedpy/plotting/plotting.py b/pedpy/plotting/plotting.py index 78539c7d..a19f158c 100644 --- a/pedpy/plotting/plotting.py +++ b/pedpy/plotting/plotting.py @@ -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) diff --git a/tests/unit_tests/methods/test_border_fill.py b/tests/unit_tests/methods/test_border_fill.py new file mode 100644 index 00000000..715373dd --- /dev/null +++ b/tests/unit_tests/methods/test_border_fill.py @@ -0,0 +1,327 @@ +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import pytest +from tests.utils.utils import get_trajectory + +from pedpy import ( + ACC_COL, + A_X_COL, + A_Y_COL, + FRAME_COL, + ID_COL, + SPEED_COL, + V_X_COL, + V_Y_COL, + X_COL, + Y_COL, + AccelerationCalculation, + BorderFillMethod, + MeasurementLine, + PedPyValueError, + SpeedCalculation, + TrajectoryData, + WalkableArea, + compute_individual_acceleration, + compute_individual_speed, + compute_individual_voronoi_polygons, + compute_time_distance_line, + plot_acceleration, + plot_speed, + plot_speed_distribution, + plot_time_distance, + plot_voronoi_cells, +) + + +def _make_linear_trajectory(number_frames: int = 12, frame_rate: float = 10.0) -> TrajectoryData: + return TrajectoryData( + data=get_trajectory( + shape=[2, 1], + number_frames=number_frames, + start_position=np.array([0.0, 0.0]), + movement_direction=np.array([0.2, 0.0]), + ped_distance=1.0, + ), + frame_rate=frame_rate, + ) + + +@pytest.mark.parametrize( + "speed_calculation", + [SpeedCalculation.BORDER_EXCLUDE, SpeedCalculation.BORDER_ADAPTIVE], +) +def test_individual_speed_border_fill_default_unchanged(speed_calculation: SpeedCalculation): + traj_data = _make_linear_trajectory(number_frames=12) + speed_default = compute_individual_speed( + traj_data=traj_data, + frame_step=3, + compute_velocity=True, + speed_calculation=speed_calculation, + ) + speed_none = compute_individual_speed( + traj_data=traj_data, + frame_step=3, + compute_velocity=True, + speed_calculation=speed_calculation, + border_fill=BorderFillMethod.NONE, + ) + + pd.testing.assert_frame_equal(speed_default, speed_none) + assert len(speed_default) < len(traj_data.data) + + +@pytest.mark.parametrize( + "speed_calculation", + [SpeedCalculation.BORDER_EXCLUDE, SpeedCalculation.BORDER_ADAPTIVE], +) +def test_individual_speed_border_fill_nan(speed_calculation: SpeedCalculation): + traj_data = _make_linear_trajectory(number_frames=12) + speed_truncated = compute_individual_speed( + traj_data=traj_data, + frame_step=3, + compute_velocity=True, + speed_calculation=speed_calculation, + ) + speed_nan = compute_individual_speed( + traj_data=traj_data, + frame_step=3, + compute_velocity=True, + speed_calculation=speed_calculation, + border_fill=BorderFillMethod.NAN, + ) + + assert len(speed_nan) == len(traj_data.data) + pd.testing.assert_frame_equal( + speed_nan[[ID_COL, FRAME_COL]].reset_index(drop=True), + traj_data.data[[ID_COL, FRAME_COL]].reset_index(drop=True), + ) + + valid_rows = speed_nan.dropna().reset_index(drop=True) + pd.testing.assert_frame_equal( + valid_rows.sort_values([ID_COL, FRAME_COL]).reset_index(drop=True), + speed_truncated.sort_values([ID_COL, FRAME_COL]).reset_index(drop=True), + ) + + # First and last frame of each pedestrian must be NaN + for _, ped_df in speed_nan.groupby(ID_COL): + ped_sorted = ped_df.sort_values(FRAME_COL) + assert np.isnan(ped_sorted.iloc[0][SPEED_COL]) + assert np.isnan(ped_sorted.iloc[-1][SPEED_COL]) + assert np.isnan(ped_sorted.iloc[0][V_X_COL]) + assert np.isnan(ped_sorted.iloc[-1][V_Y_COL]) + + +@pytest.mark.parametrize( + "speed_calculation", + [SpeedCalculation.BORDER_EXCLUDE, SpeedCalculation.BORDER_ADAPTIVE], +) +def test_individual_speed_border_fill_last_value(speed_calculation: SpeedCalculation): + # Accelerating single pedestrian so start and end valid speeds differ + frames = np.arange(10) + traj_df = pd.DataFrame( + { + ID_COL: [1] * 10, + FRAME_COL: frames, + X_COL: 0.1 * frames**2, + Y_COL: np.zeros_like(frames, dtype=float), + } + ) + traj_data = TrajectoryData(data=traj_df, frame_rate=10.0) + + speed_none = compute_individual_speed( + traj_data=traj_data, + frame_step=2, + compute_velocity=True, + speed_calculation=speed_calculation, + ).sort_values(FRAME_COL) + speed_last = compute_individual_speed( + traj_data=traj_data, + frame_step=2, + compute_velocity=True, + speed_calculation=speed_calculation, + border_fill=BorderFillMethod.LAST_VALUE, + ).sort_values(FRAME_COL) + + assert len(speed_last) == len(traj_data.data) + assert not speed_last[[SPEED_COL, V_X_COL, V_Y_COL]].isna().any().any() + + first_valid_frame = int(speed_none[FRAME_COL].min()) + last_valid_frame = int(speed_none[FRAME_COL].max()) + first_valid_speed = float(speed_none.iloc[0][SPEED_COL]) + last_valid_speed = float(speed_none.iloc[-1][SPEED_COL]) + + leading = speed_last[speed_last[FRAME_COL] < first_valid_frame][SPEED_COL] + trailing = speed_last[speed_last[FRAME_COL] > last_valid_frame][SPEED_COL] + assert np.allclose(leading, first_valid_speed) + assert np.allclose(trailing, last_valid_speed) + + +@pytest.mark.parametrize( + "border_fill", + [BorderFillMethod.NONE, BorderFillMethod.NAN, BorderFillMethod.LAST_VALUE], +) +def test_individual_speed_single_sided_ignores_border_fill(border_fill: BorderFillMethod): + # Include a 1-frame pedestrian (whose single-sided speed is NaN) to verify + # border_fill has strictly zero effect when BORDER_SINGLE_SIDED is selected. + traj_df = pd.DataFrame( + { + ID_COL: [1, 1, 1, 1, 2], + FRAME_COL: [0, 1, 2, 3, 0], + X_COL: [0.0, 0.5, 1.0, 1.5, 2.0], + Y_COL: [0.0, 0.0, 0.0, 0.0, 1.0], + } + ) + traj_data = TrajectoryData(data=traj_df, frame_rate=10.0) + + baseline = compute_individual_speed( + traj_data=traj_data, + frame_step=2, + speed_calculation=SpeedCalculation.BORDER_SINGLE_SIDED, + ) + with_fill = compute_individual_speed( + traj_data=traj_data, + frame_step=2, + speed_calculation=SpeedCalculation.BORDER_SINGLE_SIDED, + border_fill=border_fill, + ) + + pd.testing.assert_frame_equal(baseline, with_fill) + + +def test_individual_acceleration_border_fill_strategies(): + frames = np.arange(12) + traj_df = pd.DataFrame( + { + ID_COL: [1] * 12, + FRAME_COL: frames, + X_COL: 0.02 * frames**3, + Y_COL: np.zeros_like(frames, dtype=float), + } + ) + traj_data = TrajectoryData(data=traj_df, frame_rate=10.0) + + acc_default = compute_individual_acceleration( + traj_data=traj_data, + frame_step=2, + compute_acceleration_components=True, + acceleration_calculation=AccelerationCalculation.BORDER_EXCLUDE, + ) + acc_nan = compute_individual_acceleration( + traj_data=traj_data, + frame_step=2, + compute_acceleration_components=True, + acceleration_calculation=AccelerationCalculation.BORDER_EXCLUDE, + border_fill=BorderFillMethod.NAN, + ) + acc_last = compute_individual_acceleration( + traj_data=traj_data, + frame_step=2, + compute_acceleration_components=True, + acceleration_calculation=AccelerationCalculation.BORDER_EXCLUDE, + border_fill=BorderFillMethod.LAST_VALUE, + ) + + assert len(acc_default) == 8 + assert len(acc_nan) == len(traj_data.data) + assert len(acc_last) == len(traj_data.data) + + # First 2 * frame_step = 4 frames are dropped in acceleration calculation + assert acc_nan.iloc[:4][ACC_COL].isna().all() + assert acc_nan.iloc[:4][A_X_COL].isna().all() + assert acc_nan.iloc[:4][A_Y_COL].isna().all() + pd.testing.assert_frame_equal( + acc_nan.iloc[4:].reset_index(drop=True), + acc_default.reset_index(drop=True), + ) + + assert not acc_last[[ACC_COL, A_X_COL, A_Y_COL]].isna().any().any() + assert np.allclose(acc_last.iloc[:4][ACC_COL], acc_default.iloc[0][ACC_COL]) + + +def test_border_fill_last_value_does_not_leak_across_pedestrians(): + # Ped 2 has only 2 frames (too short for frame_step=2) between Ped 1 and Ped 3 + traj_df = pd.DataFrame( + { + ID_COL: [1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 3], + FRAME_COL: [0, 1, 2, 3, 4, 0, 1, 0, 1, 2, 3, 4], + X_COL: [0.0, 1.0, 2.0, 3.0, 4.0, 0.0, 0.0, 0.0, 2.0, 4.0, 6.0, 8.0], + Y_COL: [0.0] * 12, + } + ) + # Shuffle row order to also verify 1:1 row order preservation + shuffled_df = traj_df.iloc[[5, 0, 7, 1, 6, 8, 2, 9, 3, 10, 4, 11]].reset_index(drop=True) + traj_data = TrajectoryData(data=shuffled_df, frame_rate=1.0) + + speed_last = compute_individual_speed( + traj_data=traj_data, + frame_step=2, + speed_calculation=SpeedCalculation.BORDER_EXCLUDE, + border_fill=BorderFillMethod.LAST_VALUE, + ) + + pd.testing.assert_frame_equal( + speed_last[[ID_COL, FRAME_COL]], + traj_data.data[[ID_COL, FRAME_COL]], + ) + assert np.allclose(speed_last[speed_last[ID_COL] == 1][SPEED_COL], 1.0) + assert np.allclose(speed_last[speed_last[ID_COL] == 3][SPEED_COL], 2.0) + assert speed_last[speed_last[ID_COL] == 2][SPEED_COL].isna().all() + + +def test_invalid_border_fill_raises_value_error(): + traj_data = _make_linear_trajectory(number_frames=6) + with pytest.raises(PedPyValueError, match="border fill method"): + compute_individual_speed( + traj_data=traj_data, + frame_step=1, + border_fill="nan", # type: ignore[arg-type] + ) + with pytest.raises(PedPyValueError, match="border fill method"): + compute_individual_acceleration( + traj_data=traj_data, + frame_step=1, + border_fill="last_value", # type: ignore[arg-type] + ) + + +def test_plotting_handles_nan_filled_speed_and_acceleration(): + traj_data = _make_linear_trajectory(number_frames=10) + walkable_area = WalkableArea([(-2, -2), (10, -2), (10, 5), (-2, 5)]) + measurement_line = MeasurementLine([(5, -2), (5, 5)]) + + speed_nan = compute_individual_speed( + traj_data=traj_data, + frame_step=3, + speed_calculation=SpeedCalculation.BORDER_EXCLUDE, + border_fill=BorderFillMethod.NAN, + ) + acc_nan = compute_individual_acceleration( + traj_data=traj_data, + frame_step=2, + border_fill=BorderFillMethod.NAN, + ) + + fig, axes = plt.subplots(2, 3) + try: + plot_speed(speed=speed_nan[speed_nan[ID_COL] == 0], axes=axes[0, 0]) + plot_acceleration(acceleration=acc_nan[acc_nan[ID_COL] == 0], axes=axes[0, 1]) + plot_speed_distribution(speed=speed_nan, axes=axes[0, 2]) + + # Also check all-NaN speed distribution does not raise + all_nan_speed = speed_nan.copy() + all_nan_speed[SPEED_COL] = np.nan + plot_speed_distribution(speed=all_nan_speed, axes=axes[1, 0]) + + td = compute_time_distance_line(traj_data=traj_data, measurement_line=measurement_line) + plot_time_distance(time_distance=td, speed=speed_nan, axes=axes[1, 1]) + + voronoi = compute_individual_voronoi_polygons(traj_data=traj_data, walkable_area=walkable_area).merge( + speed_nan, on=[ID_COL, FRAME_COL] + ) + plot_voronoi_cells(voronoi_data=voronoi, frame=0, color_by_column=SPEED_COL, axes=axes[1, 2]) + finally: + plt.close(fig)