### Start CARLA Server Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/getting_started.md Launches the CARLA simulation environment. Ensure you are in the CARLA installation directory when running this command. ```bash ./CarlaUE4.sh ``` -------------------------------- ### Install Prerequisites for ScenarioRunner Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/getting_started.md Installs the necessary Python packages for the ScenarioRunner using pip. It handles potential conflicts with existing networkx installations. ```bash #Python 2.x sudo apt remove python-networkx #if installed, remove old version of networkx pip2 install --user -r requirements.txt #Python 3.x sudo apt remove python3-networkx #if installed, remove old version of networkx pip3 install --user -r requirements.txt ``` -------------------------------- ### Set up CARLA Python API Path Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/getting_started.md Configures the Python path to include the CARLA Python API and agent directories. Replace placeholders with your actual CARLA installation path and version. ```bash export CARLA_ROOT=/path/to/your/carla/installation export PYTHONPATH=$PYTHONPATH:${CARLA_ROOT}/PythonAPI/carla/dist/carla-.egg:${CARLA_ROOT}/PythonAPI/carla/agents:${CARLA_ROOT}/PythonAPI/carla ``` -------------------------------- ### Example Route-Based Scenario Execution Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/getting_started.md Provides a concrete example of running a route-based scenario with specific file paths for routes, scenarios, and an NPC agent. ```python python scenario_runner.py /scenario_runner/srunner/routes_debug.xml /scenario_runner/srunner/data/all_towns_traffic_scenarios1_3_4.json 0 --agent srunner/autoagents/npc_agent.py ``` -------------------------------- ### Get ScenarioRunner Help Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/getting_started.md Displays the help message for the ScenarioRunner, listing all available command-line options and parameters. Useful for exploring functionalities. ```python python scenario_runner.py --help ``` -------------------------------- ### Run Single Scenario Example Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/getting_started.md Executes a specific scenario, 'FollowLeadingVehicle_1', and reloads the CARLA world. This is a basic command to test scenario execution. ```python python scenario_runner.py --scenario FollowLeadingVehicle_1 --reloadWorld ``` -------------------------------- ### Build and Serve Documentation Locally with MkDocs Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/CONTRIBUTING.md Instructions for installing MkDocs and serving the CARLA documentation locally. This requires Python and pip to be installed. ```bash sudo pip install mkdocs mkdocs serve ``` -------------------------------- ### Startup Script Example for RosAgent (Bash) Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/ros_agent.md An example of a startup script (start.sh) for the RosAgent in Challenge Mode. This script is responsible for launching the ROS stack and must remain running while the agent is active. It uses `roslaunch` to start the challenge. ```bash #!/bin/bash -e roslaunch $TEAM_CODE_ROOT/challenge.launch ``` -------------------------------- ### Run OpenSCENARIO Format Scenarios Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/getting_started.md Launches a scenario defined using the OpenSCENARIO format. Requires the path to the .xosc file. ```python python scenario_runner.py --openscenario ``` -------------------------------- ### Launch CARLA Server (Build from Source) Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/getting_scenariorunner.md Launches the CARLA server from a source build. This involves navigating to the CARLA directory and executing the 'make launch' command, followed by manually starting the server in the Unreal Engine editor. ```sh cd ~/carla # Change the path accordingly make launch # Press Play in the UE Editor ``` -------------------------------- ### Run Route-Based Scenarios Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/getting_started.md Executes route-based scenarios, similar to the CARLA AD Challenge. Requires paths to route and scenario definition files, and an agent file for control. ```python python scenario_runner.py --route [route id] --agent ``` -------------------------------- ### Manual Ego Vehicle Control for OpenSCENARIO 2.0 Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/getting_started.md Starts the manual control interface for the ego vehicle, specifically for OpenSCENARIO 2.0 scenarios, with role name specification. ```python python manual_control.py -a --rolename=ego_vehicle ``` -------------------------------- ### Run OpenSCENARIO 2.0 Format Scenarios Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/getting_started.md Executes a scenario based on the OpenSCENARIO 2.0 format. Requires the path to the .osc file. ```python python scenario_runner.py --openscenario2 ``` -------------------------------- ### Install JDK 17 Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/README_OpenSCENARIO_2.0.md Installs OpenJDK 17, a prerequisite for many Java-based tools including Antlr. This command uses apt to install the JDK package. ```bash sudo apt install openjdk-17-jdk ``` -------------------------------- ### Define Basic Scenario Setup in OSC2 Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/README_OpenSCENARIO_2.0.md This snippet demonstrates the initial setup for an OSC2 scenario, including importing other definitions, defining the scenario name, setting up the map and path, and specifying ego and NPC vehicles. ```osc import basic.osc scenario top: path: Path # A path in the map path.set_map("Town04") # Map to employ path.path_min_driving_lanes(2) # Path should have at least two lanes ego_vehicle: Model3 # Ego car npc: Rubicon # The other car event start # Define start and end events event end ``` -------------------------------- ### Manual Ego Vehicle Control Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/getting_started.md Starts the manual control interface for the ego vehicle in CARLA. This allows a user to drive the vehicle manually during a scenario. ```python python manual_control.py ``` -------------------------------- ### Install Graphviz Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/README_OpenSCENARIO_2.0.md Installs Graphviz, a tool for visualizing graphs and ASTs. While optional, it is useful for debugging and inspecting the structure of parsed scenarios. ```bash sudo apt-get install graphviz ``` -------------------------------- ### Run OpenSCENARIO with Global Parameter Overwrite Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/getting_started.md Executes an OpenSCENARIO file while overwriting global parameters. Allows dynamic parameter adjustment for scenarios. ```python python scenario_runner.py --openscenario --openscenarioparams 'param1: value1, param2: value2' ``` -------------------------------- ### Verify Java Installation Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/README_OpenSCENARIO_2.0.md Checks if the Java Development Kit (JDK) has been successfully installed by displaying its version information. This command queries the system's Java runtime. ```bash java -version ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/README_OpenSCENARIO_2.0.md Installs all required Python packages listed in the 'requirements.txt' file. This ensures that all project dependencies are met for the scenario runner. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install OpenSCENARIO 2.0 Dependencies and Configure Environment Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/getting_scenariorunner.md Installs Java JDK, graphviz, and ANTLR for OpenSCENARIO 2.0 format support. It downloads the ANTLR JAR, copies it to the system library, and then updates the ~/.bashrc file with necessary environment variables and aliases for ANTLR tools. ```sh sudo apt-get install -y openjdk-17-jdk graphviz curl -O https://www.antlr.org/download/antlr-4.10.1-complete.jar sudo cp antlr-4.10.1-complete.jar /usr/local/lib/ sudo gedit ~/.bashrc # Add environment variables into ~/.bashrc: export CLASSPATH=".:/usr/local/lib/antlr-4.10.1-complete.jar:$CLASSPATH" alias antlr4='java -jar /usr/local/lib/antlr-4.10.1-complete.jar' alias grun='java org.antlr.v4.gui.TestRig' source ~/.bashrc ``` -------------------------------- ### Python: CARLA Initial Route Representation Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/agent_evaluation.md This Python snippet shows the structure of the initial route plan for an agent in the CARLA simulator. It's a list of tuples, where each tuple contains a waypoint (latitude, longitude, altitude) and a recommended road option (e.g., LANEFOLLOW, LEFT, RIGHT). This plan guides the agent throughout its simulated journey. ```Python [({'z': 0.0, 'lat': 48.99822669411668, 'lon': 8.002271601998707}, ), ({'z': 0.0, 'lat': 48.99822669411668, 'lon': 8.002709765148996}, ), ... ({'z': 0.0, 'lat': 48.99822679980298, 'lon': 8.002735250105061}, )] ``` -------------------------------- ### Run Grouped Scenarios by Class Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/getting_started.md Executes all scenarios belonging to a specific class, such as 'FollowLeadingVehicle'. This is useful for testing multiple related scenarios. ```python python scenario_runner.py --scenario group:FollowLeadingVehicle ``` -------------------------------- ### Run CARLA Simulation Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/README_OpenSCENARIO_2.0.md Launches the CARLA Unreal Engine application, which serves as the simulator environment. This command navigates to the CARLA installation directory and executes the simulation executable. ```bash cd /home/xxx/CARLA_0.9.16 ./CarlaUE4.sh ``` -------------------------------- ### Install Antlr 4.10.1 and Configure Environment Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/README_OpenSCENARIO_2.0.md Installs the Antlr 4.10.1 parser generator and configures environment variables and aliases for its command-line usage. This involves downloading the JAR, copying it to the lib directory, and updating the bashrc file. ```bash sudo apt install curl curl -O https://www.antlr.org/download/antlr-4.10.1-complete.jar sudo cp antlr-4.10.1-complete.jar /usr/local/lib/ sudo gedit ~/.bashrc export CLASSPATH=".:/usr/local/lib/antlr-4.10.1-complete.jar:$CLASSPATH" alias antlr4='java -jar /usr/local/lib/antlr-4.10.1-complete.jar' alias grun='java org.antlr.v4.gui.TestRig' source ~/.bashrc ``` -------------------------------- ### Clone ScenarioRunner Repository Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/getting_scenariorunner.md Clones the ScenarioRunner Git repository to download the source code. This is a prerequisite for building ScenarioRunner from source. ```sh git clone https://github.com/carla-simulator/scenario_runner.git ``` -------------------------------- ### Control CARLA Scenario Execution with ScenarioManager Source: https://context7.com/carla-simulator/scenario_runner/llms.txt This Python code demonstrates the setup and initialization of the `ScenarioManager` for controlling CARLA scenario executions. It includes connecting to the CARLA client, configuring synchronous mode, and setting up the `CarlaDataProvider`. This allows for programmatic control over scenario loading and execution. ```python from srunner.scenariomanager.scenario_manager import ScenarioManager from srunner.scenarioconfigs.scenario_configuration import ScenarioConfiguration from srunner.scenarios.follow_leading_vehicle import FollowLeadingVehicle from srunner.scenariomanager.carla_data_provider import CarlaDataProvider import carla # Connect to CARLA client = carla.Client('127.0.0.1', 2000) client.set_timeout(10.0) world = client.get_world() # Setup synchronous mode settings = world.get_settings() settings.synchronous_mode = True settings.fixed_delta_seconds = 0.05 world.apply_settings(settings) # Initialize data provider CarlaDataProvider.set_client(client) CarlaDataProvider.set_world(world) # Create scenario configuration config = ScenarioConfiguration() config.town = 'Town01' config.name = 'FollowLeadingVehicle_Test' config.type = 'FollowLeadingVehicle' ``` -------------------------------- ### Install Antlr Python Runtime Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/README_OpenSCENARIO_2.0.md Installs the Python 3 runtime for Antlr version 4.10. This is necessary for parsing Antlr grammars within Python applications. ```bash pip install antlr4-python3-runtime==4.10 ``` -------------------------------- ### Install Python 2 Requirements for ScenarioRunner Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/getting_scenariorunner.md Installs the necessary Python 2 packages for ScenarioRunner using pip. It includes removing an older version of networkx if present and then installing requirements from the 'requirements.txt' file. ```sh sudo apt remove python-networkx #if installed, remove old version of networkx pip2 install --user -r requirements.txt ``` -------------------------------- ### Install Python 3 Requirements for ScenarioRunner Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/getting_scenariorunner.md Installs the necessary Python 3 packages for ScenarioRunner using pip3. It includes removing an older version of networkx if present and then installing requirements from the 'requirements.txt' file. ```sh sudo apt remove python3-networkx #if installed, remove old version of networkx pip3 install --user -r requirements.txt ``` -------------------------------- ### Install Specific Networkx Version for Agent Navigation Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/FAQ.md This snippet addresses a TypeError related to the Python Networkx package. It advises on removing an outdated version and installing a specific compatible version (2.2) to resolve agent navigation issues. ```bash sudo apt-get remove python-networkx pip install --user networkx==2.2 ``` -------------------------------- ### Update ScenarioRunner from Source Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/getting_scenariorunner.md Updates the ScenarioRunner installation when built from source. It involves navigating to the repository, checking out the master branch, and pulling the latest changes. ```sh cd ~/scenario_runner git branch master git pull ``` -------------------------------- ### Run Metrics Manager with Example Metric and Log Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/metrics_module.md This command executes the metrics manager script. It requires specifying the Python file for the metric to be calculated and the log file containing the simulation data. A simulation must be running for the map API to be accessible. The script generates a plot window that remains open until closed. ```sh python metrics_manager.py --metric srunner/metrics/examples/distance_between_vehicles.py --log srunner/metrics/data/DistanceBetweenVehicles.log ``` -------------------------------- ### Python: Implement Custom Autonomous Agent for Carla ScenarioRunner Source: https://context7.com/carla-simulator/scenario_runner/llms.txt This Python code defines a custom autonomous agent by subclassing `AutonomousAgent`. It includes methods for initializing the agent (`setup`), defining the sensor suite (`sensors`), executing control logic in each simulation step (`run_step`), and cleaning up resources (`destroy`). Dependencies include the `carla` library and `srunner.autoagents.autonomous_agent.AutonomousAgent`. ```python import carla from srunner.autoagents.autonomous_agent import AutonomousAgent class MyAutonomousAgent(AutonomousAgent): """ Custom autonomous driving agent implementation """ def setup(self, path_to_conf_file): """Initialize agent with configuration""" self.track = 'SENSORS' # Load configuration, models, etc. # self.model = load_model(path_to_conf_file) pass def sensors(self): """Define required sensor suite""" sensors = [ # RGB camera - front { 'type': 'sensor.camera.rgb', 'x': 0.7, 'y': 0.0, 'z': 1.60, 'roll': 0.0, 'pitch': 0.0, 'yaw': 0.0, 'width': 800, 'height': 600, 'fov': 100, 'id': 'Center' }, # LIDAR { 'type': 'sensor.lidar.ray_cast', 'x': 0.7, 'y': 0.0, 'z': 1.60, 'roll': 0.0, 'pitch': 0.0, 'yaw': 0.0, 'range': 50, 'channels': 32, 'points_per_second': 320000, 'rotation_frequency': 20, 'id': 'LIDAR' }, # IMU { 'type': 'sensor.other.imu', 'x': 0.0, 'y': 0.0, 'z': 0.0, 'roll': 0.0, 'pitch': 0.0, 'yaw': 0.0, 'id': 'IMU' }, # GNSS { 'type': 'sensor.other.gnss', 'x': 0.0, 'y': 0.0, 'z': 0.0, 'id': 'GPS' }, # Speedometer { 'type': 'sensor.speedometer', 'id': 'speed' } ] return sensors def run_step(self, input_data, timestamp): """ Execute one step of navigation Args: input_data: Dictionary of sensor data timestamp: Current simulation timestamp Returns: carla.VehicleControl: Control commands """ # Access sensor data rgb_center = input_data['Center'][1][:, :, :3] # RGB image lidar_data = input_data['LIDAR'][1] imu_data = input_data['IMU'][1] gps_data = input_data['GPS'][1] speed = input_data['speed'][1]['speed'] # Process sensor data and compute control # control = self.model.predict(rgb_center, lidar_data, speed) # Return vehicle control control = carla.VehicleControl() control.steer = 0.0 # [-1.0, 1.0] control.throttle = 0.5 # [0.0, 1.0] control.brake = 0.0 # [0.0, 1.0] control.hand_brake = False control.reverse = False return control def destroy(self): """Cleanup when agent is destroyed""" # Clean up resources, models, etc. pass ``` -------------------------------- ### Configure CARLA Environment Variables Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/README_OpenSCENARIO_2.0.md Sets the CARLA_ROOT environment variable and updates the PYTHONPATH to include the necessary CARLA Python API modules and examples. This allows Python scripts to find and import CARLA modules. ```bash export CARLA_ROOT=/home/dut-aiid/CARLA_0.9.13 export PYTHONPATH=$PYTHONPATH:${CARLA_ROOT}/PythonAPI/carla/dist/carla-0.9.13-py3.7-linux-x86_64.egg:${CARLA_ROOT}/PythonAPI/carla/agents:${CARLA_ROOT}/PythonAPI/carla/agents/navigation:${CARLA_ROOT}/PythonAPI/carla:${CARLA_ROOT}/PythonAPI/examples:${CARLA_ROOT}/PythonAPI ``` -------------------------------- ### Set CARLA and ScenarioRunner Environment Variables (Windows) Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/getting_scenariorunner.md Sets environment variables on Windows to specify the CARLA and ScenarioRunner installation directories and adds the CARLA Python API to the PYTHONPATH. This is essential for the system to find CARLA components and Python modules. ```bat # %CARLA_ROOT% is the CARLA installation directory # %SCENARIO_RUNNER% is the ScenarioRunner installation directory # is the correct string for the Python version being used # In a build from source, the .egg files may be in: ${CARLA_ROOT}/PythonAPI/dist/ instead of ${CARLA_ROOT}/PythonAPI set CARLA_ROOT=\\path\\to\\your\\carla\\installation set SCENARIO_RUNNER_ROOT=\\path\\to\\your\\scenario\\runner\\installation set PYTHONPATH=%PYTHONPATH%;%CARLA_ROOT%\\PythonAPI\\carla\\dist\\carla-.egg set PYTHONPATH=%PYTHONPATH%;%CARLA_ROOT%\\PythonAPI\\carla ``` -------------------------------- ### Define Sensor Setup in RosAgent (Python) Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/ros_agent.md This snippet shows how to define sensor configurations for a custom ROS agent by deriving from RosAgent and implementing the sensors() method. The sensors() method should return a list of sensor definitions. ```python from srunner.autoagents.ros_agent import RosAgent class MyRosAgent(RosAgent): def sensors(self): return [ ] ``` -------------------------------- ### Bash: Run CARLA Scenario Evaluator with Custom Agent Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/agent_evaluation.md This command executes the CARLA challenge evaluator script, specifying a custom agent and a configuration file. It's used to test an autonomous agent's performance in a simulated environment based on predefined routes and evaluation criteria. ```Bash python srunner/challenge/challenge_evaluator_routes.py --agent= --config=myconfigfilename.format ``` -------------------------------- ### XML Custom Scenario Configuration in Carla Simulator Source: https://context7.com/carla-simulator/scenario_runner/llms.txt Defines custom scenarios for Carla Simulator using XML. This includes specifying the ego vehicle's initial state, positions and models of other actors, weather conditions, and scenario-specific parameters like target speed and trigger distance. The structure allows for detailed environmental and actor setup. ```xml ``` -------------------------------- ### Python: Define Agent Sensors for CARLA Evaluation Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/agent_evaluation.md This function defines the sensors required by an autonomous agent in the CARLA simulator. It returns a list of dictionaries, where each dictionary specifies a sensor's type, ID, and other parameters like position and field of view. These sensors provide crucial data for the agent's decision-making process. ```Python def sensors(self): sensors = [{'type': 'sensor.camera.rgb', 'x':0.7, 'y':0.0, 'z':1.60, 'roll':0.0, 'pitch':0.0, 'yaw':0.0, 'width':800, 'height': 600, 'fov':100, 'id': 'Center'}, {'type': 'sensor.camera.rgb', 'x':0.7, 'y':-0.4, 'z': 1.60, 'roll': 0.0, 'pitch': 0.0, 'yaw': -45.0, 'width': 800, 'height': 600, 'fov': 100, 'id': 'Left'}, {'type': 'sensor.camera.rgb', 'x':0.7, 'y':0.4, 'z':1.60, 'roll':0.0, 'pitch':0.0, 'yaw':45.0, 'width':800, 'height':600, 'fov':100, 'id': 'Right'}, {'type': 'sensor.lidar.ray_cast', 'x': 0.7, 'y': -0.4, 'z': 1.60, 'roll': 0.0, 'pitch': 0.0, 'yaw': -45.0, 'id': 'LIDAR'}, {'type': 'sensor.other.gnss', 'x': 0.7, 'y': -0.4, 'z': 1.60, 'id': 'GPS'}, {'type': 'sensor.speedometer','reading_frequency': 25, 'id': 'speed'} ] return sensors ``` -------------------------------- ### Execute and Analyze CARLA Scenario with ScenarioRunner Source: https://context7.com/carla-simulator/scenario_runner/llms.txt This Python code snippet demonstrates the core functionality of the CARLA ScenarioRunner. It initializes a ScenarioManager, spawns an ego vehicle, loads and runs a 'FollowLeadingVehicle' scenario, analyzes its results, prints performance metrics, and finally cleans up the simulation environment. ```python from carla_scenario_runner.scenarios.follow_leading_vehicle import FollowLeadingVehicle from carla_scenario_runner.scenario_manager.scenario_manager import ScenarioManager # Assume world, config, and settings are already defined # Example initialization (replace with actual setup) # import carla # client = carla.Client('localhost', 2000) # world = client.get_world() # settings = world.get_settings() manager = ScenarioManager(debug_mode=True, sync_mode=True, timeout=10.0) try: # Spawn ego vehicle spawn_point = carla.Transform( carla.Location(x=107, y=133, z=0.5), carla.Rotation(yaw=0) ) ego_vehicle = world.spawn_actor( world.get_blueprint_library().find('vehicle.lincoln.mkz_2017'), spawn_point ) # Create and load scenario scenario = FollowLeadingVehicle( world=world, ego_vehicles=[ego_vehicle], config=config, # Assuming 'config' is a valid scenario configuration object randomize=False, debug_mode=True ) manager.load_scenario(scenario, agent=None) # agent=None if no specific agent is controlling the ego vehicle # Run scenario manager.run_scenario() # Analyze results success = manager.analyze_scenario( output=True, filename='results.txt', junit_filename='results.xml', json_filename='results.json' ) print(f"Scenario duration (sim): {manager.scenario_duration_game:.2f}s") print(f"Scenario duration (real): {manager.scenario_duration_system:.2f}s") print(f"Success: {success}") finally: # Cleanup manager.cleanup() if 'ego_vehicle' in locals() and ego_vehicle is not None: ego_vehicle.destroy() # Reset to asynchronous mode if needed # settings.synchronous_mode = False # world.apply_settings(settings) ``` -------------------------------- ### Implement the Main Metric Method _create_metric Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/metrics_module.md This snippet outlines the implementation of the `_create_metric` method, which is the core logic for any custom metric. It accepts `town_map`, `log`, and `criteria` as inputs to access scenario data and calculate desired metrics. ```python def _create_metric(self, town_map, log, criteria): """ Implementation of the metric. This is an example to show how to use the recorder, accessed via the log. """ ``` -------------------------------- ### Configure Multiple Ego Vehicles in Scenario XML (XML) Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/creating_new_scenario.md An XML snippet demonstrating how to configure multiple ego vehicles for a CARLA scenario. It shows how to define different ego vehicles with specific positions, yaw angles, models, and role names, allowing for multi-ego vehicle scenarios. ```xml ``` -------------------------------- ### Set CARLA and ScenarioRunner Environment Variables (Linux) Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/getting_scenariorunner.md Sets environment variables on Linux to specify the CARLA and ScenarioRunner installation directories and adds the CARLA Python API to the PYTHONPATH. This is crucial for the system to locate CARLA components and Python modules. ```sh # ${CARLA_ROOT} is the CARLA installation directory # ${SCENARIO_RUNNER} is the ScenarioRunner installation directory # is the correct string for the Python version being used # In a build from source, the .egg files may be in: ${CARLA_ROOT}/PythonAPI/dist/ instead of ${CARLA_ROOT}/PythonAPI export CARLA_ROOT=/path/to/your/carla/installation export SCENARIO_RUNNER_ROOT=/path/to/your/scenario/runner/installation export PYTHONPATH=$PYTHONPATH:${CARLA_ROOT}/PythonAPI/carla/dist/carla-.egg export PYTHONPATH=$PYTHONPATH:${CARLA_ROOT}/PythonAPI/carla ``` -------------------------------- ### Define Custom Expressions in OSC2 Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/README_OpenSCENARIO_2.0.md This example demonstrates defining a custom structure named 'speeds' with a 'compute' method that subtracts two velocities, illustrating expression definition in OSC2. ```osc struct speeds: def compute(x:velocity, y:velocity) -> velocity is expression x-y ``` -------------------------------- ### Migrate OpenSCENARIO 0.9.x to 1.0 using xsltproc Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/openscenario_support.md This snippet demonstrates how to convert OpenSCENARIO 0.9.x files to the 1.0 standard using the xsltproc command-line tool. It requires the migration0_9_1to1_0.xslt stylesheet and input/output file paths. The output is a new OpenSCENARIO 1.0 file. ```bash xsltproc -o newScenario.xosc migration0_9_1to1_0.xslt oldScenario.xosc ``` -------------------------------- ### Record CARLA Scenario Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/metrics_module.md Records a CARLA simulation scenario to a specified file path. This process generates two files: a CARLA recording (`.log`) containing frame-by-frame simulation data, and a criteria file (`.json`) storing scenario-specific attributes. The path is relative to the SCENARIO_RUNNER_ROOT environment variable. Only JSON serializable attributes are saved in the criteria file. ```sh python scenario_runner.py --scenario --record ``` -------------------------------- ### Run Metrics Manager Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/metrics_module.md Execute the metrics manager script to generate metrics from log files. Ensure a simulation is running to access map APIs. ```APIDOC ## Run Metrics Manager ### Description Run the metrics manager script to process scenario data and generate metrics using predefined metric files and log data. A simulation must be running for the module to access map APIs. ### Command ```sh python metrics_manager.py --metric --log ``` ### Parameters - `--metric` (string) - Required - Path to the metric definition file (e.g., `srunner/metrics/examples/distance_between_vehicles.py`). - `--log` (string) - Required - Path to the log file containing scenario data (e.g., `srunner/metrics/data/DistanceBetweenVehicles.log`). ### Notes - A simulation must be running for the module to function correctly. - The script will not terminate until the output window displaying the results is closed. ``` -------------------------------- ### Execute OpenSCENARIO Files with ScenarioRunner Source: https://context7.com/carla-simulator/scenario_runner/llms.txt Load and execute traffic scenarios defined in OpenSCENARIO (1.0 and 2.0) formats using the scenario_runner.py script. This approach allows for parameter customization, output generation in JUnit or JSON formats, and specification of output directories. It requires providing the path to the scenario file and CARLA host/port. ```bash # Execute OpenSCENARIO 1.0 file python scenario_runner.py \ --openscenario path/to/scenario.xosc \ --host 127.0.0.1 \ --port 2000 \ --sync # Execute with custom parameter overrides python scenario_runner.py \ --openscenario path/to/scenario.xosc \ --openscenarioparams "TargetSpeed:15.0, WeatherCondition:rainy" \ --output \ --junit # Execute OpenSCENARIO 2.0 file python scenario_runner.py \ --openscenario2 path/to/scenario.osc2 \ --sync \ --json \ --outputDir ./results ``` -------------------------------- ### Create Empty Python Scenario Class (Python) Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/creating_new_scenario.md Defines an empty Python class 'NewScenario' that inherits from 'BasicScenario'. This class serves as a template for creating new custom scenarios in CARLA. It includes essential methods like __init__, _create_behavior, and _create_test_criteria, along with documentation for parameters. ```python class NewScenario(BasicScenario): """ Some documentation on NewScenario :param world is the CARLA world :param ego_vehicles is a list of ego vehicles for this scenario :param config is the scenario configuration (ScenarioConfiguration) :param randomize can be used to select parameters randomly (optional, default=False) :param debug_mode can be used to provide more comprehensive console output (optional, default=False) :param criteria_enable can be used to disable/enable scenario evaluation based on test criteria (optional, default=True) :param timeout is the overall scenario timeout (optional, default=60 seconds) """ # some ego vehicle parameters # some parameters for the other vehicles def __init__(self, world, ego_vehicles, config, randomize=False, debug_mode=False, criteria_enable=True, timeout=60): """ Initialize all parameters required for NewScenario """ # Call constructor of BasicScenario super(NewScenario, self).__init__( "NewScenario", ego_vehicles, config, world, debug_mode, criteria_enable=criteria_enable) def _create_behavior(self): """ Setup the behavior for NewScenario """ def _create_test_criteria(self): """ Setup the evaluation criteria for NewScenario """ ``` -------------------------------- ### Run OpenSCENARIO 2.0 Scenario Source: https://github.com/carla-simulator/scenario_runner/blob/master/Docs/README_OpenSCENARIO_2.0.md Executes a scenario defined in OpenSCENARIO 2.0 format using the scenario runner. The `--openscenario2` flag specifies the path to the .osc file, and `--reloadWorld` ensures a clean simulation environment for each run. ```bash python scenario_runner.py --sync --openscenario2 srunner/examples/overtake_concrete.osc --reloadWorld ```