Source code for launch_tools.csv_tools
1"""Contains snippets that can can import/export vehicle positions from/to csv files."""
2
3from __future__ import annotations
4
5# pyright: reportUnknownMemberType=none
6# pyright: reportUnknownVariableType=information
7from typing import TYPE_CHECKING
8
9if TYPE_CHECKING:
10 from os import PathLike
11
12import carla
13import pandas as pd
14
15__all__ = [
16 "csv_to_transformations",
17 "transform_to_pandas",
18 "vehicle_location_to_dataframe",
19]
20
21# A dataframe template to store the locations of vehicles
22LOC_DF = pd.DataFrame(columns=["x", "y", "z", "pitch", "yaw", "roll"])
23
24# -----------------------------------
25
26
[docs]
27def transform_to_pandas(transform: carla.Transform) -> pd.Series[float]:
28 """
29 Format a :py:class:`carla.Transform` object to a :py:class:`pandas.Series`.
30 """
31 loc = transform.location
32 rot = transform.rotation
33 return pd.Series({"x": loc.x, "y": loc.y, "z": loc.z, "pitch": rot.pitch, "yaw": rot.yaw, "roll": rot.roll})
34
35
[docs]
36def vehicle_location_to_dataframe(vehicles: list[carla.Actor]) -> pd.DataFrame:
37 """
38 Exports the locations of vehicles to a :py:class:`pandas.Dataframe`.
39 """
40 df = LOC_DF.copy()
41 for i, v in enumerate(vehicles):
42 df.loc[i] = transform_to_pandas(v.get_transform())
43 return df
44
45
[docs]
46def csv_to_transformations(path: str | PathLike[str]) -> list[carla.Transform]:
47 """
48 Read a csv file and return a list of Transform objects.
49 Expected columns: :code:`x, y, z, pitch, yaw, roll`.
50 """
51 df = pd.read_csv(path) # pyright: ignore
52 transformations: list[carla.Transform] = []
53 for _, data in df.iterrows(): # pyright: ignore
54 loc = carla.Location(data.x, data.y, data.z) # type: ignore[attr-defined]
55 rot = carla.Rotation(pitch=data.pitch, yaw=data.yaw, roll=data.roll) # type: ignore[attr-defined]
56 t = carla.Transform(loc, rot)
57 transformations.append(t)
58 return transformations