Skip to content

Tabular

Factory

crdata.conversion.tabular.factory

TabularConverterFactory

Bases: AbstractConverterFactory[TabularJob], Generic[WindowMetaT]

Factory base class for building producer-consumer pipelines in the tabular API.

Source code in crdata/conversion/tabular/factory.py
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
class TabularConverterFactory(
    AbstractConverterFactory[TabularJob], Generic[WindowMetaT]
):
    """Factory base class for building producer-consumer pipelines in the tabular API."""

    output_dir: Path
    num_time_steps: int | None = 150
    num_planning_problems: int = 1
    downsample: int = 1
    file_writer_type: FileFormat = FileFormat.XML
    max_scenarios: int | None = None
    routability_check: RoutabilityCheck = RoutabilityCheck.Nocheck
    keep_ego: bool = False
    obstacles_start_at_zero: bool = True
    samples_per_recording: int | None = None
    start_time_step: int | None = None
    end_time_step: int | None = None
    ego_vehicle_id: int | None = None
    enforced_planning_problem_selection: bool = True
    #: Seconds of context before / after the ego in obstacle-centred windows.
    time_before_ego: float = 0.0
    time_after_ego: float = 0.0
    seed: int = 42

    def _rng(self) -> np.random.Generator | None:
        return None if self.seed == -1 else np.random.default_rng(self.seed)

    @abstractmethod
    def build_recording_generator(self) -> Iterable[tuple[Window, WindowMetaT]]:
        pass

    def build_job_generator(self) -> TabularJobProducer:
        recoding_generator = self.build_recording_generator()
        window_generator = self.build_window_generator()

        def generator() -> Generator[tuple[Window, WindowMetaT], None, None]:
            for recording in recoding_generator:
                yield from window_generator(*recording)

        return TabularJobProducer(
            self.build_scenario_prototype_creator(),
            self.build_planning_problem_set_creator(),
            generator(),
            self.max_scenarios,
        )

    def build_scenario_prototype_creator(self) -> ScenarioPrototypeCreator:
        return ScenarioPrototypeCreator(
            self.build_scenario_id_creator(),
            self.build_meta_scenario_creator(),
        )

    @abstractmethod
    def build_meta_scenario_creator(self) -> IMetaScenarioCreator:
        pass

    def build_scenario_id_creator(self) -> ScenarioIDCreator:
        return ScenarioIDCreator()

    def build_window_generator(
        self,
    ) -> Callable[[Window, WindowMetaT], Iterable[tuple[Window, WindowMetaT]]]:
        if self.ego_vehicle_id is not None:
            time_range = None
            if self.start_time_step is not None and self.end_time_step is not None:
                time_range = (self.start_time_step, self.end_time_step)
            window_generator: IWindowGenerator = ObstacleWindowGenerator(
                self.time_before_ego,
                self.time_after_ego,
                obstacle_id=self.ego_vehicle_id,
                time_range=time_range,
            )
        elif self.samples_per_recording is None:
            if self.num_time_steps is None:
                assert self.num_planning_problems == 1
                window_generator = self.build_obstacle_window_generator()
            else:
                window_generator = RollingWindowGenerator(self.num_time_steps)
        else:
            if self.num_time_steps is None:
                assert self.num_planning_problems == 1
                window_generator = VehicleSamplingWindowGenerator(
                    self.samples_per_recording,
                    self.build_obstacle_window_generator(),
                    self._rng(),
                )
            else:
                window_generator = TimeSliceSamplingWindowGenerator(
                    self.num_time_steps, self.samples_per_recording, self._rng()
                )

        if self.downsample > 1:
            window_generator = DownsamplingWindowWrapper(
                window_generator, self.downsample
            )
        return window_generator

    def build_obstacle_window_generator(self):
        return ObstacleWindowGenerator(self.time_before_ego, self.time_after_ego)

    def build_planning_problem_set_creator(self) -> PlanningProblemCreator:
        if self.ego_vehicle_id is not None:
            return FixedEgoPlanningProblemCreator(
                self.ego_vehicle_id,
                self.keep_ego,
                self.start_time_step,
                self.end_time_step,
            )
        if self.num_planning_problems <= 0:
            planning_problem_creator = PlanningProblemCreator()
        else:
            planning_problem_creator = EgoPlanningProblemCreator(
                self.keep_ego,
                self.obstacles_start_at_zero,
            )

        if self.num_time_steps is not None:
            planning_problem_creator = RandomObstaclePlanningProblemWrapper(
                planning_problem_creator,
                self.num_planning_problems,
                self.enforced_planning_problem_selection,
                self._rng(),
            )

        return planning_problem_creator

    def build_job_processor(self) -> TabularJobConsumer:
        return TabularJobConsumer(
            self.output_dir,
            self.file_writer_type,
            self.obstacles_start_at_zero,
        )

    def build_job_filter(self) -> Callable[[TabularJob], bool]:
        """
        Filter scenarios without planning problems, if window is rolling.

        Explanation: For rolling windows usually the planning problem is not really needed,
        since scenarios are usually just used to represent the dataset in CommonRoad format,
        e.g., for machine learning.

        :return: filter function
        """

        def has_planning_problems(job):
            """Check if the job has planning problems."""
            return len(job.planning_problem_set.planning_problem_dict) > 0

        if self.num_time_steps is not None:
            filter_fn = has_planning_problems
        else:
            filter_fn = super().build_job_filter()

        if self.routability_check != RoutabilityCheck.Nocheck:
            routability_filter = RoutabilityFilter(self.routability_check)

            def wrapper(job: TabularJob) -> bool:
                return filter_fn(job) and routability_filter(job)

            return wrapper
        else:
            return filter_fn
build_job_filter()

Filter scenarios without planning problems, if window is rolling.

Explanation: For rolling windows usually the planning problem is not really needed, since scenarios are usually just used to represent the dataset in CommonRoad format, e.g., for machine learning.

Returns:

Type Description
Callable[[TabularJob], bool]

filter function

Source code in crdata/conversion/tabular/factory.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
def build_job_filter(self) -> Callable[[TabularJob], bool]:
    """
    Filter scenarios without planning problems, if window is rolling.

    Explanation: For rolling windows usually the planning problem is not really needed,
    since scenarios are usually just used to represent the dataset in CommonRoad format,
    e.g., for machine learning.

    :return: filter function
    """

    def has_planning_problems(job):
        """Check if the job has planning problems."""
        return len(job.planning_problem_set.planning_problem_dict) > 0

    if self.num_time_steps is not None:
        filter_fn = has_planning_problems
    else:
        filter_fn = super().build_job_filter()

    if self.routability_check != RoutabilityCheck.Nocheck:
        routability_filter = RoutabilityFilter(self.routability_check)

        def wrapper(job: TabularJob) -> bool:
            return filter_fn(job) and routability_filter(job)

        return wrapper
    else:
        return filter_fn

Filters

crdata.conversion.tabular.filters

RoutabilityFilter dataclass

Source code in crdata/conversion/tabular/filters.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
@dataclass
class RoutabilityFilter:
    routability_type: RoutabilityCheck

    def __call__(self, job: TabularJob) -> bool:
        """
        Checks if a planning problem is routable on scenario

        :return: bool, True if CommonRoad planning problem is routeable with max_difficulty
        """
        if self.routability_type == RoutabilityCheck.Nocheck:
            return True

        # TODO: Distinction between regular and strict?
        for planning_problem in job.planning_problem_set.planning_problem_dict.values():
            try:
                route_planner = RoutePlanner(
                    job.meta_scenario.lanelet_network,
                    planning_problem,
                    job.meta_scenario,
                )
                routes = route_planner.plan_routes()
                if len(routes) <= 0:
                    return False
            except Exception as e:
                _logger.error(
                    f"An error occurred during route planning for problem {planning_problem.planning_problem_id}: {e}"
                )
                return False  # or handle it in another way

        return True
__call__(job)

Checks if a planning problem is routable on scenario

Returns:

Type Description
bool

bool, True if CommonRoad planning problem is routeable with max_difficulty

Source code in crdata/conversion/tabular/filters.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def __call__(self, job: TabularJob) -> bool:
    """
    Checks if a planning problem is routable on scenario

    :return: bool, True if CommonRoad planning problem is routeable with max_difficulty
    """
    if self.routability_type == RoutabilityCheck.Nocheck:
        return True

    # TODO: Distinction between regular and strict?
    for planning_problem in job.planning_problem_set.planning_problem_dict.values():
        try:
            route_planner = RoutePlanner(
                job.meta_scenario.lanelet_network,
                planning_problem,
                job.meta_scenario,
            )
            routes = route_planner.plan_routes()
            if len(routes) <= 0:
                return False
        except Exception as e:
            _logger.error(
                f"An error occurred during route planning for problem {planning_problem.planning_problem_id}: {e}"
            )
            return False  # or handle it in another way

    return True

Interface

crdata.conversion.tabular.interface

IMetaScenarioCreator

Bases: Generic[WindowMetaT]

Create the static elements of a dataset window.

Source code in crdata/conversion/tabular/interface.py
38
39
40
41
42
43
class IMetaScenarioCreator(Generic[WindowMetaT], metaclass=ABCMeta):
    """Create the static elements of a dataset window."""

    @abstractmethod
    def __call__(self, window: Window, window_meta: WindowMetaT) -> Scenario:
        pass

IRecordingGenerator

Bases: Generic[WindowMetaT]

Iterate over the independent recordings of a dataset.

Source code in crdata/conversion/tabular/interface.py
46
47
48
49
50
51
52
53
54
55
56
class IRecordingGenerator(Generic[WindowMetaT], metaclass=ABCMeta):
    """Iterate over the independent recordings of a dataset."""

    @abstractmethod
    def __iter__(self) -> Iterator[tuple[Window, WindowMetaT]]:
        """
        Create an iterator that iterates over independent recordings.

        :return: Tuple of the full recordings window and a generic meta information
            object to be used by subsequent steps to identify the recording.
        """
__iter__() abstractmethod

Create an iterator that iterates over independent recordings.

Returns:

Type Description
Iterator[tuple[Window, WindowMetaT]]

Tuple of the full recordings window and a generic meta information object to be used by subsequent steps to identify the recording.

Source code in crdata/conversion/tabular/interface.py
49
50
51
52
53
54
55
56
@abstractmethod
def __iter__(self) -> Iterator[tuple[Window, WindowMetaT]]:
    """
    Create an iterator that iterates over independent recordings.

    :return: Tuple of the full recordings window and a generic meta information
        object to be used by subsequent steps to identify the recording.
    """

IWindowGenerator

Bases: Generic[WindowMetaT]

Subdivide a larger window.

Source code in crdata/conversion/tabular/interface.py
28
29
30
31
32
33
34
35
class IWindowGenerator(Generic[WindowMetaT], metaclass=ABCMeta):
    """Subdivide a larger window."""

    @abstractmethod
    def __call__(
        self, window: Window, window_meta: WindowMetaT
    ) -> Iterable[tuple[Window, WindowMetaT]]:
        pass

Window dataclass

Contiguous subset of time steps of a dataset, consisting of vehicle states.

Source code in crdata/conversion/tabular/interface.py
10
11
12
13
14
15
16
17
18
19
20
21
22
@dataclass
class Window:
    """Contiguous subset of time steps of a dataset, consisting of vehicle states."""

    #: DataFrame with MultiIndex that has the last two levels obstacle id and time step
    #: columns should match CommonRoad state attributes, except x, y which will be converted
    #: into position.
    vehicle_states: pd.DataFrame
    #: DataFrame with Index obstacle id, and at least columns
    #: obstacle_type, width, length
    vehicle_meta: pd.DataFrame
    #: Time step length in seconds.
    dt: float

Job Consumer

crdata.conversion.tabular.job_consumer

TabularJobConsumer dataclass

Bases: IScenarioJobConsumer[TabularJob]

Consume conversion jobs of the tabular API.

Source code in crdata/conversion/tabular/job_consumer.py
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
@dataclass
class TabularJobConsumer(IScenarioJobConsumer[TabularJob]):
    """Consume conversion jobs of the tabular API."""

    #: Output directory for the converted scenarios.
    output_dir: Path
    #: File format of the converted scenarios.
    file_format: FileFormat = FileFormat.XML
    #: Let the scenario start at time step 0.
    obstacles_start_at_zero: bool = True
    #: Infer turning indicator signal from curvature.
    create_turning_indicator: bool = False

    def _create_scenario(self, job: TabularJob) -> Scenario:
        traj_df = job.vehicle_states.copy()
        # Offset trajectories if required
        traj_df["time_step"] = (
            traj_df.index.get_level_values(-1)
            - traj_df.index.get_level_values(-1).min() * self.obstacles_start_at_zero
        )
        scenario = job.meta_scenario

        idx = pd.IndexSlice
        # Create obstacles
        for track_id, vehicle_meta in job.vehicle_meta.iterrows():
            track_df = traj_df.loc[idx[track_id, :]]
            if len(track_df) < 2:
                continue

            # Create the obstacle
            obs = _create_obstacle(track_df, vehicle_meta, track_id)
            if self.create_turning_indicator:
                # Derive turning indicator from trajectory curvature
                if obs.obstacle_type in [
                    ObstacleType.TAXI,
                    ObstacleType.CAR,
                    ObstacleType.PRIORITY_VEHICLE,
                    ObstacleType.TRUCK,
                    ObstacleType.BUS,
                    ObstacleType.MOTORCYCLE,
                ]:
                    signal_states = _add_indicator_lights_based_on_trajectory(
                        obs.prediction.trajectory,
                        [40, 30],
                        obs.initial_state.time_step,
                        obs.prediction.trajectory.state_list[-1].time_step,
                    )
                else:
                    signal_states = _generate_empty_signal_series(
                        obs.initial_state.time_step,
                        obs.prediction.trajectory.state_list[-1].time_step,
                    )
                obs.initial_signal_state = signal_states[0]
                obs.signal_series = signal_states[1:]
            scenario.add_objects(obs)

        # A scenario is cooperative if it has more than one planning problem
        if len(job.planning_problem_set.planning_problem_dict) > 1:
            scenario.scenario_id.cooperative = True

        return scenario

    def _save_scenario(
        self, scenario: Scenario, planning_problem: PlanningProblemSet
    ) -> None:
        cw = CommonRoadFileWriter(
            scenario, planning_problem, file_format=self.file_format
        )
        # TODO: Can be simplified with next CommonRoad release
        if self.file_format == FileFormat.XML:
            suffix = "xml"
        elif self.file_format == FileFormat.PROTOBUF:
            suffix = "pb"
        else:
            assert False
        cw.write_to_file(
            str(self.output_dir / f"{scenario.scenario_id}.{suffix}"),
            OverwriteExistingFile.ALWAYS,
        )

    def __call__(self, job: TabularJob) -> None:
        scenario = self._create_scenario(job)

        if len(scenario.dynamic_obstacles) == 0:
            # Skip scenario if it is empty.
            return

        # Write scenario file
        self._save_scenario(scenario, job.planning_problem_set)

Job Producer

crdata.conversion.tabular.job_producer

TabularJob dataclass

Scenario job of the tabular API.

Source code in crdata/conversion/tabular/job_producer.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
@dataclass
class TabularJob:
    """Scenario job of the tabular API."""

    #: DataFrame with MultiIndex that has the last two levels obstacle id and time step
    #: columns should match CommonRoad state attributes, except x, y which will be converted
    #: into position.
    vehicle_states: pd.DataFrame
    #: DataFrame with Index obstacle id, and at least columns
    #: obstacle_type, width, length
    vehicle_meta: pd.DataFrame
    #: Empty base scenario containing all static objects.
    meta_scenario: Scenario
    #: Planning problem set written to the scenario file.
    planning_problem_set: PlanningProblemSet

Planning Problem

Planning problem inheritance diagram

crdata.conversion.tabular.planning_problem

EgoPlanningProblemCreator dataclass

Bases: PlanningProblemCreator

Create a planning problem for all specified dynamic obstacle ids.

Planning problems are created by using the initial state of a dynamic obstacle as initial state of the planning problem and the final state as the center of the goal region. The goal region is an enlarged version of the vehicle's shape. Constraints on the goal time step, orientation, and velocity can be specified by interval half ranges.

Source code in crdata/conversion/tabular/planning_problem.py
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
@dataclass
class EgoPlanningProblemCreator(PlanningProblemCreator):
    """Create a planning problem for all specified dynamic obstacle ids.

    Planning problems are created by using the initial state of a dynamic obstacle as initial state
    of the planning problem and the final state as the center of the goal region.
    The goal region is an enlarged version of the vehicle's shape.
    Constraints on the goal time step, orientation, and velocity can be specified by interval half ranges.
    """

    #: Whether to keep the original ego vehicle's in the scenario.
    keep_ego: bool
    obstacles_start_at_zero: bool = True
    orientation_half_range: float = 0.2  # rad
    velocity_half_range: float = 10.0  # m/s
    #: Number of time steps the goal may be reached after the ego's last state.
    time_step_half_range: int = 100  # 1

    def __call__(  # type: ignore[override]
        self, window_job: EgoWindow, meta_scenario: Scenario
    ) -> PlanningProblemSet:
        planning_problem_set = PlanningProblemSet()
        for ego_id in window_job.ego:
            ego_meta = window_job.vehicle_meta.loc[ego_id]
            min_timestep = window_job.vehicle_states.index.get_level_values(-1).min()
            dynamic_obstacle_shape = Rectangle(ego_meta.length, ego_meta.width)
            states = window_job.vehicle_states.loc[ego_id]

            # Tracks may start or end beyond the map, so the initial and goal state
            # are the first and last state of the dynamic obstacle on a lanelet
            lanelet_network = meta_scenario.lanelet_network
            first_idx = next(
                (
                    i
                    for i in range(len(states))
                    if _on_lanelet(states.iloc[i], lanelet_network)
                ),
                None,
            )
            if first_idx is None:
                _logger.info(
                    "No state on a lanelet for dynamic obstacle %s, skipping it.",
                    ego_id,
                )
                continue
            last_idx = next(
                i
                for i in reversed(range(len(states)))
                if _on_lanelet(states.iloc[i], lanelet_network)
            )
            dynamic_obstacle_initial_state = states.iloc[first_idx]
            dynamic_obstacle_final_state = states.iloc[last_idx]
            ego_timestep = states.index.get_level_values(-1)[first_idx]

            # define orientation, velocity and time step intervals as goal region
            orientation_interval = AngleInterval(
                dynamic_obstacle_final_state.orientation - self.orientation_half_range,
                dynamic_obstacle_final_state.orientation + self.orientation_half_range,
            )
            velocity_interval = Interval(
                dynamic_obstacle_final_state.velocity - self.velocity_half_range,
                dynamic_obstacle_final_state.velocity + self.velocity_half_range,
            )

            # Only depends on the ego, not on the scenario end, so the goal deadline
            # does not change with --time-after-ego. It may exceed the scenario end.
            final_time_step = (
                window_job.vehicle_states.loc[ego_id].index.max()
                + self.time_step_half_range
            )

            # FIXME: should the time_step_interval start at the timestep of the initial state of the planning problem
            #  or of the first obstacle in the scenario?
            # -> Ansgar: I think it should start a few seconds before the planning problem. Then you have some obstacle history. If you start at the first obstacle you'll always have the entire recording in the scenario, right?! That would be too much data.

            time_step_interval = Interval(
                ego_timestep - min_timestep * self.obstacles_start_at_zero,
                final_time_step - min_timestep * self.obstacles_start_at_zero,
            )

            goal_shape = Rectangle(
                length=dynamic_obstacle_shape.length + 2.0,
                width=max(dynamic_obstacle_shape.width + 1.0, 3.5),
                center=dynamic_obstacle_final_state[["x", "y"]].values,
                orientation=dynamic_obstacle_final_state.orientation,
            )

            goal_position = _cut_lanelet_polygon(
                dynamic_obstacle_final_state[["x", "y"]].values,
                dynamic_obstacle_shape.length + 2.0,
                meta_scenario.lanelet_network,
            )
            if goal_position.shapely_object.area < goal_shape.shapely_object.area:
                goal_position = goal_shape

            goal_region = GoalRegion(
                [
                    CustomState(
                        position=goal_position,
                        orientation=orientation_interval,
                        velocity=velocity_interval,
                        time_step=time_step_interval,
                    )
                ]
            )

            dynamic_obstacle_initial_state = dynamic_obstacle_initial_state.copy()
            # do not always initialize these attributes
            dynamic_obstacle_initial_state["yaw_rate"] = 0.0
            dynamic_obstacle_initial_state["slip_angle"] = 0.0
            # FIXME
            planning_problem = PlanningProblem(
                ego_id + 100000,
                InitialState(
                    time_step=ego_timestep
                    - min_timestep * self.obstacles_start_at_zero,
                    position=dynamic_obstacle_initial_state[["x", "y"]].values,
                    **dynamic_obstacle_initial_state.drop(labels=["x", "y"]),
                ),
                goal_region,
            )
            planning_problem_set.add_planning_problem(planning_problem)
            if not self.keep_ego:
                window_job.vehicle_meta.drop(index=ego_id, inplace=True)

        return planning_problem_set

FixedEgoPlanningProblemCreator dataclass

Bases: PlanningProblemCreator

Creates a PlanningProblemSet for a fixed ego vehicle within a specified time interval.

Attributes: ego_vehicle_id (int): The ID of the ego vehicle for which the planning problem is to be created. keep_ego (bool): Indicates whether the ego vehicle should be retained in the meta-scenario. start_time_step (Optional[int]): Start time step for selecting the ego vehicle's states. end_time_step (Optional[int]): End time step for selecting the ego vehicle's states. obstacles_start_at_zero (bool): Whether obstacles should start at time step 0.

Methods: call(window_job: Window, meta_scenario: Scenario) -> PlanningProblemSet: Creates a PlanningProblemSet for the specified ego vehicle and time interval.

Source code in crdata/conversion/tabular/planning_problem.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
@dataclass
class FixedEgoPlanningProblemCreator(PlanningProblemCreator):
    """
    Creates a PlanningProblemSet for a fixed ego vehicle within a specified time interval.

    Attributes:
        ego_vehicle_id (int): The ID of the ego vehicle for which the planning problem is to be created.
        keep_ego (bool): Indicates whether the ego vehicle should be retained in the meta-scenario.
        start_time_step (Optional[int]): Start time step for selecting the ego vehicle's states.
        end_time_step (Optional[int]): End time step for selecting the ego vehicle's states.
        obstacles_start_at_zero (bool): Whether obstacles should start at time step 0.

    Methods:
        __call__(window_job: Window, meta_scenario: Scenario) -> PlanningProblemSet:
            Creates a PlanningProblemSet for the specified ego vehicle and time interval.
    """

    ego_vehicle_id: int
    keep_ego: bool
    start_time_step: int | None = None
    end_time_step: int | None = None
    obstacles_start_at_zero: bool = True

    def __call__(
        self, window_job: Window, meta_scenario: Scenario
    ) -> PlanningProblemSet:
        if self.ego_vehicle_id not in window_job.vehicle_meta.index:
            return PlanningProblemSet()
        vehicle_states = window_job.vehicle_states
        if self.start_time_step is not None and self.end_time_step is not None:
            # Only restrict the ego's states, so the time steps stay relative to the window
            idx = vehicle_states.index
            is_ego = idx.get_level_values(-2) == self.ego_vehicle_id
            in_range = (idx.get_level_values(-1) >= self.start_time_step) & (
                idx.get_level_values(-1) <= self.end_time_step
            )
            if not (is_ego & in_range).any():
                return PlanningProblemSet()
            vehicle_states = vehicle_states[~is_ego | in_range]
        ego_window_job = EgoWindow(
            vehicle_states,
            window_job.vehicle_meta,
            window_job.dt,
            [self.ego_vehicle_id],
        )
        return EgoPlanningProblemCreator(self.keep_ego, self.obstacles_start_at_zero)(
            ego_window_job, meta_scenario
        )

PlanningProblemCreator

Create an empty planning problem.

Source code in crdata/conversion/tabular/planning_problem.py
34
35
36
37
38
39
40
class PlanningProblemCreator:
    """Create an empty planning problem."""

    def __call__(
        self, window_job: Window, meta_scenario: Scenario
    ) -> PlanningProblemSet:
        return PlanningProblemSet()

RandomObstaclePlanningProblemWrapper dataclass

Bases: PlanningProblemCreator

Randomly choose dynamic obstacles from a window as a basis for planning problems.

Only dynamic obstacles of type "car" are considered!

Source code in crdata/conversion/tabular/planning_problem.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
@dataclass
class RandomObstaclePlanningProblemWrapper(PlanningProblemCreator):
    """Randomly choose dynamic obstacles from a window as a basis for planning problems.

    Only dynamic obstacles of type "car" are considered!
    """

    wrapped_planning_problem_creator: PlanningProblemCreator
    #: Number of planning problems to create per scenario
    num_planning_problems: int = 1
    #: Only choose obstacles that are present at the first time step and for at least
    #: 75% (fallback 50%) of the window. Only supported for a single planning problem.
    enforced_selection: bool = True
    #: Random generator for the ego selection. None uses numpy's global state.
    random_state: np.random.Generator | None = None

    def __post_init__(self) -> None:
        if self.enforced_selection and self.num_planning_problems > 1:
            _logger.warning(
                "Enforced planning problem selection only supports one planning "
                "problem, ignoring it."
            )
            self.enforced_selection = False

    def __call__(self, window: Window, meta_scenario: Scenario) -> PlanningProblemSet:
        num_states = window.vehicle_states.groupby(level=0).x.count()
        eligible = (num_states > 1) & (window.vehicle_meta.obstacle_type == "car")
        if self.enforced_selection:
            steps = window.vehicle_states.index.get_level_values(-1)
            first_step = (
                steps.to_series(index=window.vehicle_states.index)
                .groupby(level=0)
                .min()
            )
            at_start = first_step == steps.min()
            share = num_states / (steps.max() - steps.min() + 1)
            for min_share in (0.75, 0.5):
                candidates = window.vehicle_meta.loc[
                    eligible & at_start & (share >= min_share)
                ]
                if len(candidates) >= self.num_planning_problems:
                    break
            else:
                _logger.warning(
                    "No obstacle is present from the first time step for at least "
                    "50%% of scenario %s, skipping it.",
                    meta_scenario.scenario_id,
                )
                return PlanningProblemSet()
        else:
            candidates = window.vehicle_meta.loc[eligible]
        if len(candidates) >= self.num_planning_problems:
            ego_ids = candidates.sample(
                self.num_planning_problems, random_state=self.random_state
            ).index.values
            ego_window_job = EgoWindow(
                window.vehicle_states, window.vehicle_meta, window.dt, ego_ids
            )
            return self.wrapped_planning_problem_creator(ego_window_job, meta_scenario)
        else:
            return super().__call__(window, meta_scenario)

Prototype Scenario

crdata.conversion.tabular.prototype_scenario

ScenarioIDCreator

Create a ScenarioID for a Window.

EgoWindow appends ego<ID> to the map name, to avoid overwriting.

Source code in crdata/conversion/tabular/prototype_scenario.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class ScenarioIDCreator:
    """Create a ``ScenarioID`` for a ``Window``.

    ``EgoWindow`` appends ``ego<ID>`` to the map name, to avoid overwriting.
    """

    def __call__(self, window_job: Window, meta_scenario: Scenario) -> ScenarioID:
        meta_scenario_id = meta_scenario.scenario_id
        map_name = meta_scenario_id.map_name
        if isinstance(window_job, EgoWindow):
            map_name += "".join(
                f"ego{int(ego_id)}" for ego_id in sorted(window_job.ego)
            )
        scenario_id = ScenarioID(
            country_id=meta_scenario_id.country_id,
            map_name=map_name,
            map_id=meta_scenario_id.map_id,
            obstacle_behavior="T",
            configuration_id=int(
                str(meta_scenario_id.configuration_id or "")
                + str(window_job.vehicle_states.index.get_level_values(-1).min())
            ),
            prediction_id=window_job.vehicle_states.index.get_level_values(-1).max(),
        )
        return scenario_id

ScenarioPrototypeCreator dataclass

Bases: Generic[WindowMetaT]

Create the actual scenario prototype to which the dynamic obstacles are added.

The prototype is created form the meta scenario. Country, map name, map id, author, source, affiliation, and location fields are copied from the meta scenario. Note, that the difference to the MetaScenarioGenerator is the dynamic scenario id of the prototype scenario. The meta scenario has the fixed scenario id of the map.

Source code in crdata/conversion/tabular/prototype_scenario.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
@dataclass
class ScenarioPrototypeCreator(Generic[WindowMetaT]):
    """Create the actual scenario prototype to which the dynamic obstacles are added.

    The prototype is created form the meta scenario. Country, map name, map id, author, source, affiliation,
    and location fields are copied from the meta scenario.
    Note, that the difference to the MetaScenarioGenerator is the dynamic scenario id of the
    prototype scenario. The meta scenario has the fixed scenario id of the map.
    """

    scenario_id_generator: ScenarioIDCreator
    meta_scenario_creator: IMetaScenarioCreator[WindowMetaT]

    def __call__(self, window_job: Window, window_meta: WindowMetaT) -> Scenario:
        meta_scenario = self.meta_scenario_creator(window_job, window_meta)
        scenario_id = self.scenario_id_generator(window_job, meta_scenario)
        scn = Scenario(
            window_job.dt,
            scenario_id,
            meta_scenario.author,
            meta_scenario.tags,
            meta_scenario.affiliation,
            meta_scenario.source,
            meta_scenario.location,
        )
        scn.add_objects(meta_scenario.lanelet_network)
        return scn

Windowing

Windowing inheritance diagram

crdata.conversion.tabular.windowing

DownsamplingWindowWrapper dataclass

Bases: IWindowGenerator

Wrap a window generator to downsample the time domain by a fixed factor.

Source code in crdata/conversion/tabular/windowing.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
@dataclass
class DownsamplingWindowWrapper(IWindowGenerator):
    """Wrap a window generator to downsample the time domain by a fixed factor."""

    base_window_generator: IWindowGenerator
    #: Only use every n-th time step of the input window.
    downsampling_factor: int

    def __call__(
        self, recording: Window, window_meta: WindowMetaT
    ) -> Iterable[tuple[Window, WindowMetaT]]:
        for window, window_meta in self.base_window_generator(recording, window_meta):
            window.vehicle_states = window.vehicle_states.assign(
                time_stamp=pd.to_timedelta(
                    window.vehicle_states.index.get_level_values(-1), unit="s"
                )
            )
            window.vehicle_states = window.vehicle_states.groupby(
                [
                    pd.Grouper(key="time_stamp", freq=f"{self.downsampling_factor}s"),
                    pd.Grouper(level=-2),
                ],
                group_keys=True,
            ).first()
            # Apply downsampling factor to DateTimeIndex and reorder to obstacle_id, time_step
            window.vehicle_states.index = window.vehicle_states.index.set_levels(
                window.vehicle_states.index.levels[0].seconds
                // self.downsampling_factor,
                level=0,
            ).swaplevel()
            # Select vehicles that are still available after downsampling
            vehicles = window.vehicle_states.index.levels[-2]
            window.vehicle_meta = window.vehicle_meta.loc[vehicles]
            window.dt = window.dt * self.downsampling_factor
            yield window, window_meta

ObstacleWindowGenerator dataclass

Bases: IWindowGenerator

Create a window for each dynamic obstacle.

Source code in crdata/conversion/tabular/windowing.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
@dataclass
class ObstacleWindowGenerator(IWindowGenerator):
    """Create a window for each dynamic obstacle."""

    #: Seconds included before the obstacle's time range, clipped to the recording.
    time_before_ego: float = 0.0
    #: Seconds included after the obstacle's time range, clipped to the recording.
    time_after_ego: float = 0.0
    #: Only create a window for this obstacle (of any type) instead of for every car.
    obstacle_id: int | None = None
    #: Time steps (start, end) used instead of the obstacle's first and last time step.
    time_range: tuple[int, int] | None = None

    def __call__(
        self, recording: Window, window_meta: WindowMetaT
    ) -> Iterable[tuple[EgoWindow, WindowMetaT]]:
        for obstacle in self._get_index(recording):
            window = self.get_obstacle_window(obstacle, recording)
            yield window, window_meta

    def get_obstacle_window(self, obstacle, recording):
        obstacle_states = recording.vehicle_states.loc[(obstacle,) + (slice(None),)]
        start_timestep, end_timestep = self.time_range or (
            obstacle_states.index.get_level_values(-1).min(),
            obstacle_states.index.get_level_values(-1).max(),
        )
        start_timestep -= round(self.time_before_ego / recording.dt)
        end_timestep += round(self.time_after_ego / recording.dt)
        states: pd.DataFrame = recording.vehicle_states.loc[
            (recording.vehicle_states.index.get_level_values(-1) >= start_timestep)
            & (recording.vehicle_states.index.get_level_values(-1) <= end_timestep)
        ]
        meta = recording.vehicle_meta.loc[states.index.droplevel(-1).unique()]
        window = EgoWindow(states, meta, recording.dt, [obstacle])
        return window

    def _get_index(self, recording: Window) -> pd.Index:
        """Provide index values of ego obstacles."""
        if self.obstacle_id is not None:
            return recording.vehicle_meta.index.intersection([self.obstacle_id])
        index = recording.vehicle_meta.index[
            recording.vehicle_meta.obstacle_type == "car"
        ]
        # Skip parked cars: their planning problems are trivial (goal = start)
        positions = recording.vehicle_states[["x", "y"]].groupby(level=-2)
        extent = positions.max() - positions.min()
        moving = extent.index[(extent.x**2 + extent.y**2) ** 0.5 >= PARKED_MAX_EXTENT]
        return index.intersection(moving)

RollingWindowGenerator dataclass

Bases: IWindowGenerator

Create windows of fixed length from a recording.

Source code in crdata/conversion/tabular/windowing.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
@dataclass
class RollingWindowGenerator(IWindowGenerator):
    """Create windows of fixed length from a recording."""

    #: Window length in time steps.
    window_length: int

    def __call__(
        self, recording: Window, window_meta: WindowMetaT
    ) -> Iterable[tuple[Window, WindowMetaT]]:
        states = recording.vehicle_states.copy()
        # Not actually using seconds, just pseudo for resampling
        states["timestamp"] = pd.to_timedelta(
            states.index.get_level_values(-1), unit="s"
        )
        resampler = states.resample(
            pd.Timedelta(self.window_length, unit="s"), on="timestamp"
        )

        for period, resampled_states in resampler:
            meta = recording.vehicle_meta.loc[
                resampled_states.index.droplevel(-1).unique()
            ]
            # TODO: Filter
            window = Window(
                resampled_states.drop(columns=["timestamp"]), meta, recording.dt
            )
            yield window, window_meta

TimeSliceSamplingWindowGenerator dataclass

Bases: IWindowGenerator

Sample windows from recording by window sizes.

Note: Resulting windows may overlap!

Source code in crdata/conversion/tabular/windowing.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
@dataclass
class TimeSliceSamplingWindowGenerator(IWindowGenerator):
    """
    Sample windows from recording by window sizes.

    Note: Resulting windows may overlap!
    """

    window_length: int
    samples_per_recording: int
    random_state: np.random.Generator | None = None

    def __call__(
        self, window: Window, window_meta: WindowMetaT
    ) -> Iterable[tuple[Window, WindowMetaT]]:
        time_steps = (
            window.vehicle_states.index.get_level_values(-1)
            .unique()
            .to_series()
            .sort_values()
        )
        # Make sure we have full windows
        time_steps = time_steps.head(-self.window_length)
        start_ts = time_steps.sample(
            n=min(self.samples_per_recording, len(time_steps.index)),
            random_state=self.random_state,
        ).values
        for ts in start_ts:
            vehicle_states = window.vehicle_states[
                (window.vehicle_states.index.get_level_values(-1) >= ts)
                & (
                    window.vehicle_states.index.get_level_values(-1)
                    < ts + self.window_length
                )
            ]
            vehicles = vehicle_states.index.get_level_values(-2).unique()
            vehicle_meta = window.vehicle_meta.loc[vehicles]
            yield Window(vehicle_states, vehicle_meta, window.dt), window_meta

VehicleSamplingWindowGenerator dataclass

Bases: IWindowGenerator

Source code in crdata/conversion/tabular/windowing.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
@dataclass
class VehicleSamplingWindowGenerator(IWindowGenerator):
    samples_per_recording: int
    base_window_generator: ObstacleWindowGenerator
    random_state: np.random.Generator | None = None

    def __call__(
        self, window: Window, window_meta: WindowMetaT
    ) -> Iterable[tuple[Window, WindowMetaT]]:
        for obstacle in self._get_index(window):
            yield (
                self.base_window_generator.get_obstacle_window(obstacle, window),
                window_meta,
            )

    def _get_index(self, recording: Window) -> pd.Index:
        """Provide index values of ego obstacles."""
        index = self.base_window_generator._get_index(recording)
        df = index.to_frame().sample(
            n=min(self.samples_per_recording, len(index)),
            random_state=self.random_state,
        )
        return df.index