Esempio n. 1
0
def _radar(df: pd.DataFrame,
           ax: plt.Axes,
           label: str,
           all_tags: Sequence[str],
           color: str,
           alpha: float = 0.2,
           edge_alpha: float = 0.85,
           zorder: int = 2,
           edge_style: str = '-'):
    """Plot utility for generating the underlying radar plot."""
    tmp = df.groupby('tag').mean().reset_index()

    values = []
    for curr_tag in all_tags:
        score = 0.
        selected = tmp[tmp['tag'] == curr_tag]
        if len(selected) == 1:
            score = float(selected['score'])
        else:
            print('{} bsuite scores found for tag {!r} with setting {!r}. '
                  'Replacing with zero.'.format(len(selected), curr_tag,
                                                label))
        values.append(score)
    values = np.maximum(values, 0.05)  # don't let radar collapse to 0.
    values = np.concatenate((values, [values[0]]))

    angles = np.linspace(0, 2 * np.pi, len(all_tags), endpoint=False)
    angles = np.concatenate((angles, [angles[0]]))

    ax.plot(angles,
            values,
            '-',
            linewidth=5,
            label=label,
            c=color,
            alpha=edge_alpha,
            zorder=zorder,
            linestyle=edge_style)
    ax.fill(angles, values, alpha=alpha, color=color, zorder=zorder)
    ax.set_thetagrids(angles * 180 / np.pi,
                      map(_tag_pretify, all_tags),
                      fontsize=18)

    # To avoid text on top of gridlines, we flip horizontalalignment
    # based on label location
    text_angles = np.rad2deg(angles)
    for label, angle in zip(ax.get_xticklabels()[:-1], text_angles[:-1]):
        if 90 <= angle <= 270:
            label.set_horizontalalignment('right')
        else:
            label.set_horizontalalignment('left')
Esempio n. 2
0
def plot_polygon(geom: Union[Polygon, Iterable[Polygon]], *args,
        ax: Axes=None, crs: CRS=None, **kwargs):
    """ Plot a Polygon geometry, projected to the coordinate system `crs` """
    kwargs.setdefault("facecolor", "none")
    kwargs.setdefault("edgecolor", "black")
    x, y = geom.get_coordinate_lists(crs=crs)
    return ax.fill(x, y, *args, **kwargs)
Esempio n. 3
0
def plot_polygon(geom: Union[Polygon, Iterable[Polygon]], *args,
        ax: Axes=None, crs: CRS=None, **kwargs):
    """ Plot a Polygon geometry, projected to the coordinate system `crs` """
    kwargs.setdefault("facecolor", "none")
    kwargs.setdefault("edgecolor", "black")
    x, y = geom.get_coordinate_lists(crs=crs)
    return ax.fill(x, y, *args, **kwargs)
Esempio n. 4
0
def plot_multipolygon(geom: Union[Multipolygon, Iterable[Multipolygon]], *args,
        ax: Axes=None, crs: CRS=None, **kwargs):
    """ Plot a Line geometry, projected to the coordinate system `crs` """
    kwargs.setdefault("facecolor", "none")
    kwargs.setdefault("edgecolor", "black")
    out = []
    for polygon in geom:
        x, y = polygon.get_coordinate_lists(crs=crs)
        out.append(ax.fill(x, y, *args, **kwargs))
    return out
Esempio n. 5
0
def plot_multipolygon(geom: Union[Multipoint, Iterable[Multipoint]],
                      *args,
                      ax: Axes = None,
                      crs: CRS = None,
                      **kwargs):
    """ Plot a Line geometry, projected to the coordinate system `crs` """
    kwargs.setdefault("facecolor", "none")
    kwargs.setdefault("edgecolor", "black")
    out = []
    for polygon in geom:
        x, y = polygon.get_coordinate_lists(crs=crs)
        out.append(ax.fill(x, y, *args, **kwargs))
    return out
Esempio n. 6
0
    def plot(
            self,
            ax: plt.Axes,
            component_x: str = 'x',
            component_y: str = 'y',
            component_z: str = 'z',
            components: typ.Tuple[str, str] = ('x', 'y'),
            # color: str = 'black',
            transform_extra: typ.Optional[
                kgpy.transforms.TransformList] = None,
            to_global: bool = False,
            **kwargs):

        kwargs = {**self.plot_kwargs, **kwargs}

        if to_global:
            if transform_extra is None:
                transform_extra = kgpy.transforms.TransformList()
            transform_extra = transform_extra + self.transform

        top = kgpy.vectors.Cartesian3D(
            x=u.Quantity([0 * u.mm, 0 * u.mm, self.width, self.width]),
            y=0 * u.mm,
            z=u.Quantity([0 * u.mm, self.length, self.length, 0 * u.mm]),
        )
        bottom = top.copy()
        bottom.y = -self.thickness
        points = np.stack([top, bottom])
        points = transform_extra(points)

        c0, c1 = components
        ax.fill(points.get_component(c0).T,
                points.get_component(c1).T,
                fill=False,
                **kwargs)
        ax.plot(points.get_component(c0), points.get_component(c1), **kwargs)

        return ax
Esempio n. 7
0
def plot_map(odr_map: Map, ax: plt.Axes = None, **kwargs) -> plt.Axes:
    """ Draw the road layout of the map

    Args:
        odr_map: The Map to plot
        ax: Axes to draw on

    Keyword Args:
        midline: True if the midline of roads should be drawn (default: False)
        midline_direction: Whether to show directed arrows for the midline (default: False)
        road_ids: If True, then the IDs of roads will be drawn (default: False)
        markings: If True, then draw LaneMarkers (default: False)
        road_color: Plot color of the road boundary (default: black)
        junction_color: Face color of junctions (default: [0.941, 1.0, 0.420, 0.5])
        midline_color: Color of the midline

    Returns:
        The axes onto which the road layout was drawn
    """
    colors = plt.get_cmap("tab10").colors

    if ax is None:
        _, ax = plt.subplots(1, 1)

    ax.set_xlim([odr_map.west, odr_map.east])
    ax.set_ylim([odr_map.south, odr_map.north])
    ax.set_facecolor("grey")

    for road_id, road in odr_map.roads.items():
        boundary = road.boundary.boundary
        if boundary.geom_type == "LineString":
            ax.plot(boundary.xy[0],
                    boundary.xy[1],
                    color=kwargs.get("road_color", "k"))
        elif boundary.geom_type == "MultiLineString":
            for b in boundary:
                ax.plot(b.xy[0],
                        b.xy[1],
                        color=kwargs.get("road_color", "orange"))

        color = kwargs.get(
            "midline_color",
            colors[road_id %
                   len(colors)] if kwargs.get("road_ids", False) else "r")
        if kwargs.get("midline", False):
            for lane_section in road.lanes.lane_sections:
                for lane in lane_section.all_lanes:
                    if lane.id == 0:
                        continue
                    if kwargs.get("midline_direction", False):
                        x = np.array(lane.midline.xy[0])
                        y = np.array(lane.midline.xy[1])
                        ax.quiver(x[:-1],
                                  y[:-1],
                                  x[1:] - x[:-1],
                                  y[1:] - y[:-1],
                                  width=0.0025,
                                  headwidth=2,
                                  scale_units='xy',
                                  angles='xy',
                                  scale=1,
                                  color="red")
                    else:
                        ax.plot(lane.midline.xy[0],
                                lane.midline.xy[1],
                                color=color)

        if kwargs.get("road_ids", False):
            mid_point = len(road.midline.xy) // 2
            ax.text(road.midline.xy[0][mid_point],
                    road.midline.xy[1][mid_point],
                    road.id,
                    color=color,
                    fontsize=15)

        if kwargs.get("markings", False):
            for lane_section in road.lanes.lane_sections:
                for lane in lane_section.all_lanes:
                    for marker in lane.markers:
                        line_styles = marker.type_to_linestyle
                        for i, style in enumerate(line_styles):
                            if style is None:
                                continue
                            df = 0.13  # Distance between parallel lines
                            side = "left" if lane.id <= 0 else "right"
                            line = lane.reference_line.parallel_offset(
                                i * df, side=side)
                            ax.plot(line.xy[0],
                                    line.xy[1],
                                    color=marker.color_to_rgb,
                                    linestyle=style,
                                    linewidth=marker.plot_width)

    for junction_id, junction in odr_map.junctions.items():
        if junction.boundary.geom_type == "Polygon":
            ax.fill(junction.boundary.boundary.xy[0],
                    junction.boundary.boundary.xy[1],
                    color=kwargs.get("junction_color",
                                     (0.941, 1.0, 0.420, 0.5)))
        else:
            for polygon in junction.boundary:
                ax.fill(polygon.boundary.xy[0],
                        polygon.boundary.xy[1],
                        color=kwargs.get("junction_color",
                                         (0.941, 1.0, 0.420, 0.5)))
    return ax
Esempio n. 8
0
    def render_bev_labels_mpl(
        self,
        city_name: str,
        ax: plt.Axes,
        axis: str,
        # lidar_pts: np.ndarray,
        local_lane_polygons: np.ndarray,
        local_das: np.ndarray,
        log_id: str,
        timestamp: int,
        timestamp_ind: int,
        city_to_egovehicle_se3: SE3,
        avm: ArgoverseMap,
    ) -> None:
        """Plot nearby lane polygons and nearby driveable areas (da) on the Matplotlib axes.

        Args:
            city_name: The name of a city, e.g. `"PIT"`
            ax: Matplotlib axes
            axis: string, either 'ego_axis' or 'city_axis' to demonstrate the
            lidar_pts:  Numpy array of shape (N,3)
            local_lane_polygons: Polygons representing the local lane set
            local_das: Numpy array of objects of shape (N,) where each object is of shape (M,3)
            log_id: The ID of a log
            timestamp: In nanoseconds
            city_to_egovehicle_se3: Transformation from egovehicle frame to city frame
            avm: ArgoverseMap instance
        """
        if axis is not "city_axis":
            # rendering instead in the egovehicle reference frame
            for da_idx, local_da in enumerate(local_das):
                local_da = city_to_egovehicle_se3.inverse_transform_point_cloud(
                    local_da)
                # local_das[da_idx] = rotate_polygon_about_pt(local_da, city_to_egovehicle_se3.rotation, np.zeros(3))
                local_das[da_idx] = local_da

            for lane_idx, local_lane_polygon in enumerate(local_lane_polygons):
                local_lane_polygon = city_to_egovehicle_se3.inverse_transform_point_cloud(
                    local_lane_polygon)
                # local_lane_polygons[lane_idx] = rotate_polygon_about_pt(
                #     local_lane_polygon, city_to_egovehicle_se3.rotation, np.zeros(3)
                # )
                local_lane_polygons[lane_idx] = local_lane_polygon

        draw_lane_polygons(ax, local_lane_polygons, color="tab:gray")
        draw_lane_polygons(ax, local_das, color=(1, 0, 1))

        # render ego vehicle
        bbox_ego = np.array([[-1.0, -1.0, 0.0], [3.0, -1.0, 0.0],
                             [-1.0, 1.0, 0.0], [3.0, 1.0, 0.0]])
        # bbox_ego = rotate_polygon_about_pt(bbox_ego, city_to_egovehicle_se3.rotation, np.zeros((3,)))
        plot_bbox_2D(ax, bbox_ego, 'g')

        # render surrounding vehicle and pedestrians
        objects = self.log_timestamp_dict[log_id][timestamp]
        hist_objects = {}

        all_occluded = True
        for frame_rec in objects:
            if frame_rec.occlusion_val != IS_OCCLUDED_FLAG:
                all_occluded = False
            hist_objects[frame_rec.track_uuid] = [
                None for i in range(0, SURR_TIME_STEP + 1)
            ]
            hist_objects[
                frame_rec.track_uuid][SURR_TIME_STEP] = frame_rec.bbox_city_fr

        if not all_occluded:
            for ind, i in enumerate(
                    range(timestamp_ind - SURR_TIME_STEP, timestamp_ind)):
                objects = self.log_timestamp_dict[log_id][self.timestamps[i]]
                for frame_rec in objects:
                    if frame_rec.track_uuid in hist_objects:
                        hist_objects[
                            frame_rec.track_uuid][ind] = frame_rec.bbox_city_fr

            # render color with decreasing lightness
            color_lightness = np.linspace(1, 0,
                                          SURR_TIME_STEP + 2)[1:].tolist()
            for track_id in hist_objects:
                for ind_color, bbox_city_fr in enumerate(
                        hist_objects[track_id]):
                    if bbox_city_fr is None:
                        continue
                    bbox_relative = city_to_egovehicle_se3.inverse_transform_point_cloud(
                        bbox_city_fr)

                    x = bbox_relative[:, 0].tolist()
                    y = bbox_relative[:, 1].tolist()
                    x[1], x[2], x[3], y[1], y[2], y[3] = x[2], x[3], x[1], y[
                        2], y[3], y[1]
                    ax.fill(x,
                            y,
                            c=(1, 1, color_lightness[ind_color]),
                            alpha=1,
                            zorder=1)

        else:
            logger.info(f"all occluded at {timestamp}")
            xcenter = city_to_egovehicle_se3.translation[0]
            ycenter = city_to_egovehicle_se3.translation[1]
            ax.text(xcenter - 146,
                    ycenter + 50,
                    "ALL OBJECTS OCCLUDED",
                    fontsize=30)