{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Scenario loading and structure \n",
"\n",
"`GPUDrive` is a multi-agent driving simulator built on top of the [Waymo Open Motion Dataset (WOMD)](https://waymo.com/open/) (See also [Ettinger et al., 2021](https://arxiv.org/abs/2104.10133)). \n",
"\n",
"In this tutorial, we explain the structure of a traffic scenario and show use processed scenario data with `GPUDrive`.\n",
"\n",
"**Useful links to learn more**:\n",
"- [`waymo-open-dataset`](https://github.com/waymo-research/waymo-open-dataset): Official dataset repo\n",
"- [tf.Example proto format](https://waymo.com/open/data/motion/tfexample): Data dictionary for a raw WOMD scenario\n",
"- [GPUDrive `data_utils`](https://github.com/Emerge-Lab/gpudrive/tree/main/data_utils): Docs and code we use to process the WOMD scenarios"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [],
"source": [
"# Dependencies\n",
"import json\n",
"import matplotlib.pyplot as plt\n",
"import os\n",
"from pathlib import Path\n",
"import seaborn as sns\n",
"import pandas as pd\n",
"\n",
"# Set working directory to the base directory 'gpudrive'\n",
"working_dir = Path.cwd()\n",
"while working_dir.name != 'gpudrive':\n",
" working_dir = working_dir.parent\n",
" if working_dir == Path.home():\n",
" raise FileNotFoundError(\"Base directory 'gpudrive' not found\")\n",
"os.chdir(working_dir)\n",
"\n",
"cmap = [\"r\", \"g\", \"b\", \"y\", \"c\"]\n",
"%config InlineBackend.figure_format = 'svg'\n",
"sns.set(\"notebook\", font_scale=1.1, rc={\"figure.figsize\": (8, 3)})\n",
"sns.set_style(\"ticks\", rc={\"figure.facecolor\": \"none\", \"axes.facecolor\": \"none\"})"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Iterating through the WOMD dataset\n",
"\n",
"We upload a folder containing three scenarios in the `data/processed/examples` directory that you can work with. The full dataset can be downloaded [here](https://github.com/Emerge-Lab/gpudrive/tree/main?tab=readme-ov-file#dataset). \n",
"\n",
"\n",
"Notice that the data folder is structured as follows:\n",
"\n",
"```bash\n",
"data/\n",
" - tfrecord-xxxxx-of-xxxxx\n",
" - ....\n",
" - tfrecord-xxxxx-of-xxxxx\n",
"```\n",
"\n",
"Every file beginning with `tfrecord` is a unique traffic scenario.\n",
"\n",
"To use the dataset with the simulator, we use the conventions from [PyTorch dataloaders](https://pytorch.org/tutorials/beginner/basics/data_tutorial.html). \n",
"\n",
"\n",
"Here is example of how to set up a dataloader:"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [],
"source": [
"from gpudrive.env.dataset import SceneDataLoader\n",
"\n",
"data_loader = SceneDataLoader(\n",
" root=\"data/processed/examples\", # Path to the dataset\n",
" batch_size=10, # Batch size, you want this to be equal to the number of worlds (envs) so that every world receives a different scene\n",
" dataset_size=4, # Total number of different scenes we want to use\n",
" sample_with_replacement=True, \n",
" seed=42, \n",
" shuffle=True, \n",
")"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['data/processed/examples/tfrecord-00002-of-01000_407.json',\n",
" 'data/processed/examples/tfrecord-00002-of-01000_407.json',\n",
" 'data/processed/examples/tfrecord-00000-of-01000_402.json',\n",
" 'data/processed/examples/tfrecord-00000-of-01000_222.json',\n",
" 'data/processed/examples/tfrecord-00000-of-01000_325.json',\n",
" 'data/processed/examples/tfrecord-00000-of-01000_402.json',\n",
" 'data/processed/examples/tfrecord-00000-of-01000_325.json',\n",
" 'data/processed/examples/tfrecord-00000-of-01000_222.json',\n",
" 'data/processed/examples/tfrecord-00000-of-01000_222.json',\n",
" 'data/processed/examples/tfrecord-00000-of-01000_325.json']"
]
},
"execution_count": 40,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# The full dataset that we will be using\n",
"data_loader.dataset"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'data/processed/examples/tfrecord-00000-of-01000_222.json',\n",
" 'data/processed/examples/tfrecord-00000-of-01000_325.json',\n",
" 'data/processed/examples/tfrecord-00000-of-01000_402.json',\n",
" 'data/processed/examples/tfrecord-00002-of-01000_407.json'}"
]
},
"execution_count": 41,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Notice that it only has 4 unique scenes, since we set the dataset_size to 4\n",
"set(data_loader.dataset)"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'data/processed/examples/tfrecord-00002-of-01000_407.json'"
]
},
"execution_count": 42,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"data_files = next(iter(data_loader))\n",
"\n",
"data_files[0]"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [],
"source": [
"from gpudrive.env.env_torch import GPUDriveTorchEnv\n",
"from gpudrive.env.config import EnvConfig"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [],
"source": [
"# Pass the data_loader to the environment \n",
"env = GPUDriveTorchEnv(\n",
" config=EnvConfig(),\n",
" data_loader=data_loader,\n",
" max_cont_agents=64, \n",
" device=\"cpu\",\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Deep dive: What is inside a traffic scenario? 🤔🔬"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"Though every scenario in the WOMD is unique, they all share the same basic data structure. Traffic scenarios are essentially dictionaries, which you can inspect using tools like [JSON Formatter](https://jsonformatter.org/json-viewer). We'll also look at one in this notebook. In a nutshell, traffic scenarios contain a few key elements:\n",
"\n",
"- **Road map**: The layout and structure of the roads.\n",
"- **Human driving (expert) demonstrations**: Examples of human driving behavior.\n",
"- **Road objects**: Elements such as stop signs and other traffic signals."
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"dict_keys(['name', 'scenario_id', 'objects', 'roads', 'tl_states', 'metadata'])"
]
},
"execution_count": 45,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Take an example scene\n",
"data_path = \"data/processed/examples/tfrecord-00000-of-01000_222.json\"\n",
"\n",
"with open(data_path) as file:\n",
" traffic_scene = json.load(file)\n",
"\n",
"traffic_scene.keys()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"We will show you how to render a scene in ⏭️ tutorial `03`, which introduces the gym environment wrapper. Let's first take a closer look at the data structure."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### Global Overview\n",
"\n",
"A traffic scene includes the following key elements:\n",
"\n",
"- **`name`**: The name of the traffic scenario. \n",
"- **`scenario_id`**: Unique identifier for every scenario.\n",
"- **`objects`**: Dynamic entities such as vehicles or other moving elements in the scene. \n",
"- **`roads`**: Stationary elements, including road points and fixed objects. \n",
"- **`tl_states`**: Traffic light states (currently not included in processing). \n",
"- **`metadata`**: Additional details about the traffic scenario, such as the index of the self-driving car (SDC) and details for the WOSAC Challenge."
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{}"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"traffic_scene[\"tl_states\"]"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'tfrecord-00000-of-00150_78.json'"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"traffic_scene[\"name\"]"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'sdc_track_index': 11,\n",
" 'objects_of_interest': [14, 41],\n",
" 'tracks_to_predict': [{'track_index': 7, 'difficulty': 0},\n",
" {'track_index': 10, 'difficulty': 0},\n",
" {'track_index': 1, 'difficulty': 0}]}"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"traffic_scene[\"metadata\"]"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'fcb5b4973f486e78'"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"traffic_scene[\"scenario_id\"]"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"pd.Series(\n",
" [\n",
" traffic_scene[\"objects\"][idx][\"type\"]\n",
" for idx in range(len(traffic_scene[\"objects\"]))\n",
" ]\n",
").value_counts().plot(kind=\"bar\", rot=45, color=cmap)\n",
"plt.title(\n",
" f'Distribution of road objects in traffic scene. Total # objects: {len(traffic_scene[\"objects\"])}'\n",
")\n",
"plt.show()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"This traffic scenario only contains vehicles and pedestrians, some scenes have cyclists as well."
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"pd.Series(\n",
" [traffic_scene[\"roads\"][idx][\"type\"] for idx in range(len(traffic_scene[\"roads\"]))]\n",
").value_counts().plot(kind=\"bar\", rot=45, color=cmap)\n",
"plt.title(\n",
" f'Distribution of road points in traffic scene. Total # points: {len(traffic_scene[\"roads\"])}'\n",
")\n",
"plt.show()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### In-Depth: Road Objects\n",
"\n",
"This is a list of different road objects in the traffic scene. For each road object, we have information about its position, velocity, size, in which direction it's heading, whether it's a valid object, the type, and the final position of the vehicle."
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"dict_keys(['position', 'width', 'length', 'height', 'heading', 'velocity', 'valid', 'goalPosition', 'type', 'id', 'mark_as_expert'])"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Take the first object\n",
"idx = 0\n",
"\n",
"# For each object, we have this information:\n",
"traffic_scene[\"objects\"][idx].keys()"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[\n",
" {\n",
" \"x\": 1769.906982421875,\n",
" \"y\": -4880.38330078125,\n",
" \"z\": -142.78407973639492\n",
" },\n",
" {\n",
" \"x\": 1769.90283203125,\n",
" \"y\": -4880.6923828125,\n",
" \"z\": -142.7745534732751\n",
" },\n",
" {\n",
" \"x\": 1769.9061279296875,\n",
" \"y\": -4880.966796875,\n",
" \"z\": -142.76056932836318\n",
" },\n",
" {\n",
" \"x\": 1769.903076171875,\n",
" \"y\": -4881.26220703125,\n",
" \"z\": -142.7467465274731\n",
" },\n",
" {\n",
" \"x\": 1769.893798828125,\n",
" \"y\": -4881.5322265625,\n",
" \"z\": -142.75370648323303\n",
" },\n",
" {\n",
" \"x\": 1769.889892578125,\n",
" \"y\": -4881.7978515625,\n",
" \"z\": -142.73502097033202\n",
" },\n",
" {\n",
" \"x\": 1769.886962890625,\n",
" \"y\": -4882.04833984375,\n",
" \"z\": -142.73322709385124\n",
" },\n",
" {\n",
" \"x\": 1769.8853759765625,\n",
" \"y\": -4882.24951171875,\n",
" \"z\": -142.7076711328151\n",
" },\n",
" {\n",
" \"x\": 1769.8785400390625,\n",
" \"y\": -4882.4990234375,\n",
" \"z\": -142.70739824649579\n",
" },\n",
" {\n",
" \"x\": 1769.8828125,\n",
" \"y\": -4882.708984375,\n",
" \"z\": -142.71031548280774\n",
" }\n",
"]\n"
]
}
],
"source": [
"# Position contains the (x, y) coordinates for the vehicle at every time step\n",
"print(json.dumps(traffic_scene[\"objects\"][idx][\"position\"][:10], indent=4))"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(2.1302132606506348, 4.532253742218018)"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Width and length together make the size of the object, and is used to see if there is a collision\n",
"traffic_scene[\"objects\"][idx][\"width\"], traffic_scene[\"objects\"][idx][\"length\"]"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"An object's heading refers to the direction it is pointing or moving in. The default coordinate system in Nocturne is right-handed, where the positive x and y axes point to the right and downwards, respectively. In a right-handed coordinate system, 0 degrees is located on the x-axis and the angle increases counter-clockwise.\n",
"\n",
"Because the scene is created from the viewpoint of an ego driver, there may be instances where the heading of certain vehicles is not available. These cases are represented by the value `-10_000`, to indicate that these steps should be filtered out or are invalid."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"# Heading is the direction in which the vehicle is pointing\n",
"plt.plot(traffic_scene[\"objects\"][idx][\"heading\"])\n",
"plt.xlabel(\"Time step\")\n",
"plt.ylabel(\"Heading\")\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[\n",
" {\n",
" \"x\": 0.040283203125,\n",
" \"y\": -2.8857421875\n",
" },\n",
" {\n",
" \"x\": -0.04150390625,\n",
" \"y\": -3.0908203125\n",
" },\n",
" {\n",
" \"x\": 0.032958984375,\n",
" \"y\": -2.744140625\n",
" },\n",
" {\n",
" \"x\": -0.030517578125,\n",
" \"y\": -2.9541015625\n",
" },\n",
" {\n",
" \"x\": -0.0927734375,\n",
" \"y\": -2.7001953125\n",
" },\n",
" {\n",
" \"x\": -0.0390625,\n",
" \"y\": -2.65625\n",
" },\n",
" {\n",
" \"x\": -0.029296875,\n",
" \"y\": -2.5048828125\n",
" },\n",
" {\n",
" \"x\": -0.015869140625,\n",
" \"y\": -2.01171875\n",
" },\n",
" {\n",
" \"x\": -0.068359375,\n",
" \"y\": -2.4951171875\n",
" },\n",
" {\n",
" \"x\": 0.042724609375,\n",
" \"y\": -2.099609375\n",
" }\n",
"]\n"
]
}
],
"source": [
"# Velocity shows the velocity in the x- and y- directions\n",
"print(json.dumps(traffic_scene[\"objects\"][idx][\"velocity\"][:10], indent=4))"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"# Valid indicates if the state of the vehicle was observed for each timepoint\n",
"plt.xlabel(\"Time step\")\n",
"plt.ylabel(\"IS VALID\")\n",
"plt.plot(traffic_scene[\"objects\"][idx][\"valid\"], \"_\", lw=5)\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'x': 1769.8800048828125, 'y': -4882.9111328125, 'z': -142.70326633499866}"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Each object has a goalPosition, an (x, y) position within the scene\n",
"traffic_scene[\"objects\"][idx][\"goalPosition\"]"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'vehicle'"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Finally, we have the type of the vehicle\n",
"traffic_scene[\"objects\"][idx][\"type\"]"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### In-Depth: Road Points\n",
"\n",
"Road points are static objects in the scene."
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"dict_keys(['geometry', 'type', 'map_element_id', 'id'])"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"traffic_scene[\"roads\"][idx].keys()"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'road_line'"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# This point represents the edge of a road\n",
"traffic_scene[\"roads\"][idx][\"type\"]"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[\n",
" {\n",
" \"x\": 1774.635980601552,\n",
" \"y\": -4778.721456255188,\n",
" \"z\": -145.05792806647807\n",
" },\n",
" {\n",
" \"x\": 1774.6294258416444,\n",
" \"y\": -4779.218941088273,\n",
" \"z\": -145.05028100765452\n",
" },\n",
" {\n",
" \"x\": 1774.6245077883877,\n",
" \"y\": -4779.716444838109,\n",
" \"z\": -145.042633948831\n",
" },\n",
" {\n",
" \"x\": 1774.6210581920316,\n",
" \"y\": -4780.213960978309,\n",
" \"z\": -145.03498689000747\n",
" },\n",
" {\n",
" \"x\": 1774.6189087713544,\n",
" \"y\": -4780.711484469765,\n",
" \"z\": -145.02733983118395\n",
" },\n",
" {\n",
" \"x\": 1774.6178912287696,\n",
" \"y\": -4781.209011595056,\n",
" \"z\": -145.0196927723604\n",
" },\n",
" {\n",
" \"x\": 1774.6178372641725,\n",
" \"y\": -4781.706539785734,\n",
" \"z\": -145.01204571353688\n",
" },\n",
" {\n",
" \"x\": 1774.6185785636114,\n",
" \"y\": -4782.204067448844,\n",
" \"z\": -145.00439865471336\n",
" },\n",
" {\n",
" \"x\": 1774.6199468194288,\n",
" \"y\": -4782.701593801315,\n",
" \"z\": -144.99675159588983\n",
" },\n",
" {\n",
" \"x\": 1774.6217737176728,\n",
" \"y\": -4783.199118693311,\n",
" \"z\": -144.98910453706628\n",
" }\n",
"]\n"
]
}
],
"source": [
"# Geometry contains the (x, y) position(s) for a road point\n",
"# Note that this will be a list for road lanes and edges but a single (x, y) tuple for stop signs and alike\n",
"print(json.dumps(traffic_scene[\"roads\"][idx][\"geometry\"][:10], indent=4));"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "gpudrive",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.9"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}