{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":15768,"databundleVersionId":700263,"sourceType":"competition"}],"dockerImageVersionId":30588,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"from IPython.display import HTML\nHTML('<center><iframe width=\"700\" height=\"400\" src=\"https://www.youtube.com/embed/tlThdr3O5Qo?rel=0&amp;controls=0&amp;showinfo=0\" frameborder=\"0\" allowfullscreen></iframe></center>')","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-02-01T03:41:22.987774Z","iopub.execute_input":"2024-02-01T03:41:22.988103Z","iopub.status.idle":"2024-02-01T03:41:23.000826Z","shell.execute_reply.started":"2024-02-01T03:41:22.988074Z","shell.execute_reply":"2024-02-01T03:41:22.999934Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install lyft_dataset_sdk","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:41:23.021577Z","iopub.execute_input":"2024-02-01T03:41:23.022164Z","iopub.status.idle":"2024-02-01T03:41:39.992225Z","shell.execute_reply.started":"2024-02-01T03:41:23.022135Z","shell.execute_reply":"2024-02-01T03:41:39.991216Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pip install --upgrade pip\n","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:41:39.994376Z","iopub.execute_input":"2024-02-01T03:41:39.994739Z","iopub.status.idle":"2024-02-01T03:42:01.949672Z","shell.execute_reply.started":"2024-02-01T03:41:39.994702Z","shell.execute_reply":"2024-02-01T03:42:01.948514Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport gc\nimport numpy as np\nimport pandas as pd\n\nimport json\nimport math\nimport sys\nimport time\nfrom datetime import datetime\nfrom typing import Tuple, List\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport sklearn.metrics\nfrom PIL import Image\n\nfrom matplotlib.axes import Axes\nfrom matplotlib import animation, rc\nimport plotly.graph_objs as go\nimport plotly.tools as tls\nfrom plotly.offline import plot, init_notebook_mode\nimport plotly.figure_factory as ff\n\ninit_notebook_mode(connected=True)\n\nimport seaborn as sns\nfrom pyquaternion import Quaternion\nfrom tqdm import tqdm\n\nfrom lyft_dataset_sdk.utils.map_mask import MapMask\nfrom lyft_dataset_sdk.lyftdataset import LyftDataset\nfrom lyft_dataset_sdk.utils.geometry_utils import view_points, box_in_image, BoxVisibility\nfrom lyft_dataset_sdk.utils.geometry_utils import view_points, transform_matrix\nfrom pathlib import Path\n\nimport struct\nfrom abc import ABC, abstractmethod\nfrom functools import reduce\nfrom typing import Tuple, List, Dict\nimport copy","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:42:01.951594Z","iopub.execute_input":"2024-02-01T03:42:01.952018Z","iopub.status.idle":"2024-02-01T03:42:04.655737Z","shell.execute_reply.started":"2024-02-01T03:42:01.951978Z","shell.execute_reply":"2024-02-01T03:42:04.654937Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DATA_PATH = '../input/3d-object-detection-for-autonomous-vehicles/'","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:42:04.657757Z","iopub.execute_input":"2024-02-01T03:42:04.658069Z","iopub.status.idle":"2024-02-01T03:42:04.662253Z","shell.execute_reply.started":"2024-02-01T03:42:04.658042Z","shell.execute_reply":"2024-02-01T03:42:04.661219Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv(DATA_PATH + 'train.csv')\nsample_submission = pd.read_csv(DATA_PATH + 'sample_submission.csv')","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:42:04.663572Z","iopub.execute_input":"2024-02-01T03:42:04.664323Z","iopub.status.idle":"2024-02-01T03:42:05.995221Z","shell.execute_reply.started":"2024-02-01T03:42:04.664289Z","shell.execute_reply":"2024-02-01T03:42:05.994174Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Taken from https://www.kaggle.com/gaborfodor/eda-3d-object-detection-challenge\n\nobject_columns = ['sample_id', 'object_id', 'center_x', 'center_y', 'center_z',\n                  'width', 'length', 'height', 'yaw', 'class_name']\nobjects = []\nfor sample_id, ps in tqdm(train.values[:]):\n    object_params = ps.split()\n    n_objects = len(object_params)\n    for i in range(n_objects // 8):\n        x, y, z, w, l, h, yaw, c = tuple(object_params[i * 8: (i + 1) * 8])\n        objects.append([sample_id, i, x, y, z, w, l, h, yaw, c])\ntrain_objects = pd.DataFrame(\n    objects,\n    columns = object_columns\n)","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:42:05.996548Z","iopub.execute_input":"2024-02-01T03:42:05.996937Z","iopub.status.idle":"2024-02-01T03:42:09.208184Z","shell.execute_reply.started":"2024-02-01T03:42:05.996899Z","shell.execute_reply":"2024-02-01T03:42:09.207379Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"numerical_cols = ['object_id', 'center_x', 'center_y', 'center_z', 'width', 'length', 'height', 'yaw']\ntrain_objects[numerical_cols] = np.float32(train_objects[numerical_cols].values)\ntrain_objects.head()","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:42:09.209301Z","iopub.execute_input":"2024-02-01T03:42:09.209605Z","iopub.status.idle":"2024-02-01T03:42:11.206719Z","shell.execute_reply.started":"2024-02-01T03:42:09.209578Z","shell.execute_reply":"2024-02-01T03:42:11.205727Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, ax = plt.subplots(figsize=(10, 10))\nsns.distplot(train_objects['center_x'], color='darkorange', ax=ax).set_title('center_x and center_y', fontsize=16)\nsns.distplot(train_objects['center_y'], color='purple', ax=ax).set_title('center_x and center_y', fontsize=16)\nplt.xlabel('center_x and center_y', fontsize=15)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:42:11.208168Z","iopub.execute_input":"2024-02-01T03:42:11.208532Z","iopub.status.idle":"2024-02-01T03:42:16.581919Z","shell.execute_reply.started":"2024-02-01T03:42:11.208499Z","shell.execute_reply":"2024-02-01T03:42:16.580850Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"new_train_objects = train_objects.query('class_name == \"car\"')\nplot = sns.jointplot(x=new_train_objects['center_x'][:1000], y=new_train_objects['center_y'][:1000], kind='kde', color='blueviolet')\nplot.set_axis_labels('center_x', 'center_y', fontsize=16)\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:42:16.583269Z","iopub.execute_input":"2024-02-01T03:42:16.583590Z","iopub.status.idle":"2024-02-01T03:42:17.940962Z","shell.execute_reply.started":"2024-02-01T03:42:16.583562Z","shell.execute_reply":"2024-02-01T03:42:17.940070Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, ax = plt.subplots(figsize=(10, 10))\nsns.distplot(train_objects['center_z'], color='navy', ax=ax).set_title('center_z', fontsize=16)\nplt.xlabel('center_z', fontsize=15)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:42:17.945628Z","iopub.execute_input":"2024-02-01T03:42:17.946264Z","iopub.status.idle":"2024-02-01T03:42:20.686277Z","shell.execute_reply.started":"2024-02-01T03:42:17.946235Z","shell.execute_reply":"2024-02-01T03:42:20.685331Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, ax = plt.subplots(figsize=(10, 10))\nsns.distplot(train_objects['yaw'], color='darkgreen', ax=ax).set_title('yaw', fontsize=16)\nplt.xlabel('yaw', fontsize=15)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:42:20.687393Z","iopub.execute_input":"2024-02-01T03:42:20.687676Z","iopub.status.idle":"2024-02-01T03:42:23.249524Z","shell.execute_reply.started":"2024-02-01T03:42:20.687651Z","shell.execute_reply":"2024-02-01T03:42:23.248640Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Lyft Dataset SDK dev-kit.\n# Code written by Oscar Beijbom, 2018.\n# Licensed under the Creative Commons [see licence.txt]\n# Modified by Vladimir Iglovikov 2019.\n\nclass PointCloud(ABC):\n    \"\"\"\n    Abstract class for manipulating and viewing point clouds.\n    Every point cloud (lidar and radar) consists of points where:\n    - Dimensions 0, 1, 2 represent x, y, z coordinates.\n        These are modified when the point cloud is rotated or translated.\n    - All other dimensions are optional. Hence these have to be manually modified if the reference frame changes.\n    \"\"\"\n\n    def __init__(self, points: np.ndarray):\n        \"\"\"\n        Initialize a point cloud and check it has the correct dimensions.\n        :param points: <np.float: d, n>. d-dimensional input point cloud matrix.\n        \"\"\"\n        assert points.shape[0] == self.nbr_dims(), (\n            \"Error: Pointcloud points must have format: %d x n\" % self.nbr_dims()\n        )\n        self.points = points\n\n    @staticmethod\n    @abstractmethod\n    def nbr_dims() -> int:\n        \"\"\"Returns the number of dimensions.\n        Returns: Number of dimensions.\n        \"\"\"\n        pass\n\n    @classmethod\n    @abstractmethod\n    def from_file(cls, file_name: str) -> \"PointCloud\":\n        \"\"\"Loads point cloud from disk.\n        Args:\n            file_name: Path of the pointcloud file on disk.\n        Returns: PointCloud instance.\n        \"\"\"\n        pass\n\n    @classmethod\n    def from_file_multisweep(\n        cls, lyftd, sample_rec: Dict, chan: str, ref_chan: str, num_sweeps: int = 26, min_distance: float = 1.0\n    ) -> Tuple[\"PointCloud\", np.ndarray]:\n        \"\"\"Return a point cloud that aggregates multiple sweeps.\n        As every sweep is in a different coordinate frame, we need to map the coordinates to a single reference frame.\n        As every sweep has a different timestamp, we need to account for that in the transformations and timestamps.\n        Args:\n            lyftd: A LyftDataset instance.\n            sample_rec: The current sample.\n            chan: The radar channel from which we track back n sweeps to aggregate the point cloud.\n            ref_chan: The reference channel of the current sample_rec that the point clouds are mapped to.\n            num_sweeps: Number of sweeps to aggregated.\n            min_distance: Distance below which points are discarded.\n        Returns: (all_pc, all_times). The aggregated point cloud and timestamps.\n        \"\"\"\n\n        # Init\n        points = np.zeros((cls.nbr_dims(), 0))\n        all_pc = cls(points)\n        all_times = np.zeros((1, 0))\n\n        # Get reference pose and timestamp\n        ref_sd_token = sample_rec[\"data\"][ref_chan]\n        ref_sd_rec = lyftd.get(\"sample_data\", ref_sd_token)\n        ref_pose_rec = lyftd.get(\"ego_pose\", ref_sd_rec[\"ego_pose_token\"])\n        ref_cs_rec = lyftd.get(\"calibrated_sensor\", ref_sd_rec[\"calibrated_sensor_token\"])\n        ref_time = 1e-6 * ref_sd_rec[\"timestamp\"]\n\n        # Homogeneous transform from ego car frame to reference frame\n        ref_from_car = transform_matrix(ref_cs_rec[\"translation\"], Quaternion(ref_cs_rec[\"rotation\"]), inverse=True)\n\n        # Homogeneous transformation matrix from global to _current_ ego car frame\n        car_from_global = transform_matrix(\n            ref_pose_rec[\"translation\"], Quaternion(ref_pose_rec[\"rotation\"]), inverse=True\n        )\n\n        # Aggregate current and previous sweeps.\n        sample_data_token = sample_rec[\"data\"][chan]\n        current_sd_rec = lyftd.get(\"sample_data\", sample_data_token)\n        for _ in range(num_sweeps):\n            # Load up the pointcloud.\n            current_pc = cls.from_file(lyftd.data_path / ('train_' + current_sd_rec[\"filename\"]))\n\n            # Get past pose.\n            current_pose_rec = lyftd.get(\"ego_pose\", current_sd_rec[\"ego_pose_token\"])\n            global_from_car = transform_matrix(\n                current_pose_rec[\"translation\"], Quaternion(current_pose_rec[\"rotation\"]), inverse=False\n            )\n\n            # Homogeneous transformation matrix from sensor coordinate frame to ego car frame.\n            current_cs_rec = lyftd.get(\"calibrated_sensor\", current_sd_rec[\"calibrated_sensor_token\"])\n            car_from_current = transform_matrix(\n                current_cs_rec[\"translation\"], Quaternion(current_cs_rec[\"rotation\"]), inverse=False\n            )\n\n            # Fuse four transformation matrices into one and perform transform.\n            trans_matrix = reduce(np.dot, [ref_from_car, car_from_global, global_from_car, car_from_current])\n            current_pc.transform(trans_matrix)\n\n            # Remove close points and add timevector.\n            current_pc.remove_close(min_distance)\n            time_lag = ref_time - 1e-6 * current_sd_rec[\"timestamp\"]  # positive difference\n            times = time_lag * np.ones((1, current_pc.nbr_points()))\n            all_times = np.hstack((all_times, times))\n\n            # Merge with key pc.\n            all_pc.points = np.hstack((all_pc.points, current_pc.points))\n\n            # Abort if there are no previous sweeps.\n            if current_sd_rec[\"prev\"] == \"\":\n                break\n            else:\n                current_sd_rec = lyftd.get(\"sample_data\", current_sd_rec[\"prev\"])\n\n        return all_pc, all_times\n\n    def nbr_points(self) -> int:\n        \"\"\"Returns the number of points.\"\"\"\n        return self.points.shape[1]\n\n    def subsample(self, ratio: float) -> None:\n        \"\"\"Sub-samples the pointcloud.\n        Args:\n            ratio: Fraction to keep.\n        \"\"\"\n        selected_ind = np.random.choice(np.arange(0, self.nbr_points()), size=int(self.nbr_points() * ratio))\n        self.points = self.points[:, selected_ind]\n\n    def remove_close(self, radius: float) -> None:\n        \"\"\"Removes point too close within a certain radius from origin.\n        Args:\n            radius: Radius below which points are removed.\n        Returns:\n        \"\"\"\n        x_filt = np.abs(self.points[0, :]) < radius\n        y_filt = np.abs(self.points[1, :]) < radius\n        not_close = np.logical_not(np.logical_and(x_filt, y_filt))\n        self.points = self.points[:, not_close]\n\n    def translate(self, x: np.ndarray) -> None:\n        \"\"\"Applies a translation to the point cloud.\n        Args:\n            x: <np.float: 3, 1>. Translation in x, y, z.\n        \"\"\"\n        for i in range(3):\n            self.points[i, :] = self.points[i, :] + x[i]\n\n    def rotate(self, rot_matrix: np.ndarray) -> None:\n        \"\"\"Applies a rotation.\n        Args:\n            rot_matrix: <np.float: 3, 3>. Rotation matrix.\n        Returns:\n        \"\"\"\n        self.points[:3, :] = np.dot(rot_matrix, self.points[:3, :])\n\n    def transform(self, transf_matrix: np.ndarray) -> None:\n        \"\"\"Applies a homogeneous transform.\n        Args:\n            transf_matrix: transf_matrix: <np.float: 4, 4>. Homogenous transformation matrix.\n        \"\"\"\n        self.points[:3, :] = transf_matrix.dot(np.vstack((self.points[:3, :], np.ones(self.nbr_points()))))[:3, :]\n\n    def render_height(\n        self,\n        ax: Axes,\n        view: np.ndarray = np.eye(4),\n        x_lim: Tuple = (-20, 20),\n        y_lim: Tuple = (-20, 20),\n        marker_size: float = 1,\n    ) -> None:\n        \"\"\"Simple method that applies a transformation and then scatter plots the points colored by height (z-value).\n        Args:\n            ax: Axes on which to render the points.\n            view: <np.float: n, n>. Defines an arbitrary projection (n <= 4).\n            x_lim: (min <float>, max <float>). x range for plotting.\n            y_lim: (min <float>, max <float>). y range for plotting.\n            marker_size: Marker size.\n        \"\"\"\n        self._render_helper(2, ax, view, x_lim, y_lim, marker_size)\n\n    def render_intensity(\n        self,\n        ax: Axes,\n        view: np.ndarray = np.eye(4),\n        x_lim: Tuple = (-20, 20),\n        y_lim: Tuple = (-20, 20),\n        marker_size: float = 1,\n    ) -> None:\n        \"\"\"Very simple method that applies a transformation and then scatter plots the points colored by intensity.\n        Args:\n            ax: Axes on which to render the points.\n            view: <np.float: n, n>. Defines an arbitrary projection (n <= 4).\n            x_lim: (min <float>, max <float>).\n            y_lim: (min <float>, max <float>).\n            marker_size: Marker size.\n        Returns:\n        \"\"\"\n        self._render_helper(3, ax, view, x_lim, y_lim, marker_size)\n\n    def _render_helper(\n        self, color_channel: int, ax: Axes, view: np.ndarray, x_lim: Tuple, y_lim: Tuple, marker_size: float\n    ) -> None:\n        \"\"\"Helper function for rendering.\n        Args:\n            color_channel: Point channel to use as color.\n            ax: Axes on which to render the points.\n            view: <np.float: n, n>. Defines an arbitrary projection (n <= 4).\n            x_lim: (min <float>, max <float>).\n            y_lim: (min <float>, max <float>).\n            marker_size: Marker size.\n        \"\"\"\n        points = view_points(self.points[:3, :], view, normalize=False)\n        ax.scatter(points[0, :], points[1, :], c=self.points[color_channel, :], s=marker_size)\n        ax.set_xlim(x_lim[0], x_lim[1])\n        ax.set_ylim(y_lim[0], y_lim[1])\n\n\nclass LidarPointCloud(PointCloud):\n    @staticmethod\n    def nbr_dims() -> int:\n        \"\"\"Returns the number of dimensions.\n        Returns: Number of dimensions.\n        \"\"\"\n        return 4\n\n    @classmethod\n    def from_file(cls, file_name: Path) -> \"LidarPointCloud\":\n        \"\"\"Loads LIDAR data from binary numpy format. Data is stored as (x, y, z, intensity, ring index).\n        Args:\n            file_name: Path of the pointcloud file on disk.\n        Returns: LidarPointCloud instance (x, y, z, intensity).\n        \"\"\"\n\n        assert file_name.suffix == \".bin\", \"Unsupported filetype {}\".format(file_name)\n\n        scan = np.fromfile(str(file_name), dtype=np.float32)\n        points = scan.reshape((-1, 5))[:, : cls.nbr_dims()]\n        return cls(points.T)\n\n\nclass RadarPointCloud(PointCloud):\n\n    # Class-level settings for radar pointclouds, see from_file().\n    invalid_states = [0]  # type: List[int]\n    dynprop_states = range(7)  # type: List[int] # Use [0, 2, 6] for moving objects only.\n    ambig_states = [3]  # type: List[int]\n\n    @staticmethod\n    def nbr_dims() -> int:\n        \"\"\"Returns the number of dimensions.\n        Returns: Number of dimensions.\n        \"\"\"\n        return 18\n\n    @classmethod\n    def from_file(\n        cls,\n        file_name: Path,\n        invalid_states: List[int] = None,\n        dynprop_states: List[int] = None,\n        ambig_states: List[int] = None,\n    ) -> \"RadarPointCloud\":\n        \"\"\"Loads RADAR data from a Point Cloud Data file. See details below.\n        Args:\n            file_name: The path of the pointcloud file.\n            invalid_states: Radar states to be kept. See details below.\n            dynprop_states: Radar states to be kept. Use [0, 2, 6] for moving objects only. See details below.\n            ambig_states: Radar states to be kept. See details below. To keep all radar returns,\n                set each state filter to range(18).\n        Returns: <np.float: d, n>. Point cloud matrix with d dimensions and n points.\n        Example of the header fields:\n        # .PCD v0.7 - Point Cloud Data file format\n        VERSION 0.7\n        FIELDS x y z dyn_prop id rcs vx vy vx_comp vy_comp is_quality_valid ambig_\n                                                            state x_rms y_rms invalid_state pdh0 vx_rms vy_rms\n        SIZE 4 4 4 1 2 4 4 4 4 4 1 1 1 1 1 1 1 1\n        TYPE F F F I I F F F F F I I I I I I I I\n        COUNT 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n        WIDTH 125\n        HEIGHT 1\n        VIEWPOINT 0 0 0 1 0 0 0\n        POINTS 125\n        DATA binary\n        Below some of the fields are explained in more detail:\n        x is front, y is left\n        vx, vy are the velocities in m/s.\n        vx_comp, vy_comp are the velocities in m/s compensated by the ego motion.\n        We recommend using the compensated velocities.\n        invalid_state: state of Cluster validity state.\n        (Invalid states)\n        0x01\tinvalid due to low RCS\n        0x02\tinvalid due to near-field artefact\n        0x03\tinvalid far range cluster because not confirmed in near range\n        0x05\treserved\n        0x06\tinvalid cluster due to high mirror probability\n        0x07\tInvalid cluster because outside sensor field of view\n        0x0d\treserved\n        0x0e\tinvalid cluster because it is a harmonics\n        (Valid states)\n        0x00\tvalid\n        0x04\tvalid cluster with low RCS\n        0x08\tvalid cluster with azimuth correction due to elevation\n        0x09\tvalid cluster with high child probability\n        0x0a\tvalid cluster with high probability of being a 50 deg artefact\n        0x0b\tvalid cluster but no local maximum\n        0x0c\tvalid cluster with high artefact probability\n        0x0f\tvalid cluster with above 95m in near range\n        0x10\tvalid cluster with high multi-target probability\n        0x11\tvalid cluster with suspicious angle\n        dynProp: Dynamic property of cluster to indicate if is moving or not.\n        0: moving\n        1: stationary\n        2: oncoming\n        3: stationary candidate\n        4: unknown\n        5: crossing stationary\n        6: crossing moving\n        7: stopped\n        ambig_state: State of Doppler (radial velocity) ambiguity solution.\n        0: invalid\n        1: ambiguous\n        2: staggered ramp\n        3: unambiguous\n        4: stationary candidates\n        pdh0: False alarm probability of cluster (i.e. probability of being an artefact caused\n                                                                                    by multipath or similar).\n        0: invalid\n        1: <25%\n        2: 50%\n        3: 75%\n        4: 90%\n        5: 99%\n        6: 99.9%\n        7: <=100%\n        \"\"\"\n\n        assert file_name.suffix == \".pcd\", \"Unsupported filetype {}\".format(file_name)\n\n        meta = []\n        with open(str(file_name), \"rb\") as f:\n            for line in f:\n                line = line.strip().decode(\"utf-8\")\n                meta.append(line)\n                if line.startswith(\"DATA\"):\n                    break\n\n            data_binary = f.read()\n\n        # Get the header rows and check if they appear as expected.\n        assert meta[0].startswith(\"#\"), \"First line must be comment\"\n        assert meta[1].startswith(\"VERSION\"), \"Second line must be VERSION\"\n        sizes = meta[3].split(\" \")[1:]\n        types = meta[4].split(\" \")[1:]\n        counts = meta[5].split(\" \")[1:]\n        width = int(meta[6].split(\" \")[1])\n        height = int(meta[7].split(\" \")[1])\n        data = meta[10].split(\" \")[1]\n        feature_count = len(types)\n        assert width > 0\n        assert len([c for c in counts if c != c]) == 0, \"Error: COUNT not supported!\"\n        assert height == 1, \"Error: height != 0 not supported!\"\n        assert data == \"binary\"\n\n        # Lookup table for how to decode the binaries.\n        unpacking_lut = {\n            \"F\": {2: \"e\", 4: \"f\", 8: \"d\"},\n            \"I\": {1: \"b\", 2: \"h\", 4: \"i\", 8: \"q\"},\n            \"U\": {1: \"B\", 2: \"H\", 4: \"I\", 8: \"Q\"},\n        }\n        types_str = \"\".join([unpacking_lut[t][int(s)] for t, s in zip(types, sizes)])\n\n        # Decode each point.\n        offset = 0\n        point_count = width\n        points = []\n        for i in range(point_count):\n            point = []\n            for p in range(feature_count):\n                start_p = offset\n                end_p = start_p + int(sizes[p])\n                assert end_p < len(data_binary)\n                point_p = struct.unpack(types_str[p], data_binary[start_p:end_p])[0]\n                point.append(point_p)\n                offset = end_p\n            points.append(point)\n\n        # A NaN in the first point indicates an empty pointcloud.\n        point = np.array(points[0])\n        if np.any(np.isnan(point)):\n            return cls(np.zeros((feature_count, 0)))\n\n        # Convert to numpy matrix.\n        points = np.array(points).transpose()\n\n        # If no parameters are provided, use default settings.\n        invalid_states = cls.invalid_states if invalid_states is None else invalid_states\n        dynprop_states = cls.dynprop_states if dynprop_states is None else dynprop_states\n        ambig_states = cls.ambig_states if ambig_states is None else ambig_states\n\n        # Filter points with an invalid state.\n        valid = [p in invalid_states for p in points[-4, :]]\n        points = points[:, valid]\n\n        # Filter by dynProp.\n        valid = [p in dynprop_states for p in points[3, :]]\n        points = points[:, valid]\n\n        # Filter by ambig_state.\n        valid = [p in ambig_states for p in points[11, :]]\n        points = points[:, valid]\n\n        return cls(points)\n\n\nclass Box:\n    \"\"\" Simple data class representing a 3d box including, label, score and velocity. \"\"\"\n\n    def __init__(\n        self,\n        center: List[float],\n        size: List[float],\n        orientation: Quaternion,\n        label: int = np.nan,\n        score: float = np.nan,\n        velocity: Tuple = (np.nan, np.nan, np.nan),\n        name: str = None,\n        token: str = None,\n    ):\n        \"\"\"\n        Args:\n            center: Center of box given as x, y, z.\n            size: Size of box in width, length, height.\n            orientation: Box orientation.\n            label: Integer label, optional.\n            score: Classification score, optional.\n            velocity: Box velocity in x, y, z direction.\n            name: Box name, optional. Can be used e.g. for denote category name.\n            token: Unique string identifier from DB.\n        \"\"\"\n        assert not np.any(np.isnan(center))\n        assert not np.any(np.isnan(size))\n        assert len(center) == 3\n        assert len(size) == 3\n        assert type(orientation) == Quaternion\n\n        self.center = np.array(center)\n        self.wlh = np.array(size)\n        self.orientation = orientation\n        self.label = int(label) if not np.isnan(label) else label\n        self.score = float(score) if not np.isnan(score) else score\n        self.velocity = np.array(velocity)\n        self.name = name\n        self.token = token\n\n    def __eq__(self, other):\n        center = np.allclose(self.center, other.center)\n        wlh = np.allclose(self.wlh, other.wlh)\n        orientation = np.allclose(self.orientation.elements, other.orientation.elements)\n        label = (self.label == other.label) or (np.isnan(self.label) and np.isnan(other.label))\n        score = (self.score == other.score) or (np.isnan(self.score) and np.isnan(other.score))\n        vel = np.allclose(self.velocity, other.velocity) or (\n            np.all(np.isnan(self.velocity)) and np.all(np.isnan(other.velocity))\n        )\n\n        return center and wlh and orientation and label and score and vel\n\n    def __repr__(self):\n        repr_str = (\n            \"label: {}, score: {:.2f}, xyz: [{:.2f}, {:.2f}, {:.2f}], wlh: [{:.2f}, {:.2f}, {:.2f}], \"\n            \"rot axis: [{:.2f}, {:.2f}, {:.2f}], ang(degrees): {:.2f}, ang(rad): {:.2f}, \"\n            \"vel: {:.2f}, {:.2f}, {:.2f}, name: {}, token: {}\"\n        )\n\n        return repr_str.format(\n            self.label,\n            self.score,\n            self.center[0],\n            self.center[1],\n            self.center[2],\n            self.wlh[0],\n            self.wlh[1],\n            self.wlh[2],\n            self.orientation.axis[0],\n            self.orientation.axis[1],\n            self.orientation.axis[2],\n            self.orientation.degrees,\n            self.orientation.radians,\n            self.velocity[0],\n            self.velocity[1],\n            self.velocity[2],\n            self.name,\n            self.token,\n        )\n\n    @property\n    def rotation_matrix(self) -> np.ndarray:\n        \"\"\"Return a rotation matrix.\n        Returns: <np.float: 3, 3>. The box's rotation matrix.\n        \"\"\"\n        return self.orientation.rotation_matrix\n\n    def translate(self, x: np.ndarray) -> None:\n        \"\"\"Applies a translation.\n        Args:\n            x: <np.float: 3, 1>. Translation in x, y, z direction.\n        \"\"\"\n        self.center += x\n\n    def rotate(self, quaternion: Quaternion) -> None:\n        \"\"\"Rotates box.\n        Args:\n            quaternion: Rotation to apply.\n        \"\"\"\n        self.center = np.dot(quaternion.rotation_matrix, self.center)\n        self.orientation = quaternion * self.orientation\n        self.velocity = np.dot(quaternion.rotation_matrix, self.velocity)\n\n    def corners(self, wlh_factor: float = 1.0) -> np.ndarray:\n        \"\"\"Returns the bounding box corners.\n        Args:\n            wlh_factor: Multiply width, length, height by a factor to scale the box.\n        Returns: First four corners are the ones facing forward.\n                The last four are the ones facing backwards.\n        \"\"\"\n\n        width, length, height = self.wlh * wlh_factor\n\n        # 3D bounding box corners. (Convention: x points forward, y to the left, z up.)\n        x_corners = length / 2 * np.array([1, 1, 1, 1, -1, -1, -1, -1])\n        y_corners = width / 2 * np.array([1, -1, -1, 1, 1, -1, -1, 1])\n        z_corners = height / 2 * np.array([1, 1, -1, -1, 1, 1, -1, -1])\n        corners = np.vstack((x_corners, y_corners, z_corners))\n\n        # Rotate\n        corners = np.dot(self.orientation.rotation_matrix, corners)\n\n        # Translate\n        x, y, z = self.center\n        corners[0, :] = corners[0, :] + x\n        corners[1, :] = corners[1, :] + y\n        corners[2, :] = corners[2, :] + z\n\n        return corners\n\n    def bottom_corners(self) -> np.ndarray:\n        \"\"\"Returns the four bottom corners.\n        Returns: <np.float: 3, 4>. Bottom corners. First two face forward, last two face backwards.\n        \"\"\"\n        return self.corners()[:, [2, 3, 7, 6]]\n\n    def render(\n        self,\n        axis: Axes,\n        view: np.ndarray = np.eye(3),\n        normalize: bool = False,\n        colors: Tuple = (\"b\", \"r\", \"k\"),\n        linewidth: float = 2,\n    ):\n        \"\"\"Renders the box in the provided Matplotlib axis.\n        Args:\n            axis: Axis onto which the box should be drawn.\n            view: <np.array: 3, 3>. Define a projection in needed (e.g. for drawing projection in an image).\n            normalize: Whether to normalize the remaining coordinate.\n            colors: (<Matplotlib.colors>: 3). Valid Matplotlib colors (<str> or normalized RGB tuple) for front,\n            back and sides.\n            linewidth: Width in pixel of the box sides.\n        \"\"\"\n        corners = view_points(self.corners(), view, normalize=normalize)[:2, :]\n\n        def draw_rect(selected_corners, color):\n            prev = selected_corners[-1]\n            for corner in selected_corners:\n                axis.plot([prev[0], corner[0]], [prev[1], corner[1]], color=color, linewidth=linewidth)\n                prev = corner\n\n        # Draw the sides\n        for i in range(4):\n            axis.plot(\n                [corners.T[i][0], corners.T[i + 4][0]],\n                [corners.T[i][1], corners.T[i + 4][1]],\n                color=colors[2],\n                linewidth=linewidth,\n            )\n\n        # Draw front (first 4 corners) and rear (last 4 corners) rectangles(3d)/lines(2d)\n        draw_rect(corners.T[:4], colors[0])\n        draw_rect(corners.T[4:], colors[1])\n\n        # Draw line indicating the front\n        center_bottom_forward = np.mean(corners.T[2:4], axis=0)\n        center_bottom = np.mean(corners.T[[2, 3, 7, 6]], axis=0)\n        axis.plot(\n            [center_bottom[0], center_bottom_forward[0]],\n            [center_bottom[1], center_bottom_forward[1]],\n            color=colors[0],\n            linewidth=linewidth,\n        )\n\n    def render_cv2(\n        self,\n        image: np.ndarray,\n        view: np.ndarray = np.eye(3),\n        normalize: bool = False,\n        colors: Tuple = ((0, 0, 255), (255, 0, 0), (155, 155, 155)),\n        linewidth: int = 2,\n    ) -> None:\n        \"\"\"Renders box using OpenCV2.\n        Args:\n            image: <np.array: width, height, 3>. Image array. Channels are in BGR order.\n            view: <np.array: 3, 3>. Define a projection if needed (e.g. for drawing projection in an image).\n            normalize: Whether to normalize the remaining coordinate.\n            colors: ((R, G, B), (R, G, B), (R, G, B)). Colors for front, side & rear.\n            linewidth: Linewidth for plot.\n        Returns:\n        \"\"\"\n        corners = view_points(self.corners(), view, normalize=normalize)[:2, :]\n\n        def draw_rect(selected_corners, color):\n            prev = selected_corners[-1]\n            for corner in selected_corners:\n                cv2.line(image, (int(prev[0]), int(prev[1])), (int(corner[0]), int(corner[1])), color, linewidth)\n                prev = corner\n\n        # Draw the sides\n        for i in range(4):\n            cv2.line(\n                image,\n                (int(corners.T[i][0]), int(corners.T[i][1])),\n                (int(corners.T[i + 4][0]), int(corners.T[i + 4][1])),\n                colors[2][::-1],\n                linewidth,\n            )\n\n        # Draw front (first 4 corners) and rear (last 4 corners) rectangles(3d)/lines(2d)\n        draw_rect(corners.T[:4], colors[0][::-1])\n        draw_rect(corners.T[4:], colors[1][::-1])\n\n        # Draw line indicating the front\n        center_bottom_forward = np.mean(corners.T[2:4], axis=0)\n        center_bottom = np.mean(corners.T[[2, 3, 7, 6]], axis=0)\n        cv2.line(\n            image,\n            (int(center_bottom[0]), int(center_bottom[1])),\n            (int(center_bottom_forward[0]), int(center_bottom_forward[1])),\n            colors[0][::-1],\n            linewidth,\n        )\n\n    def copy(self) -> \"Box\":\n        \"\"\"        Create a copy of self.\n        Returns: A copy.\n        \"\"\"\n        return copy.deepcopy(self)\n","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:42:23.251359Z","iopub.execute_input":"2024-02-01T03:42:23.251719Z","iopub.status.idle":"2024-02-01T03:42:23.335310Z","shell.execute_reply.started":"2024-02-01T03:42:23.251686Z","shell.execute_reply":"2024-02-01T03:42:23.334435Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Lyft Dataset SDK dev-kit.\n# Code written by Oscar Beijbom, 2018.\n# Licensed under the Creative Commons [see licence.txt]\n# Modified by Vladimir Iglovikov 2019.\n\nPYTHON_VERSION = sys.version_info[0]\n\nif not PYTHON_VERSION == 3:\n    raise ValueError(\"LyftDataset sdk only supports Python version 3.\")\n\n\nclass LyftDataset:\n    \"\"\"Database class for Lyft Dataset to help query and retrieve information from the database.\"\"\"\n\n    def __init__(self, data_path: str, json_path: str, verbose: bool = True, map_resolution: float = 0.1):\n        \"\"\"Loads database and creates reverse indexes and shortcuts.\n        Args:\n            data_path: Path to the tables and data.\n            json_path: Path to the folder with json files\n            verbose: Whether to print status messages during load.\n            map_resolution: Resolution of maps (meters).\n        \"\"\"\n\n        self.data_path = Path(data_path).expanduser().absolute()\n        self.json_path = Path(json_path)\n\n        self.table_names = [\n            \"category\",\n            \"attribute\",\n            \"visibility\",\n            \"instance\",\n            \"sensor\",\n            \"calibrated_sensor\",\n            \"ego_pose\",\n            \"log\",\n            \"scene\",\n            \"sample\",\n            \"sample_data\",\n            \"sample_annotation\",\n            \"map\",\n        ]\n\n        start_time = time.time()\n\n        # Explicitly assign tables to help the IDE determine valid class members.\n        self.category = self.__load_table__(\"category\")\n        self.attribute = self.__load_table__(\"attribute\")\n        self.visibility = self.__load_table__(\"visibility\")\n        self.instance = self.__load_table__(\"instance\")\n        self.sensor = self.__load_table__(\"sensor\")\n        self.calibrated_sensor = self.__load_table__(\"calibrated_sensor\")\n        self.ego_pose = self.__load_table__(\"ego_pose\")\n        self.log = self.__load_table__(\"log\")\n        self.scene = self.__load_table__(\"scene\")\n        self.sample = self.__load_table__(\"sample\")\n        self.sample_data = self.__load_table__(\"sample_data\")\n        self.sample_annotation = self.__load_table__(\"sample_annotation\")\n        self.map = self.__load_table__(\"map\")\n\n        # Initialize map mask for each map record.\n        for map_record in self.map:\n            map_record[\"mask\"] = MapMask(self.data_path / 'train_maps/map_raster_palo_alto.png', resolution=map_resolution)\n\n        if verbose:\n            for table in self.table_names:\n                print(\"{} {},\".format(len(getattr(self, table)), table))\n            print(\"Done loading in {:.1f} seconds.\\n======\".format(time.time() - start_time))\n\n        # Make reverse indexes for common lookups.\n        self.__make_reverse_index__(verbose)\n\n        # Initialize LyftDatasetExplorer class\n        self.explorer = LyftDatasetExplorer(self)\n\n    def __load_table__(self, table_name) -> dict:\n        \"\"\"Loads a table.\"\"\"\n        with open(str(self.json_path.joinpath(\"{}.json\".format(table_name)))) as f:\n            table = json.load(f)\n        return table\n\n    def __make_reverse_index__(self, verbose: bool) -> None:\n        \"\"\"De-normalizes database to create reverse indices for common cases.\n        Args:\n            verbose: Whether to print outputs.\n        \"\"\"\n\n        start_time = time.time()\n        if verbose:\n            print(\"Reverse indexing ...\")\n\n        # Store the mapping from token to table index for each table.\n        self._token2ind = dict()\n        for table in self.table_names:\n            self._token2ind[table] = dict()\n\n            for ind, member in enumerate(getattr(self, table)):\n                self._token2ind[table][member[\"token\"]] = ind\n\n        # Decorate (adds short-cut) sample_annotation table with for category name.\n        for record in self.sample_annotation:\n            inst = self.get(\"instance\", record[\"instance_token\"])\n            record[\"category_name\"] = self.get(\"category\", inst[\"category_token\"])[\"name\"]\n\n        # Decorate (adds short-cut) sample_data with sensor information.\n        for record in self.sample_data:\n            cs_record = self.get(\"calibrated_sensor\", record[\"calibrated_sensor_token\"])\n            sensor_record = self.get(\"sensor\", cs_record[\"sensor_token\"])\n            record[\"sensor_modality\"] = sensor_record[\"modality\"]\n            record[\"channel\"] = sensor_record[\"channel\"]\n\n        # Reverse-index samples with sample_data and annotations.\n        for record in self.sample:\n            record[\"data\"] = {}\n            record[\"anns\"] = []\n\n        for record in self.sample_data:\n            if record[\"is_key_frame\"]:\n                sample_record = self.get(\"sample\", record[\"sample_token\"])\n                sample_record[\"data\"][record[\"channel\"]] = record[\"token\"]\n\n        for ann_record in self.sample_annotation:\n            sample_record = self.get(\"sample\", ann_record[\"sample_token\"])\n            sample_record[\"anns\"].append(ann_record[\"token\"])\n\n        # Add reverse indices from log records to map records.\n        if \"log_tokens\" not in self.map[0].keys():\n            raise Exception(\"Error: log_tokens not in map table. This code is not compatible with the teaser dataset.\")\n        log_to_map = dict()\n        for map_record in self.map:\n            for log_token in map_record[\"log_tokens\"]:\n                log_to_map[log_token] = map_record[\"token\"]\n        for log_record in self.log:\n            log_record[\"map_token\"] = log_to_map[log_record[\"token\"]]\n\n        if verbose:\n            print(\"Done reverse indexing in {:.1f} seconds.\\n======\".format(time.time() - start_time))\n\n    def get(self, table_name: str, token: str) -> dict:\n        \"\"\"Returns a record from table in constant runtime.\n        Args:\n            table_name: Table name.\n            token: Token of the record.\n        Returns: Table record.\n        \"\"\"\n\n        assert table_name in self.table_names, \"Table {} not found\".format(table_name)\n\n        return getattr(self, table_name)[self.getind(table_name, token)]\n\n    def getind(self, table_name: str, token: str) -> int:\n        \"\"\"Returns the index of the record in a table in constant runtime.\n        Args:\n            table_name: Table name.\n            token: The index of the record in table, table is an array.\n        Returns:\n        \"\"\"\n        return self._token2ind[table_name][token]\n\n    def field2token(self, table_name: str, field: str, query) -> List[str]:\n        \"\"\"Query all records for a certain field value, and returns the tokens for the matching records.\n        Runs in linear time.\n        Args:\n            table_name: Table name.\n            field: Field name.\n            query: Query to match against. Needs to type match the content of the query field.\n        Returns: List of tokens for the matching records.\n        \"\"\"\n        matches = []\n        for member in getattr(self, table_name):\n            if member[field] == query:\n                matches.append(member[\"token\"])\n        return matches\n\n    def get_sample_data_path(self, sample_data_token: str) -> Path:\n        \"\"\"Returns the path to a sample_data.\n        Args:\n            sample_data_token:\n        Returns:\n        \"\"\"\n\n        sd_record = self.get(\"sample_data\", sample_data_token)\n        return self.data_path / sd_record[\"filename\"]\n\n    def get_sample_data(\n        self,\n        sample_data_token: str,\n        box_vis_level: BoxVisibility = BoxVisibility.ANY,\n        selected_anntokens: List[str] = None,\n        flat_vehicle_coordinates: bool = False,\n    ) -> Tuple[Path, List[Box], np.array]:\n        \"\"\"Returns the data path as well as all annotations related to that sample_data.\n        The boxes are transformed into the current sensor's coordinate frame.\n        Args:\n            sample_data_token: Sample_data token.\n            box_vis_level: If sample_data is an image, this sets required visibility for boxes.\n            selected_anntokens: If provided only return the selected annotation.\n            flat_vehicle_coordinates: Instead of current sensor's coordinate frame, use vehicle frame which is\n        aligned to z-plane in world\n        Returns: (data_path, boxes, camera_intrinsic <np.array: 3, 3>)\n        \"\"\"\n\n        # Retrieve sensor & pose records\n        sd_record = self.get(\"sample_data\", sample_data_token)\n        cs_record = self.get(\"calibrated_sensor\", sd_record[\"calibrated_sensor_token\"])\n        sensor_record = self.get(\"sensor\", cs_record[\"sensor_token\"])\n        pose_record = self.get(\"ego_pose\", sd_record[\"ego_pose_token\"])\n\n        data_path = self.get_sample_data_path(sample_data_token)\n\n        if sensor_record[\"modality\"] == \"camera\":\n            cam_intrinsic = np.array(cs_record[\"camera_intrinsic\"])\n            imsize = (sd_record[\"width\"], sd_record[\"height\"])\n        else:\n            cam_intrinsic = None\n            imsize = None\n\n        # Retrieve all sample annotations and map to sensor coordinate system.\n        if selected_anntokens is not None:\n            boxes = list(map(self.get_box, selected_anntokens))\n        else:\n            boxes = self.get_boxes(sample_data_token)\n\n        # Make list of Box objects including coord system transforms.\n        box_list = []\n        for box in boxes:\n            if flat_vehicle_coordinates:\n                # Move box to ego vehicle coord system parallel to world z plane\n                ypr = Quaternion(pose_record[\"rotation\"]).yaw_pitch_roll\n                yaw = ypr[0]\n\n                box.translate(-np.array(pose_record[\"translation\"]))\n                box.rotate(Quaternion(scalar=np.cos(yaw / 2), vector=[0, 0, np.sin(yaw / 2)]).inverse)\n\n            else:\n                # Move box to ego vehicle coord system\n                box.translate(-np.array(pose_record[\"translation\"]))\n                box.rotate(Quaternion(pose_record[\"rotation\"]).inverse)\n\n                #  Move box to sensor coord system\n                box.translate(-np.array(cs_record[\"translation\"]))\n                box.rotate(Quaternion(cs_record[\"rotation\"]).inverse)\n\n            if sensor_record[\"modality\"] == \"camera\" and not box_in_image(\n                box, cam_intrinsic, imsize, vis_level=box_vis_level\n            ):\n                continue\n\n            box_list.append(box)\n\n        return data_path, box_list, cam_intrinsic\n\n    def get_box(self, sample_annotation_token: str) -> Box:\n        \"\"\"Instantiates a Box class from a sample annotation record.\n        Args:\n            sample_annotation_token: Unique sample_annotation identifier.\n        Returns:\n        \"\"\"\n        record = self.get(\"sample_annotation\", sample_annotation_token)\n        return Box(\n            record[\"translation\"],\n            record[\"size\"],\n            Quaternion(record[\"rotation\"]),\n            name=record[\"category_name\"],\n            token=record[\"token\"],\n        )\n\n    def get_boxes(self, sample_data_token: str) -> List[Box]:\n        \"\"\"Instantiates Boxes for all annotation for a particular sample_data record. If the sample_data is a\n        keyframe, this returns the annotations for that sample. But if the sample_data is an intermediate\n        sample_data, a linear interpolation is applied to estimate the location of the boxes at the time the\n        sample_data was captured.\n        Args:\n            sample_data_token: Unique sample_data identifier.\n        Returns:\n        \"\"\"\n\n        # Retrieve sensor & pose records\n        sd_record = self.get(\"sample_data\", sample_data_token)\n        curr_sample_record = self.get(\"sample\", sd_record[\"sample_token\"])\n\n        if curr_sample_record[\"prev\"] == \"\" or sd_record[\"is_key_frame\"]:\n            # If no previous annotations available, or if sample_data is keyframe just return the current ones.\n            boxes = list(map(self.get_box, curr_sample_record[\"anns\"]))\n\n        else:\n            prev_sample_record = self.get(\"sample\", curr_sample_record[\"prev\"])\n\n            curr_ann_recs = [self.get(\"sample_annotation\", token) for token in curr_sample_record[\"anns\"]]\n            prev_ann_recs = [self.get(\"sample_annotation\", token) for token in prev_sample_record[\"anns\"]]\n\n            # Maps instance tokens to prev_ann records\n            prev_inst_map = {entry[\"instance_token\"]: entry for entry in prev_ann_recs}\n\n            t0 = prev_sample_record[\"timestamp\"]\n            t1 = curr_sample_record[\"timestamp\"]\n            t = sd_record[\"timestamp\"]\n\n            # There are rare situations where the timestamps in the DB are off so ensure that t0 < t < t1.\n            t = max(t0, min(t1, t))\n\n            boxes = []\n            for curr_ann_rec in curr_ann_recs:\n\n                if curr_ann_rec[\"instance_token\"] in prev_inst_map:\n                    # If the annotated instance existed in the previous frame, interpolate center & orientation.\n                    prev_ann_rec = prev_inst_map[curr_ann_rec[\"instance_token\"]]\n\n                    # Interpolate center.\n                    center = [\n                        np.interp(t, [t0, t1], [c0, c1])\n                        for c0, c1 in zip(prev_ann_rec[\"translation\"], curr_ann_rec[\"translation\"])\n                    ]\n\n                    # Interpolate orientation.\n                    rotation = Quaternion.slerp(\n                        q0=Quaternion(prev_ann_rec[\"rotation\"]),\n                        q1=Quaternion(curr_ann_rec[\"rotation\"]),\n                        amount=(t - t0) / (t1 - t0),\n                    )\n\n                    box = Box(\n                        center,\n                        curr_ann_rec[\"size\"],\n                        rotation,\n                        name=curr_ann_rec[\"category_name\"],\n                        token=curr_ann_rec[\"token\"],\n                    )\n                else:\n                    # If not, simply grab the current annotation.\n                    box = self.get_box(curr_ann_rec[\"token\"])\n\n                boxes.append(box)\n        return boxes\n\n    def box_velocity(self, sample_annotation_token: str, max_time_diff: float = 1.5) -> np.ndarray:\n        \"\"\"Estimate the velocity for an annotation.\n        If possible, we compute the centered difference between the previous and next frame.\n        Otherwise we use the difference between the current and previous/next frame.\n        If the velocity cannot be estimated, values are set to np.nan.\n        Args:\n            sample_annotation_token: Unique sample_annotation identifier.\n            max_time_diff: Max allowed time diff between consecutive samples that are used to estimate velocities.\n        Returns: <np.float: 3>. Velocity in x/y/z direction in m/s.\n        \"\"\"\n\n        current = self.get(\"sample_annotation\", sample_annotation_token)\n        has_prev = current[\"prev\"] != \"\"\n        has_next = current[\"next\"] != \"\"\n\n        # Cannot estimate velocity for a single annotation.\n        if not has_prev and not has_next:\n            return np.array([np.nan, np.nan, np.nan])\n\n        if has_prev:\n            first = self.get(\"sample_annotation\", current[\"prev\"])\n        else:\n            first = current\n\n        if has_next:\n            last = self.get(\"sample_annotation\", current[\"next\"])\n        else:\n            last = current\n\n        pos_last = np.array(last[\"translation\"])\n        pos_first = np.array(first[\"translation\"])\n        pos_diff = pos_last - pos_first\n\n        time_last = 1e-6 * self.get(\"sample\", last[\"sample_token\"])[\"timestamp\"]\n        time_first = 1e-6 * self.get(\"sample\", first[\"sample_token\"])[\"timestamp\"]\n        time_diff = time_last - time_first\n\n        if has_next and has_prev:\n            # If doing centered difference, allow for up to double the max_time_diff.\n            max_time_diff *= 2\n\n        if time_diff > max_time_diff:\n            # If time_diff is too big, don't return an estimate.\n            return np.array([np.nan, np.nan, np.nan])\n        else:\n            return pos_diff / time_diff\n\n    def list_categories(self) -> None:\n        self.explorer.list_categories()\n\n    def list_attributes(self) -> None:\n        self.explorer.list_attributes()\n\n    def list_scenes(self) -> None:\n        self.explorer.list_scenes()\n\n    def list_sample(self, sample_token: str) -> None:\n        self.explorer.list_sample(sample_token)\n\n    def render_pointcloud_in_image(\n        self,\n        sample_token: str,\n        dot_size: int = 5,\n        pointsensor_channel: str = \"LIDAR_TOP\",\n        camera_channel: str = \"CAM_FRONT\",\n        out_path: str = None,\n    ) -> None:\n        self.explorer.render_pointcloud_in_image(\n            sample_token,\n            dot_size,\n            pointsensor_channel=pointsensor_channel,\n            camera_channel=camera_channel,\n            out_path=out_path,\n        )\n\n    def render_sample(\n        self,\n        sample_token: str,\n        box_vis_level: BoxVisibility = BoxVisibility.ANY,\n        nsweeps: int = 1,\n        out_path: str = None,\n    ) -> None:\n        self.explorer.render_sample(sample_token, box_vis_level, nsweeps=nsweeps, out_path=out_path)\n\n    def render_sample_data(\n        self,\n        sample_data_token: str,\n        with_anns: bool = True,\n        box_vis_level: BoxVisibility = BoxVisibility.ANY,\n        axes_limit: float = 40,\n        ax: Axes = None,\n        nsweeps: int = 1,\n        out_path: str = None,\n        underlay_map: bool = False,\n    ) -> None:\n        return self.explorer.render_sample_data(\n            sample_data_token,\n            with_anns,\n            box_vis_level,\n            axes_limit,\n            ax,\n            num_sweeps=nsweeps,\n            out_path=out_path,\n            underlay_map=underlay_map,\n        )\n\n    def render_annotation(\n        self,\n        sample_annotation_token: str,\n        margin: float = 10,\n        view: np.ndarray = np.eye(4),\n        box_vis_level: BoxVisibility = BoxVisibility.ANY,\n        out_path: str = None,\n    ) -> None:\n        self.explorer.render_annotation(sample_annotation_token, margin, view, box_vis_level, out_path)\n\n    def render_instance(self, instance_token: str, out_path: str = None) -> None:\n        self.explorer.render_instance(instance_token, out_path=out_path)\n\n    def render_scene(self, scene_token: str, freq: float = 10, imwidth: int = 640, out_path: str = None) -> None:\n        self.explorer.render_scene(scene_token, freq, image_width=imwidth, out_path=out_path)\n\n    def render_scene_channel(\n        self,\n        scene_token: str,\n        channel: str = \"CAM_FRONT\",\n        freq: float = 10,\n        imsize: Tuple[float, float] = (640, 360),\n        out_path: str = None,\n    ) -> None:\n        self.explorer.render_scene_channel(\n            scene_token=scene_token, channel=channel, freq=freq, image_size=imsize, out_path=out_path\n        )\n\n    def render_egoposes_on_map(self, log_location: str, scene_tokens: List = None, out_path: str = None) -> None:\n        self.explorer.render_egoposes_on_map(log_location, scene_tokens, out_path=out_path)","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:42:23.336810Z","iopub.execute_input":"2024-02-01T03:42:23.337160Z","iopub.status.idle":"2024-02-01T03:42:23.397552Z","shell.execute_reply.started":"2024-02-01T03:42:23.337125Z","shell.execute_reply":"2024-02-01T03:42:23.396500Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class LyftDatasetExplorer:\n    \"\"\"Helper class to list and visualize Lyft Dataset data. These are meant to serve as tutorials and templates for\n    working with the data.\"\"\"\n\n    def __init__(self, lyftd: LyftDataset):\n        self.lyftd = lyftd\n\n    @staticmethod\n    def get_color(category_name: str) -> Tuple[int, int, int]:\n        \"\"\"Provides the default colors based on the category names.\n        This method works for the general Lyft Dataset categories, as well as the Lyft Dataset detection categories.\n        Args:\n            category_name:\n        Returns:\n        \"\"\"\n        if \"bicycle\" in category_name or \"motorcycle\" in category_name:\n            return 255, 61, 99  # Red\n        elif \"vehicle\" in category_name or category_name in [\"bus\", \"car\", \"construction_vehicle\", \"trailer\", \"truck\"]:\n            return 255, 158, 0  # Orange\n        elif \"pedestrian\" in category_name:\n            return 0, 0, 230  # Blue\n        elif \"cone\" in category_name or \"barrier\" in category_name:\n            return 0, 0, 0  # Black\n        else:\n            return 255, 0, 255  # Magenta\n\n    def list_categories(self) -> None:\n        \"\"\"Print categories, counts and stats.\"\"\"\n\n        print(\"Category stats\")\n\n        # Add all annotations\n        categories = dict()\n        for record in self.lyftd.sample_annotation:\n            if record[\"category_name\"] not in categories:\n                categories[record[\"category_name\"]] = []\n            categories[record[\"category_name\"]].append(record[\"size\"] + [record[\"size\"][1] / record[\"size\"][0]])\n\n        # Print stats\n        for name, stats in sorted(categories.items()):\n            stats = np.array(stats)\n            print(\n                \"{:27} n={:5}, width={:5.2f}\\u00B1{:.2f}, len={:5.2f}\\u00B1{:.2f}, height={:5.2f}\\u00B1{:.2f}, \"\n                \"lw_aspect={:5.2f}\\u00B1{:.2f}\".format(\n                    name[:27],\n                    stats.shape[0],\n                    np.mean(stats[:, 0]),\n                    np.std(stats[:, 0]),\n                    np.mean(stats[:, 1]),\n                    np.std(stats[:, 1]),\n                    np.mean(stats[:, 2]),\n                    np.std(stats[:, 2]),\n                    np.mean(stats[:, 3]),\n                    np.std(stats[:, 3]),\n                )\n            )\n\n    def list_attributes(self) -> None:\n        \"\"\"Prints attributes and counts.\"\"\"\n        attribute_counts = dict()\n        for record in self.lyftd.sample_annotation:\n            for attribute_token in record[\"attribute_tokens\"]:\n                att_name = self.lyftd.get(\"attribute\", attribute_token)[\"name\"]\n                if att_name not in attribute_counts:\n                    attribute_counts[att_name] = 0\n                attribute_counts[att_name] += 1\n\n        for name, count in sorted(attribute_counts.items()):\n            print(\"{}: {}\".format(name, count))\n\n    def list_scenes(self) -> None:\n        \"\"\" Lists all scenes with some meta data. \"\"\"\n\n        def ann_count(record):\n            count = 0\n            sample = self.lyftd.get(\"sample\", record[\"first_sample_token\"])\n            while not sample[\"next\"] == \"\":\n                count += len(sample[\"anns\"])\n                sample = self.lyftd.get(\"sample\", sample[\"next\"])\n            return count\n\n        recs = [\n            (self.lyftd.get(\"sample\", record[\"first_sample_token\"])[\"timestamp\"], record)\n            for record in self.lyftd.scene\n        ]\n\n        for start_time, record in sorted(recs):\n            start_time = self.lyftd.get(\"sample\", record[\"first_sample_token\"])[\"timestamp\"] / 1000000\n            length_time = self.lyftd.get(\"sample\", record[\"last_sample_token\"])[\"timestamp\"] / 1000000 - start_time\n            location = self.lyftd.get(\"log\", record[\"log_token\"])[\"location\"]\n            desc = record[\"name\"] + \", \" + record[\"description\"]\n            if len(desc) > 55:\n                desc = desc[:51] + \"...\"\n            if len(location) > 18:\n                location = location[:18]\n\n            print(\n                \"{:16} [{}] {:4.0f}s, {}, #anns:{}\".format(\n                    desc,\n                    datetime.utcfromtimestamp(start_time).strftime(\"%y-%m-%d %H:%M:%S\"),\n                    length_time,\n                    location,\n                    ann_count(record),\n                )\n            )\n\n    def list_sample(self, sample_token: str) -> None:\n        \"\"\"Prints sample_data tokens and sample_annotation tokens related to the sample_token.\"\"\"\n\n        sample_record = self.lyftd.get(\"sample\", sample_token)\n        print(\"Sample: {}\\n\".format(sample_record[\"token\"]))\n        for sd_token in sample_record[\"data\"].values():\n            sd_record = self.lyftd.get(\"sample_data\", sd_token)\n            print(\n                \"sample_data_token: {}, mod: {}, channel: {}\".format(\n                    sd_token, sd_record[\"sensor_modality\"], sd_record[\"channel\"]\n                )\n            )\n        print(\"\")\n        for ann_token in sample_record[\"anns\"]:\n            ann_record = self.lyftd.get(\"sample_annotation\", ann_token)\n            print(\"sample_annotation_token: {}, category: {}\".format(ann_record[\"token\"], ann_record[\"category_name\"]))\n\n    def map_pointcloud_to_image(self, pointsensor_token: str, camera_token: str) -> Tuple:\n        \"\"\"Given a point sensor (lidar/radar) token and camera sample_data token, load point-cloud and map it to\n        the image plane.\n        Args:\n            pointsensor_token: Lidar/radar sample_data token.\n            camera_token: Camera sample_data token.\n        Returns: (pointcloud <np.float: 2, n)>, coloring <np.float: n>, image <Image>).\n        \"\"\"\n\n        cam = self.lyftd.get(\"sample_data\", camera_token)\n        pointsensor = self.lyftd.get(\"sample_data\", pointsensor_token)\n        pcl_path = self.lyftd.data_path / ('train_' + pointsensor[\"filename\"])\n        if pointsensor[\"sensor_modality\"] == \"lidar\":\n            pc = LidarPointCloud.from_file(pcl_path)\n        else:\n            pc = RadarPointCloud.from_file(pcl_path)\n        im = Image.open(str(self.lyftd.data_path / ('train_' + cam[\"filename\"])))\n\n        # Points live in the point sensor frame. So they need to be transformed via global to the image plane.\n        # First step: transform the point-cloud to the ego vehicle frame for the timestamp of the sweep.\n        cs_record = self.lyftd.get(\"calibrated_sensor\", pointsensor[\"calibrated_sensor_token\"])\n        pc.rotate(Quaternion(cs_record[\"rotation\"]).rotation_matrix)\n        pc.translate(np.array(cs_record[\"translation\"]))\n\n        # Second step: transform to the global frame.\n        poserecord = self.lyftd.get(\"ego_pose\", pointsensor[\"ego_pose_token\"])\n        pc.rotate(Quaternion(poserecord[\"rotation\"]).rotation_matrix)\n        pc.translate(np.array(poserecord[\"translation\"]))\n\n        # Third step: transform into the ego vehicle frame for the timestamp of the image.\n        poserecord = self.lyftd.get(\"ego_pose\", cam[\"ego_pose_token\"])\n        pc.translate(-np.array(poserecord[\"translation\"]))\n        pc.rotate(Quaternion(poserecord[\"rotation\"]).rotation_matrix.T)\n\n        # Fourth step: transform into the camera.\n        cs_record = self.lyftd.get(\"calibrated_sensor\", cam[\"calibrated_sensor_token\"])\n        pc.translate(-np.array(cs_record[\"translation\"]))\n        pc.rotate(Quaternion(cs_record[\"rotation\"]).rotation_matrix.T)\n\n        # Fifth step: actually take a \"picture\" of the point cloud.\n        # Grab the depths (camera frame z axis points away from the camera).\n        depths = pc.points[2, :]\n\n        # Retrieve the color from the depth.\n        coloring = depths\n\n        # Take the actual picture (matrix multiplication with camera-matrix + renormalization).\n        points = view_points(pc.points[:3, :], np.array(cs_record[\"camera_intrinsic\"]), normalize=True)\n\n        # Remove points that are either outside or behind the camera. Leave a margin of 1 pixel for aesthetic reasons.\n        mask = np.ones(depths.shape[0], dtype=bool)\n        mask = np.logical_and(mask, depths > 0)\n        mask = np.logical_and(mask, points[0, :] > 1)\n        mask = np.logical_and(mask, points[0, :] < im.size[0] - 1)\n        mask = np.logical_and(mask, points[1, :] > 1)\n        mask = np.logical_and(mask, points[1, :] < im.size[1] - 1)\n        points = points[:, mask]\n        coloring = coloring[mask]\n\n        return points, coloring, im\n\n    def render_pointcloud_in_image(\n        self,\n        sample_token: str,\n        dot_size: int = 2,\n        pointsensor_channel: str = \"LIDAR_TOP\",\n        camera_channel: str = \"CAM_FRONT\",\n        out_path: str = None,\n    ) -> None:\n        \"\"\"Scatter-plots a point-cloud on top of image.\n        Args:\n            sample_token: Sample token.\n            dot_size: Scatter plot dot size.\n            pointsensor_channel: RADAR or LIDAR channel name, e.g. 'LIDAR_TOP'.\n            camera_channel: Camera channel name, e.g. 'CAM_FRONT'.\n            out_path: Optional path to save the rendered figure to disk.\n        Returns:\n        \"\"\"\n        sample_record = self.lyftd.get(\"sample\", sample_token)\n\n        # Here we just grab the front camera and the point sensor.\n        pointsensor_token = sample_record[\"data\"][pointsensor_channel]\n        camera_token = sample_record[\"data\"][camera_channel]\n\n        points, coloring, im = self.map_pointcloud_to_image(pointsensor_token, camera_token)\n        plt.figure(figsize=(9, 16))\n        plt.imshow(im)\n        plt.scatter(points[0, :], points[1, :], c=coloring, s=dot_size)\n        plt.axis(\"off\")\n\n        if out_path is not None:\n            plt.savefig(out_path)\n\n    def render_sample(\n        self, token: str, box_vis_level: BoxVisibility = BoxVisibility.ANY, nsweeps: int = 1, out_path: str = None\n    ) -> None:\n        \"\"\"Render all LIDAR and camera sample_data in sample along with annotations.\n        Args:\n            token: Sample token.\n            box_vis_level: If sample_data is an image, this sets required visibility for boxes.\n            nsweeps: Number of sweeps for lidar and radar.\n            out_path: Optional path to save the rendered figure to disk.\n        Returns:\n        \"\"\"\n        record = self.lyftd.get(\"sample\", token)\n\n        # Separate RADAR from LIDAR and vision.\n        radar_data = {}\n        nonradar_data = {}\n        for channel, token in record[\"data\"].items():\n            sd_record = self.lyftd.get(\"sample_data\", token)\n            sensor_modality = sd_record[\"sensor_modality\"]\n            if sensor_modality in [\"lidar\", \"camera\"]:\n                nonradar_data[channel] = token\n            else:\n                radar_data[channel] = token\n\n        num_radar_plots = 1 if len(radar_data) > 0 else 0\n\n        # Create plots.\n        n = num_radar_plots + len(nonradar_data)\n        cols = 2\n        fig, axes = plt.subplots(int(np.ceil(n / cols)), cols, figsize=(16, 24))\n\n        if len(radar_data) > 0:\n            # Plot radar into a single subplot.\n            ax = axes[0, 0]\n            for i, (_, sd_token) in enumerate(radar_data.items()):\n                self.render_sample_data(\n                    sd_token, with_anns=i == 0, box_vis_level=box_vis_level, ax=ax, num_sweeps=nsweeps\n                )\n            ax.set_title(\"Fused RADARs\")\n\n        # Plot camera and lidar in separate subplots.\n        for (_, sd_token), ax in zip(nonradar_data.items(), axes.flatten()[num_radar_plots:]):\n            self.render_sample_data(sd_token, box_vis_level=box_vis_level, ax=ax, num_sweeps=nsweeps)\n\n        axes.flatten()[-1].axis(\"off\")\n        plt.tight_layout()\n        fig.subplots_adjust(wspace=0, hspace=0)\n\n        if out_path is not None:\n            plt.savefig(out_path)\n\n    def render_ego_centric_map(self, sample_data_token: str, axes_limit: float = 40, ax: Axes = None) -> None:\n        \"\"\"Render map centered around the associated ego pose.\n        Args:\n            sample_data_token: Sample_data token.\n            axes_limit: Axes limit measured in meters.\n            ax: Axes onto which to render.\n        \"\"\"\n\n        def crop_image(image: np.array, x_px: int, y_px: int, axes_limit_px: int) -> np.array:\n            x_min = int(x_px - axes_limit_px)\n            x_max = int(x_px + axes_limit_px)\n            y_min = int(y_px - axes_limit_px)\n            y_max = int(y_px + axes_limit_px)\n\n            cropped_image = image[y_min:y_max, x_min:x_max]\n\n            return cropped_image\n\n        sd_record = self.lyftd.get(\"sample_data\", sample_data_token)\n\n        # Init axes.\n        if ax is None:\n            _, ax = plt.subplots(1, 1, figsize=(9, 9))\n\n        sample = self.lyftd.get(\"sample\", sd_record[\"sample_token\"])\n        scene = self.lyftd.get(\"scene\", sample[\"scene_token\"])\n        log = self.lyftd.get(\"log\", scene[\"log_token\"])\n        map = self.lyftd.get(\"map\", log[\"map_token\"])\n        map_mask = map[\"mask\"]\n\n        pose = self.lyftd.get(\"ego_pose\", sd_record[\"ego_pose_token\"])\n        pixel_coords = map_mask.to_pixel_coords(pose[\"translation\"][0], pose[\"translation\"][1])\n\n        scaled_limit_px = int(axes_limit * (1.0 / map_mask.resolution))\n        mask_raster = map_mask.mask()\n\n        cropped = crop_image(mask_raster, pixel_coords[0], pixel_coords[1], int(scaled_limit_px * math.sqrt(2)))\n\n        ypr_rad = Quaternion(pose[\"rotation\"]).yaw_pitch_roll\n        yaw_deg = -math.degrees(ypr_rad[0])\n\n        rotated_cropped = np.array(Image.fromarray(cropped).rotate(yaw_deg))\n        ego_centric_map = crop_image(\n            rotated_cropped, rotated_cropped.shape[1] / 2, rotated_cropped.shape[0] / 2, scaled_limit_px\n        )\n        ax.imshow(\n            ego_centric_map, extent=[-axes_limit, axes_limit, -axes_limit, axes_limit], cmap=\"gray\", vmin=0, vmax=150\n        )\n\n    def render_sample_data(\n        self,\n        sample_data_token: str,\n        with_anns: bool = True,\n        box_vis_level: BoxVisibility = BoxVisibility.ANY,\n        axes_limit: float = 40,\n        ax: Axes = None,\n        num_sweeps: int = 1,\n        out_path: str = None,\n        underlay_map: bool = False,\n    ):\n        \"\"\"Render sample data onto axis.\n        Args:\n            sample_data_token: Sample_data token.\n            with_anns: Whether to draw annotations.\n            box_vis_level: If sample_data is an image, this sets required visibility for boxes.\n            axes_limit: Axes limit for lidar and radar (measured in meters).\n            ax: Axes onto which to render.\n            num_sweeps: Number of sweeps for lidar and radar.\n            out_path: Optional path to save the rendered figure to disk.\n            underlay_map: When set to true, LIDAR data is plotted onto the map. This can be slow.\n        \"\"\"\n\n        # Get sensor modality.\n        sd_record = self.lyftd.get(\"sample_data\", sample_data_token)\n        sensor_modality = sd_record[\"sensor_modality\"]\n\n        if sensor_modality == \"lidar\":\n            # Get boxes in lidar frame.\n            _, boxes, _ = self.lyftd.get_sample_data(\n                sample_data_token, box_vis_level=box_vis_level, flat_vehicle_coordinates=True\n            )\n\n            # Get aggregated point cloud in lidar frame.\n            sample_rec = self.lyftd.get(\"sample\", sd_record[\"sample_token\"])\n            chan = sd_record[\"channel\"]\n            ref_chan = \"LIDAR_TOP\"\n            pc, times = LidarPointCloud.from_file_multisweep(\n                self.lyftd, sample_rec, chan, ref_chan, num_sweeps=num_sweeps\n            )\n\n            # Compute transformation matrices for lidar point cloud\n            cs_record = self.lyftd.get(\"calibrated_sensor\", sd_record[\"calibrated_sensor_token\"])\n            pose_record = self.lyftd.get(\"ego_pose\", sd_record[\"ego_pose_token\"])\n            vehicle_from_sensor = np.eye(4)\n            vehicle_from_sensor[:3, :3] = Quaternion(cs_record[\"rotation\"]).rotation_matrix\n            vehicle_from_sensor[:3, 3] = cs_record[\"translation\"]\n\n            ego_yaw = Quaternion(pose_record[\"rotation\"]).yaw_pitch_roll[0]\n            rot_vehicle_flat_from_vehicle = np.dot(\n                Quaternion(scalar=np.cos(ego_yaw / 2), vector=[0, 0, np.sin(ego_yaw / 2)]).rotation_matrix,\n                Quaternion(pose_record[\"rotation\"]).inverse.rotation_matrix,\n            )\n\n            vehicle_flat_from_vehicle = np.eye(4)\n            vehicle_flat_from_vehicle[:3, :3] = rot_vehicle_flat_from_vehicle\n\n            # Init axes.\n            if ax is None:\n                _, ax = plt.subplots(1, 1, figsize=(9, 9))\n\n            if underlay_map:\n                self.render_ego_centric_map(sample_data_token=sample_data_token, axes_limit=axes_limit, ax=ax)\n\n            # Show point cloud.\n            points = view_points(\n                pc.points[:3, :], np.dot(vehicle_flat_from_vehicle, vehicle_from_sensor), normalize=False\n            )\n            dists = np.sqrt(np.sum(pc.points[:2, :] ** 2, axis=0))\n            colors = np.minimum(1, dists / axes_limit / np.sqrt(2))\n            ax.scatter(points[0, :], points[1, :], c=colors, s=0.2)\n\n            # Show ego vehicle.\n            ax.plot(0, 0, \"x\", color=\"red\")\n\n            # Show boxes.\n            if with_anns:\n                for box in boxes:\n                    c = np.array(self.get_color(box.name)) / 255.0\n                    box.render(ax, view=np.eye(4), colors=(c, c, c))\n\n            # Limit visible range.\n            ax.set_xlim(-axes_limit, axes_limit)\n            ax.set_ylim(-axes_limit, axes_limit)\n\n        elif sensor_modality == \"radar\":\n            # Get boxes in lidar frame.\n            sample_rec = self.lyftd.get(\"sample\", sd_record[\"sample_token\"])\n            lidar_token = sample_rec[\"data\"][\"LIDAR_TOP\"]\n            _, boxes, _ = self.lyftd.get_sample_data(lidar_token, box_vis_level=box_vis_level)\n\n            # Get aggregated point cloud in lidar frame.\n            # The point cloud is transformed to the lidar frame for visualization purposes.\n            chan = sd_record[\"channel\"]\n            ref_chan = \"LIDAR_TOP\"\n            pc, times = RadarPointCloud.from_file_multisweep(\n                self.lyftd, sample_rec, chan, ref_chan, num_sweeps=num_sweeps\n            )\n\n            # Transform radar velocities (x is front, y is left), as these are not transformed when loading the point\n            # cloud.\n            radar_cs_record = self.lyftd.get(\"calibrated_sensor\", sd_record[\"calibrated_sensor_token\"])\n            lidar_sd_record = self.lyftd.get(\"sample_data\", lidar_token)\n            lidar_cs_record = self.lyftd.get(\"calibrated_sensor\", lidar_sd_record[\"calibrated_sensor_token\"])\n            velocities = pc.points[8:10, :]  # Compensated velocity\n            velocities = np.vstack((velocities, np.zeros(pc.points.shape[1])))\n            velocities = np.dot(Quaternion(radar_cs_record[\"rotation\"]).rotation_matrix, velocities)\n            velocities = np.dot(Quaternion(lidar_cs_record[\"rotation\"]).rotation_matrix.T, velocities)\n            velocities[2, :] = np.zeros(pc.points.shape[1])\n\n            # Init axes.\n            if ax is None:\n                _, ax = plt.subplots(1, 1, figsize=(9, 9))\n\n            # Show point cloud.\n            points = view_points(pc.points[:3, :], np.eye(4), normalize=False)\n            dists = np.sqrt(np.sum(pc.points[:2, :] ** 2, axis=0))\n            colors = np.minimum(1, dists / axes_limit / np.sqrt(2))\n            sc = ax.scatter(points[0, :], points[1, :], c=colors, s=3)\n\n            # Show velocities.\n            points_vel = view_points(pc.points[:3, :] + velocities, np.eye(4), normalize=False)\n            max_delta = 10\n            deltas_vel = points_vel - points\n            deltas_vel = 3 * deltas_vel  # Arbitrary scaling\n            deltas_vel = np.clip(deltas_vel, -max_delta, max_delta)  # Arbitrary clipping\n            colors_rgba = sc.to_rgba(colors)\n            for i in range(points.shape[1]):\n                ax.arrow(points[0, i], points[1, i], deltas_vel[0, i], deltas_vel[1, i], color=colors_rgba[i])\n\n            # Show ego vehicle.\n            ax.plot(0, 0, \"x\", color=\"black\")\n\n            # Show boxes.\n            if with_anns:\n                for box in boxes:\n                    c = np.array(self.get_color(box.name)) / 255.0\n                    box.render(ax, view=np.eye(4), colors=(c, c, c))\n\n            # Limit visible range.\n            ax.set_xlim(-axes_limit, axes_limit)\n            ax.set_ylim(-axes_limit, axes_limit)\n\n        elif sensor_modality == \"camera\":\n            # Load boxes and image.\n            data_path, boxes, camera_intrinsic = self.lyftd.get_sample_data(\n                sample_data_token, box_vis_level=box_vis_level\n            )\n\n            data = Image.open(str(data_path)[:len(str(data_path)) - 46] + 'train_images/' +\\\n                              str(data_path)[len(str(data_path)) - 39 : len(str(data_path))])\n\n            # Init axes.\n            if ax is None:\n                _, ax = plt.subplots(1, 1, figsize=(9, 16))\n\n            # Show image.\n            ax.imshow(data)\n\n            # Show boxes.\n            if with_anns:\n                for box in boxes:\n                    c = np.array(self.get_color(box.name)) / 255.0\n                    box.render(ax, view=camera_intrinsic, normalize=True, colors=(c, c, c))\n\n            # Limit visible range.\n            ax.set_xlim(0, data.size[0])\n            ax.set_ylim(data.size[1], 0)\n\n        else:\n            raise ValueError(\"Error: Unknown sensor modality!\")\n\n        ax.axis(\"off\")\n        ax.set_title(sd_record[\"channel\"])\n        ax.set_aspect(\"equal\")\n\n        if out_path is not None:\n            num = len([name for name in os.listdir(out_path)])\n            out_path = out_path + str(num).zfill(5) + \"_\" + sample_data_token + \".png\"\n            plt.savefig(out_path)\n            plt.close(\"all\")\n            return out_path\n\n    def render_annotation(\n        self,\n        ann_token: str,\n        margin: float = 10,\n        view: np.ndarray = np.eye(4),\n        box_vis_level: BoxVisibility = BoxVisibility.ANY,\n        out_path: str = None,\n    ) -> None:\n        \"\"\"Render selected annotation.\n        Args:\n            ann_token: Sample_annotation token.\n            margin: How many meters in each direction to include in LIDAR view.\n            view: LIDAR view point.\n            box_vis_level: If sample_data is an image, this sets required visibility for boxes.\n            out_path: Optional path to save the rendered figure to disk.\n        \"\"\"\n\n        ann_record = self.lyftd.get(\"sample_annotation\", ann_token)\n        sample_record = self.lyftd.get(\"sample\", ann_record[\"sample_token\"])\n        assert \"LIDAR_TOP\" in sample_record[\"data\"].keys(), \"No LIDAR_TOP in data, cant render\"\n\n        fig, axes = plt.subplots(1, 2, figsize=(18, 9))\n\n        # Figure out which camera the object is fully visible in (this may return nothing)\n        boxes, cam = [], []\n        cams = [key for key in sample_record[\"data\"].keys() if \"CAM\" in key]\n        for cam in cams:\n            _, boxes, _ = self.lyftd.get_sample_data(\n                sample_record[\"data\"][cam], box_vis_level=box_vis_level, selected_anntokens=[ann_token]\n            )\n            if len(boxes) > 0:\n                break  # We found an image that matches. Let's abort.\n        assert len(boxes) > 0, \"Could not find image where annotation is visible. Try using e.g. BoxVisibility.ANY.\"\n        assert len(boxes) < 2, \"Found multiple annotations. Something is wrong!\"\n\n        cam = sample_record[\"data\"][cam]\n\n        # Plot LIDAR view\n        lidar = sample_record[\"data\"][\"LIDAR_TOP\"]\n        data_path, boxes, camera_intrinsic = self.lyftd.get_sample_data(lidar, selected_anntokens=[ann_token])\n        LidarPointCloud.from_file(Path(str(data_path)[:len(str(data_path)) - 46] + 'train_lidar/' +\\\n                                       str(data_path)[len(str(data_path)) - 40 : len(str(data_path))])).render_height(axes[0], view=view)\n        for box in boxes:\n            c = np.array(self.get_color(box.name)) / 255.0\n            box.render(axes[0], view=view, colors=(c, c, c))\n            corners = view_points(boxes[0].corners(), view, False)[:2, :]\n            axes[0].set_xlim([np.min(corners[0, :]) - margin, np.max(corners[0, :]) + margin])\n            axes[0].set_ylim([np.min(corners[1, :]) - margin, np.max(corners[1, :]) + margin])\n            axes[0].axis(\"off\")\n            axes[0].set_aspect(\"equal\")\n\n        # Plot CAMERA view\n        data_path, boxes, camera_intrinsic = self.lyftd.get_sample_data(cam, selected_anntokens=[ann_token])\n        im = Image.open(Path(str(data_path)[:len(str(data_path)) - 46] + 'train_images/' +\\\n                             str(data_path)[len(str(data_path)) - 39 : len(str(data_path))]))\n        axes[1].imshow(im)\n        axes[1].set_title(self.lyftd.get(\"sample_data\", cam)[\"channel\"])\n        axes[1].axis(\"off\")\n        axes[1].set_aspect(\"equal\")\n        for box in boxes:\n            c = np.array(self.get_color(box.name)) / 255.0\n            box.render(axes[1], view=camera_intrinsic, normalize=True, colors=(c, c, c))\n\n        if out_path is not None:\n            plt.savefig(out_path)\n\n    def render_instance(self, instance_token: str, out_path: str = None) -> None:\n        \"\"\"Finds the annotation of the given instance that is closest to the vehicle, and then renders it.\n        Args:\n            instance_token: The instance token.\n            out_path: Optional path to save the rendered figure to disk.\n        Returns:\n        \"\"\"\n\n        ann_tokens = self.lyftd.field2token(\"sample_annotation\", \"instance_token\", instance_token)\n        closest = [np.inf, None]\n        for ann_token in ann_tokens:\n            ann_record = self.lyftd.get(\"sample_annotation\", ann_token)\n            sample_record = self.lyftd.get(\"sample\", ann_record[\"sample_token\"])\n            sample_data_record = self.lyftd.get(\"sample_data\", sample_record[\"data\"][\"LIDAR_TOP\"])\n            pose_record = self.lyftd.get(\"ego_pose\", sample_data_record[\"ego_pose_token\"])\n            dist = np.linalg.norm(np.array(pose_record[\"translation\"]) - np.array(ann_record[\"translation\"]))\n            if dist < closest[0]:\n                closest[0] = dist\n                closest[1] = ann_token\n        self.render_annotation(closest[1], out_path=out_path)\n\n    def render_scene(self, scene_token: str, freq: float = 10, image_width: int = 640, out_path: Path = None) -> None:\n        \"\"\"Renders a full scene with all surround view camera channels.\n        Args:\n            scene_token: Unique identifier of scene to render.\n            freq: Display frequency (Hz).\n            image_width: Width of image to render. Height is determined automatically to preserve aspect ratio.\n            out_path: Optional path to write a video file of the rendered frames.\n        \"\"\"\n\n        if out_path is not None:\n            assert out_path.suffix == \".avi\"\n\n        # Get records from DB.\n        scene_rec = self.lyftd.get(\"scene\", scene_token)\n        first_sample_rec = self.lyftd.get(\"sample\", scene_rec[\"first_sample_token\"])\n        last_sample_rec = self.lyftd.get(\"sample\", scene_rec[\"last_sample_token\"])\n\n        channels = [\"CAM_FRONT_LEFT\", \"CAM_FRONT\", \"CAM_FRONT_RIGHT\", \"CAM_BACK_LEFT\", \"CAM_BACK\", \"CAM_BACK_RIGHT\"]\n\n        horizontal_flip = [\"CAM_BACK_LEFT\", \"CAM_BACK\", \"CAM_BACK_RIGHT\"]  # Flip these for aesthetic reasons.\n\n        time_step = 1 / freq * 1e6  # Time-stamps are measured in micro-seconds.\n\n        window_name = \"{}\".format(scene_rec[\"name\"])\n        cv2.namedWindow(window_name)\n        cv2.moveWindow(window_name, 0, 0)\n\n        # Load first sample_data record for each channel\n        current_recs = {}  # Holds the current record to be displayed by channel.\n        prev_recs = {}  # Hold the previous displayed record by channel.\n        for channel in channels:\n            current_recs[channel] = self.lyftd.get(\"sample_data\", first_sample_rec[\"data\"][channel])\n            prev_recs[channel] = None\n\n        # We assume that the resolution is the same for all surround view cameras.\n        image_height = int(image_width * current_recs[channels[0]][\"height\"] / current_recs[channels[0]][\"width\"])\n        image_size = (image_width, image_height)\n\n        # Set some display parameters\n        layout = {\n            \"CAM_FRONT_LEFT\": (0, 0),\n            \"CAM_FRONT\": (image_size[0], 0),\n            \"CAM_FRONT_RIGHT\": (2 * image_size[0], 0),\n            \"CAM_BACK_LEFT\": (0, image_size[1]),\n            \"CAM_BACK\": (image_size[0], image_size[1]),\n            \"CAM_BACK_RIGHT\": (2 * image_size[0], image_size[1]),\n        }\n\n        canvas = np.ones((2 * image_size[1], 3 * image_size[0], 3), np.uint8)\n        if out_path is not None:\n            fourcc = cv2.VideoWriter_fourcc(*\"MJPG\")\n            out = cv2.VideoWriter(out_path, fourcc, freq, canvas.shape[1::-1])\n        else:\n            out = None\n\n        current_time = first_sample_rec[\"timestamp\"]\n\n        while current_time < last_sample_rec[\"timestamp\"]:\n\n            current_time += time_step\n\n            # For each channel, find first sample that has time > current_time.\n            for channel, sd_rec in current_recs.items():\n                while sd_rec[\"timestamp\"] < current_time and sd_rec[\"next\"] != \"\":\n                    sd_rec = self.lyftd.get(\"sample_data\", sd_rec[\"next\"])\n                    current_recs[channel] = sd_rec\n\n            # Now add to canvas\n            for channel, sd_rec in current_recs.items():\n\n                # Only update canvas if we have not already rendered this one.\n                if not sd_rec == prev_recs[channel]:\n\n                    # Get annotations and params from DB.\n                    image_path, boxes, camera_intrinsic = self.lyftd.get_sample_data(\n                        sd_rec[\"token\"], box_vis_level=BoxVisibility.ANY\n                    )\n\n                    # Load and render\n                    if not image_path.exists():\n                        raise Exception(\"Error: Missing image %s\" % image_path)\n                    im = cv2.imread(str(image_path))\n                    for box in boxes:\n                        c = self.get_color(box.name)\n                        box.render_cv2(im, view=camera_intrinsic, normalize=True, colors=(c, c, c))\n\n                    im = cv2.resize(im, image_size)\n                    if channel in horizontal_flip:\n                        im = im[:, ::-1, :]\n\n                    canvas[\n                        layout[channel][1] : layout[channel][1] + image_size[1],\n                        layout[channel][0] : layout[channel][0] + image_size[0],\n                        :,\n                    ] = im\n\n                    prev_recs[channel] = sd_rec  # Store here so we don't render the same image twice.\n\n            # Show updated canvas.\n            cv2.imshow(window_name, canvas)\n            if out_path is not None:\n                out.write(canvas)\n\n            key = cv2.waitKey(1)  # Wait a very short time (1 ms).\n\n            if key == 32:  # if space is pressed, pause.\n                key = cv2.waitKey()\n\n            if key == 27:  # if ESC is pressed, exit.\n                cv2.destroyAllWindows()\n                break\n\n        cv2.destroyAllWindows()\n        if out_path is not None:\n            out.release()\n\n    def render_scene_channel(\n        self,\n        scene_token: str,\n        channel: str = \"CAM_FRONT\",\n        freq: float = 10,\n        image_size: Tuple[float, float] = (640, 360),\n        out_path: Path = None,\n    ) -> None:\n        \"\"\"Renders a full scene for a particular camera channel.\n        Args:\n            scene_token: Unique identifier of scene to render.\n            channel: Channel to render.\n            freq: Display frequency (Hz).\n            image_size: Size of image to render. The larger the slower this will run.\n            out_path: Optional path to write a video file of the rendered frames.\n        \"\"\"\n\n        valid_channels = [\n            \"CAM_FRONT_LEFT\",\n            \"CAM_FRONT\",\n            \"CAM_FRONT_RIGHT\",\n            \"CAM_BACK_LEFT\",\n            \"CAM_BACK\",\n            \"CAM_BACK_RIGHT\",\n        ]\n\n        assert image_size[0] / image_size[1] == 16 / 9, \"Aspect ratio should be 16/9.\"\n        assert channel in valid_channels, \"Input channel {} not valid.\".format(channel)\n\n        if out_path is not None:\n            assert out_path.suffix == \".avi\"\n\n        # Get records from DB\n        scene_rec = self.lyftd.get(\"scene\", scene_token)\n        sample_rec = self.lyftd.get(\"sample\", scene_rec[\"first_sample_token\"])\n        sd_rec = self.lyftd.get(\"sample_data\", sample_rec[\"data\"][channel])\n\n        # Open CV init\n        name = \"{}: {} (Space to pause, ESC to exit)\".format(scene_rec[\"name\"], channel)\n        cv2.namedWindow(name)\n        cv2.moveWindow(name, 0, 0)\n\n        if out_path is not None:\n            fourcc = cv2.VideoWriter_fourcc(*\"MJPG\")\n            out = cv2.VideoWriter(out_path, fourcc, freq, image_size)\n        else:\n            out = None\n\n        has_more_frames = True\n        while has_more_frames:\n\n            # Get data from DB\n            image_path, boxes, camera_intrinsic = self.lyftd.get_sample_data(\n                sd_rec[\"token\"], box_vis_level=BoxVisibility.ANY\n            )\n\n            # Load and render\n            if not image_path.exists():\n                raise Exception(\"Error: Missing image %s\" % image_path)\n            image = cv2.imread(str(image_path))\n            for box in boxes:\n                c = self.get_color(box.name)\n                box.render_cv2(image, view=camera_intrinsic, normalize=True, colors=(c, c, c))\n\n            # Render\n            image = cv2.resize(image, image_size)\n            cv2.imshow(name, image)\n            if out_path is not None:\n                out.write(image)\n\n            key = cv2.waitKey(10)  # Images stored at approx 10 Hz, so wait 10 ms.\n            if key == 32:  # If space is pressed, pause.\n                key = cv2.waitKey()\n\n            if key == 27:  # if ESC is pressed, exit\n                cv2.destroyAllWindows()\n                break\n\n            if not sd_rec[\"next\"] == \"\":\n                sd_rec = self.lyftd.get(\"sample_data\", sd_rec[\"next\"])\n            else:\n                has_more_frames = False\n\n        cv2.destroyAllWindows()\n        if out_path is not None:\n            out.release()\n\n    def render_egoposes_on_map(\n        self,\n        log_location: str,\n        scene_tokens: List = None,\n        close_dist: float = 100,\n        color_fg: Tuple[int, int, int] = (167, 174, 186),\n        color_bg: Tuple[int, int, int] = (255, 255, 255),\n        out_path: Path = None,\n    ) -> None:\n        \"\"\"Renders ego poses a the map. These can be filtered by location or scene.\n        Args:\n            log_location: Name of the location, e.g. \"singapore-onenorth\", \"singapore-hollandvillage\",\n                             \"singapore-queenstown' and \"boston-seaport\".\n            scene_tokens: Optional list of scene tokens.\n            close_dist: Distance in meters for an ego pose to be considered within range of another ego pose.\n            color_fg: Color of the semantic prior in RGB format (ignored if map is RGB).\n            color_bg: Color of the non-semantic prior in RGB format (ignored if map is RGB).\n            out_path: Optional path to save the rendered figure to disk.\n        Returns:\n        \"\"\"\n\n        # Get logs by location\n        log_tokens = [l[\"token\"] for l in self.lyftd.log if l[\"location\"] == log_location]\n        assert len(log_tokens) > 0, \"Error: This split has 0 scenes for location %s!\" % log_location\n\n        # Filter scenes\n        scene_tokens_location = [e[\"token\"] for e in self.lyftd.scene if e[\"log_token\"] in log_tokens]\n        if scene_tokens is not None:\n            scene_tokens_location = [t for t in scene_tokens_location if t in scene_tokens]\n        if len(scene_tokens_location) == 0:\n            print(\"Warning: Found 0 valid scenes for location %s!\" % log_location)\n\n        map_poses = []\n        map_mask = None\n\n        print(\"Adding ego poses to map...\")\n        for scene_token in tqdm(scene_tokens_location):\n\n            # Get records from the database.\n            scene_record = self.lyftd.get(\"scene\", scene_token)\n            log_record = self.lyftd.get(\"log\", scene_record[\"log_token\"])\n            map_record = self.lyftd.get(\"map\", log_record[\"map_token\"])\n            map_mask = map_record[\"mask\"]\n\n            # For each sample in the scene, store the ego pose.\n            sample_tokens = self.lyftd.field2token(\"sample\", \"scene_token\", scene_token)\n            for sample_token in sample_tokens:\n                sample_record = self.lyftd.get(\"sample\", sample_token)\n\n                # Poses are associated with the sample_data. Here we use the lidar sample_data.\n                sample_data_record = self.lyftd.get(\"sample_data\", sample_record[\"data\"][\"LIDAR_TOP\"])\n                pose_record = self.lyftd.get(\"ego_pose\", sample_data_record[\"ego_pose_token\"])\n\n                # Calculate the pose on the map and append\n                map_poses.append(\n                    np.concatenate(\n                        map_mask.to_pixel_coords(pose_record[\"translation\"][0], pose_record[\"translation\"][1])\n                    )\n                )\n\n        # Compute number of close ego poses.\n        print(\"Creating plot...\")\n        map_poses = np.vstack(map_poses)\n        dists = sklearn.metrics.pairwise.euclidean_distances(map_poses * map_mask.resolution)\n        close_poses = np.sum(dists < close_dist, axis=0)\n\n        if len(np.array(map_mask.mask()).shape) == 3 and np.array(map_mask.mask()).shape[2] == 3:\n            # RGB Colour maps\n            mask = map_mask.mask()\n        else:\n            # Monochrome maps\n            # Set the colors for the mask.\n            mask = Image.fromarray(map_mask.mask())\n            mask = np.array(mask)\n\n            maskr = color_fg[0] * np.ones(np.shape(mask), dtype=np.uint8)\n            maskr[mask == 0] = color_bg[0]\n            maskg = color_fg[1] * np.ones(np.shape(mask), dtype=np.uint8)\n            maskg[mask == 0] = color_bg[1]\n            maskb = color_fg[2] * np.ones(np.shape(mask), dtype=np.uint8)\n            maskb[mask == 0] = color_bg[2]\n            mask = np.concatenate(\n                (np.expand_dims(maskr, axis=2), np.expand_dims(maskg, axis=2), np.expand_dims(maskb, axis=2)), axis=2\n            )\n\n        # Plot.\n        _, ax = plt.subplots(1, 1, figsize=(10, 10))\n        ax.imshow(mask)\n        title = \"Number of ego poses within {}m in {}\".format(close_dist, log_location)\n        ax.set_title(title, color=\"k\")\n        sc = ax.scatter(map_poses[:, 0], map_poses[:, 1], s=10, c=close_poses)\n        color_bar = plt.colorbar(sc, fraction=0.025, pad=0.04)\n        plt.rcParams[\"figure.facecolor\"] = \"black\"\n        color_bar_ticklabels = plt.getp(color_bar.ax.axes, \"yticklabels\")\n        plt.setp(color_bar_ticklabels, color=\"k\")\n        plt.rcParams[\"figure.facecolor\"] = \"white\"  # Reset for future plots\n\n        if out_path is not None:\n            plt.savefig(out_path)\n            plt.close(\"all\")\n","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:42:23.399116Z","iopub.execute_input":"2024-02-01T03:42:23.399414Z","iopub.status.idle":"2024-02-01T03:42:23.540080Z","shell.execute_reply.started":"2024-02-01T03:42:23.399389Z","shell.execute_reply":"2024-02-01T03:42:23.539209Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lyft_dataset = LyftDataset(data_path=DATA_PATH, json_path=DATA_PATH+'train_data')\n","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:42:23.541097Z","iopub.execute_input":"2024-02-01T03:42:23.541400Z","iopub.status.idle":"2024-02-01T03:42:44.000808Z","shell.execute_reply.started":"2024-02-01T03:42:23.541375Z","shell.execute_reply":"2024-02-01T03:42:43.999897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"my_scene = lyft_dataset.scene[0]\nmy_scene","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:42:44.002080Z","iopub.execute_input":"2024-02-01T03:42:44.002389Z","iopub.status.idle":"2024-02-01T03:42:44.008627Z","shell.execute_reply.started":"2024-02-01T03:42:44.002362Z","shell.execute_reply":"2024-02-01T03:42:44.007705Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def render_scene(index):\n    my_scene = lyft_dataset.scene[index]\n    my_sample_token = my_scene[\"first_sample_token\"]\n    lyft_dataset.render_sample(my_sample_token)","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:42:44.010014Z","iopub.execute_input":"2024-02-01T03:42:44.010351Z","iopub.status.idle":"2024-02-01T03:42:44.021056Z","shell.execute_reply.started":"2024-02-01T03:42:44.010317Z","shell.execute_reply":"2024-02-01T03:42:44.020209Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"render_scene(0)","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:42:44.022154Z","iopub.execute_input":"2024-02-01T03:42:44.023119Z","iopub.status.idle":"2024-02-01T03:42:57.896817Z","shell.execute_reply.started":"2024-02-01T03:42:44.023082Z","shell.execute_reply":"2024-02-01T03:42:57.895813Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"my_sample_token = my_scene[\"first_sample_token\"]\nmy_sample = lyft_dataset.get('sample', my_sample_token)\nlyft_dataset.render_pointcloud_in_image(sample_token = my_sample[\"token\"],\n                                        dot_size = 1,\n                                        camera_channel = 'CAM_FRONT')","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:42:57.898211Z","iopub.execute_input":"2024-02-01T03:42:57.898520Z","iopub.status.idle":"2024-02-01T03:42:59.022016Z","shell.execute_reply.started":"2024-02-01T03:42:57.898493Z","shell.execute_reply":"2024-02-01T03:42:59.021059Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"my_sample['data']","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:42:59.023220Z","iopub.execute_input":"2024-02-01T03:42:59.023530Z","iopub.status.idle":"2024-02-01T03:42:59.029824Z","shell.execute_reply.started":"2024-02-01T03:42:59.023503Z","shell.execute_reply":"2024-02-01T03:42:59.028952Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sensor_channel = 'CAM_FRONT'\nmy_sample_data = lyft_dataset.get('sample_data', my_sample['data'][sensor_channel])\n\nlyft_dataset.render_sample_data(my_sample_data['token'])","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:42:59.031280Z","iopub.execute_input":"2024-02-01T03:42:59.031766Z","iopub.status.idle":"2024-02-01T03:42:59.938569Z","shell.execute_reply.started":"2024-02-01T03:42:59.031733Z","shell.execute_reply":"2024-02-01T03:42:59.937645Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sensor_channel = 'CAM_BACK'\nmy_sample_data = lyft_dataset.get('sample_data', my_sample['data'][sensor_channel])\nlyft_dataset.render_sample_data(my_sample_data['token'])","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:42:59.939864Z","iopub.execute_input":"2024-02-01T03:42:59.940203Z","iopub.status.idle":"2024-02-01T03:43:00.906689Z","shell.execute_reply.started":"2024-02-01T03:42:59.940174Z","shell.execute_reply":"2024-02-01T03:43:00.905723Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sensor_channel = 'CAM_FRONT_LEFT'\nmy_sample_data = lyft_dataset.get('sample_data', my_sample['data'][sensor_channel])\nlyft_dataset.render_sample_data(my_sample_data['token'])\n","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:43:00.907828Z","iopub.execute_input":"2024-02-01T03:43:00.908146Z","iopub.status.idle":"2024-02-01T03:43:01.909455Z","shell.execute_reply.started":"2024-02-01T03:43:00.908120Z","shell.execute_reply":"2024-02-01T03:43:01.908492Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sensor_channel = 'CAM_FRONT_RIGHT'\nmy_sample_data = lyft_dataset.get('sample_data', my_sample['data'][sensor_channel])\nlyft_dataset.render_sample_data(my_sample_data['token'])\n","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:43:01.910680Z","iopub.execute_input":"2024-02-01T03:43:01.910994Z","iopub.status.idle":"2024-02-01T03:43:02.874739Z","shell.execute_reply.started":"2024-02-01T03:43:01.910967Z","shell.execute_reply":"2024-02-01T03:43:02.873819Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sensor_channel = 'CAM_BACK_LEFT'\nmy_sample_data = lyft_dataset.get('sample_data', my_sample['data'][sensor_channel])\nlyft_dataset.render_sample_data(my_sample_data['token'])\n","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:43:02.876006Z","iopub.execute_input":"2024-02-01T03:43:02.876359Z","iopub.status.idle":"2024-02-01T03:43:03.676722Z","shell.execute_reply.started":"2024-02-01T03:43:02.876328Z","shell.execute_reply":"2024-02-01T03:43:03.675812Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sensor_channel = 'CAM_BACK_RIGHT'\nmy_sample_data = lyft_dataset.get('sample_data', my_sample['data'][sensor_channel])\nlyft_dataset.render_sample_data(my_sample_data['token'])\n","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:43:03.678073Z","iopub.execute_input":"2024-02-01T03:43:03.678403Z","iopub.status.idle":"2024-02-01T03:43:04.461730Z","shell.execute_reply.started":"2024-02-01T03:43:03.678374Z","shell.execute_reply":"2024-02-01T03:43:04.460850Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"my_annotation_token = my_sample['anns'][10]\nmy_annotation =  my_sample_data.get('sample_annotation', my_annotation_token)\nlyft_dataset.render_annotation(my_annotation_token)\n","metadata":{"execution":{"iopub.status.busy":"2024-02-01T03:43:04.462881Z","iopub.execute_input":"2024-02-01T03:43:04.463239Z","iopub.status.idle":"2024-02-01T03:43:07.100944Z","shell.execute_reply.started":"2024-02-01T03:43:04.463205Z","shell.execute_reply":"2024-02-01T03:43:07.100041Z"},"trusted":true},"execution_count":null,"outputs":[]}]}