Python API for communicating with the CARLA server.
Project description
This is the Python package for the CARLA Python API used for controlling and communicating-with CARLA - The open-source simulator for autonomous driving research.
This package allows you to control the CARLA simulator and retrieve simulation data through the Python API. For instance, you can control any actor (vehicle, pedestrian, traffic light, etc...) in the simulation, attach sensors to vehicles, and read the sensor data etc.
For more information, refer to the Guide for getting started with CARLA.
Usage:
- Install:
pip install carla
- Use:
#!/usr/bin/env python
import carla
...
Python API tutorial
In this tutorial we introduce the basic concepts of the CARLA Python API, as well as an overview of its most important functionalities. The reference of all classes and methods available can be found at Python API reference.
!!! note
This document applies only to the latest development version.
The API has been significantly changed in the latest versions starting at
0.9.0. We commonly refer to the new API as 0.9.X API as opposed to
the previous 0.8.X API.
First of all, we need to introduce a few core concepts:
- Actor: Actor is anything that plays a role in the simulation and can be moved around, examples of actors are vehicles, pedestrians, and sensors.
- Blueprint: Before spawning an actor you need to specify its attributes, and that's what blueprints are for. We provide a blueprint library with the definitions of all the actors available.
- World: The world represents the currently loaded map and contains the functions for converting a blueprint into a living actor, among other. It also provides access to the road map and functions to change the weather conditions.
Connecting and retrieving the world
To connect to a simulator we need to create a "Client" object, to do so we need to provide the IP address and port of a running instance of the simulator
client = carla.Client('localhost', 2000)
The first recommended thing to do right after creating a client instance is setting its time-out. This time-out sets a time limit to all networking operations, if the time-out is not set networking operations may block forever
client.set_timeout(10.0) # seconds
Once we have the client configured we can directly retrieve the world
world = client.get_world()
Typically we won't need the client object anymore, all the objects created by the world will connect to the IP and port provided if they need to. These operations are usually done in the background and are transparent to the user.
Blueprints
A blueprint contains the information necessary to create a new actor. For instance, if the blueprint defines a car, we can change its color here, if it defines a lidar, we can decide here how many channels the lidar will have. A blueprints also has an ID that uniquely identifies it and all the actor instances created with it. Examples of IDs are "vehicle.nissan.patrol" or "sensor.camera.depth".
The list of all available blueprints is kept in the blueprint library
blueprint_library = world.get_blueprint_library()
The library allows us to find specific blueprints by ID, filter them with wildcards, or just choosing one at random
# Find specific blueprint.
collision_sensor_bp = blueprint_library.find('sensor.other.collision')
# Chose a vehicle blueprint at random.
vehicle_bp = random.choice(blueprint_library.filter('vehicle.bmw.*'))
Some of the attributes of the blueprints can be modified while some other are just read-only. For instance, we cannot modify the number of wheels of a vehicle but we can change its color
vehicles = blueprint_library.filter('vehicle.*')
bikes = [x for x in vehicles if int(x.get_attribute('number_of_wheels')) == 2]
for bike in bikes:
bike.set_attribute('color', '255,0,0')
Modifiable attributes also come with a list of recommended values
for attr in blueprint:
if attr.is_modifiable:
blueprint.set_attribute(attr.id, random.choice(attr.recommended_values))
The blueprint system has been designed to ease contributors adding their custom actors directly in Unreal Editor, we'll add a tutorial on this soon, stay tuned!
Spawning actors
Once we have the blueprint set up, spawning an actor is pretty straightforward
transform = Transform(Location(x=230, y=195, z=40), Rotation(yaw=180))
actor = world.spawn_actor(blueprint, transform)
The spawn actor function comes in two flavours, spawn_actor
and
try_spawn_actor
. The former will raise an exception if the actor could not be
spawned, the later will return None
instead. The most typical cause of
failure is collision at spawn point, meaning the actor does not fit at the spot
we chose; probably another vehicle is in that spot or we tried to spawn into a
static object.
To ease the task of finding a spawn location, each map provides a list of recommended transforms
spawn_points = world.get_map().get_spawn_points()
We'll add more on the map object later in this tutorial.
Finally, the spawn functions have an optional argument that controls whether the actor is going to be attached to another actor. This is specially useful for sensors. In the next example, the camera remains rigidly attached to our vehicle during the rest of the simulation
camera = world.spawn_actor(camera_bp, relative_transform, attach_to=my_vehicle)
Note that in this case, the transform provided is treated relative to the parent actor.
Handling actors
Once we have an actor alive in the world, we can move this actor around and check its dynamic properties
location = actor.get_location()
location.z += 10.0
actor.set_location(location)
print(actor.get_acceleration())
print(actor.get_velocity())
We can even freeze an actor by disabling its physics simulation
actor.set_simulate_physics(False)
And once we get tired of an actor we can remove it from the simulation with
actor.destroy()
Note that actors are not cleaned up automatically when the Python script finishes, if we want to get rid of them we need to explicitly destroy them.
!!! important Known issue: To improve performance, most of the methods send requests to the simulator asynchronously. The simulator queues each of these requests, but only has a limited amount of time each update to parse them. If we flood the simulator by calling "set" methods too often, e.g. set_transform, the requests will accumulate a significant lag.
Vehicles
Vehicles are a special type of actor that provide a few extra methods. Apart from the handling methods common to all actors, vehicles can also be controlled by providing throttle, break, and steer values
vehicle.apply_control(carla.VehicleControl(throttle=1.0, steer=-1.0))
These are all the parameters of the VehicleControl object and their default values
carla.VehicleControl(
throttle = 0.0
steer = 0.0
brake = 0.0
hand_brake = False
reverse = False
manual_gear_shift = False
gear = 0)
Our vehicles also come with a handy autopilot
vehicle.set_autopilot(True)
As has been a common misconception, we need to clarify that this autopilot control is purely hard-coded into the simulator and it's not based at all in machine learning techniques.
Finally, vehicles also have a bounding box that encapsulates them
box = vehicle.bounding_box
print(box.location) # Location relative to the vehicle.
print(box.extent) # XYZ half-box extents in meters.
Sensors
Sensors are actors that produce a stream of data. Sensors are such a key component of CARLA that they deserve their own documentation page, so here we'll limit ourselves to show a small example of how sensors work
camera_bp = blueprint_library.find('sensor.camera.rgb')
camera = world.spawn_actor(camera_bp, relative_transform, attach_to=my_vehicle)
camera.listen(lambda image: image.save_to_disk('output/%06d.png' % image.frame_number))
In this example we have attached a camera to a vehicle, and told the camera to save to disk each of the images that are going to be generated.
The full list of sensors and their measurement is explained in Cameras and sensors.
Other actors
Apart from vehicles and sensors, there are a few other actors in the world. The full list can be requested to the world with
actor_list = world.get_actors()
The actor list object returned has functions for finding, filtering, and iterating actors
# Find an actor by id.
actor = actor_list.find(id)
# Print the location of all the speed limit signs in the world.
for speed_sign in actor_list.filter('traffic.speed_limit.*'):
print(speed_sign.get_location())
Among the actors you can find in this list are
- Traffic lights with a
state
property to check the light's current state. - Speed limit signs with the speed codified in their type_id.
- The Spectator actor that can be used to move the view of the simulator window.
Changing the weather
The lighting and weather conditions can be requested and changed with the world object
weather = carla.WeatherParameters(
cloudyness=80.0,
precipitation=30.0,
sun_altitude_angle=70.0)
world.set_weather(weather)
print(world.get_weather())
For convenience, we also provided a list of predefined weather presets that can be directly applied to the world
world.set_weather(carla.WeatherParameters.WetCloudySunset)
The full list of presets can be found in the WeatherParameters reference.
Map and waypoints
One of the key features of CARLA is that our roads are fully annotated. All our maps come accompanied by OpenDrive files that defines the road layout. Furthermore, we provide a higher level API for querying and navigating this information.
These objects were a recent addition to our API and are still in heavy development, we hope to make them much more powerful soon.
Let's start by getting the map of the current world
map = world.get_map()
For starters, the map has a name
attribute that matches the name of the
currently loaded city, e.g. Town01. And, as we've seen before, we can also ask
the map to provide a list of recommended locations for spawning vehicles,
map.get_spawn_points()
.
However, the real power of this map API comes apparent when we introduce waypoints. We can tell the map to give us a waypoint on the road closest to our vehicle
waypoint = map.get_waypoint(vehicle.get_location())
This waypoint's transform
is located on a drivable lane, and it's oriented
according to the road direction at that point.
Waypoints also have function to query the "next" waypoints; this method returns a list of waypoints at a certain distance that can be accessed from this waypoint following the traffic rules. In other words, if a vehicle is placed in this waypoint, give me the list of posible locations that this vehicle can drive to. Let's see a practical example
# Retrieve the closest waypoint.
waypoint = map.get_waypoint(vehicle.get_location())
# Disable physics, in this example we're just teleporting the vehicle.
vehicle.set_simulate_physics(False)
while True:
# Find next waypoint 2 meters ahead.
waypoint = random.choice(waypoint.next(2.0))
# Teleport the vehicle.
vehicle.set_transform(waypoint.transform)
The map object also provides methods for generating in bulk waypoints all over the map at an approximated distance between them
waypoint_list = map.generate_waypoints(2.0)
For routing purposes, it is also possible to retrieve a topology graph of the roads
waypoint_tuple_list = map.get_topology()
this method returns a list of pairs (tuples) of waypoints, for each pair, the first element connects with the second one. Only the minimal set of waypoints to define the topology are generated by this method, only a waypoint for each lane for each road segment in the map.
Finally, to allow access to the whole road information, the map object can be converted to OpenDrive format, and saved to disk as such.
Python API Reference
!!! important Versions prior to 0.9.0 have a very different API. For the documentation of the stable version please switch to the stable branch.
carla.Client
Client(host, port, worker_threads=0)
set_timeout(float_seconds)
get_client_version()
get_server_version()
get_world()
carla.World
id
map_name
debug
get_blueprint_library()
get_map()
get_spectator()
get_weather()
set_weather(weather_parameters)
get_actors()
spawn_actor(blueprint, transform, attach_to=None)
try_spawn_actor(blueprint, transform, attach_to=None)
wait_for_tick(seconds=1.0)
on_tick(callback)
carla.DebugHelper
draw_point(location, size=0.1, color=carla.Color(), life_time=-1.0, persistent_lines=True)
draw_line(begin, end, thickness=0.1, color=carla.Color(), life_time=-1.0, persistent_lines=True)
draw_arrow(begin, end, thickness=0.1, arrow_size=0.1, color=carla.Color(), life_time=-1.0, persistent_lines=True)
draw_box(box, rotation, thickness=0.1, color=carla.Color(), life_time=-1.0, persistent_lines=True)
draw_string(location, text, draw_shadow=False, color=carla.Color(), life_time=-1.0, persistent_lines=True)
carla.BlueprintLibrary
find(id)
filter(wildcard_pattern)
__getitem__(pos)
__len__()
__iter__()
carla.ActorBlueprint
id
tags
has_tag(tag)
match_tags(wildcard_pattern)
has_attribute(key)
get_attribute(key)
set_attribute(key, value)
__len__()
__iter__()
carla.ActorAttribute
id
type
recommended_values
is_modifiable
as_bool()
as_int()
as_float()
as_str()
as_color()
__eq__(other)
__ne__(other)
__nonzero__()
__bool__()
__int__()
__float__()
__str__()
carla.ActorList
find(id)
filter(wildcard_pattern)
__getitem__(pos)
__len__()
__iter__()
carla.Actor
id
type_id
parent
semantic_tags
is_alive
attributes
get_world()
get_location()
get_transform()
get_velocity()
get_acceleration()
set_location(location)
set_transform(transform)
set_simulate_physics(enabled=True)
destroy()
carla.Vehicle(carla.Actor)
bounding_box
apply_control(vehicle_control)
get_control()
set_autopilot(enabled=True)
get_speed_limit()
get_traffic_light_state()
is_at_traffic_light()
get_traffic_light()
carla.TrafficLight(carla.Actor)
state
set_state(traffic_light_state)
get_state()
set_green_time(green_time)
get_green_time()
set_yellow_time(yellow_time)
get_yellow_time()
set_red_time(red_time)
get_red_time()
get_elapsed_time()
freeze(True)
is_frozen()
carla.Sensor(carla.Actor)
is_listening
listen(callback_function)
stop()
carla.SensorData
frame_number
transform
carla.Image(carla.SensorData)
width
height
fov
raw_data
convert(color_converter)
save_to_disk(path, color_converter=None)
__len__()
__iter__()
__getitem__(pos)
__setitem__(pos, color)
carla.LidarMeasurement(carla.SensorData)
horizontal_angle
channels
raw_data
get_point_count(channel)
save_to_disk(path)
__len__()
__iter__()
__getitem__(pos)
__setitem__(pos, location)
carla.CollisionEvent(carla.SensorData)
actor
other_actor
normal_impulse
carla.LaneInvasionEvent(carla.SensorData)
actor
crossed_lane_markings
carla.GnssEvent(carla.SensorData)
latitude
longitude
altitude
carla.ObstacleDetectionSensorEvent(carla.SensorData)
actor
other_actor
distance
carla.VehicleControl
throttle
steer
brake
hand_brake
reverse
__eq__(other)
__ne__(other)
carla.Map
name
get_spawn_points()
get_waypoint(location, project_to_road=True)
get_topology()
generate_waypoints(distance)
to_opendrive()
save_to_disk(path=self.name)
carla.Waypoint
transform
is_intersection
lane_width
road_id
lane_id
next(distance)
carla.WeatherParameters
cloudyness
precipitation
precipitation_deposits
wind_intensity
sun_azimuth_angle
sun_altitude_angle
__eq__(other)
__ne__(other)
Static presets
carla.WeatherParameters.ClearNoon
carla.WeatherParameters.CloudyNoon
carla.WeatherParameters.WetNoon
carla.WeatherParameters.WetCloudyNoon
carla.WeatherParameters.MidRainyNoon
carla.WeatherParameters.HardRainNoon
carla.WeatherParameters.SoftRainNoon
carla.WeatherParameters.ClearSunset
carla.WeatherParameters.CloudySunset
carla.WeatherParameters.WetSunset
carla.WeatherParameters.WetCloudySunset
carla.WeatherParameters.MidRainSunset
carla.WeatherParameters.HardRainSunset
carla.WeatherParameters.SoftRainSunset
carla.Vector3D
x
y
z
__add__(other)
__sub__(other)
__eq__(other)
__ne__(other)
carla.Location
x
y
z
distance(other)
__add__(other)
__sub__(other)
__eq__(other)
__ne__(other)
carla.Rotation
pitch
yaw
roll
get_forward_vector()
__eq__(other)
__ne__(other)
carla.Transform
location
rotation
transform(geom_object)
get_forward_vector()
__eq__(other)
__ne__(other)
carla.BoundingBox
location
extent
__eq__(other)
__ne__(other)
carla.Timestamp
frame_count
elapsed_seconds
delta_seconds
platform_timestamp
__eq__(other)
__ne__(other)
carla.Color
r
g
b
a
__eq__(other)
__ne__(other)
carla.ColorConverter
Raw
Depth
LogarithmicDepth
CityScapesPalette
carla.ActorAttributeType
Bool
Int
Float
RGBColor
carla.TrafficLightState
Red
Yellow
Green
Off
Unknown
carla.LaneMarking
Other
Broken
Solid
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distributions
Built Distributions
Hashes for carla-0.9.3-cp37-cp37m-manylinux1_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | e0dbab8b7a8ad4b662c2d18993f2461e8a09bcdb5dbf53efdb61aea8ba886320 |
|
MD5 | 2a7a906ec4df45a963058252320e9203 |
|
BLAKE2b-256 | 0be1d9dd31fa13760fe8b693ff068ff037e318a80faf48cd0cde7548ad206fd6 |
Hashes for carla-0.9.3-cp36-cp36m-manylinux1_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | c4e70c9c50f55c91e35c0f78bb219797b7bb41d2f69fce3c5023560e87acd823 |
|
MD5 | 93d7998009cfd8ea865648e8f3383427 |
|
BLAKE2b-256 | d309dd942f012ae1d277fbf5b6d3be1f76419c982af09fc96de0dfee2d611725 |
Hashes for carla-0.9.3-cp35-cp35m-manylinux1_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | b6de28ccf4ae4b71726ea0677fd2b41de8f353430aabe9dc163ddca054307833 |
|
MD5 | 38f45a6a162a0fbebc449f0606677730 |
|
BLAKE2b-256 | f65810f0feb717e43c3506a9cbede404e5a3eb463c7a234b7e554883ed6ae838 |
Hashes for carla-0.9.3-cp34-cp34m-manylinux1_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 58334fe04d85770e3fe5b57437ebe67b58b6723ea32a1af1b2f48536fb2b4008 |
|
MD5 | f46508ecacde9c61f35209f4aa2d8d40 |
|
BLAKE2b-256 | 16d1669605019c4a0b24b6c1c55994a952fab0f3bf9473d1b9eb9ca40290ce5f |
Hashes for carla-0.9.3-cp27-cp27mu-manylinux1_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | f8bfe64b7f4e68797232149aa8ce17062ae9e5cbcf21158041e9b30ea8d7bdfe |
|
MD5 | a7a39489a4512c76526ba951d6a9b478 |
|
BLAKE2b-256 | c33a6c442b3139bbc3f39c0a3cb3fe6c0411c176c7e18e1f18c1b1b90405f3de |