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 typeAny.If an attribute with this value is accessed from a
DictConfig, it will raise aMissingMandatoryValueerror.
- agents.tools.config_creation.NestedConfigDict
Dict[str, NestedConfigDict | AgentConfig | DictConfig | Any]- Type:
Alias for nested configurations
- class agents.tools.config_creation.AgentConfig[source]
Bases:
objectBase interface and utility class 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 export_options(path: str | PathLike[str], *, resolve: bool = False, with_comments: bool = False, detailed_rules: bool = False, include_private: bool = False) None[source]
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.
- Return type:
None
- classmethod to_yaml(resolve: bool = False, yaml_commented: bool = True, detailed_rules: bool = False, *, include_private: bool = False) str[source]
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:
- classmethod from_yaml(path: str, *, merge: bool = True) Self[source]
Loads the options from a yaml file.
- Parameters:
- Returns:
An instance of this class
- Return type:
- classmethod load_schema(path: str | None = None) AsDictConfig[Self][source]
Classes decorated with
@config_pathcan be loaded with this method.- This is equivalent to:
create(as_dictconfig=True, dict_config_no_parent=False)
See also
Hydra ConfigStore
- Parameters:
path (Optional[str])
- Return type:
AsDictConfig[Self]
- classmethod create(settings: os.PathLike[str] | str | DictConfig | NestedConfigDict | OverwriteDictTypes | 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][source]
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 | OverwriteDictTypes | AgentConfig, None]) – The argument specifying the agent settings. It can be a path to a YAML file, a dictionary, a
@dataclassdecorated class or aomegaconf.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
DictConfigand 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); actuallyomegaconf.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[source]
strictness == 1type-cast the config to this class, assuring all keys are present. However the type and correctness of the field-contents are not checked.strictness > 1the config will be a object. as_dict_config is ignored.strictness == 2: Will assure that the initial types are correct.strictness >= 2will 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
carlamodule, this especially includes carla’s enum objects. For what is supported see https://omegaconf.readthedocs.io/en/2.3_branch/structured_config.html.- Parameters:
- Returns:
A version of this class or a duck-typed .
- Return type:
- classmethod to_dict_config(*, lock_interpolations: bool = True, lock_fields: List[str] | None = None) DictConfig[source]
Returns a
omegaconf.DictConfigfrom the current options.Interpolations can be locked to prevent them from being overwritten. E.g.
speed.current_speedcannot diverge fromlive_info.current_speed.- Parameters:
- Returns:
The options as a
DictConfig.- Return type:
AgentConfig(duck-typed); actuallyomegaconf.DictConfig)
- classmethod get(key: str, default: _T = _NOTSET) Any | _T[source]
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[source]
Updates the options with a new dictionary. Will call
update()recursively for nestedAgentConfigobjects.- Parameters:
options (NestedConfigDict | DictConfig | AgentConfig) – The new options to update with.
clean (bool) – Whether to call
_clean_options()after updating. Defaults to True.
- Return type:
None
- classmethod uses_overwrite_interface(cls_: type[Self] | None = None) TypeGuard[type[ConfigWithOverwrites[Self]]] | bool[source]
Whether or not the class is created by a single parameter “overwrites” or via keyword arguments for each field.
- class agents.tools.config_creation.BasicAgentSettings(overwrites: Optional[OverwriteDictTypes] = <factory>)[source]
Bases:
AgentConfigSettings used by the
BasicAgentprovided 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)[source]
Bases:
AgentConfigSettings used by the
BehaviorAgentprovided 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
- class agents.tools.config_creation.CallFunctionFromConfig(_target_: 'str', _args_: 'List[Any]' = <factory>, random_lane_change: 'bool' = False)[source]
Bases:
object- random_lane_change: bool = False
For
create_default_rules(); Should theRandomLaneChangeRulebe added
- class agents.tools.config_creation.CameraConfig(width: int = '${width}', height: int = '${height}', gamma: float = '${gamma}', spectator: bool = True, camera_blueprints: list = <factory>, recorder: RecorderSettings = <factory>, hud: HUDConfig = <factory>)[source]
Bases:
AgentConfig- Parameters:
- width: int = '${width}'
With pygame window. Takes the value from the
LaunchConfig.
- height: int = '${height}'
Height of pygame window. Takes the value from the
LaunchConfig.
- gamma: float = '${gamma}'
Gamma correction of the camera. Takes the value from the
LaunchConfig.
- camera_blueprints: list
Cameras and sensors attached to the ego vehicle that can be viewed by the user in the pygame window.
Used with the
CameraManager.sensors.Attention
Usage not yet implemented.
- class RecorderSettings(enabled: bool = MISSING, output_path: str = '${hydra:runtime.output_dir}/recorder/session%03d/%08d.bmp', frame_interval: int = 4)[source]
Bases:
AgentConfigRecorder settings for the camera.
- 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.
- recorder: RecorderSettings
- class HUDConfig(enabled: bool = True, font_size: int = 20, font_color: Tuple[int, int, int] = (255, 255, 255), font: str = 'arial', detection_matrix: DetectionMatrixHUDConfig = <factory>)[source]
Bases:
AgentConfigHUD settings for the pygame window.
- Parameters:
- 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>)[source]
Bases:
AgentConfigDetectionMatrix settings for the HUD
Attention
Keys must match keywords of
DetectionMatrix.render()- Parameters:
- detection_matrix: DetectionMatrixHUDConfig
- class agents.tools.config_creation.ContextSettings(overwrites: Optional[OverwriteDictTypes] = <factory>, rules: list[RuleCreatingParameters] = <factory>)[source]
Bases:
LunaticAgentSettingsConfig class for the
Contextobject.Extends the
LunaticAgentSettingsby the current_rule attribute to accesses theRule.self_configattribute from the context.- Parameters:
overwrites (Optional[OverwriteDictTypes])
rules (list[RuleCreatingParameters])
- current_rule: RuleConfig = '${self}'
Special settings of the current rule. Only available from
Contextwithin rulesctx.config.current_ruleNote
Internally
Context.config.current_ruleandRule.self_configare the same object.See also
RuleConfig.self_config
- 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)[source]
Bases:
objectKeywords to instantiate Rule classes
omegaconf.MISSING(alias for'???') attributes will not be passed to aRule’s__init__()method.- Parameters:
_target_ (str)
_args_ (Optional[List[Any]])
condition (Optional[str])
action (Optional[str])
false_action (Optional[str])
description (str)
self_config (NestedConfigDict)
priority (RulePriority)
cooldown_reset_value (Optional[int])
group (Optional[str])
enabled (bool)
rules (List[CreateRuleFromConfig])
execute_all_rules (bool)
repeat_if_not_applicable (bool)
ignore_phase (bool)
MAX_TICKS (Optional[int])
max_tick_callback (Optional[str])
gameframework (Optional[GameFramework])
- 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
- rules: List[CreateRuleFromConfig] = MISSING
- gameframework: GameFramework | None = MISSING
Needed explicitly for
BlockingRulesonce. Depending on setup can be omitted
- 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, timeout: 'float' = 10.0, 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, restart_clean_sensors: 'Optional[bool]' = None, agent: 'LunaticAgentSettings' = MISSING, camera: 'CameraConfig' = <factory>, pygame: 'bool' = True, hydra: 'HydraConf' = MISSING)[source]
Bases:
AgentConfig- Parameters:
verbose (bool)
debug (bool)
interactive (bool)
seed (Optional[int])
map (str)
host (str)
port (int)
timeout (float)
fps (int)
sync (Union[bool, None])
handle_ticks (bool)
loop (bool)
width (int)
height (int)
gamma (float)
externalActor (bool)
rolename (str)
filter (str)
generation (Literal[1, 2, 'all'])
autopilot (bool)
restart_clean_sensors (Optional[bool])
agent (LunaticAgentSettings)
camera (CameraConfig)
pygame (bool)
hydra (HydraConf)
- 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.
- interactive: bool = False
If True will create an interactive session with command line input - NOTE: Needs custom code in the main file (Not implemented)
- timeout: float = 10.0
Timeout for the
carla.Clientconnection.
- fps: int = 20
Used to fix
carla.WorldSettings.fixed_delta_secondsExperimental 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.
- 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.
- 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 CARLA’s
carla.TrafficManagerto autopilot the agentNote
This disables the usage of the LunaticAgent, however needs to be enabled in the main script by the user to work.
- restart_clean_sensors: bool | None = None
If None will remove all sensors from an externalActor if
WorldModel.restart()is called outside from the initialization, i.e.restart()it is called a second time. Else will always/never remove the sensors when usingWorldModel.restart().
- agent: LunaticAgentSettings = MISSING
The settings of the agent
- camera: CameraConfig
- pygame: bool = True
Deactivates the pygame window and interface.
Attention
Setting this to False is experimental.
- hydra: HydraConf = MISSING
Hydra config dict.
Attention
This field is not guaranteed to be present or the complete
HydraConfschema.
- leaderboard: Annotated[DictConfig, 'Only present for the', LunaticChallenger]
- class agents.tools.config_creation.LunaticAgentSettings(overwrites: Optional[OverwriteDictTypes] = <factory>, rules: list[RuleCreatingParameters] = <factory>)[source]
Bases:
AgentConfigConfig schema definition for the
LunaticAgentclass- 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
- class agents.tools.config_creation.RuleConfig(instance: object = MISSING)[source]
Bases:
objectSubconfig for rules; can have arbitrary keys
- Parameters:
instance (object)
- agents.tools.config_creation.config_path(path: str | None = None)[source]
Decorator to register the schema of the current class with Hydra’s
ConfigStore.. Use the path relative to the launch_config.yaml, where the config is stored to use.Create subclasses in the following way:
@config_path("agent/speed") @dataclass class AgentSpeedSettings(AgentConfig):
Attention
Use “/” as separator and not dots.
This is used for the Hydra schema registration and repeated paths will overwrite each other.
This value is inherited (if !=
NOT_GIVEN), and the value of the parent is taken as default. Do not type-hint this value it must be a ClassVar to not conflict with dataclasses.
- Returns:
(Callable[[type[AgentConfig]], type[AgentConfig]]) Wrapper function to register the schema.
- Parameters:
path (Optional[str])
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)[source]
Bases:
NamedTuple- Parameters:
traffic_light_was_found (bool)
traffic_light (carla.TrafficLight | None)
- traffic_light: carla.TrafficLight | None
The found traffic light. If no traffic light was found, the value is None.
- __bool__()[source]
- Returns:
Value of
traffic_light_was_found.
- class agents.tools.hints.ObstacleDetectionResult(obstacle_was_found, obstacle, distance)[source]
Bases:
NamedTuple- Parameters:
obstacle_was_found (bool)
obstacle (carla.Actor | None)
- 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[source]
- Returns:
Value of
obstacle_was_found.- Return type:
- class agents.tools.hints.CameraBlueprint(blueprint_path: str, color_convert: carla.ColorConverter, name: str, actual_blueprint: carla.ActorBlueprint | None = None)[source]
Bases:
NamedTupleRepresents a camera blueprint to spawn a camera sensor to be used with the
CameraManager.- Parameters:
blueprint_path (str)
color_convert (carla.ColorConverter)
name (str)
actual_blueprint (carla.ActorBlueprint | None)
- color_convert: carla.ColorConverter
Color converter for the camera. If none is needed set to
carla.ColorConverter.Raw
- actual_blueprint: carla.ActorBlueprint | None
The actual blueprint object; filled in later
agents.tools.logs 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.logs.USE_HYDRA_IF_POSSIBLE = True
If
Trueand Hydra is available,make_logger()will return only a simple logger with just the name set.
- agents.tools.logs.TRACE = 5
Logging value below
logging.DEBUG
- agents.tools.logs.make_logger(name: str | None = None, level: int = logging.DEBUG) Logger[source]
Create a logger object with the specified name and log level. If
USE_HYDRA_IF_POSSIBLEisTrueand the hydra package is installed, this function will return a simplelogging.Loggerwith only the name set. Otherwise it will create a logger that is formatted based on_setup_loggerfrom this file.
agents.tools.lunatic_agent_tools module
Helper functions and methods for the LunaticAgent, some methods are variants
from the original CARLA agents that have been simplified and outsourced to this
module.
- agents.tools.lunatic_agent_tools.result_to_context(key: str) Callable[[CallableT], CallableT][source]
Decorator to use for the agent. Sets the key attribute of the
Context.
- agents.tools.lunatic_agent_tools.must_clear_hazard(func: CallableT) CallableT[source]
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:
- 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)[source]
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 anyLunaticAgentExceptionare raised. Defaults toFalse.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: HasConfig['BehaviorAgentSettings | LunaticAgentSettings'], lane: Literal['same_lane', 'other_lane', 'overtaking', 'tailgating']) float[source]
Convenience function to be used with
lunatic_agent_tools.detect_vehicles()andLunaticAgent.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 (HasConfig['BehaviorAgentSettings | LunaticAgentSettings']) – An object that implements the config and live_info attributes
lane (Literal['same_lane', 'other_lane', 'overtaking', 'tailgating']) – The lane to consider.
- Return type:
Note
lane must be a key in
BehaviorAgentObstacleSettings.SpeedLimitDetectionDownscale.
- agents.tools.lunatic_agent_tools.detect_obstacles_in_path(self: CanDetectNearbyObstacles, obstacle_list: Sequence[carla.Actor] | carla.ActorList | Literal['all'] | None) ObstacleDetectionResult[source]
This module is in charge of warning in case of a collision and managing possible tailgating chances.
- Parameters:
self (CanDetectNearbyObstacles) – The agent
obstacle_list (Optional[Union[Sequence[carla.Actor], carla.ActorList, Literal['all']]]) – The list of obstacles that should be checked
- Return type:
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_obstacles(self: CanDetectObstacles, actor_list: Sequence[carla.Actor] | carla.ActorList | None = None, max_distance: float | None = None, up_angle_th: float = 90, low_angle_th: float = 0, *, lane_offset: int = 0) ObstacleDetectionResult[source]
Method to check if there is a vehicle in front or around the agent blocking its path.
- Parameters:
self (CanDetectObstacles) – The agent
actor_list (Optional[Sequence[carla.Actor] | carla.ActorList]) – list containing relevant actors to check. If
None, all vehicle in the scene are used.max_distance (Optional[float]) – max free-space to check for obstacles. If
None, theLunaticAgentSettings.obstacles.base_vehicle_thresholdvalue 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:
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_vehicles(self: CanDetectObstacles, vehicle_list: Sequence[carla.Actor] | carla.ActorList | None = None, max_distance: float | None = None, up_angle_th: float = 90, low_angle_th: float = 0, lane_offset: int = 0) ObstacleDetectionResult[source]
Method to check if there is a vehicle in front or around the agent blocking its path.
- Parameters:
self (CanDetectObstacles) – The agent
vehicle_list (Optional[Sequence[carla.Actor] | carla.ActorList]) – 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, theLunaticAgentSettings.obstacles.base_vehicle_thresholdvalue 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:
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.
Deprecated since version Use:
detect_obstacles()instead.
- agents.tools.lunatic_agent_tools.detect_obstacles_in_front(self: CanDetectObstacles, vehicle_list: Sequence[carla.Actor] | carla.ActorList | 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:
self (CanDetectObstacles)
vehicle_list (Optional[Sequence[carla.Actor] | carla.ActorList])
max_distance (Optional[float])
up_angle_th (float)
low_angle_th (float)
lane_offset (int)
- Return type:
- agents.tools.lunatic_agent_tools.detect_obstacles_behind(self: CanDetectObstacles, vehicle_list: Sequence[carla.Actor] | carla.ActorList | 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:
self (CanDetectObstacles)
vehicle_list (Optional[Sequence[carla.Actor] | carla.ActorList])
max_distance (Optional[float])
up_angle_th (float)
low_angle_th (float)
lane_offset (int)
- Return type:
- 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]][source]
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:
distance_same_lane in the same lane.
lane_change_distance while reaching the other lane.
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 ignorescarla.Waypoint.lane_change.lane_changes (int)
step_distance (float)
- Return type:
- agents.tools.lunatic_agent_tools.create_agent_config(self: HasBaseSettings[AgentConfigT], source: 'type[AgentConfigT]' | AgentConfigT | DictConfig | str | None = None, world_model: 'WorldModel' | None = None, overwrite_options: Dict[str, Any] | None = None) AgentConfigT[source]
Method to create the
AgentConfigfrom different input types.- Parameters:
self (
LunaticAgent) – The agentsource (Union['type[AgentConfigT]', AgentConfigT, DictConfig, str, None]) –
Nonetakes the config from the world model if available.AgentConfig(class or instance) to be used.omegaconf.DictConfig, a dictionary with the configuration, i.e. duck-typed asAgentConfig.
world_model (Optional['WorldModel'])
- Returns:
The configuration object. The actual type depends on source. If it is a
str,AgentConfigorDictConfig, the actual return type will be aomegaconf.DictConfig.- Return type:
self.BASE_SETTINGS(duck-typed)