예제 #1
0
def create_map():
    shp = fiona.open("./Kaupunginosajako/KaupunginosajakoPolygon_WGS84.shp"
                     )  # helsinki districts shapefile
    coords = shp.bounds  # Extract the bound coordinates from the shapefile
    shp.close()

    fig, ax = plt.subplots(figsize=(8, 8))  # figure and axis objects
    m = Basemap(
        projection='tmerc',
        ellps='WGS84',  # set transverse mercator proj. and ellipsoid
        lon_0=(coords[0] + coords[2]) / 2,  # longitude center
        lat_0=(coords[1] + coords[3]) / 2,  # latitude center
        llcrnrlon=coords[0],  # left lower corner
        llcrnrlat=coords[1],
        urcrnrlon=coords[2],  # upper right corner
        urcrnrlat=coords[3],
        resolution='c',
        suppress_ticks=True)

    m.readshapefile("./Kaupunginosajako/KaupunginosajakoPolygon_WGS84",
                    name='helsinki',
                    drawbounds=True,
                    color='blue')

    df_map = pd.DataFrame({
        "poly": [Polygon(xy) for xy in m.helsinki],
        "district": [x["nimi_fi"] for x in m.helsinki_info]
    })
    df_map["area_km"] = df_map["poly"].map(lambda x: x.area / 1000)

    map_points = [
        Point(m(x, y)) for x, y in zip(stations.longitude, stations.latitude)
    ]  # Convert Data Points to projection, then to Shapely
    all_points = MultiPoint(map_points)
    district_poly = prep(MultiPolygon(list(df_map.poly.values)))
    all_points = list(
        filter(district_poly.contains,
               all_points))  # Select only points within map boundaries

    df_map["bikes_count"] = df_map.poly.apply(points_per_poly,
                                              args=(all_points, ))
    df_map["bikes_per_area"] = df_map.bikes_count / df_map.area_km
    df_map.patch = df_map.poly.map(lambda x: PolygonPatch(x))
    pc = PatchCollection(df_map.patch, match_original=False, zorder=2)

    pc.set(array=df_map.bikes_per_area.values,
           cmap='Reds')  # impose color map onto patch collection
    fig.colorbar(pc,
                 label="Bike density")  # Draw Colorbar and display the measure
    ax.add_collection(pc)  # add patchcollection to axis

    centroids = df_map["poly"].map(
        lambda x: x.centroid)  # get center of each polygon
    for i, (point, label) in enumerate(zip(centroids, df_map.district)):
        if df_map.loc[i,
                      "bikes_per_area"] > df_map.bikes_per_area.quantile(0.05):
            ax.text(point.x, point.y, label, ha='center',
                    size=8)  # plot text in center

    plt.show()
예제 #2
0
def plot_field(mesh,
               element_values,
               labels=None,
               title=None,
               vmin=None,
               vmax=None,
               save=None):
    '''
    Creates a plot of a scalar field over the mesh as a color plot. The values of
    each element is constantly given by element_vaues.

    mesh - a mesh numpy array, each row is an element with 3 nodes ([x1, y1, x2, y2, x3, y3])
    element_values - The values to be plotted, one for each element (numpy array)
    '''
    fig, ax = plt.subplots(figsize=(10, 8))
    ev = element_values * (10**4)
    patches = []
    for i, elm in enumerate(mesh):
        if len(elm) == 6:
            ax.plot([elm[0], elm[2]], [elm[1], elm[3]], 'ro-')
            ax.plot([elm[0], elm[4]], [elm[1], elm[5]], 'ro-')
            ax.plot([elm[2], elm[4]], [elm[3], elm[5]], 'ro-')
            xy = np.array([elm[0:2], elm[2:4], elm[4:6]])
        if len(elm) == 8:
            ax.plot([elm[0], elm[2]], [elm[1], elm[3]], 'ro-')
            ax.plot([elm[2], elm[4]], [elm[3], elm[5]], 'ro-')
            ax.plot([elm[4], elm[6]], [elm[5], elm[7]], 'ro-')
            ax.plot([elm[6], elm[0]], [elm[7], elm[1]], 'ro-')
            xy = np.array([elm[0:2], elm[2:4], elm[4:6], elm[6:8]])
        polygon = Polygon(xy, True)
        patches.append(polygon)
        ax.text(np.mean(elm[0::2]), np.mean(elm[1::2]), str(i), size=17)
        if labels is not None:
            x = (elm[0] + elm[2] + elm[4]) / 3.
            y = (elm[1] + elm[3] + elm[5]) / 3.
            plt.text(x, y, str(i), size=17)

    p = PatchCollection(patches, alpha=1.0)
    if vmin is not None: ev[ev < vmin] = vmin
    if vmax is not None: ev[ev > vmax] = vmax
    p.set(array=ev, cmap='jet')
    ax.add_collection(p)
    cbar = fig.colorbar(p, ax=ax)
    cbar.ax.set_title(r'$10^{-4}$', size=27)
    cbar.ax.tick_params(labelsize=17)
    ax.tick_params(labelsize=17)

    l = 0.3 * np.abs(np.max(mesh))
    ax.text(l * 1.03, l / 10., "x", size=27)
    ax.quiver(0, 0, l, 0, angles='xy', scale_units='xy', scale=1)
    ax.text(-l / 5., 1.05 * l, "y", size=27)
    ax.quiver(0, 0, 0, l, angles='xy', scale_units='xy', scale=1)
    ax.axis('equal')
    if title is not None:
        ax.set_title(title, size=37)
    if save is not None: plt.savefig(save)
    def plot_generated_nodes(partitioner):
        import matplotlib.cm as cm
        import matplotlib.pyplot as plt
        from matplotlib.collections import PatchCollection
        from matplotlib.patches import Rectangle
        from numpy import array as np_array

        areas = list()

        fig = plt.figure()
        fig.set_size_inches(15, 20)
        ax1 = fig.add_subplot(211)

        xs = [(s.llx, s.urx) for s in partitioner.sinks + [partitioner.source]]
        ys = [(s.lly, s.ury) for s in partitioner.sinks + [partitioner.source]]

        x_max, y_max = max([x[1] for x in xs]), max([y[1] for y in ys])
        x_min, y_min = min([x[0] for x in xs]), min([y[0] for y in ys])

        for s in partitioner.sinks:
            x, y = s.llx, s.lly
            w, h = s.width, s.height
            rectangle = Rectangle((x, y), w, h, alpha=0.3)
            ax1.add_patch(rectangle)

        x, y = partitioner.source.llx, partitioner.source.lly
        w, h = partitioner.source.width, partitioner.source.height
        rectangle = Rectangle((x, y), w, h, facecolor='red', alpha=0.3)
        ax1.add_patch(rectangle)

        ax1.set_xlim([x_min, x_max])
        ax1.set_ylim([x_min, y_max])

        patches = list()
        for n in partitioner.nodes:
            x, y = n.llx, n.lly
            w, h = n.width, n.height
            rectangle = Rectangle((x, y), w, h)
            patches.append(rectangle)
            areas.append(n.area)

        ax2 = fig.add_subplot(212)
        col = PatchCollection(patches, alpha=0.4)
        col.set(array=np_array(areas), cmap='jet')

        ax2.add_collection(col)
        ax2.set_xlim([x_min, x_max])
        ax2.set_ylim([x_min, y_max])
        # plt.colorbar(col)

        fig.savefig('test.png', dpi=200)
예제 #4
0
    def __plot_patches(self, array, ax, **kwargs):
        """
        General patch plotter, workhorse of the class

        Parameters
        ----------
        array : array to plot
        ax : matplotlib.pyplot.axes
        kwargs : matplotlib keyword arguments

        Returns
        -------
            matplotlib.pyplot.axes

        """
        # if "color" not in kwargs:
        #    kwargs["facecolor"] = "None"

        if 'vmin' in kwargs:
            vmin = kwargs.pop('vmin')
        else:
            vmin = np.min(array)

        if 'vmax' in kwargs:
            vmax = kwargs.pop('vmax')
        else:
            vmax = np.max(array)

        patches = [Polygon(hru, True) for hru in self.prms_dis.xypts]

        p = PatchCollection(patches)
        p.set_array(array)
        p.set_clim(vmin=vmin, vmax=vmax)
        p.set(**kwargs)

        ax.add_collection(p)

        extent = self.extent
        ax.set_xlim([extent[0], extent[1]])
        ax.set_ylim([extent[2], extent[3]])
        return p
예제 #5
0
class SceneVisualizer:
    """Context for social nav vidualization"""
    def __init__(self,
                 scene,
                 output=None,
                 limits=None,
                 writer="imagemagick",
                 cmap="viridis",
                 agent_colors=None,
                 **kwargs):
        self.scene = scene
        self.states, self.group_states = self.scene.get_states()
        self.cmap = cmap
        self.agent_colors = agent_colors
        self.frames = self.scene.get_length()
        self.output = output
        self.writer = writer
        self.limits = limits

        self.fig, self.ax = plt.subplots(**kwargs)

        self.ani = None

        self.group_actors = None
        self.group_collection = PatchCollection([])
        self.group_collection.set(
            animated=True,
            alpha=0.2,
            cmap=self.cmap,
            facecolors="none",
            edgecolors="purple",
            linewidth=2,
            clip_on=True,
        )

        self.human_actors = None
        self.human_collection = PatchCollection([])
        self.human_collection.set(animated=True,
                                  alpha=0.6,
                                  cmap=self.cmap,
                                  clip_on=True)

    def plot(self):
        """Main method for create plot"""
        self.plot_obstacles()
        self.plot_fires()
        self.plot_exits()
        groups = self.group_states[0]  # static group for now
        if not groups:
            for ped in range(self.scene.peds.size()):
                x = self.states[:, ped, 0]
                y = self.states[:, ped, 1]
                self.ax.plot(x, y, "-o", label=f"ped {ped}", markersize=2.5)
        else:

            colors = plt.cm.rainbow(np.linspace(0, 1, len(groups)))

            for i, group in enumerate(groups):
                for ped in group:
                    x = self.states[:, ped, 0]
                    y = self.states[:, ped, 1]
                    self.ax.plot(x,
                                 y,
                                 "-o",
                                 label=f"ped {ped}",
                                 markersize=2.5,
                                 color=colors[i])
        self.ax.legend()
        return self.fig

    def animate(self):
        """Main method to create animation"""

        self.ani = mpl_animation.FuncAnimation(
            self.fig,
            init_func=self.animation_init,
            func=self.animation_update,
            frames=self.frames,
            blit=True,
            interval=200,
        )

        return self.ani

    def __enter__(self):
        logger.info("Start plotting.")
        self.fig.set_tight_layout(True)
        self.ax.grid(linestyle="dotted")
        self.ax.set_aspect("equal")
        self.ax.margins(2.0)
        self.ax.set_axisbelow(True)
        self.ax.set_xlabel("x [m]")
        self.ax.set_ylabel("y [m]")

        plt.rcParams["animation.html"] = "jshtml"

        # x, y limit from states, only for animation
        margin = 2.0
        if self.limits is None:
            xy_limits = np.array([minmax(state) for state in self.states
                                  ])  # (x_min, y_min, x_max, y_max)
            xy_min = np.min(xy_limits[:, :2], axis=0) - margin
            xy_max = np.max(xy_limits[:, 2:4], axis=0) + margin
            self.ax.set(xlim=(xy_min[0], xy_max[0]),
                        ylim=(xy_min[1], xy_max[1]))
        else:
            limits = self.limits
            self.ax.set(xlim=(limits[0] - margin, limits[1] + margin),
                        ylim=(limits[2] - margin, limits[3] + margin))

        # # recompute the ax.dataLim
        # self.ax.relim()
        # # update ax.viewLim using the new dataLim
        # self.ax.autoscale_view()
        return self

    def __exit__(self, exception_type, exception_value, traceback):
        if exception_type:
            logger.error(
                f"Exception type: {exception_type}; Exception value: {exception_value}; Traceback: {traceback}"
            )
        logger.info("Plotting ends.")
        if self.output:
            if self.ani:
                output = self.output + ".gif"
                logger.info(f"Saving animation as {output}")
                self.ani.save(output, writer=self.writer)
            else:
                output = self.output + ".png"
                logger.info(f"Saving plot as {output}")
                self.fig.savefig(output, dpi=300)
        plt.close(self.fig)

    def plot_human(self, step=-1):
        """Generate patches for human
        :param step: index of state, default is the latest
        :return: list of patches
        """
        states, _ = self.scene.get_states()
        current_state = states[step]
        # radius = 0.2 + np.linalg.norm(current_state[:, 2:4], axis=-1) / 2.0 * 0.3
        radius = [0.2] * current_state.shape[0]
        if self.human_actors:
            for i, human in enumerate(self.human_actors):
                human.center = current_state[i, :2]
                human.set_radius(0.2)
                # human.set_radius(radius[i])
        else:
            self.human_actors = [
                Circle(pos, radius=r)
                for pos, r in zip(current_state[:, :2], radius)
            ]
        self.human_collection.set_paths(self.human_actors)
        if not self.agent_colors:
            self.human_collection.set_array(np.arange(current_state.shape[0]))
        else:
            # set colors for each agent
            assert len(self.human_actors) == len(
                self.agent_colors
            ), "agent_colors must be the same length as the agents"
            self.human_collection.set_facecolor(self.agent_colors)

    def plot_groups(self, step=-1):
        """Generate patches for groups
        :param step: index of state, default is the latest
        :return: list of patches
        """
        states, group_states = self.scene.get_states()
        current_state = states[step]
        current_groups = group_states[step]
        if self.group_actors:  # update patches, else create
            points = [current_state[g, :2] for g in current_groups]
            for i, p in enumerate(points):
                self.group_actors[i].set_xy(p)
        else:
            self.group_actors = [
                Polygon(current_state[g, :2]) for g in current_groups
            ]

        self.group_collection.set_paths(self.group_actors)

    def plot_obstacles(self):
        for s in self.scene.get_obstacles():
            self.ax.add_patch(
                Rectangle((s[:, 0][0], s[:, 1][0]),
                          s[:, 0][-1] - s[:, 0][0],
                          s[:, 1][-1] - s[:, 1][0],
                          fill=True,
                          color="black"))

    def plot_fires(self):
        if self.scene.get_fires() is not None:
            f = self.scene.get_fires()[0]
            self.ax.add_patch(
                Rectangle((f[:, 0][0], f[:, 1][0]),
                          f[:, 0][-1] - f[:, 0][0],
                          f[:, 1][-1] - f[:, 1][0],
                          fill=True,
                          color="red"))
            if len(self.scene.get_fires()) > 1:
                b = self.scene.get_fires()[1]
                self.ax.add_patch(
                    Rectangle((b[:, 0][0], b[:, 1][0]),
                              b[:, 0][-1] - b[:, 0][0],
                              b[:, 1][-1] - b[:, 1][0],
                              fill=False,
                              color="red"))

    def plot_exits(self):
        if self.scene.get_exits() is not None:
            for e in self.scene.get_exits():
                # continue
                # self.ax.add_patch(Circle((e[0],e[1]), 1, fill=True, color="green", alpha=0.1))
                self.ax.add_patch(
                    Circle((e[0], e[1]),
                           e[2],
                           fill=True,
                           color="green",
                           alpha=0.1))

    def plot_smoke(self, step=-1):
        if self.scene.get_fires() is not None:
            f = self.scene.get_fires()[0]
            fcx = f[:, 0][0] + (f[:, 0][-1] - f[:, 0][0]) / 2
            fcy = f[:, 1][0] + (f[:, 1][-1] - f[:, 1][0]) / 2
            rad = self.scene.peds.get_smoke_radii()[step]
            self.ax.add_patch(
                Circle((fcx, fcy), rad, fill=True, color="black", alpha=0.005))

    def animation_init(self):
        self.plot_obstacles()
        self.plot_fires()
        self.plot_exits()
        self.ax.add_collection(self.group_collection)
        self.ax.add_collection(self.human_collection)

        return (self.group_collection, self.human_collection)

    def animation_update(self, i):
        self.plot_groups(i)
        self.plot_human(i)
        self.plot_smoke(i)
        return (self.group_collection, self.human_collection)

    def plot_data(self):
        fig, ax = plt.subplots()
        escaped = [
            i / self.scene.peds.get_nr_peds() * 100
            for i in self.scene.peds.escaped
        ]
        health = [i * 100 for i in self.scene.peds.av_health]
        panic = [i * 100 for i in self.scene.peds.av_panic]
        dead = [
            i / self.scene.peds.get_nr_peds() * 100
            for i in self.scene.peds.dead
        ]
        timesteps = [t for t in range(len(escaped))]
        ax.plot(timesteps, escaped, color="green", label="escaped")
        ax.plot(timesteps, health, color="red", label="health")
        ax.plot(timesteps, panic, color="purple", label="panic")
        ax.plot(timesteps, dead, color="black", label="dead")
        ax.set_xlabel("Timestep")
        ax.set_ylabel("[%]")
        ax.set_ylim([0, 100])
        ax.set_title(
            "Number of escaped and dead people and average health and panic.")
        ax.legend()
        ax.grid(linestyle="dotted")
        fig.savefig(self.output + "_data.png")
        logger.info("Created plot of data.")
예제 #6
0
for a in range(i):
    for b in range(j):

        ax = axes.axes_row[a][b]

        ax.set_xticks([])
        ax.set_yticks([])
        ax.set_frame_on(False)

        collection = PatchCollection([Polygon(face) for face in face_coords])
        ax.add_collection(collection)

        deviations, cmap = data_collection[a][b][to_plot]

        collection.set(array=deviations, cmap=cmap)

        ax.cax.colorbar(collection)

        contours = data_collection[a][b]["contours"]

        contours = PolyCollection(contours, closed=False, linewidth=1.0, facecolors='none', edgecolor="black")
        ax.add_collection(contours)

        mse_loss = data_collection[a][b]["mse_loss"]

        xlabel = "loss: {}".format(round(mse_loss, 2))
        ax.set_xlabel(xlabel)
        
        ax.set_aspect("equal")
        ax.autoscale(tight=True)
예제 #7
0
def plot_counties(
        ax,
        counties,
        values=None,
        edgecolors=None,
        contourcolor="white",
        hatch_surround=None,
        xlim=None,
        ylim=None,
        background=True,
        xticks=True,
        yticks=True,
        grid=True,
        frame=True,
        xlabel="Longitude [in dec. degrees]",
        ylabel="Latitude [in dec. degrees]",
        lw=1):
    polygons = [r["shape"] for r in counties.values()]
    # extend german borders :S and then shrink them again after unifying
    # gets rid of many holes at the county boundaries
    contour = cascaded_union([pol.buffer(0.01)
                              for pol in polygons]).buffer(-0.01)

    xmin, ymin, xmax, ymax = contour.bounds
    if xlim is None:
        xlim = [xmin, xmax]
    if ylim is None:
        ylim = [ymin, ymax]

    surround = PolygonPatch(Polygon([(xlim[0], ylim[0]), (xlim[0], ylim[1]), (
        xlim[1], ylim[1]), (xlim[1], ylim[0])]).difference(contour))
    contour = PolygonPatch(contour, lw=lw)

    pc = PatchCollection([PolygonPatch(p, lw=lw)
                          for p in polygons], cmap=matplotlib.cm.magma, alpha=1.0)


    

    

    if values is not None:
        if isinstance(values, (dict, OrderedDict)):
            values = np.array([values.setdefault(r, np.nan)
                               for r in counties.keys()])
        elif isinstance(values, str):
            values = np.array([r.setdefault(values, np.nan)
                               for r in counties.values()])
        else:
            assert np.size(values) == len(counties), "Number of values ({}) doesn't match number of counties ({})!".format(
                np.size(values), len(counties))
        pc.set_clim(0, 10)
        nans = np.isnan(values)
        values[nans] = 0

        values = np.ma.MaskedArray(values, mask=nans)
        pc.set(array=values, cmap='magma')
    else:
        pc.set_facecolors("none")

    if edgecolors is not None:
        if isinstance(edgecolors, (dict, OrderedDict)):
            edgecolors = np.array([edgecolors.setdefault(r, "none")
                                   for r in counties.keys()])
        elif isinstance(edgecolors, str):
            edgecolors = np.array([r.setdefault(edgecolors, "none")
                                   for r in counties.values()])
        pc.set_edgecolors(edgecolors)
    else:
        pc.set_edgecolors("none")

    if hatch_surround is not None:
        surround.set_hatch(hatch_surround)
        surround.set_facecolor("none")
        ax.add_patch(surround)

    cb = plt.colorbar(pc, shrink=0.6)
    cb.set_ticks([0,5,10])
    #cb.set_yticks([0.00004])
    ax.add_collection(pc)
    

    if contourcolor is not None:
        contour.set_edgecolor(contourcolor)
        contour.set_facecolor("none")
        ax.add_patch(contour)

    if isinstance(background, bool):
        ax.patch.set_visible(background)
    else:
        ax.patch.set_color(background)

    ax.grid(grid)

    ax.set_frame_on(frame)

    ax.set_xlim(*xlim)
    ax.set_ylim(*ylim)
    ax.set_aspect(1.43)
    if xlabel:
        ax.set_xlabel(xlabel, fontsize=14)
    if ylabel:
        ax.set_ylabel(ylabel, fontsize=14)

    ax.tick_params(axis="x", which="both", bottom=xticks, labelbottom=xticks)
    ax.tick_params(axis="y", which="both", left=yticks, labelleft=yticks)

    #plt.colorbar()
    

    return pc, contour, surround
def process_corrmatrix(out_dir, corrmatrix):
    # Pairwise Spearman correlations of log2 fold gene expression changes between each disorder and CTL in each brain region.
    # Cite: https://stackoverflow.com/questions/59381273/heatmap-with-circles-indicating-size-of-population

    N = 4
    M = 4
    ylabels = ["Parkinson", "Alzheimer"] * 2
    xlabels = ["Alzheimer", "Parkinson"] * 2
    biofluid_regions = ["Cerebrospinal", "Serum"]
    # names for positions along x-axis 0..9
    disorders_x = ["Alzheimer", "Parkinson"] * 2
    biofluid_regions_x = ["Cerebrospinal", "Cerebrospinal", "Serum", "Serum"]

    # names for positions along x-axis 0..9
    disorders_y = ["Parkinson", "Alzheimer"] * 2
    biofluid_regions_y = ["Serum", "Serum", "Cerebrospinal", "Cerebrospinal"]

    # size of circles
    s = np.zeros((N, M))

    for y in range(N):
        for x in range(M):
            lrt1 = "data/out/" + biofluid_regions_x[x] + "/" + disorders_x[
                x] + "/lrt.tsv"
            lrt2 = "data/out/" + biofluid_regions_y[y] + "/" + disorders_y[
                y] + "/lrt.tsv"
            # Make sure ltr1 exists otherwise zero correlation
            if not os.path.exists(lrt1):
                s[y][x] = 0.5
                continue
            # Make sure ltr2 exists otherwise zero correlation
            if not os.path.exists(lrt2):
                s[y][x] = 0.5
                continue
            if lrt1 != lrt2:
                df_x = pd.read_csv(lrt1, sep='\t', index_col=0)
                df_y = pd.read_csv(lrt2, sep='\t', index_col=0)
                corr = np.abs(df_x["log2FoldChange"].corr(
                    df_y["log2FoldChange"]))
                s[y][x] = corr
            else:
                s[y][x] = 0.0  #Dont set diagnols

    c = np.ones((N, M))

    fig, ax = plt.subplots(figsize=(11, 8))

    R = s / s.max() / 2
    x, y = np.meshgrid(np.arange(M), np.arange(N))
    circles = [
        plt.Circle((j, i), radius=r)
        for r, j, i in zip(R.flat, x.flat, y.flat)
    ]
    col = PatchCollection(circles)
    col.set(array=s.flatten(), cmap='coolwarm')
    ax.add_collection(col)

    ax.set(xticks=np.arange(M),
           yticks=np.arange(N),
           xticklabels=xlabels,
           yticklabels=ylabels)
    ax.set_xticks(np.arange(M + 1) - 0.5, minor=True)
    ax.set_yticks(np.arange(N + 1) - 0.5, minor=True)
    ax.grid(which='minor')
    ax.text(0, -0.9, "Cerebrospinal", size=20, color='red')
    ax.text(2, -0.9, "Serum", size=20, color='green')
    ax.text(3.55, 2, "Cerebrospinal", size=20, rotation=90, color='red')
    ax.text(3.55, 0, "Serum", size=20, rotation=90, color='green')

    fig.colorbar(col)
    plt.suptitle(corrmatrix["title"])
    plt.savefig(out_dir + "/corrmatrix.png")
    return
예제 #9
0
파일: vmap.py 프로젝트: sebmeng/flopy
    def plot_array(self, a, masked_values=None, **kwargs):
        """
        Plot an array.  If the array is three-dimensional, then the method
        will plot the layer tied to this class (self.layer).

        Parameters
        ----------
        a : numpy.ndarray
            Array to plot.
        masked_values : iterable of floats, ints
            Values to mask.
        **kwargs : dictionary
            keyword arguments passed to matplotlib.pyplot.patchcollection

        Returns
        -------
        quadmesh : matplotlib.collections.QuadMesh

        """
        if not isinstance(a, np.ndarray):
            a = np.array(a)

        if a.ndim == 2:
            plotarray = a[self.layer, :]
        elif a.ndim == 1:
            plotarray = a
        else:
            raise Exception('Array must be of dimension 1, 2 or 3')

        if masked_values is not None:
            for mval in masked_values:
                plotarray = np.ma.masked_equal(plotarray, mval)

        if 'ax' in kwargs:
            ax = kwargs.pop('ax')
        else:
            ax = self.ax

        xgrid = np.array(self.mg.xvertices)
        ygrid = np.array(self.mg.yvertices)

        patches = [Polygon(list(zip(xgrid[i], ygrid[i])), closed=True)
                   for i in range(xgrid.shape[0])]

        p = PatchCollection(patches)
        p.set_array(plotarray)

        if 'vmin' in kwargs:
            vmin = kwargs.pop('vmin')
        else:
            vmin = None

        if 'vmax' in kwargs:
            vmax = kwargs.pop('vmax')
        else:
            vmax = None

        p.set_clim(vmin=vmin, vmax=vmax)
        # send rest of kwargs to quadmesh
        p.set(**kwargs)

        ax.add_collection(p)
        ax.set_xlim(self.extent[0], self.extent[1])
        ax.set_ylim(self.extent[2], self.extent[3])
        return p
예제 #10
0
class SceneVisualizer:
    """Context for social nav vidualization"""
    def __init__(self,
                 scene,
                 output=None,
                 writer="imagemagick",
                 cmap="viridis",
                 **kwargs):
        self.scene = scene
        self.states, self.group_states = self.scene.get_states()
        self.cmap = cmap
        self.frames = self.scene.get_length()
        self.output = output
        self.writer = writer

        self.fig, self.ax = plt.subplots(**kwargs)

        self.ani = None

        self.group_actors = None
        self.group_collection = PatchCollection([])
        self.group_collection.set(
            animated=True,
            alpha=0.2,
            cmap=self.cmap,
            facecolors="none",
            edgecolors="purple",
            linewidth=2,
            clip_on=True,
        )

        self.human_actors = None
        self.human_collection = PatchCollection([])
        self.human_collection.set(animated=True,
                                  alpha=0.6,
                                  cmap=self.cmap,
                                  clip_on=True)

    def plot(self):
        """Main method for create plot"""
        self.plot_obstacles()
        groups = self.group_states[0]  # static group for now
        if not groups:
            for ped in range(self.scene.peds.size()):
                x = self.states[:, ped, 0]
                y = self.states[:, ped, 1]
                self.ax.plot(x, y, "-o", label=f"ped {ped}", markersize=2.5)
        else:

            colors = plt.cm.rainbow(np.linspace(0, 1, len(groups)))

            for i, group in enumerate(groups):
                for ped in group:
                    x = self.states[:, ped, 0]
                    y = self.states[:, ped, 1]
                    self.ax.plot(x,
                                 y,
                                 "-o",
                                 label=f"ped {ped}",
                                 markersize=2.5,
                                 color=colors[i])
        self.ax.legend()
        return self.fig

    def animate(self):
        """Main method to create animation"""

        self.ani = mpl_animation.FuncAnimation(
            self.fig,
            init_func=self.animation_init,
            func=self.animation_update,
            frames=self.frames,
            blit=True,
        )

        return self.ani

    def __enter__(self):
        logger.info("Start plotting.")
        self.fig.set_tight_layout(True)
        self.ax.grid(linestyle="dotted")
        self.ax.set_aspect("equal")
        self.ax.margins(2.0)
        self.ax.set_axisbelow(True)
        self.ax.set_xlabel("x [m]")
        self.ax.set_ylabel("y [m]")

        plt.rcParams["animation.html"] = "jshtml"

        # x, y limit from states, only for animation
        margin = 2.0
        xy_limits = np.array([minmax(state) for state in self.states
                              ])  # (x_min, y_min, x_max, y_max)
        xy_min = np.min(xy_limits[:, :2], axis=0) - margin
        xy_max = np.max(xy_limits[:, 2:4], axis=0) + margin
        self.ax.set(xlim=(xy_min[0], xy_max[0]), ylim=(xy_min[1], xy_max[1]))

        # # recompute the ax.dataLim
        # self.ax.relim()
        # # update ax.viewLim using the new dataLim
        # self.ax.autoscale_view()
        return self

    def __exit__(self, exception_type, exception_value, traceback):
        if exception_type:
            logger.error(
                f"Exception type: {exception_type}; Exception value: {exception_value}; Traceback: {traceback}"
            )
        logger.info("Plotting ends.")
        if self.output:
            if self.ani:
                output = self.output + ".gif"
                logger.info(f"Saving animation as {output}")
                self.ani.save(output, writer=self.writer)
            else:
                output = self.output + ".png"
                logger.info(f"Saving plot as {output}")
                self.fig.savefig(output, dpi=300)
        plt.close(self.fig)

    def plot_human(self, step=-1):
        """Generate patches for human
        :param step: index of state, default is the latest
        :return: list of patches
        """
        states, _ = self.scene.get_states()
        current_state = states[step]
        # radius = 0.2 + np.linalg.norm(current_state[:, 2:4], axis=-1) / 2.0 * 0.3
        radius = [0.2] * current_state.shape[0]
        if self.human_actors:
            for i, human in enumerate(self.human_actors):
                human.center = current_state[i, :2]
                human.set_radius(0.2)
                # human.set_radius(radius[i])
        else:
            self.human_actors = [
                Circle(pos, radius=r)
                for pos, r in zip(current_state[:, :2], radius)
            ]
        self.human_collection.set_paths(self.human_actors)
        self.human_collection.set_array(np.arange(current_state.shape[0]))

    def plot_groups(self, step=-1):
        """Generate patches for groups
        :param step: index of state, default is the latest
        :return: list of patches
        """
        states, group_states = self.scene.get_states()
        current_state = states[step]
        current_groups = group_states[step]
        if self.group_actors:  # update patches, else create
            points = [current_state[g, :2] for g in current_groups]
            for i, p in enumerate(points):
                self.group_actors[i].set_xy(p)
        else:
            self.group_actors = [
                Polygon(current_state[g, :2]) for g in current_groups
            ]

        self.group_collection.set_paths(self.group_actors)

    def plot_obstacles(self):
        for s in self.scene.get_obstacles():
            self.ax.plot(s[:, 0], s[:, 1], "-o", color="black", markersize=2.5)

    def animation_init(self):
        self.plot_obstacles()
        self.ax.add_collection(self.group_collection)
        self.ax.add_collection(self.human_collection)

        return (self.group_collection, self.human_collection)

    def animation_update(self, i):
        self.plot_groups(i)
        self.plot_human(i)
        return (self.group_collection, self.human_collection)
예제 #11
0
def plot_fibonacci_spiral(
    number_of_squares,
    numbers=True,
    arc=True,
    cmap="Blues",
    alpha=1,
    golden_ratio=False,
    filename="plot.png",
):
    """Short summary.

    Parameters
    ----------
    number_of_squares : type
        Description of parameter `number_of_squares`.
    numbers : type
        Description of parameter `numbers`.
    arc : type
        Description of parameter `arc`.
    cmap : type
        Description of parameter `cmap`.
    alpha : type
        Description of parameter `alpha`.
    golden_ratio : type
        Description of parameter `golden_ratio`.

    Returns
    -------
    type
        Description of returned object.

    """
    fibs = list(fib(number_of_squares))
    x = 0
    y = 0
    angle = 180
    center = (x + fibs[0], y + fibs[0])
    rectangles = []
    xs, ys = [], []

    fig, ax = plt.subplots(1, figsize=(16, 16))
    for i, side in enumerate(fibs):

        rectangles.append(Rectangle([x, y], side, side))
        if numbers and i > number_of_squares - 8:
            ax.annotate(side,
                        xy=(x + 0.45 * side, y + 0.45 * side),
                        fontsize=14)

        if arc:
            this_arc = Arc(
                center,
                2 * side,
                2 * side,
                angle=angle,
                theta1=0,
                theta2=90,
                edgecolor="black",
                antialiased=True,
            )
            ax.add_patch(this_arc)
        angle += 90

        xs.append(x)
        ys.append(y)
        if i == 0:
            x += side
            center = (x, y + side)
        elif i == 1:
            x -= side
            y += side
            center = (x, y)
        elif i in range(2, i + 1, 4):
            x -= side + previous_side
            y -= previous_side
            center = (x + side + previous_side, y)
        elif i in range(3, i + 1, 4):
            y -= side + previous_side
            center = (x + side + previous_side, y + side + previous_side)
        elif i in range(4, i + 1, 4):
            x += side
            center = (x, y + side + previous_side)
        elif i in range(5, i + 1, 4):
            x -= previous_side
            y += side
            center = (x, y)
        previous_side = side

    col = PatchCollection(rectangles, alpha=alpha, edgecolor="black")
    try:
        col.set(array=np.asarray(range(number_of_squares + 1)), cmap=cmap)
    except ValueError:
        print(f" '{cmap}' is an invalid colormap, choose a valid one from "
              "https://matplotlib.org/examples/color/colormaps_reference.html"
              " - returning to default 'Blues' colormap")
        col.set(array=np.asarray(range(number_of_squares + 1)), cmap="Blues")

    ax.add_collection(col)
    ax.set_aspect("equal", "box")
    ax.set_xticks([])
    ax.set_yticks([])

    xmin = np.min(xs)
    ymin = np.min(ys)
    xmax = np.max(xs) + fibs[np.argmax(xs)]
    ymax = np.max(ys) + fibs[np.argmax(ys)]
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    gr = str(fibs[i] / fibs[i - 1])
    if golden_ratio:
        plt.title(r"$\varphi$ = " + gr)
    plt.tight_layout()
    plt.savefig(filename)
    collection = PatchCollection([Polygon(face) for face in face_coords])
    ax.add_collection(collection)

    dataset = data_keys[i - 1]
    data = data_collection[dataset]["values"]
    cmap = data_collection[dataset]["cmap"]
    bins = data_collection[dataset].get("bins")

    if bins:
        bins = np.amax(data) + 1
        ticks = range(bins)

    cmap = plt.get_cmap(cmap, lut=bins)

    collection.set(array=data, cmap=cmap, edgecolor=None)

    if bins:
        plt.colorbar(collection, label=dataset, ticks=ticks, aspect=50)
    else:
        plt.colorbar(collection, label=dataset, aspect=50)

    # add contour plots
    # contours = PolyCollection(contour_coords, closed=False, linewidth=1.0, facecolors='none')
    # ax.add_collection(contours)

    title = "K: {}/ Epochs: {} / MSE: {}".format(n_clusters, epochs,
                                                 round(mse_loss, 2))

    ax.set_title(title)
    ax.set_aspect("equal")
예제 #13
0
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle
import numpy as np

N = 100  # Number of rectangles
x_list = np.random.random(N)
y_list = np.random.random(N)
w_list = 0.1 * np.random.random(N)
h_list = 0.1 * np.random.random(N)
patches = []

x_list = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
y_list = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
w_list = [0.1] * 10
h_list = [0.1] * 10

for x, y, w, h in zip(x_list, y_list, w_list, h_list):
    rectangle = Rectangle((x, y), w, h)
    patches.append(rectangle)

fig = plt.figure()
ax = fig.add_subplot(111)

col = PatchCollection(patches, cmap=cm.jet, alpha=0.4)
col.set(array=np.array(x_list), cmap='jet')
ax.add_collection(col)
plt.colorbar(col)

plt.show()
    def plot_array(self, a, masked_values=None, **kwargs):
        """
        Plot an array.  If the array is three-dimensional, then the method
        will plot the layer tied to this class (self.layer).

        Parameters
        ----------
        a : numpy.ndarray
            Array to plot.
        masked_values : iterable of floats, ints
            Values to mask.
        **kwargs : dictionary
            keyword arguments passed to matplotlib.pyplot.pcolormesh

        Returns
        -------
        quadmesh : matplotlib.collections.QuadMesh or
            matplotlib.collections.PatchCollection

        """
        if not isinstance(a, np.ndarray):
            a = np.array(a)

        if self.mg.grid_type == "structured":
            if a.ndim == 3:
                plotarray = a[self.layer, :, :]
            elif a.ndim == 2:
                plotarray = a
            elif a.ndim == 1:
                plotarray = a
            else:
                raise Exception('Array must be of dimension 1, 2, or 3')

        elif self.mg.grid_type == "vertex":
            if a.ndim == 2:
                plotarray = a[self.layer, :]
            elif a.ndim == 1:
                plotarray = a
            else:
                raise Exception('Array must be of dimension 1 or 2')

        elif self.mg.grid_type == "unstructured":
            plotarray = a

        else:
            raise TypeError("Unrecognized grid type {}".format(
                self.mg.grid_type))

        if masked_values is not None:
            for mval in masked_values:
                plotarray = np.ma.masked_equal(plotarray, mval)

        if 'ax' in kwargs:
            ax = kwargs.pop('ax')
        else:
            ax = self.ax

        if self.mg.grid_type in ("structured", "vertex"):
            xgrid = np.array(self.mg.xvertices)
            ygrid = np.array(self.mg.yvertices)

            if self.mg.grid_type == "structured":
                quadmesh = ax.pcolormesh(xgrid, ygrid, plotarray)

            else:
                patches = [
                    Polygon(list(zip(xgrid[i], ygrid[i])), closed=True)
                    for i in range(xgrid.shape[0])
                ]

                quadmesh = PatchCollection(patches)
                quadmesh.set_array(plotarray)

        else:
            quadmesh = plotutil.plot_cvfd(self.mg._vertices,
                                          self.mg._iverts,
                                          a=a,
                                          ax=ax)

        # set max and min
        if 'vmin' in kwargs:
            vmin = kwargs.pop('vmin')
        else:
            vmin = None

        if 'vmax' in kwargs:
            vmax = kwargs.pop('vmax')
        else:
            vmax = None

        quadmesh.set_clim(vmin=vmin, vmax=vmax)

        # send rest of kwargs to quadmesh
        quadmesh.set(**kwargs)

        # add collection to axis
        ax.add_collection(quadmesh)

        # set limits
        ax.set_xlim(self.extent[0], self.extent[1])
        ax.set_ylim(self.extent[2], self.extent[3])
        return quadmesh