### Install tactics2d from Source Source: https://tactics2d.readthedocs.io/en/latest/installation Clone the repository and install locally. Ensure GCC is installed on your system before proceeding. ```bash # clone the repository with submodules but ignore the large files (mainly the NuPlan's map data) # please download NuPlan's map data from its official website and put it in the `tactics2d/data/map/NuPlan` directory git clone --recurse-submodules git@github.com:WoodOxen/tactics2d.git cd tactics2d pip install -v . ``` -------------------------------- ### Circle Construction Examples Source: https://tactics2d.readthedocs.io/en/latest/api/geometry Examples demonstrating circle creation from points and tangent parameters. ```python >>> Circle.get_circle(point1=np.array([0, 0]), point2=np.array([1, 0])) (array([0.5, 0. ]), 0.5) ``` ```python >>> Circle.get_circle(point1=np.array([0, 0]), point2=np.array([1, 0]), point3=np.array([0, 1])) (array([0.5, 0.5]), 0.7071067811865476) ``` ```python >>> Circle.get_circle(tangent_point=np.array([1, 0]), tangent_heading=np.pi/2, radius=1, side="L") (array([1., 1.]), 1.0) ``` -------------------------------- ### Install tactics2d via PyPI Source: https://tactics2d.readthedocs.io/en/latest/installation Use this command to install the package directly from the Python Package Index. ```bash pip install tactics2d ``` -------------------------------- ### GET list_templates Source: https://tactics2d.readthedocs.io/en/latest/api/participant Functions to print default templates for different types of traffic participants. ```APIDOC ## GET list_vehicle_templates ### Description Prints the default vehicle templates in a table. ## GET list_cyclist_templates ### Description Prints the default cyclist templates in a table. ## GET list_pedestrian_templates ### Description Prints the default pedestrian templates in a table. ``` -------------------------------- ### Import Libraries for Data Analysis Source: https://tactics2d.readthedocs.io/en/latest/dataset_support/ind Imports essential Python libraries for data manipulation, numerical operations, and plotting. Includes warnings filter and logging setup. ```python %matplotlib inline import warnings warnings.filterwarnings("ignore") import logging logging.basicConfig(level=logging.WARNING) import pandas as pd import polars as pl import numpy as np import matplotlib as mpl import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt import seaborn as sns ``` -------------------------------- ### __init__ Source: https://tactics2d.readthedocs.io/en/latest/api/physics Initializes the point mass model with specific speed, acceleration, and simulation parameters. ```APIDOC ## __init__ ### Description Initialize the point mass model. ### Parameters - **speed_range** (Union[float, Tuple[float, float]]) - Optional - The range of speed in m/s. - **accel_range** (Union[float, Tuple[float, float]]) - Optional - The range of acceleration in m/s^2. - **interval** (int) - Optional - The time interval between states in milliseconds (default: 100). - **delta_t** (int) - Optional - The discrete time step for the simulation in milliseconds. - **backend** (str) - Optional - The backend for the simulation ('newton' or 'euler', default: 'newton'). ``` -------------------------------- ### Configure Dataset and Map Paths Source: https://tactics2d.readthedocs.io/en/latest/dataset_support/ind Sets the file paths for the dataset and map, and initializes the respective parsers. ```python dataset_path = "../../data/inD/data" # Replace with your dataset path map_path = "../../data/inD_map" # Replace with your map path dataset_parser = LevelXParser("inD") map_parser = OSMParser(lanelet2=True) ``` -------------------------------- ### Initialize Tactics2D Environment Source: https://tactics2d.readthedocs.io/en/latest/dataset_support/ind Imports necessary libraries and modules for data parsing, map handling, and visualization. ```python %matplotlib notebook import os import numpy as np from matplotlib.animation import FuncAnimation from shapely.geometry import Point from IPython.display import HTML from tactics2d.dataset_parser import LevelXParser from tactics2d.map.parser import OSMParser from tactics2d.map.map_config import IND_MAP_CONFIG from tactics2d.sensor import BEVCamera from tactics2d.renderer import MatplotlibRenderer ``` -------------------------------- ### GET get_trace Source: https://tactics2d.readthedocs.io/en/latest/api/participant Retrieves the trace of a traffic participant within a specified frame range. ```APIDOC ## GET get_trace ### Description Gets the trace of the traffic participant within the requested frame range. The returned trace format depends on the availability of width and length data. ### Parameters #### Query Parameters - **frame_range** (Tuple[int, int]) - Optional - The requested frame range (start frame, end frame) in milliseconds. If None, the whole trajectory is returned. ### Response #### Success Response (200) - **trace** (Union[LineString, LinearRing]) - The trace of the traffic participant. ``` -------------------------------- ### RacingEnv.__init__ Source: https://tactics2d.readthedocs.io/en/latest/api/envs Initializes the racing environment with specific rendering and action space configurations. ```APIDOC ## __init__(render_mode='human', render_fps=60, max_step=100000, continuous=True) ### Description Initialize the racing environment. ### Parameters #### Query Parameters - **render_mode** (str) - Optional - The mode of the rendering. It can be "human" or "rgb_array". Defaults to "human". - **render_fps** (int) - Optional - The frame rate of the rendering. Defaults to 60. - **max_step** (int) - Optional - The maximum time step of the scenario. Defaults to 100000. - **continuous** (bool) - Optional - Whether to use continuous action space. Defaults to True. ``` -------------------------------- ### Get Traffic Participant Trace Source: https://tactics2d.readthedocs.io/en/latest/api/participant Retrieves the trace of a traffic participant within a specified frame range. This is an abstract method and should be overridden in implementation. ```APIDOC ## GET /api/participant/trace ### Description Gets the trace of the traffic participant within the requested frame range. It should be overridden in implementation. ### Method GET ### Endpoint /api/participant/trace ### Parameters #### Query Parameters - **frame_range** (Tuple[int, int]) - Optional - The requested frame range. The first element is the start frame, and the second element is the end frame. The unit is millisecond (ms). ### Response #### Success Response (200) - **TraceData** - The trace data for the specified frame range. ``` -------------------------------- ### ParkingEnv Initialization Source: https://tactics2d.readthedocs.io/en/latest/api/envs Initializes the parking environment with configuration parameters for scenario generation and rendering. ```APIDOC ## __init__(type_proportion=0.5, render_mode='human', render_fps=60, max_step=20000, continuous=True) ### Description Initialize the parking environment with specific scenario proportions and rendering settings. ### Parameters - **type_proportion** (float) - Optional - Proportion of 'bay' parking scenarios (0 to 1). - **render_mode** (str) - Optional - Rendering mode ('human' or 'rgb_array'). - **render_fps** (int) - Optional - Frame rate for rendering. - **max_step** (int) - Optional - Maximum time steps for the scenario. - **continuous** (bool) - Optional - Whether to use continuous action space. ``` -------------------------------- ### Get Traffic Participant States Source: https://tactics2d.readthedocs.io/en/latest/api/participant Retrieves the states of a traffic participant within a specified frame range or for specific frames. If no range or frames are provided, all states are returned. ```APIDOC ## GET /api/participant/states ### Description Get the traffic participant's states within the requested frame range. ### Method GET ### Endpoint /api/participant/states ### Parameters #### Query Parameters - **frame_range** (Tuple[int, int]) - Optional - The requested frame range. The first element is the start frame, and the second element is the end frame. The unit is millisecond (ms). - **frames** (List[int]) - Optional - The requested frames. The unit is millisecond (ms). If the frames are not in the ascending order, they will be sorted before the states are returned. ### Response #### Success Response (200) - **List[State]** - A list of the traffic participant's states. If the frame_range is specified, the function will return the states within the requested range. If the frames is specified, the function will return the states at the requested frames. If neither is specified, the function will return all states. #### Error Response (400) - **ValueError** - The `frame_range` must be a tuple with two elements. - **KeyError** - Any requested frame in `frames` is not found in the trajectory. ``` -------------------------------- ### Vehicle Initialization Source: https://tactics2d.readthedocs.io/en/latest/api/participant Initializes a new vehicle instance with specific physical properties and configuration. ```APIDOC ## __init__(id_, type_='medium_car', trajectory=None, **kwargs) ### Description Initialize the vehicle with unique ID, type, and optional physical parameters. ### Parameters #### Request Body - **id_** (int) - Required - The unique identifier of the vehicle. - **type_** (str) - Optional - The type of the vehicle. Defaults to 'medium_car'. - **trajectory** (Trajectory) - Optional - The trajectory of the vehicle. - **length** (float) - Optional - Length in meters. - **width** (float) - Optional - Width in meters. - **height** (float) - Optional - Height in meters. - **color** (tuple) - Optional - Vehicle color. - **kerb_weight** (float) - Optional - Weight in kg. - **wheel_base** (float) - Optional - Wheel base in meters. - **front_overhang** (float) - Optional - Front overhang in meters. - **rear_overhang** (float) - Optional - Rear overhang in meters. - **max_steer** (float) - Optional - Max steering angle in radians. - **max_speed** (float) - Optional - Max speed in m/s. - **max_accel** (float) - Optional - Max acceleration in m/s^2. - **max_decel** (float) - Optional - Max deceleration in m/s^2. - **verify** (bool) - Optional - Whether to verify trajectory or state. - **physics_model** (PhysicsModelBase) - Optional - Custom physics model. - **driven_mode** (str) - Optional - Driven mode (FWD, RWD, 4WD, AWD). ``` -------------------------------- ### PID Controller Initialization and Methods Source: https://tactics2d.readthedocs.io/en/latest/api/controller Methods for initializing, configuring, and executing the PID controller for lateral and longitudinal vehicle control. ```APIDOC ## __init__(dt=0.05, control_mode='combined', ...) ### Description Initialize the PID controller with specific gains and constraints. ### Parameters - **dt** (float) - Optional - Control time step in seconds. Default 0.05. - **control_mode** (str) - Optional - 'combined', 'lateral', or 'longitudinal'. Default 'combined'. - **kp_lat** (float) - Optional - Proportional gain for lateral control. Default 1.5. - **ki_lat** (float) - Optional - Integral gain for lateral control. Default 0.2. - **kd_lat** (float) - Optional - Derivative gain for lateral control. Default 0.5. - **max_steering** (float) - Optional - Maximum steering angle in radians. Default 0.5. - **kp_lon** (float) - Optional - Proportional gain for longitudinal control. Default 2.0. - **ki_lon** (float) - Optional - Integral gain for longitudinal control. Default 0.3. - **kd_lon** (float) - Optional - Derivative gain for longitudinal control. Default 0.4. - **max_accel** (float) - Optional - Maximum acceleration in m/s². Default 3.0. - **min_accel** (float) - Optional - Minimum acceleration in m/s². Default -5.0. - **derivative_filter_alpha** (float) - Optional - Low-pass filter coefficient for derivative term. Default 0.1. ## configure(**kwargs) ### Description Update controller parameters dynamically. ## reset() ### Description Resets the controller's internal state, clearing integral accumulators and previous error values. ## step(ego_state, **kwargs) ### Description Compute PID control commands. ### Parameters - **ego_state** (State) - Required - Current state of the ego vehicle. - **kwargs** (dict) - Required - Additional inputs: 'target_heading', 'cross_track_error', 'target_speed', 'wheel_base'. ### Response - **Tuple[float, float]** - (steering_angle, acceleration) commands. ``` -------------------------------- ### SingleLineLidar Initialization Source: https://tactics2d.readthedocs.io/en/latest/api/sensor Initializes the SingleLineLidar with specified parameters. ```APIDOC ## POST /sensors/lidar/initialize ### Description Initialize the single line lidar. ### Method POST ### Endpoint /sensors/lidar/initialize ### Parameters #### Request Body - **id_** (int) - Required - The unique identifier of the LiDAR. - **map_** (Map) - Required - The map that the LiDAR is attached to. - **perception_range** (float) - Optional - The distance from the LiDAR to its maximum detection range. Defaults to 12.0. - **freq_scan** (float) - Optional - The frequency of the LiDAR scanning a full round. Defaults to 10.0. - **freq_detect** (float) - Optional - The frequency of the LiDAR sending and receiving the signal. Defaults to 5000.0. ### Response #### Success Response (200) - **message** (string) - Initialization successful. #### Response Example { "message": "SingleLineLidar initialized successfully." } ``` -------------------------------- ### Single-Track Dynamics Model Initialization Source: https://tactics2d.readthedocs.io/en/latest/api/physics Initializes the single-track dynamics model with various vehicle parameters. ```APIDOC ## `__init__(lf, lr, mass, mass_height, mu=0.7, I_z=1500, cf=20.89, cr=20.89, steer_range=None, speed_range=None, accel_range=None, interval=100, delta_t=None)` ### Description Initializes the single-track dynamics model. ### Parameters #### Path Parameters - **`lf`** (float) - Required - The distance from the center of mass to the front axle center. The unit is meter. - **`lr`** (float) - Required - The distance from the center of mass to the rear axle center. The unit is meter. - **`mass`** (float) - Required - The mass of the vehicle. The unit is kilogram. You can use the curb weight of the vehicle as an approximation. - **`mass_height`** (float) - Required - The height of the center of mass from the ground. The unit is meter. You can use half of the vehicle height as an approximation. - **`mu`** (float) - Optional - The friction coefficient. It is a dimensionless quantity. Default: 0.7. - **`I_z`** (float) - Optional - The moment of inertia of the vehicle. The unit is kilogram per meter squared (kg/m2^22). Default: 1500. - **`cf`** (float) - Optional - The cornering stiffness of the front wheel. The unit is 1/rad. Default: 20.89. - **`cr`** (float) - Optional - The cornering stiffness of the rear wheel. The unit is 1/rad. Default: 20.89. - **`steer_range`** (Union[float, Tuple[float, float]]) - Optional - The range of steering angle. The valid input is a positive float or a tuple of two floats represents (min steering angle, max steering angle). The unit is radian. Default: None. - **`speed_range`** (Union[float, Tuple[float, float]]) - Optional - The range of speed. The valid input is a positive float or a tuple of two floats represents (min speed, max speed). The unit is meter per second (m/s). Default: None. - **`accel_range`** (Union[float, Tuple[float, float]]) - Optional - The range of acceleration. The valid input is a positive float or a tuple of two floats represents (min acceleration, max acceleration). The unit is meter per second squared (m/s2^22). Default: None. - **`interval`** (int) - Optional - The time interval between the current state and the new state. The unit is millisecond. Default: 100. - **`delta_t`** (int) - Optional - The discrete time step for the simulation. The unit is millisecond. Default: None. ``` -------------------------------- ### SingleTrackKinematics Initialization Source: https://tactics2d.readthedocs.io/en/latest/api/physics Initializes the kinematic single-track model with specified physical parameters and constraints. ```APIDOC ## `__init__(lf, lr, steer_range=None, speed_range=None, accel_range=None, interval=100, delta_t=None)` ### Description Initialize the kinematic single-track model. ### Parameters #### Path Parameters - **`lf`** (float) - Required - The distance from the center of mass to the front axle center. The unit is meter. - **`lr`** (float) - Required - The distance from the center of mass to the rear axle center. The unit is meter. - **`steer_range`** (Union[float, Tuple[float, float]]) - Optional - The range of steering angle. The valid input is a positive float or a tuple of two floats represents (min steering angle, max steering angle). The unit is radian. Defaults to None. - **`speed_range`** (Union[float, Tuple[float, float]]) - Optional - The range of speed. The valid input is a positive float or a tuple of two floats represents (min speed, max speed). The unit is meter per second (m/s). Defaults to None. - **`accel_range`** (Union[float, Tuple[float, float]]) - Optional - The range of acceleration. The valid input is a positive float or a tuple of two floats represents (min acceleration, max acceleration). The unit is meter per second squared (m/s2^22). Defaults to None. - **`interval`** (int) - Optional - The time interval between the current state and the new state. The unit is millisecond. Defaults to 100. - **`delta_t`** (int) - Optional - The discrete time step for the simulation. The unit is millisecond. Defaults to None. ``` -------------------------------- ### Execute Parsing and Visualization Source: https://tactics2d.readthedocs.io/en/latest/dataset_support/ind Parses the trajectory data, loads the map, defines the boundary, and generates the animation video. ```python participants, actual_time_range = dataset_parser.parse_trajectory( file=7, folder=dataset_path, time_range=(0, 10000) ) map_ = map_parser.parse( file_path=os.path.join(map_path, "inD_1.osm"), configs=IND_MAP_CONFIG["inD_1"] ) print(f"Map boundary of InD location 1: {map_.boundary}.") boundary = ( map_.boundary[0] + 80, map_.boundary[1] - 50, map_.boundary[2] + 70, map_.boundary[3] - 100, ) ani = render_levelx(map_, participants, boundary, actual_time_range, resolution=(1500, 1000)) HTML(ani.to_html5_video()) ``` -------------------------------- ### RacingEnv.step Source: https://tactics2d.readthedocs.io/en/latest/api/envs Executes an action in the environment and returns the resulting observation, reward, and status flags. ```APIDOC ## step(action) ### Description This function takes a step in the environment. ### Parameters #### Request Body - **action** (Union[Tuple[float], int]) - Required - The action command for the agent vehicle. ### Response #### Success Response (200) - **observation** (array) - The BEV image observation of the environment. - **reward** (float) - The reward of the environment. - **terminated** (bool) - Whether the scenario is terminated. - **truncated** (bool) - Whether the scenario is truncated. - **infos** (dict) - The information of the environment. ``` -------------------------------- ### Pedestrian Initialization and Attributes Source: https://tactics2d.readthedocs.io/en/latest/api/participant Details on how to initialize a Pedestrian object and its available attributes. ```APIDOC ## Pedestrian Class ### Description This class defines a pedestrian with its common properties. ### Attributes - **`id_`** (Any) - The unique identifier of the pedestrian. - **`type_`** (str) - The type of the pedestrian. Defaults to "adult_male". - **`trajectory`** (Trajectory) - The trajectory of the pedestrian. Defaults to an empty trajectory. - **`color`** (Any) - The color of the pedestrian. Defaults to light-blue "#45aaf2". - **`length`** (float) - The length of the pedestrian in meters. Defaults to None. - **`width`** (float) - The width of the pedestrian in meters. Defaults to 0.4. - **`height`** (float) - The height of the pedestrian in meters. Defaults to None. - **`max_speed`** (float) - The maximum speed of the pedestrian in meters per second. Defaults to 7.0. - **`max_accel`** (float) - The maximum acceleration of the pedestrian in meters per second squared. Defaults to 1.5. - **`speed_range`** (Tuple[float, float]) - The speed range of the pedestrian in meters per second. Defaults to (-7.0, 7.0). - **`accel_range`** (Tuple[float, float]) - The acceleration range of the pedestrian in meters per second squared. Defaults to (-1.5, 1.5). - **`verify`** (bool) - Whether to verify the trajectory to bind or the state to add. Defaults to False. - **`physics_model`** (PhysicsModelBase) - The physics model of the pedestrian. Defaults to PointMass. - **`geometry`** (float) - The geometry shape of the pedestrian (radius of a circle). This attribute is read-only. - **`current_state`** (State) - The current state of the pedestrian. This attribute is read-only. ### `__init__(id_, type_='adult_male', trajectory=None, **kwargs)` Initialize the pedestrian. #### Parameters - **`id_`** (Any) - Required - The unique identifier of the pedestrian. - **`type_`** (str) - Optional - The type of the pedestrian. Defaults to 'adult_male'. - **`trajectory`** (Trajectory) - Optional - The trajectory of the pedestrian. #### Other Parameters - **`color`** (Any) - The color of the pedestrian. - **`length`** (float) - The length of the pedestrian in meters. - **`width`** (float) - The width of the pedestrian in meters. - **`height`** (float) - The height of the pedestrian in meters. - **`max_speed`** (float) - The maximum speed of the pedestrian in meters per second. - **`max_accel`** (float) - The maximum acceleration of the pedestrian in meters per second squared. - **`verify`** (bool) - Whether to verify the trajectory to bind or the state to add. - **`physics_model`** (PhysicsModelBase) - The physics model of the pedestrian. Defaults to PointMass. ``` -------------------------------- ### Lane Class Initialization Source: https://tactics2d.readthedocs.io/en/latest/api/map This snippet details the initialization of the Lane class, including all its parameters and their default values. ```APIDOC ## Lane Class This class implements the map element _Lane_. Reference Lanelet2's description of a lane. ### Attributes * **`id_`**(`str`) – The unique identifier of the lane. * **`left_side`**(`LineString`) – The left side of the lane. * **`right_side`**(`LineString`) – The right side of the lane. * **`line_ids`**(`dict`) – The ids of the roadline components. The dictionary has two keys: `left` and `right`. Defaults to dict(left=[], right=[]). * **`regulatory_ids`**(`set`) – The ids of the regulations that apply to the lane. Defaults to set(). * **`type_`**(`str`) – The type of the lane. The default value is `"lanelet"`. * **`subtype`**(`str`) – The subtype of the lane. Defaults to None. * **`color`**(`Any`) – The color of the area. If not specified, the color will be assigned based on the rendering template later. Defaults to None. * **`location`**(`str`) – The location of the lane (urban, nonurban, etc.). Defaults to None. * **`inferred_participants`**(`list`) – The allowing type of traffic participants that can pass the area. If not specified, the area is not restricted to any type of traffic participants. Defaults to None. * **`speed_limit`**(`float`) – The speed limit in this area The unit is `m/s`. Defaults to None. * **`speed_limit_mandatory`**(`bool`) – Whether the speed limit is mandatory or not. Defaults to True. * **`custom_tags`**(`dict`) – The custom tags of the area. Defaults to None. * **`predecessors`**(`set`) – The ids of the available lanes before entering the current lane. * **`successors`**(`set`) – The ids of the available lanes after exiting the current lane. * **`left_neighbors`**(`set`) – The ids of the lanes that is adjacent to the left side of the current lane and in the same direction. * **`right_neighbors`**(`set`) – The ids of the lanes that is adjacent to the right side of the current lane and in the same direction. * **`starts`**(`list`) – The start points of the lane. * **`ends`**(`list`) – The end points of the lane. * **`geometry`**(`LinearRing`) – The geometry representation of the lane. This attribute will be automatically obtained during the initialization if there is no None in left_side and right_side. * **`shape`**(`list`) – The shape of the lane. This attribute is **read-only**. ### `__init__(id_, left_side=None, right_side=None, geometry=None, line_ids=dict(left=[], right=[]), regulatory_ids=set(), type_='lanelet', subtype=None, color=None, location=None, inferred_participants=None, speed_limit=None, speed_limit_unit='km/h', speed_limit_mandatory=True, custom_tags=None)` Initialize an instance of this class. #### Parameters * **`id_`**(`str`) – Required – The unique identifier of the lane. * **`left_side`**(`LineString` , default: `None` ) – Optional – The left side of the lane. * **`right_side`**(`LineString` , default: `None` ) – Optional – The right side of the lane. * **`geometry`**(`LinearRing` , default: `None` ) – Optional – The geometry of the lane. This parameter only takes effect when the `left_side` or `right_side` is None. * **`line_ids`**(`set` , default: `dict(left=[], right=[])` ) – Optional – The ids of the lines that make up the lane. * **`regulatory_ids`**(`set` , default: `set()` ) – Optional – The ids of the regulations that apply to the lane. * **`type_`**(`str` , default: `'lanelet'` ) – Optional – The type of the lane. * **`subtype`**(`str` , default: `None` ) – Optional – The subtype of the lane. * **`color`**(`Any` , default: `None` ) – Optional – The color of the lane. If not specified, the color will be assigned based on the rendering template later. * **`location`**(`str` , default: `None` ) – Optional – The location of the lane (urban, nonurban, etc.). * **`inferred_participants`**(`list` , default: `None` ) – Optional – The allowing type of traffic participants that can pass the lane. If not specified, the lane is not restricted to any type of traffic participants. * **`speed_limit`**(`float` , default: `None` ) – Optional – The speed limit in this lane. * **`speed_limit_unit`**(`str` , default: `'km/h'` ) – Optional – The unit of speed limit in this lane. The valid units are `km/h`, `mi/h`, and `m/s`. The speed limit will be automatically converted to `m/s` when initializing the instance. If the unit is invalid, the speed limit will be set to None. * **`speed_limit_mandatory`**(`bool` , default: `True` ) – Optional – Whether the speed limit is mandatory or not. * **`custom_tags`**(`dict` , default: `None` ) – Optional – The custom tags of the lane. ``` -------------------------------- ### Environment Step Function Source: https://tactics2d.readthedocs.io/en/latest/api/envs The `step` function simulates taking an action in the environment and returns the outcome. ```APIDOC ## step(action) ### Description This function takes a step in the environment. ### Method POST ### Endpoint /websites/tactics2d_readthedocs_io_en/step ### Parameters #### Request Body - **action** (Union[tuple, int]) - Required - The action command for the agent vehicle. If the action space is continuous, the input should be a tuple, whose first element controls the steering value and the second controls the acceleration. If the action space is discrete, the input should be an index that points to a pre-defined control command. ### Request Example { "action": [0.5, 0.8] } ### Response #### Success Response (200) - **observation** (array) - The BEV image observation of the environment. - **reward** (float) - The reward of the environment. - **terminated** (bool) - Whether the scenario is terminated. If the agent has completed the scenario, the scenario is terminated. - **truncated** (bool) - Whether the scenario is truncated. If the scenario status goes abnormal or the traffic status goes abnormal, the scenario is truncated. - **infos** (dict) - The information of the environment. #### Response Example { "observation": [0.1, 0.2, 0.3], "reward": 1.0, "terminated": false, "truncated": false, "infos": {"speed": 50} } ### Raises - **InvalidAction** - If the action is not in the action space. ``` -------------------------------- ### PurePursuitController API Source: https://tactics2d.readthedocs.io/en/latest/api/controller Implementation of the Pure Pursuit algorithm for path tracking and vehicle control. ```APIDOC ## step(ego_state, waypoints, wheel_base=2.637, **kwargs) ### Description Outputs acceleration and steering commands based on the current vehicle state and path waypoints. ### Parameters - **ego_state** (State) - Required - Current state of the ego vehicle. - **waypoints** (LineString) - Required - Path to follow. - **wheel_base** (float) - Optional - Wheelbase of the vehicle in meters. Default 2.637. - **kwargs** (dict) - Optional - Additional inputs for longitudinal controller. ### Response - **steering** (float) - Steering command in radians. - **accel** (float) - Acceleration command in m/s². ``` -------------------------------- ### ParkingEnv Reset Source: https://tactics2d.readthedocs.io/en/latest/api/envs Resets the environment to its initial state. ```APIDOC ## reset(seed=None, options=None) ### Description Resets the environment and returns the initial observation and info dictionary. ### Parameters - **seed** (int) - Optional - Random seed. - **options** (dict) - Optional - Environment options. ### Response - **observation** (np.array) - The BEV image observation. - **infos** (dict) - Environment information including lidar, state, target_area, target_heading, traffic_status, and scenario_status. ``` -------------------------------- ### Single-Track Drift Model Initialization Source: https://tactics2d.readthedocs.io/en/latest/api/physics Initializes the single-track drift model with specified vehicle parameters. ```APIDOC ## `__init__(lf, lr, mass, mass_height, radius=0.344, T_sb=0.76, T_se=1, tire=Tire(), I_z=1500, I_yw=1.7, steer_range=None, speed_range=None, accel_range=None, interval=100, delta_t=None)` ### Description Initializes the single-track drift model. ### Parameters #### Path Parameters - **`lf`** (float) - Required - The distance from the center of mass to the front axle center. The unit is meter. - **`lr`** (float) - Required - The distance from the center of mass to the rear axle center. The unit is meter. - **`mass`** (float) - Required - The mass of the vehicle. The unit is kilogram. You can use the curb weight of the vehicle as an approximation. - **`mass_height`** (float) - Required - The height of the center of mass from the ground. The unit is meter. You can use half of the vehicle height as an approximation. - **`radius`** (float) - Optional - The effective radius of the wheel. The unit is meter. Default: 0.344. - **`T_sb`** (float) - Optional - The split parameter between the front and rear axles for the braking torque. Default: 0.76. - **`T_se`** (float) - Optional - The split parameter between the front and rear axles for the engine torque. Default: 1. - **`tire`** (Any) - Optional - The tire model. The current implementation refers to the parameters in CommonRoad: Vehicle Models (2020a). If you want to use a different tire model, you need to implement the tire model by yourself. Default: Tire(). - **`I_z`** (float) - Optional - The moment of inertia of the vehicle. The unit is kilogram meter squared (kg m^2). Default: 1500. - **`I_yw`** (float) - Optional - The moment of inertia of the wheel. The unit is kilogram meter squared (kg m^2). Default: 1.7. - **`steer_range`** (Union[float, Tuple[float, float]]) - Optional - The range of steering angle. The valid input is a positive float or a tuple of two floats represents (min steering angle, max steering angle). The unit is radian. Default: None. - **`speed_range`** (Union[float, Tuple[float, float]]) - Optional - The range of speed. The valid input is a positive float or a tuple of two floats represents (min speed, max speed). The unit is meter per second (m/s). Default: None. - **`accel_range`** (Union[float, Tuple[float, float]]) - Optional - The range of acceleration. The valid input is a positive float or a tuple of two floats represents (min acceleration, max acceleration). The unit is meter per second squared (m/s2^22). Default: None. - **`interval`** (int) - Optional - The time interval between the current state and the new state. The unit is millisecond. Default: 100. - **`delta_t`** (int) - Optional - The discrete time step for the simulation. The unit is millisecond. Default: None. ``` -------------------------------- ### Circle Construction Usages Source: https://tactics2d.readthedocs.io/en/latest/api/geometry Supported parameter combinations for creating a circle. ```python 1. From two points. The first point is the center, and the second point is a point on the circumference. get_circle(point1, point2) 2. From three points on the circumference. get_circle(point1, point2, point3) 3. From a tangent vector and radius. get_circle(tangent_point, tangent_heading, radius, side) ``` -------------------------------- ### ParkingEnv Close Source: https://tactics2d.readthedocs.io/en/latest/api/envs Closes the environment instance. ```APIDOC ## close() ### Description Closes the environment and releases associated resources. ``` -------------------------------- ### Configure Matplotlib and Seaborn Settings Source: https://tactics2d.readthedocs.io/en/latest/dataset_support/ind Sets up global parameters for Matplotlib figures and Seaborn palettes for consistent plotting. Adjusts DPI, font, and style for high-quality visualizations. ```python # Setting up parameters for matplotlib mpl.rcParams.update( { "figure.dpi": 200, # 200 for high quality "font.family": "DejaVu Sans Mono", "font.size": 6, "font.stretch": "semi-expanded", "animation.html": "jshtml", "animation.embed_limit": 5000, "axes.edgecolor": "black", "axes.linewidth": 0.8, "axes.grid": True, "grid.color": "#cccccc", "axes.facecolor": "white", } ) sns.set_palette("Set2") ``` -------------------------------- ### Waymo Open Motion Dataset (WOMD) Parser Source: https://tactics2d.readthedocs.io/en/latest/api/dataset_parser Implements a parser for the Waymo Open Motion Dataset (WOMD). ```APIDOC ## WOMDParser This class implements a parser for Waymo Open Motion Dataset (WOMD). Reference Ettinger, Scott, et al. "Large scale interactive motion forecasting for autonomous driving: The waymo open motion dataset." Proceedings of the IEEE/CVF International Conference on Computer Vision. 2021. Because loading the tfrecord file is time consuming, the trajectory and the map parsers provide two ways to load the file. The first way is to load the file directly from the given file path. The second way is to load the file from a tfrecord.tfrecord_iterator object. If the tfrecord.tfrecord_iterator object is given, the parser will ignore the file path. ### get_scenario_ids(dataset, cache_data=False) #### Description This function get the list of scenario ids from the given tfrecord file. #### Parameters - **dataset** (tfrecord_iterator) - Required - The dataset to parse. - **cache_data** (bool) - Optional - If True, also cache the raw data bytes for each scenario. Defaults to False. #### Returns - **id_list** (List[str]) - A list of scenario ids looking like ["637f20cafde22ff8", ...]. - **Union[List[str], List[bytes]]** - If cache_data is True, returns a tuple (id_list, data_list) where data_list contains the raw bytes for each scenario. ### parse_map(scenario_id=None, **kwargs) #### Description This function parses the map from a single WOMD file. #### Parameters - **scenario_id** (str) - Optional - The id of the scenario to parse. If the scenario id is not given, the first scenario in the file will be parsed. Defaults to None. #### Other Parameters - **dataset** (tfrecord_iterator) - The dataset to parse. - **file** (str) - The name of the trajectory file. The file is expected to be a tfrecord file (.tfrecord). - **folder** (str) - The path to the folder containing the tfrecord file. #### Returns - **map_** (Map) - A map object. #### Raises - **KeyError** - Either dataset or file and folder should be given as keyword arguments. ``` -------------------------------- ### BEVCamera Class Source: https://tactics2d.readthedocs.io/en/latest/api/sensor Documentation for the BEVCamera class, which defines the render paradigm of a BEV camera. ```APIDOC ## BEVCamera Bases: `SensorBase` This class defines the render paradigm of a BEV camera. ### Attributes - **`id_`** (int) - The unique identifier of the sensor. This attribute is **read-only** once the instance is initialized. - **`map_`** (Map) - The map that the sensor is attached to. This attribute is **read-only** once the instance is initialized. - **`perception_range`** (Union[float, Tuple[float]]) - The distance from the sensor to its maximum detection range in (left, right, front, back). When this value is undefined, the sensor is assumed to detect the whole map. Defaults to None. - **`position`** (Point) - The position of the sensor in the global 2D coordinate system. - **`bind_id`** (Any) - The unique identifier of object that the sensor is bound to. This attribute is **read-only** and can only be set using the `bind_with` method. - **`is_bound`** (bool) - Whether the sensor is bound to an object. This attribute is **read-only** once the instance is initialized. ### `__init__(id_, map_, perception_range=None)` Initialize the BEV camera. Parameters: - **`id_`** (int) - The unique identifier of the camera. - **`map_`** (Map) - The map that the camera is attached to. - **`perception_range`** (Union[float, Tuple[float]] , default: `None` ) - The distance from the camera to its maximum detection range in (left, right, front, back). When this value is undefined, the sensor is assumed to detect the whole map. This can be a single float value or a tuple of four values representing the perception range in each direction (left, right, front, back). Defaults to None. ### `update(frame, participants, participant_ids, prev_road_id_set=None, prev_participant_id_set=None, position=None, heading=None)` This function is used to update the camera's position and obtain the geometry data under specific rendering paradigm. Parameters: - **`frame`** (int) - The frame of the observation. - **`participants`** (Dict) - The participants in the scenario. - **`participant_ids`** (List) - The list of participant IDs to be rendered. - **`prev_road_id_set`** (Set , default: `None` ) - The set of road IDs that were rendered in the previous frame. Defaults to None. - **`prev_participant_id_set`** (Set , default: `None` ) - The set of participant IDs that were rendered in the previous frame. Defaults to None. - **`position`** (Point , default: `None` ) - The position of the camera. Defaults to None. - **`heading`** (float , default: `None` ) - The heading of the camera in radians. Defaults to None. Returns: - **`geometry_data`** (Dict ) - The geometry data to be rendered in unified format. - **`road_id_set`** (Set ) - The set of road IDs that were rendered in the current frame. - **`participant_id_set`** (Set ) - The set of participant IDs that were rendered in the current frame. ``` -------------------------------- ### SensorBase Class Source: https://tactics2d.readthedocs.io/en/latest/api/sensor Documentation for the SensorBase class, which defines a base interface for sensors. ```APIDOC ## SensorBase Bases: `ABC` This class defines a base interface for sensors. ### Attributes - **`id_`** (int) - The unique identifier of the sensor. This attribute is **read-only** once the instance is initialized. - **`map_`** (Map) - The map that the sensor is attached to. This attribute is **read-only** once the instance is initialized. - **`perception_range`** (Union[float, Tuple[float]]) - The distance from the sensor to its maximum detection range in (left, right, front, back). When this value is undefined, the sensor is assumed to detect the whole map. Defaults to None. This attribute is **read-only** once the instance is initialized. - **`position`** (Point) - The position of the sensor in the global 2D coordinate system. - **`bind_id`** (Any) - The unique identifier of object that the sensor is bound to. This attribute is **read-only** and can only be set using the `bind_with` method. - **`is_bound`** (bool) - Whether the sensor is bound to an object. This attribute is **read-only** once the instance is initialized. ### `__init__(id_, map_, perception_range=None)` Initialize the sensor. Parameters: - **`id_`** (int) - The unique identifier of the sensor. - **`map_`** (Map) - The map that the sensor is attached to. - **`perception_range`** (Union[float, Tuple[float]] , default: `None` ) - The distance from the sensor to its maximum detection range in (left, right, front, back). When this value is undefined, the sensor is assumed to detect the whole map. This can be a single float value or a tuple of four values representing the perception range in each direction (left, right, front, back). Defaults to None. ### `bind_with(bind_id)` Bind the sensor to a participant with the given ID. Parameters: - **`bind_id`** (int) - ID of the participant to bind to. ``` -------------------------------- ### CitySim Parser Methods Source: https://tactics2d.readthedocs.io/en/latest/api/dataset_parser Methods for retrieving time ranges and parsing trajectory data from the CitySim dataset. ```APIDOC ## CitySimParser.get_time_range ### Description Gets the time range of a single trajectory data file. ### Parameters #### Path Parameters - **file** (str) - Required - The name of the trajectory data file (.csv). - **folder** (str) - Required - The path to the folder containing the trajectory data. ### Response - **actual_time_range** (Tuple[int, int]) - The start and end time range in milliseconds. ## CitySimParser.parse_trajectory ### Description Parses the trajectory data of CitySim datasets. States are collected at 30Hz. ### Parameters #### Path Parameters - **file** (str) - Required - The name of the trajectory data file (.csv). - **folder** (str) - Required - The path to the folder containing the trajectory data. - **time_range** (Tuple[int, int]) - Optional - The time range to parse in milliseconds. - **ids** (list) - Optional - The list of trajectory IDs to parse. ### Response - **participants** (dict) - A dictionary of participants keyed by ID. - **actual_stamp_range** (Tuple[int, int]) - The start and end time range in milliseconds. ```