agents.tools package

Submodules

agents.tools.config_creation module

This module creates type-hint schemas for the Hydra and OmegaConf backend.

Note

The conf/agent/default_settings.yaml file is automatically created when this file runs.

agents.tools.config_creation.MISSING: Any

Alias for omegaconf.MISSING, is literally "???" but has type Any.

If an attribute with this value is accessed from a DictConfig, it will raise a MissingMandatoryValue error.

agents.tools.config_creation.NestedConfigDict

Dict[str, NestedConfigDict | AgentConfig | DictConfig | Any]

Type:

Alias for nested configurations

class agents.tools.config_creation.AgentConfig

Bases: object

Base interface for the agent settings.

Handling the initialization from a nested dataclass and merges in the changes from the overwrites options.

overwrites: NestedConfigDict | None = None

Overwrites of nested dictionaries for used for the initialization of the config.

classmethod get_defaults() AgentConfig

Returns the global default options.

Return type:

AgentConfig

classmethod export_options(path: str | PathLike[str], *, resolve: bool = False, with_comments: bool = False, detailed_rules: bool = False, include_private: bool = False) None

Exports the options to a YAML file. With the to_yaml() method.

Parameters:
  • path (str | PathLike[str]) – The path for the exported YAML file.

  • resolve (bool) – Whether to resolve the options before exporting. Defaults to False.

  • with_comments (bool) – Whether to include comments in the exported YAML file. Defaults to False.

  • detailed_rules (bool) – Whether to include detailed rules in the exported YAML file. Defaults to False.

  • include_private (bool) – Whether to include private fields in the exported YAML file. Defaults to False.

Returns:

None

Return type:

None

classmethod to_yaml(resolve: bool = False, yaml_commented: bool = True, detailed_rules: bool = False, *, include_private: bool = False) str

Convert the options to a YAML string representation.

Parameters:
  • resolve (bool) – Whether to resolve interpolations. Defaults to False.

  • yaml_commented (bool) – Whether to include comments in the YAML output. Defaults to True.

  • detailed_rules (bool) – Whether to include detailed rules in the YAML output. Defaults to False.

  • include_private (bool) – Whether to include fields that are marked as private. Defaults to False.

Returns:

The YAML string representation of the options.

Return type:

str

classmethod from_yaml(path: str, *, merge: bool = True) Self

Loads the options from a yaml file.

Parameters:
  • path (str) – The path to the yaml file.

  • merge (bool) – Merges the loaded yaml into the base class settings. Otherwise returns the settings as they are in the file. Defaults to True.

Returns:

An instance of this class

Return type:

AgentConfig

classmethod create(settings: os.PathLike[str] | str | DictConfig | NestedConfigDict | AgentConfig | None = None, overwrites: NestedConfigDict | None = None, *, assure_copy: bool = True, as_dictconfig: bool | None = True, dict_config_no_parent: bool = True) Self | AsDictConfig[Self]

Creates the agent settings based on the provided arguments.

Note

By default this returns a DictConfig version of this class.

Parameters:
  • settings (Union[os.PathLike[str], str, DictConfig, NestedConfigDict | AgentConfig, None]) – The argument specifying the agent settings. It can be a path to a YAML file, a dictionary, a @dataclass decorated class or a omegaconf.DictConfig.

  • overwrites (Optional[NestedConfigDict]) – Optional mapping containing additional settings to overwrite the default agent settings.

  • as_dictconfig (Optional[bool]) –

    • If True, the agent settings are returned as a DictConfig.

    • If False, the agent settings are returned as an instance of this class.

    • If None, the return type is determined by the type of the args and other arguments i.e. if args is a DictConfig and assure_copy is False, the original input is checked and returned.

  • assure_copy (bool)

  • dict_config_no_parent (bool)

Returns:

The created agent settings.

Return type:

AgentConfig (duck-typed); actually omegaconf.DictConfig)

Raises:

Exception – If the overwrites cannot be merged into the agent settings.

classmethod check_config(config: NestedConfigDict, strictness: int = 1, as_dict_config: bool = True) Self
  • strictness == 1 type-cast the config to this class, assuring all keys are present. However the type and correctness of the field-contents are not checked.

  • strictness > 1 the config will be a DictConfig object. as_dict_config is ignored.

  • strictness == 2: Will assure that the initial types are correct.

  • strictness >= 2 will return the config as a structured config, forcing the defined types during runtime as well.

Attention

Type-forcing for more complex types does not work, e.g. types from the carla module, this especially includes carla’s enum objects. For what is supported see https://omegaconf.readthedocs.io/en/2.3_branch/structured_config.html.

Parameters:
  • config (NestedConfigDict) – The configuration to check against this class

  • strictness (int) – See above. Defaults to 1.

  • as_dict_config (bool) – Whether to return a duck-typed DictConfig instead of an instance of this class. Defaults to True.

Returns:

A version of this class or a duck-typed DictConfig.

Return type:

Self

classmethod to_dict_config(*, lock_interpolations: bool = True, lock_fields: List[str] | None = None) DictConfig

Returns a omegaconf.DictConfig from the current options.

Interpolations can be locked to prevent them from being overwritten. E.g. speed.current_speed cannot diverge from live_info.current_speed.

Parameters:
  • lock_interpolations (bool) – Whether to set interpolations to readonly. Defaults to True.

  • lock_fields (Optional[List[str]]) – A list of fields to set to readonly. Defaults to None.

Returns:

The options as a DictConfig.

Return type:

AgentConfig (duck-typed); actually omegaconf.DictConfig)

copy() Self

Returns a deep copy of this object.

Return type:

Self

classmethod get(key: str, default: _T = _NOTSET) Any | _T

Analog of getattr().

Raises:

AttributeError – If the key is not found and no default is provided.

Parameters:
  • key (str)

  • default (_T)

Return type:

Any | _T

update(options: NestedConfigDict | DictConfig | AgentConfig, clean: bool = True) None

Updates the options with a new dictionary. Will call update() recursively for nested AgentConfig objects.

Parameters:
Return type:

None

classmethod uses_overwrite_interface() bool

Whether or not the class is created by a single parameter “overwrites” or via keyword arguments for each field.

Return type:

bool

classmethod cast(value: Any)

Type-hinting method to cast a value to this class.

Parameters:

value (Any)

_clean_options()

Postprocessing of possibly wrong values

class agents.tools.config_creation.BasicAgentSettings(overwrites: Optional[OverwriteDictTypes] = <factory>)

Bases: AgentConfig

Settings used by the BasicAgent provided with CARLA.

Parameters:

overwrites (Optional[OverwriteDictTypes])

live_info: LiveInfo
speed: BasicAgentSpeedSettings
distance: BasicAgentDistanceSettings
lane_change: BasicAgentLaneChangeSettings
obstacles: BasicAgentObstacleSettings
controls: BasicAgentControllerSettings
planner: BasicAgentPlannerSettings
emergency: BasicAgentEmergencySettings
class agents.tools.config_creation.BehaviorAgentSettings(overwrites: Optional[OverwriteDictTypes] = <factory>, avoid_tailgators: bool = True)

Bases: AgentConfig

Settings used by the BehaviorAgent provided with CARLA.

Parameters:
  • overwrites (Optional[OverwriteDictTypes])

  • avoid_tailgators (bool)

live_info: LiveInfo
speed: BehaviorAgentSpeedSettings
distance: BehaviorAgentDistanceSettings
lane_change: BehaviorAgentLaneChangeSettings
obstacles: BehaviorAgentObstacleSettings
controls: BehaviorAgentControllerSettings
planner: BehaviorAgentPlannerSettings
emergency: BehaviorAgentEmergencySettings
avoid_tailgators: bool = True
class agents.tools.config_creation.LunaticAgentSettings(overwrites: Optional[OverwriteDictTypes] = <factory>, rules: list[RuleCreatingParameters] = <factory>)

Bases: AgentConfig

Config schema definition for the LunaticAgent class

Parameters:
  • overwrites (Optional[OverwriteDictTypes])

  • rules (list[RuleCreatingParameters])

live_info: LiveInfo
speed: LunaticAgentSpeedSettings
distance: LunaticAgentDistanceSettings
lane_change: LunaticAgentLaneChangeSettings
obstacles: LunaticAgentObstacleSettings
controls: LunaticAgentControllerSettings
planner: LunaticAgentPlannerSettings
emergency: LunaticAgentEmergencySettings
rss: RssSettings
detection_matrix: DetectionMatrixSettings
rules: list[RuleCreatingParameters]

A list of Rule parameters that allow the instantiation of Rules, with the Hydra instantiate feature.

See also

class agents.tools.config_creation.ContextSettings(overwrites: Optional[OverwriteDictTypes] = <factory>, rules: list[RuleCreatingParameters] = <factory>)

Bases: LunaticAgentSettings

Config class for the Context object.

Extends the LunaticAgentSettings by the current_rule attribute to accesses the Rule.self_config attribute from the context.

Parameters:
  • overwrites (Optional[OverwriteDictTypes])

  • rules (list[RuleCreatingParameters])

current_rule: RuleConfig = '${self}'

Special settings of the current rule. Only available from Context within rules ctx.config.current_rule

Note

Internally Context.config.current_rule and Rule.self_config are the same object.

See also

  • RuleConfig.self_config

class agents.tools.config_creation.CallFunctionFromConfig(_target_: 'str', _args_: 'List[Any]' = <factory>, random_lane_change: 'bool' = False)

Bases: object

Parameters:
random_lane_change: bool = False

For create_default_rules(); Should the RandomLaneChangeRule be added

class agents.tools.config_creation.CreateRuleFromConfig(_target_: str, _args_: List[Any] | None = MISSING, phases: str | Phase | None = MISSING, condition: str | None = MISSING, action: str | None = MISSING, false_action: str | None = MISSING, actions: Dict[Any, str] | None = MISSING, description: str = MISSING, overwrite_settings: Dict[str, Any] | None = MISSING, self_config: NestedConfigDict = MISSING, priority: RulePriority = MISSING, cooldown_reset_value: int | None = MISSING, group: str | None = MISSING, enabled: bool = MISSING, rules: List[CreateRuleFromConfig] = MISSING, execute_all_rules: bool = MISSING, weights: Dict[str, float] | None = MISSING, repeat_if_not_applicable: bool = MISSING, ignore_phase: bool = MISSING, MAX_TICKS: int | None = MISSING, max_tick_callback: str | None = MISSING, gameframework: GameFramework | None = MISSING)

Bases: object

Keywords to instantiate Rule classes

omegaconf.MISSING (alias for '???') attributes will not be passed to a Rule’s __init__() method.

Parameters:
  • _target_ (str)

  • _args_ (Optional[List[Any]])

  • phases (Optional[Union[str, Phase]])

  • condition (Optional[str])

  • action (Optional[str])

  • false_action (Optional[str])

  • actions (Optional[Dict[Any, str]])

  • description (str)

  • overwrite_settings (Optional[Dict[str, Any]])

  • self_config (NestedConfigDict)

  • priority (RulePriority)

  • cooldown_reset_value (Optional[int])

  • group (Optional[str])

  • enabled (bool)

  • rules (List[CreateRuleFromConfig])

  • execute_all_rules (bool)

  • weights (Optional[Dict[str, float]])

  • repeat_if_not_applicable (bool)

  • ignore_phase (bool)

  • MAX_TICKS (Optional[int])

  • max_tick_callback (Optional[str])

  • gameframework (Optional[GameFramework])

phases: str | Phase | None = MISSING
condition: str | None = MISSING
action: str | None = MISSING
false_action: str | None = MISSING
actions: Dict[Any, str] | None = MISSING
description: str = MISSING
overwrite_settings: Dict[str, Any] | None = MISSING

These will be used to overwrite the settings of the agent.

self_config: NestedConfigDict = MISSING

This is a private storage for this rule instance to be used with its own condition and action functions.

Interpolation to agent, or rather, context keys is possible.

Note

  • Also has an instance key which is the instance of the rule.

  • You can access config rule also with ctx.current_rule

priority: RulePriority = MISSING
cooldown_reset_value: int | None = MISSING
group: str | None = MISSING
enabled: bool = MISSING
rules: List[CreateRuleFromConfig] = MISSING
execute_all_rules: bool = MISSING
weights: Dict[str, float] | None = MISSING
repeat_if_not_applicable: bool = MISSING
ignore_phase: bool = MISSING
MAX_TICKS: int | None = MISSING
max_tick_callback: str | None = MISSING
gameframework: GameFramework | None = MISSING

Needed explicitly for BlockingRules once. Depending on setup can be omitted

class agents.tools.config_creation.RuleConfig(instance: object = MISSING)

Bases: object

Subconfig for rules; can have arbitrary keys

Parameters:

instance (object)

instance: object = MISSING

The instance of the rule, can be accessed by ctx.current_rule.instance

class agents.tools.config_creation.CameraConfig(width: int = 1280, height: int = 720, gamma: float = 2.2, camera_blueprints: list = <factory>, hud: Dict[str, Any] = MISSING, recorder: RecorderSettings = <factory>, detection_matrix: DetectionMatrixHudConfig = <factory>)

Bases: AgentConfig

Parameters:
width: int = 1280
height: int = 720
gamma: float = 2.2

Gamma correction of the camera

camera_blueprints: list
hud: Dict[str, Any] = MISSING

Not yet implemented. Future settings for the HUD.

Type:

HUD settings

class RecorderSettings(enabled: bool = MISSING, output_path: str = '${hydra:runtime.output_dir}/recorder/session%03d/%08d.bmp', frame_interval: int = 4)

Bases: AgentConfig

Recorder settings for the camera.

Parameters:
  • enabled (bool)

  • output_path (str)

  • frame_interval (int)

output_path: str = '${hydra:runtime.output_dir}/recorder/session%03d/%08d.bmp'

Folder to record the camera

Needs two numeric conversion placeholders.

Note

When using the ${hydra:runtime.output_dir} resolver @hydra.main needs to be used or hydra must be initialized.

frame_interval: int = 4

Interval to record the camera

recorder: RecorderSettings
class DetectionMatrixHudConfig(draw: bool = True, draw_values: bool = True, vertical: bool = True, imshow_settings: ~typing.Dict[str, ~typing.Any] = <factory>, text_settings: ~typing.Dict[str, ~typing.Any] = <factory>)

Bases: AgentConfig

DetectionMatrix settings for the HUD

Attention

Keys must match keywords of DetectionMatrix.render()

Parameters:
  • draw (bool)

  • draw_values (bool)

  • vertical (bool)

  • imshow_settings (Dict[str, Any])

  • text_settings (Dict[str, Any])

draw: bool = True

Whether to draw the detection matrix

draw_values: bool = True

Whether to draw the numerical values as text

vertical: bool = True

Orient vertical (lanes are left to right) instead of horizontal.

imshow_settings: Dict[str, Any]

Settings for the pyplot.imshow function

text_settings: Dict[str, Any]

Settings for the text of pyplot.text when drawing the numerical values

detection_matrix: DetectionMatrixHudConfig
class agents.tools.config_creation.LaunchConfig(strict_config: 'Union[bool, int]' = 3, verbose: 'bool' = True, debug: 'bool' = True, interactive: 'bool' = False, seed: 'Optional[int]' = 1, map: 'str' = 'Town04_Opt', host: 'str' = '127.0.0.1', port: 'int' = 2000, fps: 'int' = 20, sync: 'Union[bool, None]' = True, handle_ticks: 'bool' = True, loop: 'bool' = True, width: 'int' = 1280, height: 'int' = 720, gamma: 'float' = 2.2, externalActor: 'bool' = True, rolename: 'str' = 'hero', filter: 'str' = 'vehicle.*', generation: "Literal[1, 2, 'all']" = 2, autopilot: 'bool' = False, agent: 'LunaticAgentSettings' = MISSING, camera: 'CameraConfig' = <factory>, hydra: 'HydraConf' = MISSING)

Bases: AgentConfig

Parameters:
strict_config: bool | int = 3

If enabled will assert that the loaded config is a subset of the LaunchConfig class.

If set to >= 2, will assert that during runtime the types are correct.

verbose: bool = True

unused kept for compatibility with carla examples.

debug: bool = True

If true will print out some more information and draws waypoints

interactive: bool = False

If True will create an interactive session with command line input - NOTE: Needs custom code in the main file (Not implemented)

seed: int | None = 1
map: str = 'Town04_Opt'
host: str = '127.0.0.1'
port: int = 2000
fps: int = 20

Used to fix carla.WorldSettings.fixed_delta_seconds

Experimental also used to cap fps in the simulation.

sync: bool | None = True

If True, the simulation will be set to run in synchronous mode. For False, the simulation will be set to run in asynchronous mode. If None the world settings for synchronous mode will not be adjusted, assuming this is handled by the user / external system.

handle_ticks: bool = True

Decide if the GameFramework & WoldModel are allowed to call carla.World.tick() or if False the ticks should be handled by an outside system.

loop: bool = True

If True the agent will look for a new waypoint after the initial route is done.

Note

Needs custom implementation in the main file by the user.

width: int = 1280

width of pygame window

height: int = 720

height of pygame window

gamma: float = 2.2

Gamma correction of the camera. Depending on the weather and map this might need to be adjusted.

externalActor: bool = True

If False will spawn a vehicle for the agent to control, using the filter and generation settings. Otherwise will not spawn a vehicle but will wait until an actor with the name defined in rolename (default: “hero”) is found.

This vehicle needs to be spawned by another process, e.g. through the scenario runner.

rolename: str = 'hero'

Actor name to wait for if externalActor is True.

filter: str = 'vehicle.*'

Filter for the ego blueprint. Kept for compatibility with carla examples.

generation: Literal[1, 2, 'all'] = 2

Generation for the ego blueprint. Kept for compatibility with carla examples.

autopilot: bool = False

Whether or not to use the CARLAS’s carla.TrafficManager to autopilot the agent

Note

This disables the usage of the LunaticAgent, however needs to be enabled in the main script by the user to work.

agent: LunaticAgentSettings = MISSING

The settings of the agent

camera: CameraConfig
hydra: HydraConf = MISSING

Hydra config dict.

Attention

This field is not guaranteed to be present or the complete HydraConf schema.

leaderboard: Annotated[DictConfig, 'Only present for the', LunaticChallenger]

agents.tools.hints module

Module to add high-level semantic return types for obstacle and traffic light detection results via named tuples.

The code is compatible with Python 2.7, <3.6 and >=3.6. The later uses the typed version of named tuples.

class agents.tools.hints.TrafficLightDetectionResult(traffic_light_was_found, traffic_light)

Bases: NamedTuple

Parameters:
traffic_light_was_found: bool
traffic_light: carla.TrafficLight | None

The found traffic light. If no traffic light was found, the value is None.

__bool__()
Returns:

Value of traffic_light_was_found.

class agents.tools.hints.ObstacleDetectionResult(obstacle_was_found, obstacle, distance)

Bases: NamedTuple

Parameters:
obstacle_was_found: bool
obstacle: carla.Actor | None

The found actor that represents the obstacle.

distance: float | Literal[-1]

The distance to the obstacle. If no obstacle was found, the distance is -1.

__bool__() bool
Returns:

Value of obstacle_was_found.

Return type:

bool

class agents.tools.hints.CameraBlueprint(blueprint_path: str, color_convert: carla.ColorConverter, name: str, actual_blueprint: carla.ActorBlueprint | None = None)

Bases: NamedTuple

Represents a camera blueprint to spawn a camera sensor to be used with the CameraManager.

Parameters:
blueprint_path: str

Blueprint name for the actor

color_convert: carla.ColorConverter

Color converter for the camera

name: str

Semantic name of the blueprint, e.g. RGB, Segmentation

actual_blueprint: carla.ActorBlueprint | None

The actual blueprint object; filled in later

agents.tools.logging module

Sets up a custom logging.Logger for the project. from agents.tools.logging import logger can be used to access the logger.

agents.tools.logging.USE_HYDRA_IF_POSSIBLE = True

If True and Hydra is available, make_logger() will return only a simple logger with just the name set.

agents.tools.logging.TRACE = 5

Logging value below logging.DEBUG

agents.tools.logging.make_logger(name: str | None = None, level: int = logging.DEBUG) Logger

Create a logger object with the specified name and log level. If USE_HYDRA_IF_POSSIBLE is True and the hydra package is installed, this function will return a simple logging.Logger with only the name set. Otherwise it will create a logger that is formatted based on _setup_logger from this file.

Parameters:
  • name (str | None) – The name of the logger. Defaults to “__main__”.

  • level (int) – The log level for the logger. Defaults to logging.DEBUG.

Returns:

The logger object.

Return type:

Logger

agents.tools.logging.logger: Logger = <Logger __main__ (WARNING)>

A constant logger object that can be imported and used throughout the project.

agents.tools.lunatic_agent_tools module

agents.tools.lunatic_agent_tools.result_to_context(key: str)

Decorator to use for the agent. Sets the key attribute of the Context.

Parameters:

key (str)

agents.tools.lunatic_agent_tools.must_clear_hazard(func: CallableT) CallableT

Decorator which raises an EmergencyStopException if self.detected_hazards is not empty after the function call.

Raises:

EmergencyStopException – If self.detected_hazards is not empty after the function call.

Parameters:

func (CallableT)

Return type:

CallableT

agents.tools.lunatic_agent_tools.phase_callback(*, on_enter: Phase | Callable[['LunaticAgent'], Any] | None = None, on_exit: Phase | Callable[['LunaticAgent'], Any] | None = None, on_exit_exceptions: Sequence['type[BaseException]'] | bool | None = (), prior_result_getter: Callable[['LunaticAgent'], Any] | str | None = None)

Decorator function for defining phase callbacks that are executed at the start and end of a function.

Parameters:
  • on_enter (Phase, optional) – The phase to execute before the decorated function. Defaults to None.

  • on_exit (Union[Phase, Callable[['LunaticAgent'], Any], None]) – Either the phase to execute after the decorated function or a callable. Defaults to None.

  • on_exit_exceptions (Tuple[BaseException] | bool)) –

    If a non-empty sequence of exceptions is provided, the on_exit phase will only be executed if one of the exceptions is raised.

    If True, the on_exit phase will be executed if any LunaticAgentException are raised. Defaults to False.

    Attention

    • The on_exit phase will only be executed if and only if one of the exceptions is raised.

    • The exception will be re-raised after executing on_exit.

  • prior_result_getter (Optional[Union[Callable[['LunaticAgent'], Any], str]]) – Can be the name of an attribute of the agent. If the attribute is a callable, it will be called without arguments. Alternatively a callable can be passed. The result will be used as the prior_results argument for the LunaticAgent.execute_phase() method.

Warns:
  • If **on_enter and on_exit are not set, the decorator will print a**

  • warning and ignore the decorator.

agents.tools.lunatic_agent_tools.max_detection_distance(self: 'Context' | 'LunaticAgent', lane: Literal['same_lane', 'other_lane', 'overtaking', 'tailgating']) float

Convenience function to be used with lunatic_agent_tools.detect_vehicles() and LunaticAgent.detect_obstacles_in_path.

The max distance to consider an obstacle is calculated as:

max(obstacles.min_proximity_threshold,
    live_info.current_speed_limit / obstacles.speed_detection_downscale.[same|other]_lane)
Parameters:
  • self (Union['Context', 'LunaticAgent']) – An object that implements the config and live_info attributes

  • lane (Literal['same_lane', 'other_lane', 'overtaking', 'tailgating']) – The lane to consider.

Return type:

float

Note

lane must be a key in BehaviorAgentObstacleSettings.SpeedLimitDetectionDownscale.

agents.tools.lunatic_agent_tools.detect_obstacles_in_path(self: LunaticAgent, obstacle_list: Sequence[carla.Actor] | Literal['all'] | None) ObstacleDetectionResult

This module is in charge of warning in case of a collision and managing possible tailgating chances.

Parameters:
  • self (LunaticAgent) – The agent

  • obstacle_list (Optional[Union[Sequence[carla.Actor], Literal['all']]]) – The list of obstacles that should be checked

Return type:

ObstacleDetectionResult

Note

  • Distance to detect vehicles that hinder a lance change are calculated with the max_detection_distance() function.

  • Former BehaviorAgent.collision_and_car_avoid_manager, which evaded cars via the tailgating function; this is now rule based.

Tip

As the first argument is the agent, this function can be used as a method, i.e it can be added / imported directly into the agent class’ body.

agents.tools.lunatic_agent_tools.detect_vehicles(self: LunaticAgent, vehicle_list: Sequence[carla.Actor] | None = None, max_distance: float | None = None, up_angle_th: float = 90, low_angle_th: float = 0, *, lane_offset: int = 0) ObstacleDetectionResult

Method to check if there is a vehicle in front or around the agent blocking its path.

Parameters:
  • self (LunaticAgent) – The agent

  • vehicle_list (Optional[Sequence[carla.Actor]]) – list containing vehicle objects. If None, all vehicle in the scene are used.

  • max_distance (Optional[float]) – max free-space to check for obstacles. If None, the LunaticAgentSettings.obstacles.base_vehicle_threshold value is used.

  • lane_offset (int) – check a different lane than the one the agent is currently in.

  • up_angle_th (float)

  • low_angle_th (float)

Return type:

ObstacleDetectionResult

The angle between the location and reference transform will also be taken into account. Being 0 a location in front and 180, one behind, i.e, the vector between has to satisfy: low_angle_th < angle < up_angle_th.

Tip

As the first argument is the agent, this function can be used as a method, i.e it can be added / imported directly into the agent class’ body.

agents.tools.lunatic_agent_tools.detect_obstacles_in_front(self: LunaticAgent, vehicle_list: Sequence[carla.Actor] | None = None, max_distance: float | None = None, *, up_angle_th: float = 90, low_angle_th: float = 0, lane_offset: int = 0) ObstacleDetectionResult

detect_vehicles() with the default parameters for detecting vehicles in front of the agent.

Parameters:
Return type:

ObstacleDetectionResult

agents.tools.lunatic_agent_tools.detect_obstacles_behind(self: LunaticAgent, vehicle_list: Sequence[carla.Actor] | None = None, max_distance: float | None = None, *, up_angle_th: float = 180, low_angle_th: float = 160, lane_offset: int = 0) ObstacleDetectionResult

detect_vehicles() with the default parameters for detecting vehicles behind the agent.

Parameters:
Return type:

ObstacleDetectionResult

agents.tools.lunatic_agent_tools.generate_lane_change_path(waypoint: carla.Waypoint, direction: Literal['left', 'right'] = 'left', distance_same_lane: float = 10, distance_other_lane: float = 25, lane_change_distance: float = 25, check: bool = True, lane_changes: int = 1, step_distance: float = 2) list[tuple[carla.Waypoint, RoadOption]]

This method generates a path that results in a lane change. Use the different distances to fine-tune the maneuver. If the lane change is impossible, the returned path will be empty.

Distance traveled:
  1. distance_same_lane in the same lane.

  2. lane_change_distance while reaching the other lane.

  3. distance_other_lane in the other lane.

Parameters:
  • waypoint (carla.Waypoint) – The starting waypoint.

  • direction (Literal['left', 'right']) – The direction of the lane change, either ‘left’ or ‘right’. Defaults to ‘left’.

  • distance_same_lane (float) – The distance to follow the same lane before the lane change.

  • distance_other_lane (float) – The distance to follow the other lane after the lane change.

  • lane_change_distance (float) – The distance to reach the center of the last lane. A low value will make a fast lane change, while a high value will make slow lane change.

  • check (bool) – If True, the method will check if the lane change is possible, i.e. that there is a valid lane that the vehicle can change to. This ignores carla.Waypoint.lane_change.

  • lane_changes (int)

  • step_distance (float)

Return type:

list[tuple[carla.Waypoint, RoadOption]]

agents.tools.lunatic_agent_tools.create_agent_config(self: HasBaseSettings[AgentConfigT], source: 'type[AgentConfig]' | AgentConfig | DictConfig | str | None = None, world_model: 'WorldModel' | None = None, overwrite_options: Dict[str, Any] | None = None)

Method to create the AgentConfig from different input types.

Parameters:
Returns:

The configuration object. The actual type depends on source. If it is a str, AgentConfig or DictConfig, the actual return type will be a omegaconf.DictConfig.

Return type:

self.BASE_SETTINGS (duck-typed)

agents.tools.lunatic_agent_tools.replace_with(func: _C) Callable[[...], _C]

Decorator that exchanges the decorated function by the wrapped function.

Warning

This is a hack to make the decorated function the identical to the function in the argument. The decorated function will be lost and will not be called!

Parameters:

func (_C)

Return type:

Callable[[…], _C]