Esempio n. 1
0
 def test_patch(self):
     geo = self.polygon.__geo_interface__
     patch = PolygonPatch(geo)
     self.failUnlessEqual(str(type(patch)), 
         "<class 'matplotlib.patches.PathPatch'>")
     path = patch.get_path()
     self.failUnless(len(path.vertices) == len(path.codes) == 198)
Esempio n. 2
0
    def plot(self, type_='pose', alpha=0.5, **kwargs):
        """Plot either the pose or point feasible regions.

        Parameters
        ----------
        type_ : {'pose','point'}
            The type of feasible region to plot.
        alpha : int
            Feasible region patch transparency
        **kwargs
            Arguements passed to PolygonPatch
        """
        if type_ == "pose":
            p = self.pose_region
        else:
            p = self.point_region

        ax.set_xlim([self.bounds[0], self.bounds[2]])
        ax.set_ylim([self.bounds[1], self.bounds[3]])

        self.patch = PolygonPatch(p, facecolor=cnames['black'],
                                  alpha=alpha, zorder=2, **kwargs)
        ax.add_patch(self.patch)

        plt.show()
Esempio n. 3
0
        def plot(self):
            levels_res = 50
            self.levels = np.linspace(0, np.max(self.gm.pdf(self.pos)), levels_res)
            self.contourf = self.ax.contourf(self.xx, self.yy,
                                               self.gm.pdf(self.pos),
                                               levels=self.levels,
                                               cmap=plt.get_cmap('jet')
                                               )
            # Plot camera
            self.cam_patch = PolygonPatch(self.detection_model.poly, facecolor='none',
                                          linewidth=2, edgecolor='white')
            self.ax.add_patch(self.cam_patch)

            # Plot ellipses
            self.ellipse_patches = self.gm.plot_ellipses(poly=self.detection_model.poly)
Esempio n. 4
0
def draw_zone_map(ax, sf, shp_dic, heat={}, text=[], arrows=[]):
    continent = [235 / 256, 151 / 256, 78 / 256]
    ocean = (89 / 256, 171 / 256, 227 / 256)
    theta = np.linspace(0, 2 * np.pi, len(text) + 1).tolist()
    ax.set_facecolor(ocean)

    # colorbar
    if len(heat) != 0:
        norm = mpl.colors.Normalize(vmin=0, vmax=max(
            heat.values()))  # norm = mpl.colors.LogNorm(vmin=1,vmax=max(heat))
        cm = plt.get_cmap('Reds')
        sm = plt.cm.ScalarMappable(cmap=cm, norm=norm)
        sm.set_array([])
        plt.colorbar(sm,
                     ticks=np.linspace(0, max(heat.values()), 8),
                     boundaries=np.arange(0 - 10,
                                          max(heat.values()) + 10, 0.1))

    for sr in sf.shapeRecords():
        shape = sr.shape
        rec = sr.record
        loc_id = rec[shp_dic['LocationID']]
        zone = rec[shp_dic['zone']]

        if len(heat) == 0:
            col = continent
        else:
            if loc_id not in heat:
                R, G, B, A = cm(norm(0))
            else:
                R, G, B, A = cm(norm(heat[loc_id]))
            col = [R, G, B]

        # check number of parts (could use MultiPolygon class of shapely?)
        nparts = len(shape.parts)  # total parts
        if nparts == 1:
            polygon = Polygon(shape.points)
            patch = PolygonPatch(polygon, facecolor=col, alpha=1.0, zorder=2)
            ax.add_patch(patch)
        else:  # loop over parts of each shape, plot separately
            for ip in range(nparts):  # loop over parts, plot separately
                i0 = shape.parts[ip]
                if ip < nparts - 1:
                    i1 = shape.parts[ip + 1] - 1
                else:
                    i1 = len(shape.points)

                polygon = Polygon(shape.points[i0:i1 + 1])
                patch = PolygonPatch(polygon,
                                     facecolor=col,
                                     alpha=1.0,
                                     zorder=2)
                ax.add_patch(patch)

        x = (shape.bbox[0] + shape.bbox[2]) / 2
        y = (shape.bbox[1] + shape.bbox[3]) / 2
        if (len(text) == 0 and rec[shp_dic['Shape_Area']] > 0.0001):
            plt.text(x,
                     y,
                     str(loc_id),
                     horizontalalignment='center',
                     verticalalignment='center')
        elif len(text) != 0 and loc_id in text:
            #plt.text(x+0.01, y-0.01, str(loc_id), fontsize=12, color="white", bbox=dict(facecolor='black', alpha=0.5))
            eta_x = 0.05 * np.cos(theta[text.index(loc_id)])
            eta_y = 0.05 * np.sin(theta[text.index(loc_id)])
            ax.annotate("[{}] {}".format(loc_id, zone),
                        xy=(x, y),
                        xytext=(x + eta_x, y + eta_y),
                        bbox=dict(facecolor='black', alpha=0.5),
                        color="white",
                        fontsize=12,
                        arrowprops=dict(facecolor='black',
                                        width=3,
                                        shrink=0.05))
    if len(arrows) != 0:
        for arr in arrows:
            ax.annotate('',
                        xy=arr['dest'],
                        xytext=arr['src'],
                        size=arr['cnt'],
                        arrowprops=dict(arrowstyle="fancy",
                                        fc="0.6",
                                        ec="none"))

    # display
    limits = get_boundaries(sf)
    plt.xlim(limits[0], limits[1])
    plt.ylim(limits[2], limits[3])
Esempio n. 5
0
def plot_polygon_collection(ax,
                            geoms,
                            values=None,
                            color=None,
                            cmap=None,
                            vmin=None,
                            vmax=None,
                            **kwargs):
    """
    Plots a collection of Polygon and MultiPolygon geometries to `ax`

    Parameters
    ----------

    ax : matplotlib.axes.Axes
        where shapes will be plotted

    geoms : a sequence of `N` Polygons and/or MultiPolygons (can be mixed)

    values : a sequence of `N` values, optional
        Values will be mapped to colors using vmin/vmax/cmap. They should
        have 1:1 correspondence with the geometries (not their components).
        Otherwise follows `color` / `facecolor` kwargs.

    edgecolor : single color or sequence of `N` colors
        Color for the edge of the polygons

    facecolor : single color or sequence of `N` colors
        Color to fill the polygons. Cannot be used together with `values`.

    color : single color or sequence of `N` colors
        Sets both `edgecolor` and `facecolor`

    **kwargs
        Additional keyword arguments passed to the collection

    Returns
    -------

    collection : matplotlib.collections.Collection that was plotted
    """

    try:
        from descartes.patch import PolygonPatch
    except ImportError:
        raise ImportError("The descartes package is required"
                          " for plotting polygons in geopandas.")
    from matplotlib.collections import PatchCollection

    geoms, values = _flatten_multi_geoms(geoms, values)
    if None in values:
        values = None

    # PatchCollection does not accept some kwargs.
    if 'markersize' in kwargs:
        del kwargs['markersize']

    # color=None overwrites specified facecolor/edgecolor with default color
    if color is not None:
        kwargs['color'] = color

    collection = PatchCollection([PolygonPatch(poly) for poly in geoms],
                                 **kwargs)

    if values is not None:
        collection.set_array(np.asarray(values))
        collection.set_cmap(cmap)
        collection.set_clim(vmin, vmax)

    ax.add_collection(collection, autolim=True)
    ax.autoscale_view()
    return collection
Esempio n. 6
0
    class camera_tester(object):
        """docstring for merged_gm"""
        def __init__(self, prior, detection_model, trajectory, num_std=1, bounds=None):
            self.fig = plt.figure(figsize=(16,8))
            self.gm = prior
            self.detection_model = detection_model
            self.trajectory = itertools.cycle(trajectory)
            self.vb = VariationalBayes()
            self.num_std = num_std
            if bounds is None:
                self.bounds = [-5, -5, 5, 5]
            else:
                self.bounds = bounds

        def update(self,i=0):
            self.camera_pose = next(self.trajectory)
            logging.info('Moving to pose {}.'.format(self.camera_pose))
            self.detection_model.move(self.camera_pose)

            # Do a VBIS update
            mu, sigma, beta = self.vb.update(measurement='No Detection',
                                        likelihood=detection_model,
                                        prior=self.gm,
                                        use_LWIS=True,
                                        poly=detection_model.poly,
                                        num_std=self.num_std
                                        )
            self.gm = GaussianMixture(weights=beta, means=mu, covariances=sigma)
            # Log what's going on
            logging.info(self.gm)
            logging.info('Weight sum: {}'.format(beta.sum()))

            self.remove()
            self.plot()

        def plot(self):
            levels_res = 50
            self.levels = np.linspace(0, np.max(self.gm.pdf(self.pos)), levels_res)
            self.contourf = self.ax.contourf(self.xx, self.yy,
                                               self.gm.pdf(self.pos),
                                               levels=self.levels,
                                               cmap=plt.get_cmap('jet')
                                               )
            # Plot camera
            self.cam_patch = PolygonPatch(self.detection_model.poly, facecolor='none',
                                          linewidth=2, edgecolor='white')
            self.ax.add_patch(self.cam_patch)

            # Plot ellipses
            self.ellipse_patches = self.gm.plot_ellipses(poly=self.detection_model.poly)

        def plot_setup(self):
            # Define gridded space for graphing
            min_x, max_x = self.bounds[0], self.bounds[2]
            min_y, max_y = self.bounds[1], self.bounds[3]
            res = 30
            self.xx, self.yy = np.mgrid[min_x:max_x:1/res,
                                        min_y:max_y:1/res]
            pos = np.empty(self.xx.shape + (2,))
            pos[:, :, 0] = self.xx; pos[:, :, 1] = self.yy;
            self.pos = pos

            # Plot setup
            self.ax = self.fig.add_subplot(111)

            self.ax.set_title('VBIS with camera detection test')
            plt.axis('scaled')
            self.ax.set_xlim([min_x, max_x])
            self.ax.set_ylim([min_y, max_y])

            levels_res = 50
            self.levels = np.linspace(0, np.max(self.gm.pdf(self.pos)), levels_res)
            cax = self.contourf = self.ax.contourf(self.xx, self.yy,
                                               self.gm.pdf(self.pos),
                                               levels=self.levels,
                                               cmap=plt.get_cmap('jet')
                                               )
            self.fig.colorbar(cax)

        def remove(self):
            if hasattr(self, 'cam_patch'):
                self.cam_patch.remove()
                del self.cam_patch

            if hasattr(self, 'ellipse_patches'):
                for patch in self.ellipse_patches:
                    patch.remove()
                del self.ellipse_patches

            if hasattr(self,'contourf'):
                for collection in self.contourf.collections:
                    collection.remove()
                del self.contourf
Esempio n. 7
0
with open('noise_info0.pickle', 'wb') as f:
    pickle.dump(noise_info0, f, protocol=2)

fig1 = plt.figure(figsize=(15, 10), dpi=1000)
plt.title('Average Seismic Noise Second Peak Maximum PDS\n S Network | 2014')
plt.xlabel('Longitude (degrees)')
plt.ylabel('Latitude (degrees)')
cm = plt.cm.get_cmap('RdYlBu')
cmin, cmax = np.min(noise_info1[:, 2]), np.max(noise_info1[:, 2])
sc = plt.scatter(noise_info1[:, 0],
                 noise_info1[:, 1],
                 c=noise_info1[:, 2],
                 norm=LogNorm(vmin=100, vmax=3e4),
                 s=35,
                 cmap=cm)

col = plt.colorbar(sc)
col.ax.set_ylabel('Maximum Power Density Spectrum (V RMS)')

if shape_path is not None and UNIQUE_SHAPE is not None:
    patch = PolygonPatch(UNIQUE_SHAPE, facecolor='white',\
    edgecolor='k', zorder=1)
    ax = fig.add_subplot(111)
    ax.add_patch(patch)

fig1.savefig('station_pds_maxima/Peak2 PDS Average Maxima 2014.svg',
             format='SVG')

with open('noise_info1.pickle', 'wb') as f:
    pickle.dump(noise_info1, f, protocol=2)
def plot_2d_cluster_ellipsoids(clusters_loc,
                               clusters_cov,
                               data=None,
                               std_levels=[1, 2],
                               labels=None,
                               ax=None,
                               legend=False,
                               cl_names=None,
                               cl_colors=None):

    n_levels = len(std_levels)
    if isinstance(clusters_loc, list):
        n_clusters = len(clusters_loc)
    elif isinstance(clusters_loc, np.ndarray):  # not supper robust here
        n_clusters = clusters_loc.shape[0]
    elif isinstance(clusters_loc, dict):
        n_clusters = len(clusters_loc)
    else:
        print("Invalid input")
        return

    cluster_ellipsoids = np.zeros((n_clusters, n_levels), dtype=object)

    for cl in range(n_clusters):
        for jj, level in enumerate(std_levels):
            cluster_ellipsoids[cl, jj] = \
                get_2d_confidence_ellipse(mu=clusters_loc[cl], cov=clusters_cov[cl], n_std=level)

    if cl_colors is None:
        cl_colors = colors
    elif isinstance(cl_colors, str):
        cl_colors = [cl_colors]

    n_colors = len(cl_colors)

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

    label_patch = []
    if data is not None:
        ax.scatter(data[:, 0],
                   data[:, 1],
                   c=np.array(colors)[labels],
                   alpha=0.2)
        facecolors = ['grey'] * n_clusters
    else:
        facecolors = cl_colors

    if cl_names is None:
        cl_names = ['cl' + str(cl) for cl in range(n_clusters)]

    for cl in range(n_clusters):
        for jj, level in enumerate(std_levels):
            patch = PolygonPatch(cluster_ellipsoids[cl, jj],
                                 facecolor=facecolors[np.mod(cl, n_colors)],
                                 alpha=0.3)
            ax.add_patch(patch)

        label_patch.append(
            mpatches.Patch(color=facecolors[np.mod(cl, n_colors)],
                           label=cl_names[cl],
                           alpha=0.7))

    if legend:
        ax.legend(handles=label_patch, frameon=False, loc=(1.05, 0))

    _ = ax.axis('scaled')

    return ax
Esempio n. 9
0
def plot_background(ax, obj_polygon):
    background_patch = PolygonPatch(obj_polygon,
                                    facecolor=DARK_25, edgecolor=DARK_90, alpha=0.4, zorder=2)
    ax.add_patch(background_patch)
Esempio n. 10
0
if path is None:
    exit()

outside = multiLevelPoly.bounds
outside = Polygon([(outside[0], outside[1]), (outside[0], outside[3]),
                   (outside[2], outside[3]), (outside[2], outside[1])])

#ploting
fig = pyplot.figure(1)
ax = fig.add_subplot(111)

for p in multiLevelPoly:
    patch = PolygonPatch(p,
                         facecolor=methods.v_color(p),
                         edgecolor=methods.v_color(p),
                         alpha=0.5,
                         zorder=2)
    ax.add_patch(patch)

ax.text(args["s"][0] + 7,
        args["s"][1] + 15,
        r'$\sigma_{\mathit{init}}$',
        fontsize=13)
methods.plot_coords(ax, Point(args["s"]), c="#00FF00", z=6)

ax.text(args["t"][0] - 30,
        args["t"][1] + 11,
        r'$\Sigma_{\mathit{goal}}$',
        fontsize=13)
methods.plot_coords(ax, Point(args["t"]), c="#FF0000", z=6)
Esempio n. 11
0
    def roll_out(self,
                 init_obj_pose,
                 show_final_only=True,
                 show_init=False,
                 discrtimestep=2e-1,
                 t_max=5):
        self.obj.update_pose(init_obj_pose)
        pose = init_obj_pose
        pusher1 = copy.copy(self.pusher1)
        pusher2 = copy.copy(self.pusher2)

        if show_init:
            patch = PolygonPatch(self.obj.poly_world, alpha=0.25, zorder=2)
            self.ax.add_patch(patch)

        # print ('--- start simulation ---')
        start_time = time.time()
        contacts_in_world = self.obj.eval_contact_with_2pushers(
            pusher1, pusher2, pose)

        if contacts_in_world[IN_CONTACT]:
            contact_points = []
            contact_normals = []
            v_pushes = []
            for i in range(len(contacts_in_world[POINTS])):
                contact_points.append(
                    np.dot(np.linalg.inv(pose),
                           np.hstack((contacts_in_world[POINTS][i], 1.)))[:2])
                contact_normals.append(
                    np.dot(np.linalg.inv(pose[:2, :2]),
                           contacts_in_world[NORMALS][i]))
                v_pushes.append(
                    np.dot(np.linalg.inv(pose[:2, :2]),
                           contacts_in_world[V_PUSHES][i]))
            contacts = contact_points, contact_normals, v_pushes, contacts_in_world[
                IN_CONTACT]
            if len(contacts[POINTS]) == 1:  # single contact
                v_obj, contact_mode = self.motion.compute_vel_single_contact(
                    contacts[V_PUSHES][0], contacts[POINTS][0],
                    contacts[NORMALS][0], self.contact_mu, self.obj.ls_coeff)
            else:  # multi contacts
                v_obj = self.motion.compute_vel_multi_contacts(
                    contacts[V_PUSHES], contacts[POINTS], contacts[NORMALS],
                    self.contact_mu, self.obj.ls_A)
                if np.linalg.norm(v_obj) < 1e-3:
                    print 'JAMMING or STOP MOVING'
        else:
            print 'NO CONTACT'

        t_contact = contacts_in_world[TIME]
        pusher1.update_pusher(pusher1.eval_pusher(t_contact))
        pusher2.update_pusher(pusher2.eval_pusher(t_contact))
        # IPython.embed()
        t = 0
        previous_pose = self.obj.pose
        while t < t_max:
            pose = self.obj.eval_pose(discrtimestep, v_obj)

            new_poly = self.obj.compute_poly(pose)
            pusher1.update_pusher(pusher1.eval_pusher(discrtimestep))
            pusher2.update_pusher(pusher2.eval_pusher(discrtimestep))
            if pusher1.poly.intersects(new_poly) or pusher2.poly.intersects(
                    new_poly):
                if discrtimestep > 1e-5:
                    print discrtimestep
                    pusher1.update_pusher(pusher1.eval_pusher(-discrtimestep))
                    pusher2.update_pusher(pusher2.eval_pusher(-discrtimestep))
                    discrtimestep = discrtimestep / 10.
                    continue
                else:
                    break
            t += discrtimestep
            contacts_in_world = self.obj.eval_contact_with_2pushers(
                pusher1, pusher2, pose, tolerance=10. * discrtimestep)
            if contacts_in_world[IN_CONTACT]:
                self.obj.update_pose(pose)
                if not show_final_only:
                    # self.plot_pusher(self.ax,pusher1.poly)
                    # self.plot_pusher(self.ax,pusher2.poly)
                    patch = PolygonPatch(self.obj.poly_world,
                                         alpha=0.25,
                                         zorder=2)
                    for pt in contacts_in_world[POINTS]:
                        self.ax.add_patch(patch)
                        self.ax.plot(pt[0], pt[1], 'o', color='#999999')
            else:
                if len(contacts_in_world[POINTS]) == 0:
                    print 'No contact'
                    break
            contact_points = []
            contact_normals = []
            v_pushes = []

            for i in range(len(contacts_in_world[POINTS])):
                contact_points.append(
                    np.dot(np.linalg.inv(pose),
                           np.hstack((contacts_in_world[POINTS][i], 1.)))[:2])
                contact_normals.append(
                    np.dot(np.linalg.inv(pose[:2, :2]),
                           contacts_in_world[NORMALS][i]))
                v_pushes.append(
                    np.dot(np.linalg.inv(pose[:2, :2]),
                           contacts_in_world[V_PUSHES][i]))
            contacts = contact_points, contact_normals, v_pushes, contacts_in_world[
                IN_CONTACT]

            if len(contacts[POINTS]) == 1:  # single contact
                v_obj, contact_mode = self.motion.compute_vel_single_contact(
                    contacts[V_PUSHES][0], contacts[POINTS][0],
                    contacts[NORMALS][0], self.contact_mu, self.obj.ls_coeff)
                # print 'single contact'
            else:  # multi contacts
                v_obj = self.motion.compute_vel_multi_contacts(
                    contacts[V_PUSHES], contacts[POINTS], contacts[NORMALS],
                    self.contact_mu, self.obj.ls_A)
                # print 'multiple contacts'
            # print contacts_in_world[POINTS]
            # print v_obj
            # raw_input()

            if np.linalg.norm(previous_pose - pose) < 1e-4:
                print 'STOP MOVING'
                break
            else:
                previous_pose = pose
            if np.linalg.norm(v_obj[:2]) + np.abs(v_obj[2]) < 1e-5:
                print 'STOP MOVING'
                print 'at t=', t, 's'
                break

        print("--- %s seconds ---" % (time.time() - start_time))
        # print 'Final obj pose: ', self.obj.pose
        patch = PolygonPatch(self.obj.poly_world,
                             color='b',
                             alpha=0.2,
                             zorder=2)
        self.ax.add_patch(patch)
        # self.plot_pusher(self.ax,pusher1.poly)
        # self.plot_pusher(self.ax,pusher2.poly)
        # IPython.embed()
        return self.obj.pose
fig = pyplot.figure(1, figsize=SIZE, dpi=90)

# 1: valid polygon
ax = fig.add_subplot(121)

ext = [(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)]
int = [(1, 0), (0.5, 0.5), (1, 1), (1.5, 0.5), (1, 0)][::-1]
polygon = Polygon(ext, [int])

plot_coords(ax, polygon.interiors[0])
plot_coords(ax, polygon.exterior)

patch = PolygonPatch(polygon,
                     facecolor=v_color(polygon),
                     edgecolor=v_color(polygon),
                     alpha=0.5,
                     zorder=2)
ax.add_patch(patch)

ax.set_title('a) valid')

xrange = [-1, 3]
yrange = [-1, 3]
ax.set_xlim(*xrange)
ax.set_xticks(range(*xrange) + [xrange[-1]])
ax.set_ylim(*yrange)
ax.set_yticks(range(*yrange) + [yrange[-1]])
ax.set_aspect(1)

#2: invalid self-touching ring
Esempio n. 13
0
class FeasibleLayer(Layer):
    """A representation of feasible map regions.

    A polygon (or collection of polygons) that represent feasible
    regions of the map. Feasible can be defined as either feasible robot
    poses or unoccupied space.

    .. image:: img/classes_Feasible_Layer.png

    Parameters
    ----------
    max_robot_radius : float, optional
        The maximum radius of a circular approximation to the robot, used
        to determine the feasible pose regions.
    **kwargs
        Arguments passed to the ``Layer`` superclass.

    """
    def __init__(self, max_robot_radius=0.20, **kwargs):
        super(FeasibleLayer, self).__init__(**kwargs)
        self.max_robot_radius = max_robot_radius  # [m] conservative estimate

        self.point_region = None
        self.pose_region = None
        # self.define_feasible_regions()

    def define_feasible_regions(self, static_elements):
        """Generate the feasible regions from a dictionary of static map elements.

        Parameters
        ----------
        static_elements : dict
            A dictionary of map elements
        """
        # TODO: feasible space should depend on map bounds, not layer bounds
        feasible_space = box(*self.bounds)
        self.point_region = feasible_space
        self.pose_region = feasible_space.buffer(-self.max_robot_radius)

        for element in static_elements:
            # Ignore MapAreas
            if isinstance(element, MapObject):
                self.point_region = self.point_region.difference(element.shape)

                buffered_shape = element.shape.buffer(self.max_robot_radius)
                self.pose_region = self.pose_region.difference(buffered_shape)

    def plot(self, type_='pose', alpha=0.5, **kwargs):
        """Plot either the pose or point feasible regions.

        Parameters
        ----------
        type_ : {'pose','point'}
            The type of feasible region to plot.
        alpha : int
            Feasible region patch transparency
        **kwargs
            Arguements passed to PolygonPatch
        """
        if type_ == "pose":
            p = self.pose_region
        else:
            p = self.point_region

        ax.set_xlim([self.bounds[0], self.bounds[2]])
        ax.set_ylim([self.bounds[1], self.bounds[3]])

        self.patch = PolygonPatch(p, facecolor=cnames['black'],
                                  alpha=alpha, zorder=2, **kwargs)
        ax.add_patch(self.patch)

        plt.show()

        # return patch

    def remove(self):
        """Removes feasible region patch from plot"""
        if hasattr(self, 'patch'):
            self.patch.remove()

    def update(self, type_='pose', i=0):
        self.remove()
        self.plot(type_)
Esempio n. 14
0
def plot_polygon(ax, poly, color='red'):
    a = np.asarray(poly.exterior)
    # without Descartes, we could make a Patch of exterior
    ax.add_patch(PolygonPatch(poly, facecolor=color, alpha=0.3))
    ax.plot(a[:, 0], a[:, 1], color='black')
Esempio n. 15
0
    shape = shapeRec.shape
    rec = shapeRec.record

    # select polygon facecolor RGB vals based on record value
    R = 1.
    G = (rec[ndx1] - minrec) / (maxrec - minrec)
    G = G * (G < 1.0) * (G > 0) + 1.0 * (G > 1.0)
    B = 0.

    # check number of parts (could use MultiPolygon class of shapely?)
    nparts = len(shape.parts)  # total parts
    if nparts == 1:
        polygon = Polygon(shape.points)
        patch = PolygonPatch(polygon,
                             facecolor=[R, G, B],
                             edgecolor=[0, 0, 0],
                             alpha=1.0,
                             zorder=2)
        ax.add_patch(patch)

    else:  # loop over parts of each shape, plot separately
        for ip in range(nparts):  # loop over parts, plot separately
            i0 = shape.parts[ip]
            if ip < nparts - 1:
                i1 = shape.parts[ip + 1] - 1
            else:
                i1 = len(shape.points)

            # build the polygon and add it to plot
            polygon = Polygon(shape.points[i0:i1 + 1])
            patch = PolygonPatch(polygon,
Esempio n. 16
0
def plot_polygon_collection(
    ax, geoms, values=None, color=None, cmap=None, vmin=None, vmax=None, **kwargs
):
    """
    Plots a collection of Polygon and MultiPolygon geometries to `ax`

    Parameters
    ----------

    ax : matplotlib.axes.Axes
        where shapes will be plotted

    geoms : a sequence of `N` Polygons and/or MultiPolygons (can be mixed)

    values : a sequence of `N` values, optional
        Values will be mapped to colors using vmin/vmax/cmap. They should
        have 1:1 correspondence with the geometries (not their components).
        Otherwise follows `color` / `facecolor` kwargs.

    edgecolor : single color or sequence of `N` colors
        Color for the edge of the polygons

    facecolor : single color or sequence of `N` colors
        Color to fill the polygons. Cannot be used together with `values`.

    color : single color or sequence of `N` colors
        Sets both `edgecolor` and `facecolor`

    **kwargs
        Additional keyword arguments passed to the collection

    Returns
    -------

    collection : matplotlib.collections.Collection that was plotted
    """

    try:
        from descartes.patch import PolygonPatch
    except ImportError:
        raise ImportError(
            "The descartes package is required for plotting polygons in geopandas."
        )
    from matplotlib.collections import PatchCollection
    from matplotlib.colors import is_color_like

    geoms, multiindex = _flatten_multi_geoms(geoms, range(len(geoms)))
    if values is not None:
        values = np.take(values, multiindex, axis=0)

    # PatchCollection does not accept some kwargs.
    if "markersize" in kwargs:
        del kwargs["markersize"]
    if color is not None:
        if is_color_like(color):
            kwargs["color"] = color
        elif pd.api.types.is_list_like(color):
            kwargs["color"] = np.take(color, multiindex, axis=0)
        else:
            raise TypeError(
                "Color attribute has to be a single color or sequence of colors."
            )

    else:
        for att in ["facecolor", "edgecolor"]:
            if att in kwargs:
                if not is_color_like(kwargs[att]):
                    if pd.api.types.is_list_like(kwargs[att]):
                        kwargs[att] = np.take(kwargs[att], multiindex, axis=0)
                    elif kwargs[att] is not None:
                        raise TypeError(
                            "Color attribute has to be a single color or sequence "
                            "of colors."
                        )

    collection = PatchCollection([PolygonPatch(poly) for poly in geoms], **kwargs)

    if values is not None:
        collection.set_array(np.asarray(values))
        collection.set_cmap(cmap)
        if "norm" not in kwargs:
            collection.set_clim(vmin, vmax)

    ax.add_collection(collection, autolim=True)
    ax.autoscale_view()
    return collection
Esempio n. 17
0
def draw_region_map(ax, sf, shp_dic, heat={}):
    continent = [235 / 256, 151 / 256, 78 / 256]
    ocean = (89 / 256, 171 / 256, 227 / 256)

    reg_list = {
        'Staten Island': 1,
        'Queens': 2,
        'Bronx': 3,
        'Manhattan': 4,
        'EWR': 5,
        'Brooklyn': 6
    }
    reg_x = {
        'Staten Island': [],
        'Queens': [],
        'Bronx': [],
        'Manhattan': [],
        'EWR': [],
        'Brooklyn': []
    }
    reg_y = {
        'Staten Island': [],
        'Queens': [],
        'Bronx': [],
        'Manhattan': [],
        'EWR': [],
        'Brooklyn': []
    }

    # colorbar
    if len(heat) != 0:
        norm = mpl.colors.Normalize(
            vmin=math.sqrt(0), vmax=math.sqrt(max(heat.values(
            ))))  #norm = mpl.colors.LogNorm(vmin=1,vmax=max(heat))
        cm = plt.get_cmap('Reds')
        # sm = plt.cm.ScalarMappable(cmap=cm, norm=norm)
        # sm.set_array([])
        # plt.colorbar(sm, ticks=np.linspace(0,max(heat.values()),8), \
        #             boundaries=np.arange(0-10,max(heat.values())+10,.1))

    ax.set_facecolor(ocean)
    for sr in sf.shapeRecords():
        shape = sr.shape
        rec = sr.record
        reg_name = rec[shp_dic['borough']]

        if len(heat) == 0:
            norm = mpl.colors.Normalize(
                vmin=1,
                vmax=6)  #norm = mpl.colors.LogNorm(vmin=1,vmax=max(heat))
            cm = plt.get_cmap('Pastel1')
            R, G, B, A = cm(norm(reg_list[reg_name]))
            col = [R, G, B]
        else:
            R, G, B, A = cm(norm(math.sqrt(heat[reg_name])))
            col = [R, G, B]

        # check number of parts (could use MultiPolygon class of shapely?)
        nparts = len(shape.parts)  # total parts
        if nparts == 1:
            polygon = Polygon(shape.points)
            patch = PolygonPatch(polygon, facecolor=col, alpha=1.0, zorder=2)
            ax.add_patch(patch)
        else:  # loop over parts of each shape, plot separately
            for ip in range(nparts):  # loop over parts, plot separately
                i0 = shape.parts[ip]
                if ip < nparts - 1:
                    i1 = shape.parts[ip + 1] - 1
                else:
                    i1 = len(shape.points)

                polygon = Polygon(shape.points[i0:i1 + 1])
                patch = PolygonPatch(polygon,
                                     facecolor=col,
                                     alpha=1.0,
                                     zorder=2)
                ax.add_patch(patch)

        reg_x[reg_name].append((shape.bbox[0] + shape.bbox[2]) / 2)
        reg_y[reg_name].append((shape.bbox[1] + shape.bbox[3]) / 2)

    for k in reg_list:
        if len(heat) == 0:
            plt.text(np.mean(reg_x[k]),
                     np.mean(reg_y[k]),
                     k,
                     horizontalalignment='center',
                     verticalalignment='center',
                     bbox=dict(facecolor='black', alpha=0.5),
                     color="white",
                     fontsize=12)
        else:
            plt.text(np.mean(reg_x[k]),
                     np.mean(reg_y[k]),
                     "{}\n({}K)".format(k, heat[k] / 1000),
                     horizontalalignment='center',
                     verticalalignment='center',
                     bbox=dict(facecolor='black', alpha=0.5),
                     color="white",
                     fontsize=12)

    # display
    limits = get_boundaries(sf)
    plt.xlim(limits[0], limits[1])
    plt.ylim(limits[2], limits[3])
from descartes.patch import PolygonPatch

from figures import DARKGRAY, GRAY, BLUE, SIZE, set_limits

fig = plt.figure(1, figsize=SIZE, dpi=90)
fig.set_frameon(True)

# 1
ax = fig.add_subplot(121)

mp = MultiPoint([(0, 0), (0.5, 1.5), (1, 0.5), (0.5, 0.5)])
rect = mp.minimum_rotated_rectangle

for p in mp:
    ax.plot(p.x, p.y, 'o', color=GRAY)
patch = PolygonPatch(rect, facecolor=BLUE, edgecolor=BLUE, alpha=0.5, zorder=2)
ax.add_patch(patch)
ax.set_title('a) MultiPoint')

set_limits(ax, -1, 2, -1, 2)

# 2
ax = fig.add_subplot(122)
ls = LineString([(-0.5, 1.2), (0.5, 0), (1, 1), (1.5, 0), (1.5, 0.5)])
rect = ls.minimum_rotated_rectangle

ax.plot(*ls.xy, color=DARKGRAY, linewidth=3, alpha=0.5, zorder=2)
patch = PolygonPatch(rect, facecolor=BLUE, edgecolor=BLUE, alpha=0.5, zorder=2)
ax.add_patch(patch)

set_limits(ax, -1, 2, -1, 2)
Esempio n. 19
0
def draw_channel(frame, layer, trackIDs, trackPolys, trackData, fileNameIMAGEOVERLAY,fsz):
    numColors = 201
    
    
    fig=plt.figure(1,frameon=True)
    DPI = fig.get_dpi()
    figxlim=fsz[0]
    figylim=fsz[1]
    figWidth=figxlim/float(DPI)
    figHight=figylim/float(DPI)
    fig.set_size_inches(figWidth,figHight)
    
    ax = plt.axes()
    ax.clear()
    
    ax.axis("off")
    ax.set_aspect('equal',adjustable='box')
    plt.xlim(0,figxlim)
    plt.ylim(0,figylim)
    
    
    
    ax.plot([0, figxlim],[0,figylim],'w.')  ##mmmmh
    for i, this_trackID in enumerate(trackIDs):
        
        this_poly=trackPolys[i]
        this_data=trackData[i]
        
        #Define overlay properties
        if layer['channel']=='division':  #CHANNEL: divisions
            if this_data==1:
                cellEdgeColor=[0,0,0]
                cellColor=[1,1,0]
                alphaCell=1.
            else:
                cellEdgeColor=[0.5,0.5,0.5]
                cellColor=[0.9,0.9,0.9]
                alphaCell=.5
                
        elif layer['channel']=='GFP':
            cmap= plt.cm.Greens(range(0, numColors))
            if this_data==-1:
                alphaCell=0
                cellColor=[0.5,0.5,0.5]
                cellEdgeColor=[0,0,0]
            else:
                xp=np.linspace(0,201,201)
                fp=np.linspace(layer['minvalue'],layer['maxvalue'],201)
                icolor=int(np.interp(this_data, fp, xp))
                if icolor>numColors-1:
                    icolor=numColors-1
                alphaCell=1
                cellColor=cmap[icolor,:]
                cellEdgeColor=[0,0,0]
        
        elif layer['channel']=='DsRed':
            cmap= plt.cm.Reds(range(0, numColors))
            if this_data==-1:
                alphaCell=0
                cellColor=[0.5,0.5,0.5]
                cellEdgeColor=[0,0,0]
            else:
                xp=np.linspace(0,201,201)
                fp=np.linspace(layer['minvalue'],layer['maxvalue'],201)
                icolor=int(np.interp(this_data, fp, xp))
                if icolor>numColors-1:
                    icolor=numColors-1
                alphaCell=1
                cellColor=cmap[icolor,:]
                cellEdgeColor=[0,0,0]
                
        elif layer['channel']=='RYG':
            #cmap= plt.cm.RdYlGn(range(0, numColors))
            cmap = cm.get_cmap("RdYlGn", 201)
            if this_data==-1:
                alphaCell=0
                cellColor=[0.9,0.9,0.9]
                cellEdgeColor=[0.5,0.5,0.5]
            else:
                cellColor=cmap(1-this_data/np.pi)
                alphaCell=1
                cellEdgeColor=[0.5,0.5,0.5]
        elif layer['channel']=='RelInt':
            colors2=[(100,34,101),(92,204,192),(27,68,28)]
            cmap=make_cmap(colors2, bit=True)
            if this_data==-1:
                alphaCell=0
                cellColor=[0.9,0.9,0.9]
                cellEdgeColor=[0.5,0.5,0.5]
            else:
                cellColor=cmap(1-this_data/np.pi)
                alphaCell=1
                cellEdgeColor=[0.5,0.5,0.5]
                
        elif layer['channel']=='Tracking':
            cellColor=this_data
            cellEdgeColor=[0.5,0.5,0.5]
            alphaCell=.5
            
        else: #Mask
            cellColor=[0,0,0]
            cellEdgeColor=[0,0,0]
            alphaCell=1
            
        #Now draw polygon with overlay 
        if layer['contour']:
            patch = PolygonPatch(this_poly, facecolor=cellColor, edgecolor=cellEdgeColor, alpha=alphaCell, linewidth=.5, zorder=2)
        else:
            patch = PolygonPatch(this_poly, facecolor=cellColor, edgecolor=cellColor, alpha=alphaCell, zorder=2)
        ax.add_patch(patch)
        
    plt.gca().invert_yaxis()
    plt.tight_layout(pad=0,h_pad=0,w_pad=0)
    fig.savefig(fileNameIMAGEOVERLAY)
    #plt.close(fig1)
    plt.clf()
    plt.close(fig)
Esempio n. 20
0
def plot_visible(ax, visible_regions):
    for visibile_region in visible_regions:
        visible_patch =  PolygonPatch(visibile_region,
                                      facecolor=DARK_50, edgecolor=DARK_90, alpha=0.6, zorder=2)
        ax.add_patch(visible_patch)
Esempio n. 21
0
def slice_non_fence_region(
        regions,
        xl,
        yl,
        xh,
        yh,
        macro_pos_x=None,
        macro_pos_y=None,
        macro_size_x=None,
        macro_size_y=None,
        merge=False,
        plot=False,
        figname="non_fence_region.png",
        device=torch.device("cuda:0"),
):
    if type(regions) == list:
        if isinstance(regions[0], np.ndarray):
            regions = torch.from_numpy(np.concatenate(regions, 0)).to(device)
        elif isinstance(regions[0], torch.Tensor):
            regions = torch.cat(regions, dim=0).to(device)  # [n_box, 4]
    elif isinstance(regions, np.ndarray):
        regions = torch.from_numpy(regions).to(device)

    if macro_pos_x is not None:
        if isinstance(macro_pos_x, np.ndarray):
            macro_pos_x = torch.from_numpy(macro_pos_x).to(device).float()
            macro_pos_y = torch.from_numpy(macro_pos_y).to(device).float()
            macro_size_x = torch.from_numpy(macro_size_x).to(device).float()
            macro_size_y = torch.from_numpy(macro_size_y).to(device).float()

        regions = torch.cat(
            [
                regions,
                torch.stack([
                    macro_pos_x, macro_pos_y, macro_pos_x + macro_size_x,
                    macro_pos_y + macro_size_y
                ], 0).t(),
            ],
            0,
        )

    num_boxes = regions.size(0)
    regions = regions.view(num_boxes, 2, 2)
    fence_regions = MultiPolygon([
        box(regions[i, 0, 0], regions[i, 0, 1], regions[i, 1, 0],
            regions[i, 1, 1]) for i in range(num_boxes)
    ])
    fence_regions = unary_union(fence_regions)
    site = box(xl, yl, xh, yh)

    non_fence_region = unary_union(site.difference(fence_regions))

    slices = []
    xs = regions[:, :, 0].view(-1).sort()[0]
    for i in range(xs.size(0) + 1):
        x_l = xl if i == 0 else xs[i - 1]
        x_h = xh if i == xs.size(0) else xs[i]
        cvx_hull = box(x_l, yl, x_h, yh)

        if x_l >= x_h or not cvx_hull.is_valid:
            continue
        intersect = non_fence_region.intersection(cvx_hull)

        if isinstance(intersect, Polygon) and len(intersect.bounds) == 4:
            slices.append(intersect.bounds)
        elif isinstance(intersect, (GeometryCollection, MultiPolygon)):
            slices.extend([
                j.bounds for j in intersect
                if (isinstance(j, Polygon) and len(j.bounds) == 4)
            ])

    if merge:
        raw_bbox_list = sorted(slices, key=lambda x: (x[1], x[0]))

        cur_bbox = None
        bbox_list = []
        for i, p in enumerate(raw_bbox_list):
            minx, miny, maxx, maxy = p
            if cur_bbox is None:
                cur_bbox = [minx, miny, maxx, maxy]
            elif cur_bbox[1] == miny and cur_bbox[3] == maxy and cur_bbox[
                    2] == minx:
                cur_bbox[2:] = p[2:]
            else:
                bbox_list.append(cur_bbox)
                cur_bbox = [minx, miny, maxx, maxy]
        else:
            bbox_list.append(cur_bbox)
    else:
        bbox_list = slices

    if plot:
        from descartes.patch import PolygonPatch
        from matplotlib import pyplot as plt

        # from figures import BLUE, SIZE, set_limits, plot_coords, color_isvalid
        res = []
        bbox_list_np = np.array(bbox_list)
        bbox_list_np *= 1000 / np.max(bbox_list_np)
        for bbox in bbox_list_np:
            res.append(box(*bbox.tolist()))
        res = MultiPolygon(res)
        fig = plt.figure(1, figsize=SIZE, dpi=90)
        ax = fig.add_subplot(121)
        for polygon in res:
            # plot_coords(ax, polygon.exterior)
            patch = PolygonPatch(
                polygon,
                facecolor=color_isvalid(non_fence_region),
                edgecolor=color_isvalid(non_fence_region, valid=BLUE),
                alpha=0.5,
                zorder=2,
            )
            ax.add_patch(patch)

        set_limits(ax, -1, 1000, -1, 1000, dx=100, dy=100)
        # ax = fig.add_subplot(122)
        # patch = PolygonPatch(non_fence_region, facecolor=color_isvalid(
        #     non_fence_region), edgecolor=color_isvalid(non_fence_region, valid=BLUE), alpha=0.5, zorder=2)
        # ax.add_patch(patch)
        # set_limits(ax, -1, 1000, -1, 1000, dx=100, dy=100)
        plt.savefig(figname)
        plt.close()

    bbox_list = torch.tensor(bbox_list, device=device)
    # print("non fence region area after slicing:", ((bbox_list[:,2]-bbox_list[:,0])*(bbox_list[:,3]-bbox_list[:,1])).sum().item())
    return bbox_list
def create_patch_overlap_coord():
    '''This part of the code creates the path image with overlapping coordinates'''
    # img = openslide.OpenSlide(arg.svs_file)
    # img_dim = img.level_dimensions[0]
    # patch_size=10000
    # """
    # Determine what the patch size should be, and how many iterations it will take to get through the WSI
    # """
    # #num_x_patches = int(math.floor(img_dim[0]/patch_size))
    # #num_y_patches = int(math.floor(img_dim[1]/patch_size))
    # #print(str(num_x_patches)+" "+str(num_y_patches))
    # print(len(regions))
    # coords1=regions[8]
    # min=np.argmin(coords1, axis = 0)
    # #print(coords1[min[0]][0])
    # #print(coords1[min[1]][1])
    # #coords2=np.sort(coords1, axis = 0)
    # #print(coords2)
    # #sys.exit(1)
    # x1=int(coords1[min[0]][0])-10
    # y1=int(coords1[min[1]][1])-10
    # level=0
    # img_data = img.read_region((x1,y1),level, (patch_size, patch_size))
    # img_data_np = np.array(img_data)
    # img_name="sample.png"
    # im = Image.fromarray(img_data_np)
    # im.save(img_name)

    # # Create figure and axes
    # #fig,ax = plt.subplots(1)
    # fig,ax = plt.subplots()
    # # Display the image
    # ax.imshow(img_data_np)
    # #imgdata = plt.imread("sample.png")
    # #ax.imshow(imgdata)

    # # Add the patch to the Axes
    # #points = [[2, 1], [8, 1], [8, 4],[50,50],[100,100],[200,200]]
    # #plt.Polygon(points)
    # #poly = Polygon(verts, facecolor='0.9', edgecolor='0.5')
    # coords1_list=[]
    # for i in range(0,len(coords1)):
    # x_cor=int(coords1[i][0])-x1
    # y_cor=int(coords1[i][1])-y1
    # if x_cor >=0 and x_cor <= patch_size and y_cor >=0 and y_cor <=patch_size:
    # tmp=(x_cor,y_cor)
    # coords1_list.append(tmp)
    # #coords1_list.append((100,300))
    # #coords1_list.append((200,200))
    # #coords1_list.append((400,200))
    # #coords1_list.append((500,300))
    # #coords1_list.append((400,400))
    # #coords1_list.append((200,400))
    # print(coords1_list)
    # polygon = Polygon(coords1_list)
    # patch = PolygonPatch(polygon, facecolor=[0,0,0], edgecolor=[0,0.5,0], alpha=0.7, zorder=2)
    # ax.add_patch(patch)
    # plt.savefig('sample_overlay.png', alpha=True, dpi=300)
    # plt.show()

    patch_size = 2000
    OSobj = openslide.OpenSlide(arg.svs_file)
    x1 = 40000
    y1 = 37000
    img_patch = OSobj.read_region((x1, y1), 0, (patch_size, patch_size))
    img_data_np = np.array(img_patch)
    #img_name="sample3.png"
    #im = Image.fromarray(img_data_np)
    #im.save(img_name)

    # coords1_list=[]
    # # #for j in range(0,len(regions)):
    # for j in range(0,1):
    # coords1=regions[j]
    # for i in range(0,len(coords1)):
    # x_cor=int(coords1[i][0])-x1
    # y_cor=int(coords1[i][1])-y1
    # # # #print(str(x_cor)+" "+str(y_cor))
    # if x_cor >=0 and x_cor <= patch_size and y_cor >=0 and y_cor <=patch_size:
    # tmp=(x_cor,y_cor)
    # coords1_list.append(tmp)
    # # # print(coords1_list)
    # polygon = Polygon(coords1_list)
    # # print(polygon)
    # # # # Create figure and axes
    # fig,ax = plt.subplots()
    # # # # Display the image
    # ax.imshow(img_data_np)

    # # # # Add the patch to the Axes
    # patch = PolygonPatch(polygon, facecolor=[0,0,0], edgecolor=[0,0.5,0], alpha=0.7, zorder=2)
    # ax.add_patch(patch)
    # plt.savefig('sample_overlay.png', alpha=True, dpi=300)
    # plt.show()

    # #ploting Steve's way
    # #plt.style.use('dark_background')
    # f, ax = plt.subplots(frameon=False)
    # #f.set_facecolor('#eafff5')
    # #ax.set_facecolor('#eafff5')
    # f.tight_layout(pad=0, h_pad=0, w_pad=0)
    # ax.set_xlim(0, patch_size)
    # ax.set_ylim(0, patch_size)
    # #img_data_np[np.where((img_data_np != [0,0,0]).all(axis = 2))] = [0,0,0]
    # #ax.imshow(img_data_np)
    # #mask1 = np.zeros(img_data_np.shape, dtype = "uint8")
    # #mask1.fill(0)
    # mask1 = Image.new('RGBA', (patch_size, patch_size), "black")
    # ax.imshow(mask1)
    # #ax.set_axis_bgcolor("black")
    # #patch = PolygonPatch(polygon, facecolor=[0,0,0], edgecolor=[0,0.5,0], alpha=0.7, zorder=2)
    # #patch = PolygonPatch(polygon, facecolor='#FFFFFF', edgecolor='#FFFFFF', alpha=0.7, zorder=2)
    # patch = PolygonPatch(polygon, facecolor='white')
    # ax.add_patch(patch)
    # ax.set_axis_off()
    # DPI = f.get_dpi()
    # plt.subplots_adjust(left=0, bottom=0, right=1, top=1,wspace=0, hspace=0)
    # f.set_size_inches(patch_size / DPI, patch_size / DPI)
    # f.savefig("Mask_tmp.png", pad_inches='tight')

    #create a binary mask
    #mask = np.zeros(img_data_np, dtype = "uint8")
    #cv2.rectangle(mask, (x1, y1), (x1+patch_size, y1+patch_size), (255, 255, 255), -1)

    #print(img_data_np)
    # flag = np.array([37500,38000, 0,0])
    # #flag = np.array([36000,27000])
    # #img_data_np=img_data_np+flag
    # #mask = np.zeros((700,700))
    # #print(regions[0])
    # a=finalcoords
    # a=np.int64(a)-flag
    # a = a[~np.all(a < 0, axis=1)]
    # a = a[~np.all(a > 10000, axis=1)]
    # #print("sucess")
    # #a2=a1[np.logical_and(a1>=0,a1<700)]
    # print(a)
    # sys.exit(1)
    # poly = Polygon(regions[0])
    # #img = Image.new('L', (700,700), 0)
    # #ImageDraw.Draw(img).polygon(poly, outline=1, fill=1)
    # mask = np.array((700,700))
    # # Create vertex coordinates for each grid cell...
    # # (<0,0> is at the top left of the grid in this system)
    # #x, y = np.meshgrid(np.arange(700), np.arange(700))
    # #x, y = x.flatten(), y.flatten()
    # #points = np.vstack((x,y)).T
    # #grid = points_inside_poly(points, poly)
    # #grid = grid.reshape((ny,nx))
    # print(poly)
    # cv2.fillPoly(mask, poly, 1)
    # mask = mask.astype(bool)
    # plt.imshow(mask)
    #print(Polygon(img_data_np).contains(poly_regions[0]))
    #xmax, ymax = a.max(axis=0)
    #print(img_data_np.shape)
    #a = Polygon(np.array([(0, 0), (1, 1), (1,2), (2,2)]))
    #b = Polygon(np.array([(0, 0), (1, 1), (2,1), (2,2)]))
    # patch_list=[]
    # x_n=300
    # y_n=300
    # size=x_n+y_n+x_n-2+y_n-2
    # list1=[]
    # n=0
    # for x in range(0,x_n):
    # tlist=[0+39000,x+34000]
    # list1.append(tlist)
    # for x in range(0,x_n):
    # tlist=[x_n-1+39000,x+34000]
    # list1.append(tlist)
    # for x in range(1,y_n-1):
    # tlist=[x+39000,0+34000]
    # list1.append(tlist)
    # for x in range(1,y_n-1):
    # tlist=[x+39000,y_n-1+34000]
    # list1.append(tlist)

    path_poly = geo.box(x1, y1, x1 + patch_size, y1 + patch_size, ccw=True)
    # # path_poly=Polygon(np.array(list1))
    # # #path_poly=Polygon(np.array([[0, 0], [1, 0], [1, 1], [0, 1]]))
    # # print(path_poly)
    # # print(path_poly.is_valid)
    # # print(path_poly.length)
    # #print(poly_regions[0].is_valid)
    #print(len(poly_regions))
    poly_all = []
    for j in range(0, len(poly_regions)):
        #print(j)
        poly1 = path_poly.intersection(poly_regions[j])
        poly1_temp = []
        if poly1.length > 0:
            for x, y in poly1.exterior.coords:
                x = int(x) - x1
                y = int(y) - y1
                tmp = (x, y)
                poly1_temp.append(tmp)
            poly1 = Polygon(poly1_temp)
            poly_all.append(poly1)
    #multi_poly = MultiPolygon(poly_all)
    #print(len(poly_all))
    #sys.exit(1)
    #ploting Steve's way
    #plt.style.use('dark_background')
    f, ax = plt.subplots(frameon=False)
    #ax.set_facecolor('#eafff5')
    f.tight_layout(pad=0, h_pad=0, w_pad=0)
    ax.set_xlim(0, patch_size)
    ax.set_ylim(0, patch_size)
    mask1 = Image.new('RGBA', (patch_size, patch_size), "black")
    ax.imshow(mask1)
    #patch1 = PolygonPatch(poly1, facecolor="white", edgecolor="white", alpha=0.7, zorder=2)
    for j in range(0, len(poly_all)):
        patch1 = PolygonPatch(poly_all[j], facecolor="white")
        ax.add_patch(patch1)

    ax.set_axis_off()
    DPI = f.get_dpi()
    plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)
    f.set_size_inches(patch_size / DPI, patch_size / DPI)
    f.savefig("Mask_tmp1.png", pad_inches='tight')
Esempio n. 23
0
def gen_macros_for_fence_region(macro_pos_x,
                                macro_pos_y,
                                macro_size_x,
                                macro_size_y,
                                regions,
                                xl,
                                xh,
                                yl,
                                yh,
                                merge=False,
                                plot=False):
    # tt = time.time()
    macros = MultiPolygon([
        box(
            macro_pos_x[i],
            macro_pos_y[i],
            macro_pos_x[i] + macro_size_x[i],
            macro_pos_y[i] + macro_size_y[i],
        ) for i in range(macro_size_x.size(0))
    ])
    # print("macro:", time.time()-tt)

    # tt = time.time()
    num_boxes = regions.size(0)
    regions = regions.view(num_boxes, 2, 2)
    fence_regions = MultiPolygon([
        box(regions[i, 0, 0], regions[i, 0, 1], regions[i, 1, 0],
            regions[i, 1, 1]) for i in range(num_boxes)
    ])

    site = box(xl, yl, xh, yh)
    reverse = site.difference(fence_regions).union(macros)
    # print("fence region:", time.time()-tt)

    # tt = time.time()
    slices = []
    xs = torch.cat(
        [regions[:, :, 0].view(-1), macro_pos_x, macro_pos_x + macro_size_x],
        dim=0).sort()[0]
    for i in range(xs.size(0) + 1):
        x_l = xl if i == 0 else xs[i - 1]
        x_h = xh if i == xs.size(0) else xs[i]

        cvx_hull = box(x_l, yl, x_h, yh)
        intersect = reverse.intersection(cvx_hull)

        if isinstance(intersect, Polygon):
            slices.append(intersect.bounds)
        elif isinstance(intersect, (GeometryCollection, MultiPolygon)):
            slices.extend(
                [j.bounds for j in intersect if (isinstance(j, Polygon))])

    # print("slicing:", time.time()-tt)

    # tt = time.time()
    if merge:
        raw_bbox_list = sorted(slices, key=lambda x: (x[1], x[0]))

        cur_bbox = None
        bbox_list = []
        for i, p in enumerate(raw_bbox_list):
            minx, miny, maxx, maxy = p
            if cur_bbox is None:
                cur_bbox = [minx, miny, maxx, maxy]
            elif cur_bbox[1] == miny and cur_bbox[3] == maxy:
                cur_bbox[2:] = p[2:]
            else:
                bbox_list.append(cur_bbox)
                cur_bbox = [minx, miny, maxx, maxy]
        else:
            bbox_list.append(cur_bbox)
    else:
        bbox_list = slices
    # print("merge:", time.time()-tt)

    bbox_list = torch.tensor(bbox_list).float()
    pos_x = bbox_list[:, 0]
    pos_y = bbox_list[:, 1]
    node_size_x = bbox_list[:, 2] - bbox_list[:, 0]
    node_size_y = bbox_list[:, 3] - bbox_list[:, 1]

    if plot:
        from descartes.patch import PolygonPatch
        from matplotlib import pyplot as plt

        from figures import BLUE, SIZE, color_isvalid, plot_coords, set_limits

        res = []
        for bbox in bbox_list:
            res.append(box(*bbox))
        res = MultiPolygon(res)
        fig = plt.figure(1, figsize=SIZE, dpi=90)
        ax = fig.add_subplot(121)
        for polygon in res:
            # plot_coords(ax, polygon.exterior)
            patch = PolygonPatch(
                polygon,
                facecolor=color_isvalid(fence_regions),
                edgecolor=color_isvalid(fence_regions, valid=BLUE),
                alpha=0.5,
                zorder=2,
            )
            ax.add_patch(patch)

        set_limits(ax, -1, 20, -1, 20)
        ax = fig.add_subplot(122)
        patch = PolygonPatch(
            reverse,
            facecolor=color_isvalid(reverse),
            edgecolor=color_isvalid(reverse, valid=BLUE),
            alpha=0.5,
            zorder=2,
        )
        ax.add_patch(patch)
        set_limits(ax, -1, 20, -1, 20)
        plt.savefig("polygon.png")

    return pos_x, pos_y, node_size_x, node_size_y
Esempio n. 24
0
def make_map(final_regions, file_name, number, x, y, country, algorithm,
             order_choice):

    # Open shapefile for country and plot figure
    sf = shp.Reader(file_name)
    plt.figure()
    ax = plt.axes()

    # Add plot title with country name
    plt.title(country + ", algorithm " + algorithm + ", " + order_choice,
              fontsize=20)

    # Initialize counter for number of region
    counter = 0
    name_list = []

    for i in list(sf.iterRecords()):

        # Append region names to name list
        name_list.append(list(sf.iterRecords())[counter][number])
        counter += 1

    counter = 0

    for shape in list(sf.iterShapes()):

        # Get color for region
        color_value = name_list[counter]
        color = colours(final_regions)

        # Get dict with region and color for map
        color_regions = color[0]

        # Get dict with station and color for legend
        color_legend = color[1]

        # Check how many parts one region has
        nparts = len(shape.parts)

        # If region is made up of one part color whole part
        if nparts == 1:

            polygon = Polygon(shape.points)
            patch = PolygonPatch(polygon, facecolor=color_regions[color_value])
            ax.add_patch(patch)

        # If more than one part then color every part of region the same color
        else:

            for ip in range(nparts):
                iO = shape.parts[ip]

                if ip < nparts - 1:
                    il = shape.parts[ip + 1] - 1

                else:
                    il = len(shape.points)

                polygon = Polygon(shape.points[iO:il + 1])
                patch = PolygonPatch(polygon,
                                     facecolor=color_regions[color_value])
                ax.add_patch(patch)

        counter += 1

    # Add legend to plot
    station_1 = mlines.Line2D([], [],
                              color=color_legend["1"],
                              marker="s",
                              fillstyle="full",
                              label='Station 1',
                              markersize=15)
    station_2 = mlines.Line2D([], [],
                              color=color_legend["2"],
                              marker="s",
                              fillstyle="full",
                              label='Station 2',
                              markersize=15)
    station_3 = mlines.Line2D([], [],
                              color=color_legend["3"],
                              marker="s",
                              fillstyle="full",
                              label='Station 3',
                              markersize=15)
    station_4 = mlines.Line2D([], [],
                              color=color_legend["4"],
                              marker="s",
                              fillstyle="full",
                              label='Station 4',
                              markersize=15)
    station_5 = mlines.Line2D([], [],
                              color=color_legend["5"],
                              marker="s",
                              fillstyle="full",
                              label='Station 5',
                              markersize=15)
    station_6 = mlines.Line2D([], [],
                              color=color_legend["6"],
                              marker="s",
                              fillstyle="full",
                              label='Station 6',
                              markersize=15)
    station_7 = mlines.Line2D([], [],
                              color=color_legend["7"],
                              marker="s",
                              fillstyle="full",
                              label='Station 7',
                              markersize=15)

    plt.legend(handles=[
        station_1, station_2, station_3, station_4, station_5, station_6,
        station_7
    ],
               shadow=True,
               fancybox=True,
               prop={'size': 12})

    # Scale to country coordinates
    plt.xlim(x)
    plt.ylim(y)
    plt.show()
Esempio n. 25
0
    def plotPoly(self, p, c):
        patch = PolygonPatch(p, facecolor=c)
        self.ax.add_patch(patch)

        return patch
Esempio n. 26
0
def plot_hex_to_square_map(coef, hex_cells_dict, sq_cells_dict):
    '''
    DESCRIPTION:
        This function is for visualization of mapping of Hexagonal cells
        to the square cells, for checking the correctness of resolution
        of interpolation with the criteria as mentioned by Florian Sir,
        (one square cell not overlapping with more than three hexagon cells)
    USAGE:
        This function is called internally in main.py generate_interpolation
        function.
        INPUT:
            coef : the coef dictionary mapping each hexagonal cells to their
                    correspoinding square cells
            hex_cells_dict  : the dictionary of hexagonal cells obtained from
                                the root file
            sq_cells_dict   : the square cell dictionary generated by
                                get_square_cells function above and saved in
                                'sq_cells_data' directory in current location
        OUTPUT:
            Currently no output from this function
    '''
    t0 = datetime.datetime.now()
    print '>>> Calculating the area of smallar cell for filtering'
    filter_hex_cells = ([
        c.vertices.area for c in hex_cells_dict.values()
        if len(list(c.vertices.exterior.coords)) == 7
    ])
    small_wafer_area = min(filter_hex_cells)
    t1 = datetime.datetime.now()
    print '>>> Area calculated %s in time: %s sec' % (small_wafer_area,
                                                      t1 - t0)
    t0 = t1

    for hex_id, sq_overlaps in coef.items():
        hex_cell = hex_cells_dict[hex_id]
        poly = hex_cell.vertices
        #Filtering the cells in smaller region
        if poly.area != small_wafer_area:
            continue

        fig = plt.figure()
        ax1 = fig.add_subplot(111)
        x, y = poly.exterior.xy
        ax1.plot(x, y, 'o', zorder=1)
        patch = PolygonPatch(poly, alpha=0.5, zorder=2, edgecolor='blue')
        ax1.add_patch(patch)
        print '>>> Plotting hex cell: ', hex_id
        for sq_cell_data in sq_overlaps:
            sq_cell_id = sq_cell_data[0]
            overlap_coef = sq_cell_data[1]
            sq_cell = sq_cells_dict[sq_cell_id]
            print('overlapping with sq_cell: ', sq_cell_id,
                  'with overlap coef: ', overlap_coef)
            poly = sq_cell.polygon
            x, y = poly.exterior.xy
            ax1.plot(x, y, 'o', zorder=1)
            patch = PolygonPatch(poly, alpha=0.5, zorder=2, edgecolor='red')
            ax1.add_patch(patch)
        t1 = datetime.datetime.now()
        print 'one hex cell overlap complete in: ', t1 - t0, ' sec\n'
        plt.show()
Esempio n. 27
0
    for imageId in trainImageIds:
        fig, axArr, ax = visualize_image(imageId, plot_all=False)
        plt.savefig('Objects--' + imageId + '.png')
        plt.clf()


def makeClassMap(imageId, nClass):
    poly = wkt_loads(df[df.ImageId == imageId].MultipolygonWKT.values[nClass])
    (xmax, ymin, W, H) = get_size(imageId)


# Optionally, view images immediately:
# pylab.show()
# Uncomment to show plot when interactive mode is off
# (this function blocks till fig is closed)

# My code
testId = '6100_1_3'
df[df.ImageId == testId]
gs[gs.ImageId == testId]
pp = wkt_loads(df[df.ImageId == testId].MultipolygonWKT.values[1])
fig, axArr = plt.subplots(figsize=(20, 20))
for polygon in pp:
    mpl_poly = PolygonPatch(polygon, color='0.7', lw=0, alpha=0.7, zorder=1)
    axArr.add_patch(mpl_poly)

axArr.autoscale_view()
axArr.set_title('Objects')
axArr.set_xticks([])
axArr.set_yticks([])
Esempio n. 28
0
def _plot_polygon_collection(
    ax, geoms, values=None, color=None, cmap=None, vmin=None, vmax=None, **kwargs
):
    """
    Plots a collection of Polygon and MultiPolygon geometries to `ax`

    Parameters
    ----------
    ax : matplotlib.axes.Axes
        where shapes will be plotted
    geoms : a sequence of `N` Polygons and/or MultiPolygons (can be mixed)

    values : a sequence of `N` values, optional
        Values will be mapped to colors using vmin/vmax/cmap. They should
        have 1:1 correspondence with the geometries (not their components).
        Otherwise follows `color` / `facecolor` kwargs.
    edgecolor : single color or sequence of `N` colors
        Color for the edge of the polygons
    facecolor : single color or sequence of `N` colors
        Color to fill the polygons. Cannot be used together with `values`.
    color : single color or sequence of `N` colors
        Sets both `edgecolor` and `facecolor`
    **kwargs
        Additional keyword arguments passed to the collection

    Returns
    -------
    collection : matplotlib.collections.Collection that was plotted
    """

    try:
        from descartes.patch import PolygonPatch
    except ImportError:
        raise ImportError(
            "The descartes package is required for plotting polygons in geopandas. "
            "You can install it using 'conda install -c conda-forge descartes' or "
            "'pip install descartes'."
        )
    from matplotlib.collections import PatchCollection

    geoms, multiindex = _flatten_multi_geoms(geoms)
    if values is not None:
        values = np.take(values, multiindex, axis=0)

    # PatchCollection does not accept some kwargs.
    kwargs = {
        att: value
        for att, value in kwargs.items()
        if att not in ["markersize", "marker"]
    }

    # Add to kwargs for easier checking below.
    if color is not None:
        kwargs["color"] = color

    _expand_kwargs(kwargs, multiindex)

    collection = PatchCollection([PolygonPatch(poly) for poly in geoms], **kwargs)

    if values is not None:
        collection.set_array(np.asarray(values))
        collection.set_cmap(cmap)
        if "norm" not in kwargs:
            collection.set_clim(vmin, vmax)

    ax.add_collection(collection, autolim=True)
    ax.autoscale_view()
    return collection
Esempio n. 29
0
 def test_patch(self):
     patch = PolygonPatch(self.thing)
     self.failUnlessEqual(str(type(patch)), 
         "<class 'matplotlib.patches.PathPatch'>")
     path = patch.get_path()
     self.failUnless(len(path.vertices) == len(path.codes) == 198)
# print("Threshold value:", crimeThreshold)
# for value in blockCrimeRate_dict.values():
#     if value[1] > crimeThreshold:
#         polygon = polygons[value[0]]
#         patch = PolygonPatch(polygon, facecolor='yellow', edgecolor='yellow', alpha=1)
#         ax.add_patch(patch)
#         userMap.blockedPolygons.append(polygon)
#     else:
#         break;

crimeData = list(blockCrimeRate_dict.values())
# print(len(crimeData))
for i in range(len(crimeData)):
    if i < thresholdIndex:
        polygon = userMap.polygons[crimeData[i][0]]
        patch = PolygonPatch(polygon, facecolor='yellow', edgecolor='yellow', alpha=1)
        ax.add_patch(patch)
        userMap.blockedPolygons.append(polygon)
    else:
        break;

for i in range(len(userMap.polygons)):
    x1, y1 = userMap.polygons[i].bounds[0], userMap.polygons[i].bounds[1]
    node = Node(x1, y1, 0)
    childNodes = []
    cellsize = userMap.cellsize

    if(is_inside_area(x1, y1+cellsize, userMap)) :
        edgeCost = get_edge_cost(x1, y1, x1, y1+cellsize, userMap.blockedPolygons, False, "T")
        if(edgeCost > 0):
            childNodes.append(Node(x1, y1+cellsize, edgeCost))
Esempio n. 31
0

def affine_h(geom, m):
    return affine_transform(
        geom, [m[0, 0], m[0, 1], m[1, 0], m[1, 1], m[0, 2], m[1, 2]])


ax = plt.axes()

p1 = Polygon([(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)])

p2 = affine_h(p1, transl(0, 1) @ rot(pi / 4, 0, 0))

patch = PolygonPatch(p1,
                     facecolor='#ff3333',
                     edgecolor='#6699cc',
                     alpha=0.5,
                     zorder=2)
ax.add_patch(patch)

patch = PolygonPatch(p2,
                     facecolor='#ff3333',
                     edgecolor='#6699cc',
                     alpha=0.5,
                     zorder=2)
ax.add_patch(patch)

ax.set_xlim(-1, 3)
ax.set_xticks(range(-1, 4))
ax.set_ylim(-1, 3)
ax.set_yticks(range(-1, 4))
Esempio n. 32
0
 def test_patch(self):
     patch = PolygonPatch(self.thing)
     self.failUnlessEqual(str(type(patch)),
                          "<class 'matplotlib.patches.PathPatch'>")
     path = patch.get_path()
     self.failUnless(len(path.vertices) == len(path.codes) == 330)
Esempio n. 33
0
def data_visualisation( nb_clust, mask_type, dct_patch, IMG_SIZE, LOD, img_id, terminaison='', namefolder='./',suffixe='', nClassest=2 ):


    # print('Total time in seconds:', interval)

    term_score = {}
    class_color = 0
    fig, ax = plt.subplots()

    mask_type = load_annotations("./annoWeird.csv", "./anno.csv", img_id, nb_clust, ax)

    pred = []
    real = []
    classesorder = []
    for key, ptch in dct_patch.items():

        try:
            colour = ptch.colour
            if colour != -1 :
                sh = shapely.geometry.Polygon(
                    [(ptch.column * ptch.size * LOD, IMG_SIZE[1] * LOD - ptch.row * ptch.size * LOD),
                     (ptch.column * ptch.size * LOD + ptch.size * LOD, IMG_SIZE[1] * LOD - ptch.row * ptch.size * LOD),
                     (ptch.column * ptch.size * LOD + ptch.size * LOD,
                      IMG_SIZE[1] * LOD - ptch.row * ptch.size * LOD + ptch.size * LOD),
                     (ptch.column * ptch.size * LOD, IMG_SIZE[1] * LOD - ptch.row * ptch.size * LOD + ptch.size * LOD)])
                for i, j in mask_type.items():
                    if j["WKT"].contains(sh):  # j["WKT"].intersects(sh): #
                        if j["Term"] not in term_score:
                            term_score[j["Term"]] = {}
                            term_score[j["Term"]]["Predicted"] = []
                            term_score[j["Term"]]["Patches"] = []
                            term_score[j["Term"]]["Real"] = class_color
                            classesorder.append(j["Term"])
                            class_color += 1
                        ax.add_patch(PolygonPatch(sh, color=hsv_to_rgb( [colour/ nb_clust, 1, 1])))
                        j["Clust"][colour].append(colour)
                        term_score[j["Term"]]["Predicted"].append(colour)
                        term_score[j["Term"]]["Patches"].append(key)
                        pred.append(colour)
                        real.append(term_score[j["Term"]]["Real"])
        except KeyError:
            pass

    # just show the
    fig.set_size_inches(30, 15)
    plt.title("coloration des zones déjà annotées" + terminaison)
    plt.savefig(namefolder + "coloration_zones_annotées_" + terminaison + suffixe + ".png", format="png")
    # ax.cla()

    print("Pour", nb_clust, "clusters \nARI=", adjusted_mutual_info_score(real, pred), "\nNMI=",
          normalized_mutual_info_score(real, pred), "\nhomogenitiy=", )
    predt=[]
    rt=[]
    for i in range(len(pred)):
        if real[i] == term_score["tumor"]["Real"]:
            predt.append(pred[i])
            rt.append(term_score["tumor"]["Real"])
    #True positive False_Positive for tumor


    maxs=[]

    for i in range(nb_clust):
      if i in pred:
        q=(predt.count(i)/pred.count(i))
        if q>0.5:
               maxs.append(i)

    fsc, sens, spec = 0 ,0 ,0
    if maxs:
        cptf=0
        cptt=0
        for i in maxs:
            cptt += predt.count(i)
            cptf += pred.count(i)
        print(maxs)
        print(cptt)
        print(len(predt))
        vp = cptt
        fp = cptf - cptt
        vn = len(pred) - len(predt) - cptf + cptt
        fn = len(predt) - cptt

        spec = vn / (vn + fp)
        sens = vp / (vp + fn)
        fsc =vp/(vp+(fp+fn)/2)

        print("vrai positif:", vp)
        print("faux positif:", fp )
        print("vrai négatif:", vn )
        print("faux négatif:",fn)
        print("sensibilité:", sens)
        print("spécificité:", spec)
        print("fscore:", fsc)





    classesorder ={}
    for k, i in term_score.items():
        classesorder[len(i["Predicted"])] = k
        print(k, len(i["Predicted"]))




    fig, ax = plt.subplots()
    fig.set_size_inches(20, 20)
    confusion_matrix( pred, real, class_color, nb_clust, ax, list(classesorder.values()))

    plt.title("Matrice de confusion" + terminaison)
    plt.savefig(namefolder + "Matrice_confusion_" + terminaison +suffixe+ ".png", format="png")
    ax.cla()

    nb_square = 100
    a = [(j["Term"], j) for i, j in mask_type.items()]

    rms = []
    for i, j in a:
        rm = True
        for b in j["Clust"]:
            if b:
                rm = False
                break
        if rm:
            rms.append((i, j))

    for r in rms:
        a.remove(r)
    a = sample(a, k=min(nb_square, len(a)))
    a = sorted(a, key=lambda x: x[0])

    nb_lines = 5

    x = 1
    fig, ax = plt.subplots()
    for i, j in a:
        ax = plt.subplot(nb_lines, nb_square // nb_lines, x)
        ax.set_title(j["Term"])
        draw_square_xy(j["Clust"], ax)
        ax.axis([0, 10, 0, 10])
        ax.axis("off")
        x += 1
    fig.set_size_inches(30, 15)
    plt.savefig(namefolder + "coloration_carrés_annotées" + terminaison + suffixe+ ".png", format="png")
    plt.close('all')
    return adjusted_mutual_info_score(real, pred), fsc
Esempio n. 34
0
def obstacle_simulation():
    """MISSING DOC

    Parameters
    ----------

    Returns
    -------
    None
    """
    start_time = time.time()

    # CA properties.
    CA_width = 3
    CA_length = 67
    trials_count = 1000
    trial_area_sidelength = 1000
    num_of_obstacles = 861

    obstacle_width_mu = 17
    obstacle_width_sigma = 3
    obstacle_length_mu = 8
    obstacle_length_sigma = 2

    # Booleans to control the computations and visualization
    do_compute_coverage = True
    do_sanity_check = False
    do_theory = True
    do_viz = True
    do_not_show_CAs = True
    do_houses_along_roads = True

    OS = Obstacles(CA_width, CA_length, trial_area_sidelength)

    gen_polygons_time = time.time()
    if do_houses_along_roads:
        houses_along_street = 30
        rows_of_houses = 15
        distance_between_two_houses = 20
        OS.generate_rectangular_obstacles_along_curves(obstacle_width_mu, obstacle_width_sigma, obstacle_length_mu,
                                                       obstacle_length_sigma, houses_along_street, rows_of_houses,
                                                       distance_between_two_houses)
    else:
        OS.generate_rectangular_obstacles_normal_distributed(num_of_obstacles, obstacle_width_mu, obstacle_width_sigma,
                                                             obstacle_length_mu, obstacle_length_sigma)

    # Number of obstacles may come from OS, so use that value
    obstacle_density = OS.num_of_obstacles / OS.trial_area_sidelength / OS.trial_area_sidelength

    OS.generate_CAs(trials_count)
    print('Generate polygons time:  {:1.3f} sec'.format(time.time() - gen_polygons_time))

    # Run trials.
    intersection_time = time.time()
    OS.compute_reduced_CAs()
    OS.compute_CA_lengths()
    print('Intersection time:       {:1.3f} sec'.format(time.time() - intersection_time))
    if do_compute_coverage:
        coverage_time = time.time()
        OS.compute_coverage()
        print('Coverage time:           {:1.3f} sec'.format(time.time() - coverage_time))

    if do_sanity_check:
        sanity_check_time = time.time()
        problematic_area, problematic_obstacles, problematic_CAs = OS.sanity_check()
        print('Sanity check time:       {:1.3f} sec'.format(time.time() - sanity_check_time))
    else:
        print('Sanity check time:       None')

    # Compute the probability based on theory.
    if do_theory:
        theory_time = time.time()
        x_resolution = 100
        x = np.linspace(0, CA_length, x_resolution)
        pdf_resolution = 25
        p_x, EX, beta_analytical, sanity_check = OS.cdf(x, obstacle_density, obstacle_width_mu,
                                                        obstacle_width_sigma, obstacle_length_mu,
                                                        obstacle_length_sigma, pdf_resolution)
        print('Theory time:             {:1.3f} sec'.format(time.time() - theory_time))
        beta_numerical = OS.total_coverage / OS.trial_area_sidelength / OS.trial_area_sidelength

    # Create figure for visual output.
    viz_time = time.time()
    show_CA_as_size = True
    fig = plt.figure(1, figsize=(12, 8), dpi=90)
    if do_viz:
        ax1 = fig.add_subplot(121)
        OS.show_simulation(ax1, CAs=(not do_not_show_CAs), CAs_reduced=(not do_not_show_CAs), obstacles_original=True,
                           obstacles_intersected=(not do_not_show_CAs), CA_first_point=False, debug_points=False)
        ax2 = fig.add_subplot(122)
    else:
        ax2 = fig.add_subplot(111)

    OS.show_CDF(ax2, show_CA_as_size)

    if do_sanity_check & do_viz:
        for o in problematic_obstacles:
            ax1.add_patch(PolygonPatch(o, facecolor='#ffff00', edgecolor='#000000', alpha=1, zorder=10, linewidth=0.25))
        for CAr in problematic_CAs:
            ax1.add_patch(
                PolygonPatch(CAr, facecolor='#ffff00', edgecolor='#000000', alpha=1, zorder=10, linewidth=0.25))

    print('Visualization time:      {:1.3f} sec'.format(time.time() - viz_time))

    print('Total time:              {:1.3f} sec'.format(time.time() - start_time))

    print('---------------------------')

    print('Original CA:             {:1.0f} m^2'.format(OS.CA_length * OS.CA_width))
    print('Average reduced CA:      {:1.0f} m^2 ({:d}%)'.format(np.mean(OS.CA_lengths) * OS.CA_width, int(
        round(100 * np.mean(OS.CA_lengths) / OS.CA_length))))
    print('Analytical reduced CA    {:1.0f} m^2'.format(EX * OS.CA_width))

    print('---------------------------')
    if do_sanity_check:
        print('Total intersection area: {:1.0f} m^2 (should be small or zero)'.format(problematic_area))
    print('Number of CA reduced:    {:d}   ({:d}%)'.format(OS.num_of_reduced_CA,
                                                           int(round(100 * OS.num_of_reduced_CA / OS.trials_count))))
    print('Number of CA empty:      {:d}   ({:d}%)'.format(OS.num_of_empty_CA,
                                                           int(round(100 * OS.num_of_empty_CA / OS.trials_count))))
    print('Obstacle density:        {:1.0f} #/km^2'.format(obstacle_density * 1E6))
    if do_compute_coverage:
        print('Obstacle total area:     {:1.0f} m^2'.format(OS.total_obstacle_area))
        print('Obstacle coverage (num): {:1.0f} m^2'.format(OS.total_coverage))
        print('Obstacle coverage (ana): {:1.0f} m^2'.format(
            OS.num_of_obstacles * obstacle_width_mu * obstacle_length_mu))
        print('Coverage ratio:          {:1.3f}'.format(OS.total_coverage / OS.total_obstacle_area))
    if do_theory:
        print('beta (numerical):        {:1.5f}'.format(beta_numerical))
        print('beta (analytical):       {:1.5f}'.format(beta_analytical))
        print('fractiona of empty CA):  {:1.3f}'.format(OS.num_of_empty_CA / trials_count))
    if do_sanity_check:
        print('PDF sanity check:        {:1.3f}'.format(sanity_check))

    # Show the curve from theory    
    if do_theory:
        if not show_CA_as_size:
            ax2.plot(x, p_x, '.', label='Model CDF')
        else:
            ax2.plot(x * OS.CA_width, p_x, '-', label='Model CDF')
        ax2.plot(0, beta_analytical, 'o', color='#00ff00', label='beta anlytical')
        ax2.plot(0, beta_numerical, 'o', color='#ff0000', label='beta numerical')
        ax2.plot(0, OS.num_of_empty_CA / trials_count, 'o', color='#0000ff', label='Frac of empty CA')
        ax2.legend(loc="upper left", )
        ax2.grid()
        ax2.yaxis.set_ticks(np.arange(0, 1, 0.1))

    plt.show()

    fig.savefig('Sim_random.png', format='png', dpi=300)
Esempio n. 35
0
                xytext=(0, 8))


fig = pyplot.figure(1, figsize=SIZE, dpi=90)

triangle = Polygon([(1, 1), (2, 3), (3, 1)])

xrange = [0, 5]
yrange = [0, 4]

# 1
ax = fig.add_subplot(121)

patch = PolygonPatch(triangle,
                     facecolor=GRAY,
                     edgecolor=GRAY,
                     alpha=0.5,
                     zorder=1)
triangle_a = affinity.scale(triangle, xfact=1.5, yfact=-1)
patch_a = PolygonPatch(triangle_a,
                       facecolor=BLUE,
                       edgecolor=BLUE,
                       alpha=0.5,
                       zorder=2)
ax.add_patch(patch)
ax.add_patch(patch_a)

add_origin(ax, triangle, 'center')

ax.set_title("a) xfact=1.5, yfact=-1")