From 795c16f95cefaff11e2b471e845b50d2e674b56a Mon Sep 17 00:00:00 2001 From: Mark Colley <39366189+M-Colley@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:28:59 +0000 Subject: [PATCH 1/2] feat(io): allow preserving extra columns in load_trajectory_from_txt --- pedpy/io/ped_data_archive_loader.py | 88 +++++++++++++++++-- pedpy/io/trajectory_loader.py | 6 +- .../io/test_ped_data_archive_loader.py | 46 ++++++++++ 3 files changed, 131 insertions(+), 9 deletions(-) diff --git a/pedpy/io/ped_data_archive_loader.py b/pedpy/io/ped_data_archive_loader.py index 932f7fc3..a1359274 100644 --- a/pedpy/io/ped_data_archive_loader.py +++ b/pedpy/io/ped_data_archive_loader.py @@ -1,23 +1,74 @@ """Load trajectories from the Pedestrian Dynamics Data Archive to the internal trajectory data format.""" import pathlib -from typing import Any, Optional, Tuple +from typing import Any, Final, Mapping, Optional, Sequence, Tuple, Union import h5py import pandas as pd -from pedpy.column_identifier import FRAME_COL, ID_COL, X_COL, Y_COL +from pedpy.column_identifier import FRAME_COL, ID_COL, POINT_COL, X_COL, Y_COL from pedpy.data.geometry import WalkableArea from pedpy.data.trajectory_data import TrajectoryData -from pedpy.errors import LoadTrajectoryError, PedPyValueError +from pedpy.errors import LoadTrajectoryError, PedPyTypeError, PedPyValueError from pedpy.io.helper import TrajectoryUnit, _validate_is_file +_FIRST_EXTRA_COL_IDX: Final = 4 +_RESERVED_COLS: Final = frozenset({ID_COL, FRAME_COL, X_COL, Y_COL, POINT_COL}) + + +def _resolve_extra_columns( + extra_columns: Optional[Union[Sequence[str], Mapping[int, str]]], +) -> Tuple[list[int], list[str]]: + """Validate and normalize optional extra column specifications.""" + if extra_columns is None: + return [], [] + if isinstance(extra_columns, (str, bytes)): + raise PedPyTypeError( + "extra_columns must be a sequence of column names or a mapping from column index (>= 4) to name, not str." + ) + + pairs: list[Tuple[int, str]] = [] + if isinstance(extra_columns, Mapping): + for idx, col_name in extra_columns.items(): + if not isinstance(idx, int) or isinstance(idx, bool): + raise PedPyTypeError( + f"Extra column index must be an int >= {_FIRST_EXTRA_COL_IDX}, got {type(idx).__name__}." + ) + if idx < _FIRST_EXTRA_COL_IDX: + raise PedPyValueError( + f"Extra column index must be >= {_FIRST_EXTRA_COL_IDX} (columns 0..3 are id, frame, x, y), got {idx}." + ) + if not isinstance(col_name, str) or not col_name.strip(): + raise PedPyValueError("Extra column names must be non-empty strings.") + pairs.append((idx, col_name)) + pairs.sort(key=lambda item: item[0]) + elif isinstance(extra_columns, Sequence): + for offset, col_name in enumerate(extra_columns): + if not isinstance(col_name, str) or not col_name.strip(): + raise PedPyValueError("Extra column names must be non-empty strings.") + pairs.append((_FIRST_EXTRA_COL_IDX + offset, col_name)) + else: + raise PedPyTypeError( + f"extra_columns must be a sequence of column names or a mapping from column index to name, got {type(extra_columns).__name__}." + ) + + seen: set[str] = set() + for _, name in pairs: + if name in _RESERVED_COLS: + raise PedPyValueError(f"Extra column name '{name}' conflicts with reserved TrajectoryData column.") + if name in seen: + raise PedPyValueError(f"Duplicate extra column name '{name}'.") + seen.add(name) + + return [idx for idx, _ in pairs], [name for _, name in pairs] + def load_trajectory_from_txt( *, trajectory_file: pathlib.Path, default_frame_rate: Optional[float] = None, default_unit: Optional[TrajectoryUnit] = None, + extra_columns: Optional[Union[Sequence[str], Mapping[int, str]]] = None, ) -> TrajectoryData: """Loads the trajectory file in the internal :class:`~trajectory_data.TrajectoryData` format. @@ -31,6 +82,12 @@ def load_trajectory_from_txt( from file is used default_unit: unit in which the coordinates are stored in the file, None if unit should be parsed from the file + extra_columns: optional extra columns beyond ``id``, ``frame``, ``x``, + ``y`` (0-based indices ``>= 4``) to preserve on ``traj.data``. + Pass a sequence of names (e.g. ``["z", "marker_id"]`` for columns + 4 and 5) or a mapping from 0-based column index to name (e.g. + ``{4: "z", 6: "marker_id"}``). When ``None`` (default), columns + past the first four are dropped. Returns: TrajectoryData: :class:`~trajectory_data.TrajectoryData` @@ -43,30 +100,43 @@ def load_trajectory_from_txt( default_frame_rate=default_frame_rate, default_unit=default_unit, ) - traj_dataframe = _load_trajectory_data_from_txt(trajectory_file=trajectory_file, unit=traj_unit) + traj_dataframe = _load_trajectory_data_from_txt( + trajectory_file=trajectory_file, + unit=traj_unit, + extra_columns=extra_columns, + ) return TrajectoryData(data=traj_dataframe, frame_rate=traj_frame_rate) -def _load_trajectory_data_from_txt(*, trajectory_file: pathlib.Path, unit: TrajectoryUnit) -> pd.DataFrame: +def _load_trajectory_data_from_txt( + *, + trajectory_file: pathlib.Path, + unit: TrajectoryUnit, + extra_columns: Optional[Union[Sequence[str], Mapping[int, str]]] = None, +) -> pd.DataFrame: """Parse the trajectory file for trajectory data. Args: trajectory_file: file containing the trajectory unit: unit in which the coordinates are stored in the file, None if unit should be parsed from the file + extra_columns: optional sequence of names or index-to-name mapping for columns >= 4 Returns: The trajectory data as :class:`DataFrame`, the coordinates are converted to meter (m). """ + extra_indices, extra_names = _resolve_extra_columns(extra_columns) + usecols = [0, 1, 2, 3, *extra_indices] + col_names = [ID_COL, FRAME_COL, X_COL, Y_COL, *extra_names] try: data = pd.read_csv( trajectory_file, sep=r"\s+", comment="#", header=None, - names=[ID_COL, FRAME_COL, X_COL, Y_COL], - usecols=[0, 1, 2, 3], + names=col_names, + usecols=usecols, dtype={ ID_COL: "int64", FRAME_COL: "int64", @@ -89,7 +159,9 @@ def _load_trajectory_data_from_txt(*, trajectory_file: pathlib.Path, unit: Traje data.y = data.y.div(100) return data - except pd.errors.ParserError as exc: + except (pd.errors.ParserError, ValueError) as exc: + if isinstance(exc, PedPyValueError): + raise raise PedPyValueError( "The given trajectory file could not be parsed. It should " "contain at least 5 columns: ID, frame, X, Y, Z. The values " diff --git a/pedpy/io/trajectory_loader.py b/pedpy/io/trajectory_loader.py index e252413b..566e943a 100644 --- a/pedpy/io/trajectory_loader.py +++ b/pedpy/io/trajectory_loader.py @@ -1,7 +1,7 @@ """Load trajectories to the internal trajectory data format.""" import pathlib -from typing import Optional +from typing import Mapping, Optional, Sequence, Union from pedpy.data.trajectory_data import TrajectoryData from pedpy.io.helper import TrajectoryUnit @@ -13,6 +13,7 @@ def load_trajectory( trajectory_file: pathlib.Path, default_frame_rate: Optional[float] = None, default_unit: Optional[TrajectoryUnit] = None, + extra_columns: Optional[Union[Sequence[str], Mapping[int, str]]] = None, ) -> TrajectoryData: """Loads the trajectory file in the internal :class:`~trajectory_data.TrajectoryData` format. @@ -26,6 +27,8 @@ def load_trajectory( from file is used default_unit: unit in which the coordinates are stored in the file, None if unit should be parsed from the file + extra_columns: optional extra columns beyond ``id``, ``frame``, ``x``, + ``y`` (0-based indices ``>= 4``) to preserve on ``traj.data`` Returns: TrajectoryData: :class:`~trajectory_data.TrajectoryData` @@ -35,4 +38,5 @@ def load_trajectory( trajectory_file=trajectory_file, default_frame_rate=default_frame_rate, default_unit=default_unit, + extra_columns=extra_columns, ) diff --git a/tests/unit_tests/io/test_ped_data_archive_loader.py b/tests/unit_tests/io/test_ped_data_archive_loader.py index 27825c7a..6375fea1 100644 --- a/tests/unit_tests/io/test_ped_data_archive_loader.py +++ b/tests/unit_tests/io/test_ped_data_archive_loader.py @@ -737,3 +737,49 @@ def test_load_walkable_area_from_ped_data_archive_hdf5_non_file(tmp_path): load_walkable_area_from_ped_data_archive_hdf5(trajectory_file=tmp_path) assert "is not a file" in str(error_info.value) + + +def test_load_trajectory_from_txt_preserve_extra_columns(tmp_path: pathlib.Path) -> None: + from pedpy.errors import PedPyTypeError, PedPyValueError + from pedpy.io.trajectory_loader import load_trajectory + + traj_txt = tmp_path / "extra_cols.txt" + traj_txt.write_text( + "#framerate: 10.0\n# id frame x/m y/m z/m group marker_id\n1 0 1.5 2.5 1.72 10 101\n2 1 3.0 4.0 1.65 20 202\n", + encoding="utf-8", + ) + + # Default drops extra columns + traj_default = load_trajectory_from_txt(trajectory_file=traj_txt) + assert "z" not in traj_default.data.columns + assert "marker_id" not in traj_default.data.columns + + # Sequence of extra column names (columns 4, 5, 6) + traj_seq = load_trajectory_from_txt( + trajectory_file=traj_txt, + extra_columns=["z", "group", "marker_id"], + ) + assert list(traj_seq.data["z"]) == pytest.approx([1.72, 1.65]) + assert list(traj_seq.data["group"]) == [10, 20] + assert list(traj_seq.data["marker_id"]) == [101, 202] + + # Mapping of unsorted 0-based indices >= 4 via load_trajectory + traj_map = load_trajectory( + trajectory_file=traj_txt, + extra_columns={6: "marker_id", 4: "z"}, + ) + assert list(traj_map.data["z"]) == pytest.approx([1.72, 1.65]) + assert list(traj_map.data["marker_id"]) == [101, 202] + assert "group" not in traj_map.data.columns + + # Invalid inputs raise appropriate PedPy errors + with pytest.raises(PedPyTypeError): + load_trajectory_from_txt(trajectory_file=traj_txt, extra_columns="z") + with pytest.raises(PedPyValueError, match=">= 4"): + load_trajectory_from_txt(trajectory_file=traj_txt, extra_columns={2: "bad"}) + with pytest.raises(PedPyValueError, match="reserved"): + load_trajectory_from_txt(trajectory_file=traj_txt, extra_columns=["x"]) + with pytest.raises(PedPyValueError, match="Duplicate"): + load_trajectory_from_txt(trajectory_file=traj_txt, extra_columns=["z", "z"]) + with pytest.raises(PedPyValueError, match="could not be parsed"): + load_trajectory_from_txt(trajectory_file=traj_txt, extra_columns={9: "missing"}) From 943dd8a0eb74600c7667cfe37efdc9aec568d857 Mon Sep 17 00:00:00 2001 From: Mark Colley <39366189+M-Colley@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:32:36 +0000 Subject: [PATCH 2/2] style(io): wrap long error strings to <= 120 characters --- pedpy/io/ped_data_archive_loader.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/pedpy/io/ped_data_archive_loader.py b/pedpy/io/ped_data_archive_loader.py index a1359274..40fe8a9f 100644 --- a/pedpy/io/ped_data_archive_loader.py +++ b/pedpy/io/ped_data_archive_loader.py @@ -36,7 +36,8 @@ def _resolve_extra_columns( ) if idx < _FIRST_EXTRA_COL_IDX: raise PedPyValueError( - f"Extra column index must be >= {_FIRST_EXTRA_COL_IDX} (columns 0..3 are id, frame, x, y), got {idx}." + f"Extra column index must be >= {_FIRST_EXTRA_COL_IDX} " + f"(columns 0..3 are id, frame, x, y), got {idx}." ) if not isinstance(col_name, str) or not col_name.strip(): raise PedPyValueError("Extra column names must be non-empty strings.") @@ -49,7 +50,8 @@ def _resolve_extra_columns( pairs.append((_FIRST_EXTRA_COL_IDX + offset, col_name)) else: raise PedPyTypeError( - f"extra_columns must be a sequence of column names or a mapping from column index to name, got {type(extra_columns).__name__}." + "extra_columns must be a sequence of column names or a mapping " + f"from column index to name, got {type(extra_columns).__name__}." ) seen: set[str] = set()