Ejemplo n.º 1
0
def add_country(country, color):
    if country == "Seychelles" or country == "Mauritius":
        return
    seg = map.Africa[country_codes.index(country_code_dict[country])]
    poly = Polygon(seg, facecolor=color, edgecolor=color)
    poly.set_alpha(0.4)
    ax.add_patch(poly)
Ejemplo n.º 2
0
def parallelogram_gen(origin, side1, side2, size, opacity = 1):
    # We rescale the points for the [1,1]^2 domain
    first_point = origin/size
    side1_scaled = side1/size
    side2_scaled = side2/size

    # Getting the points
    second_point= (first_point + side1_scaled)
    fourth_point= (first_point + side2_scaled)
    third_point = side1_scaled+side2_scaled+first_point

    x = [first_point[0],second_point[0],third_point[0],fourth_point[0]]
    y = [first_point[1],second_point[1],third_point[1],fourth_point[1]];

    fig = plt.figure(0,frameon=False,figsize=(1,1), dpi=size)
    ax =  plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    # Paralllogelogram
    p = Polygon(xy=list(zip(x,y)))
    ax.add_patch(p)
    p.set_alpha(None)
    p.set_facecolor(np.zeros(3))
    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)
    fig.add_axes(ax)
    plt.axis('off')
    # Convert figure to data
    data = fig2data(fig)
    plt.close(fig)
    # Take just the first color entry
    data = data[:,:,1]
    # Normalize the data
    data = data/data.max()
    data = np.flip(data,0)
    return ((data-1)*opacity)+1
 def plotReachSet_norm1(self, NUM, figname):
     fig = p.figure()
     for j in range(n):
         ax = fig.add_subplot(2,2,j+1 , aspect='equal')
         ax.set_xlim(0, 4)
         ax.set_ylim(0, 1)
         ax.set_xlabel('$x_'+str(j+1)+'$')
         ax.set_ylabel('$y_'+str(j+1)+'$')
         for trace in self:
             for i in [int(floor(k*len(trace.T)/NUM)) for k in range(NUM)]:
                 verts = [(trace.x[i][j] + 1/trace.d_norm1[i][2*j], trace.y[i][j]                          ),
                          (trace.x[i][j]                            , trace.y[i][j] - 1/trace.d_norm1[i][2*j+1]),
                          (trace.x[i][j] - 1/trace.d_norm1[i][2*j], trace.y[i][j]                          ),
                          (trace.x[i][j]                              , trace.y[i][j] + 1/trace.d_norm1[i][2*j+1])]
                 # poly = Ellipse((trace.x[i][j],trace.y[i][j]), width=trace.d1[i], height=trace.d2[i], angle=trace.theta[i])
                 poly = Polygon(verts, facecolor='0.8', edgecolor='k')
                 ax.add_artist(poly)
                 poly.set_clip_box(ax.bbox)
                 poly.set_alpha(1)
                 if i==0:
                     poly.set_facecolor('r')
                 else:
                     poly.set_facecolor(p.rand(3))
         #for trace in self:
             #e = Ellipse((trace.x[0][j],trace.y[0][j]), width=trace.d1[0], height=trace.d2[0], angle=trace.theta[0])
             #ax.add_artist(e)
             #e.set_clip_box(ax.bbox)
             #e.set_alpha(1)
             #e.set_facecolor('r')
 #e.set_edgecolor('r')
     p.savefig(figname)
Ejemplo n.º 4
0
 def fillPolygon(self,xy,color = None, fill_color = None, ax=None,zorder=None,alpha=None):
     if self.resolution is None:
         raise AttributeError('there are no boundary datasets associated with this Basemap instance')
     # get current axes instance (if none specified).
     ax = ax or self._check_ax()
     # get axis background color.
     axisbgc = ax.get_axis_bgcolor()
     npoly = 0
     polys = []
     # xa, ya = list(zip(*map.county_region[0]))
     # check to see if all four corners of domain in polygon (if so,
     # don't draw since it will just fill in the whole map).
     # ** turn this off for now since it prevents continents that
     # fill the whole map from being filled **
     # xy = list(zip(xa.tolist(),ya.tolist()))
     if self.coastpolygontypes[npoly] not in [2,4]:
         poly = Polygon(xy,facecolor=color,edgecolor=color,linewidth=0)
     else: # lakes filled with background color by default
         if fill_color is None:
             poly = Polygon(xy,facecolor=axisbgc,edgecolor=axisbgc,linewidth=0)
         else:
             poly = Polygon(xy,facecolor=fill_color,edgecolor=fill_color,linewidth=0)
     if zorder is not None:
         poly.set_zorder(zorder)
     if alpha is not None:
         poly.set_alpha(alpha)
     ax.add_patch(poly)
     polys.append(poly)
     npoly = npoly + 1
     # set axes limits to fit map region.
     self.set_axes_limits(ax=ax)
     # clip continent polygons to map limbs
     polys,c = self._cliplimb(ax,polys)
     return polys
 def __add_xy_values_as_polygon__(self, xy: list, color: str, closed=False, fill=False, alpha=0.2, line_width=2):
     xy = PlotterInterface.get_xy_from_timestamp_to_date_number(xy)
     polygon = Polygon(np.array(xy), closed=closed, fill=fill)
     polygon.set_visible(True)
     polygon.set_color(color)
     polygon.set_alpha(alpha)
     polygon.set_linewidth(line_width)
     self.axes_for_candlesticks.add_patch(polygon)
Ejemplo n.º 6
0
 def draw_enter_exit(self):
     """plot enter and exit cells on the graph"""
     start_polygon = Polygon(self.get_polygon_points(self.maze.start), True)
     exit_polygon = Polygon(self.get_polygon_points(self.maze.exit), True)
     start_polygon.set_facecolor(self.start_color)
     exit_polygon.set_facecolor(self.exit_color)
     exit_polygon.set_alpha(0.4)
     self.ax.add_patch(start_polygon)
     self.ax.add_patch(exit_polygon)
     return
Ejemplo n.º 7
0
 def animate_polygons(self, frame):
     point = self.path[frame]
     polygon = Polygon(self.get_polygon_points(point), True)
     if point not in [self.maze.start, self.maze.exit]:
         if point in self.path[:frame]:
             #backtracking
             polygon.set_facecolor(self.polygon_backtracking_color)
             polygon.set_edgecolor(self.polygon_backtracking_edge_color)
             self.ax.add_patch(polygon)
         else:
             polygon.set_facecolor(self.polygon_face_color)
             polygon.set_edgecolor(self.polygon_edge_color)
             self.ax.add_patch(polygon)
     if point == self.maze.exit:
         polygon.set_facecolor(self.exit_color)
         polygon.set_alpha(1)
         self.ax.add_patch(polygon)
     return []
Ejemplo n.º 8
0
def fill_between(x, y1, y2, ax=P.gca(), alpha=0.5, **kwargs):
    """Plot distribution to a head surface, derived from some sensor locations.

    The sensor locations are first projected onto the best fitting sphere and
    finally projected onto a circle (by simply ignoring the z-axis).

    :Parameters:
      x:
      ,y1,y2
      ax: mpl axes
        axes to plot to. Standard is pylab.
      view: one of 'top' and 'rear'
        Defines from where the head is viewed.
      **kwargs:
        All additional arguments will be passed to `pylab.imshow()`.


    :Returns:
      (map, head, sensors)
        The corresponding matplotlib objects are returned if plotted, ie.
        if plothead is set to `False`, `head` will be `None`.

          map
            The colormap that makes the actual plot, a
            matplotlib.image.AxesImage instance.
          head
            What is returned by `plot_head_outline()`.
          sensors
            The dots marking the electrodes, a matplotlib.lines.Line2d
            instance.
    """
    # add x,y2 in reverse order for proper polygon filling
    verts = zip(x,y1) + [(x[i], y2[i]) for i in range(len(x)-1,-1,-1)]
    poly = Polygon(verts, **kwargs)
    poly.set_alpha(alpha)
    ax.add_patch(poly)
    ax.autoscale_view()
    return poly
Ejemplo n.º 9
0
class PolygonInteractor(QtCore.QObject):
    """
    Polygon Interactor

    Parameters
    ----------
    axtmp : matplotlib axis
        matplotlib axis
    pntxy :

    """
    showverts = True
    epsilon = 5  # max pixel distance to count as a vertex hit
    polyi_changed = QtCore.pyqtSignal(list)

    def __init__(self, axtmp, pntxy):
        QtCore.QObject.__init__(self)
        self.ax = axtmp
        self.poly = Polygon([(1, 1)], animated=True)
        self.ax.add_patch(self.poly)
        self.canvas = self.poly.figure.canvas
        self.poly.set_alpha(0.5)
        self.pntxy = pntxy
        self.ishist = True
        self.background = self.canvas.copy_from_bbox(self.ax.bbox)

        xtmp, ytmp = list(zip(*self.poly.xy))

        self.line = Line2D(xtmp, ytmp, marker='o', markerfacecolor='r',
                           color='y', animated=True)
        self.ax.add_line(self.line)

        self.poly.add_callback(self.poly_changed)
        self._ind = None  # the active vert

        self.canvas.mpl_connect('button_press_event',
                                self.button_press_callback)
        self.canvas.mpl_connect('button_release_event',
                                self.button_release_callback)
        self.canvas.mpl_connect('motion_notify_event',
                                self.motion_notify_callback)

    def draw_callback(self):
        """ Draw callback """
        self.background = self.canvas.copy_from_bbox(self.ax.bbox)
        QtWidgets.QApplication.processEvents()

        self.canvas.restore_region(self.background)
        self.ax.draw_artist(self.poly)
        self.ax.draw_artist(self.line)
        self.canvas.update()

    def new_poly(self, npoly):
        """ New Polygon """
        self.poly.set_xy(npoly)
        self.line.set_data(list(zip(*self.poly.xy)))

        self.canvas.draw()
        self.update_plots()

    def poly_changed(self, poly):
        """ Changed Polygon """
        # this method is called whenever the polygon object is called
        # only copy the artist props to the line (except visibility)
        vis = self.line.get_visible()
        Artist.update_from(self.line, poly)
        self.line.set_visible(vis)  # don't use the poly visibility state

    def get_ind_under_point(self, event):
        """get the index of vertex under point if within epsilon tolerance"""

        # display coords
        xytmp = np.asarray(self.poly.xy)
        xyt = self.poly.get_transform().transform(xytmp)
        xtt, ytt = xyt[:, 0], xyt[:, 1]
        dtt = np.sqrt((xtt - event.x) ** 2 + (ytt - event.y) ** 2)
        indseq = np.nonzero(np.equal(dtt, np.amin(dtt)))[0]
        ind = indseq[0]

        if dtt[ind] >= self.epsilon:
            ind = None

        return ind

    def button_press_callback(self, event):
        """whenever a mouse button is pressed"""
        if event.inaxes is None:
            return
        if event.button != 1:
            return
        self._ind = self.get_ind_under_point(event)

        if self._ind is None:
            xys = self.poly.get_transform().transform(self.poly.xy)
            ptmp = self.poly.get_transform().transform([event.xdata, event.ydata])
#            ptmp = event.x, event.y  # display coords

            if len(xys) == 1:
                self.poly.xy = np.array(
                    [(event.xdata, event.ydata)] +
                    [(event.xdata, event.ydata)])
                self.line.set_data(list(zip(*self.poly.xy)))

                self.canvas.restore_region(self.background)
                self.ax.draw_artist(self.poly)
                self.ax.draw_artist(self.line)
                self.canvas.update()
                return
            dmin = -1
            imin = -1
            for i in range(len(xys) - 1):
                s0tmp = xys[i]
                s1tmp = xys[i + 1]
                dtmp = dist_point_to_segment(ptmp, s0tmp, s1tmp)

                if dmin == -1:
                    dmin = dtmp
                    imin = i
                elif dtmp < dmin:
                    dmin = dtmp
                    imin = i
            i = imin

#            breakpoint()
            self.poly.xy = np.array(list(self.poly.xy[:i + 1]) +
                                    [(event.xdata, event.ydata)] +
                                    list(self.poly.xy[i + 1:]))
            self.line.set_data(list(zip(*self.poly.xy)))

            self.canvas.restore_region(self.background)
            self.ax.draw_artist(self.poly)
            self.ax.draw_artist(self.line)
            self.canvas.update()

    def button_release_callback(self, event):
        """Whenever a mouse button is released"""
        if event.button != 1:
            return
        self._ind = None
        self.update_plots()

    def update_plots(self):
        """ Update Plots """
        polymask = Path(self.poly.xy).contains_points(self.pntxy)
        self.polyi_changed.emit(polymask.tolist())

    def motion_notify_callback(self, event):
        """on mouse movement"""
        if self._ind is None:
            return
        if event.inaxes is None:
            return
        if event.button != 1:
            return
        xtmp, ytmp = event.xdata, event.ydata

        self.poly.xy[self._ind] = xtmp, ytmp
        if self._ind == 0:
            self.poly.xy[-1] = xtmp, ytmp

        self.line.set_data(list(zip(*self.poly.xy)))

        self.canvas.restore_region(self.background)
        self.ax.draw_artist(self.poly)
        self.ax.draw_artist(self.line)
        self.canvas.update()
Ejemplo n.º 10
0
class Domain:
    def __init__(self, vertices, subdomains=[]):
        '''
        This class describes a 2D polygonal domain 
        defined by n vertices following a closed
        path:
        vertices = np.array([[x0,y0],
                             [x1,y1],
                             [x2,y2],
                              ...
                             [xn,yn]])

        '''
        self.vertices = vertices
        self.polygon = Polygon(vertices)
        self.path = self.polygon.get_path()
        self.subdomains = subdomains

    def __add__(self, other):
        if isinstance(other, Domain):
            return Domain(self.vertices, self.subdomains.append(other))
        else:
            return NotImplemented

    def __sub__(self, other):
        return None

    def __len__(self):
        return len(self.subdomains) + 1

    @property
    def area(self):
        ''' 
        Implementation of Shoelace formula using Numpy
        https://en.wikipedia.org/wiki/Shoelace_formula
        '''
        x = self.vertices[:, 0]
        y = self.vertices[:, 1]
        return 0.5 * np.abs(
            np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))

    def contains(self, points):
        """
        Return True for points inside Domain
        """
        return np.array(self.path.contains_points(points))

    def contains_all(self, points):
        """
        Return True if all points are inside Domain
        """
        return self.contains(points).all()

    def bounds(self):
        '''
        Returns a (minx, miny, maxx, maxy) tuple (float values) that bounds the object.
        '''
        return np.array(
            [np.min(self.vertices, axis=0),
             np.max(self.vertices, axis=0)])

    def addMaterial(self, Subdomain, Value):
        if self.contains_all(Subdomain.vertices):
            Subdomain.Value = Value
            self.subdomains.append(Subdomain)
        else:
            raise TypeError

    def plot(self, show=True):
        from matplotlib import pylab
        from matplotlib.lines import Line2D
        color = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w']
        fig, ax = pylab.subplots()
        self.polygon.set_alpha(0.3)
        x, y = zip(*self.polygon.xy)

        line = Line2D(x, y, linestyle='-', marker='o', markerfacecolor='k')
        ax.add_line(line)
        ax.set_title('Computational Domain')
        ax.set_xlim((min(x) - 0.1 * max(x), 1.1 * max(x)))
        ax.set_ylim((min(y) - 0.1 * max(y), 1.1 * max(y)))
        line.set_color('k')
        ax.add_patch(self.polygon)
        for i, sub in enumerate(self.subdomains):
            x, y = zip(*sub.polygon.xy)
            line = Line2D(x, y, linestyle='--', color='k')
            ax.add_line(line)
            sub.polygon.set_color(color[1])
            sub.polygon.set_alpha(0.3)
            ax.add_patch(sub.polygon)
        if show:
            pylab.show()
Ejemplo n.º 11
0
class PolygonInteractor(QtCore.QObject):
    """
    Polygon Interactor

    Parameters
    ----------
    axtmp : matplotlib axis
        matplotlib axis
    pntxy :

    """
    showverts = True
    epsilon = 5  # max pixel distance to count as a vertex hit
    polyi_changed = QtCore.pyqtSignal(list)

    def __init__(self, axtmp, pntxy):
        QtCore.QObject.__init__(self)
        self.ax = axtmp
        self.poly = Polygon([(1, 1)], animated=True)
        self.ax.add_patch(self.poly)
        self.canvas = self.poly.figure.canvas
        self.poly.set_alpha(0.5)
        self.pntxy = pntxy
        self.ishist = True
        self.background = self.canvas.copy_from_bbox(self.ax.bbox)

        xtmp, ytmp = list(zip(*self.poly.xy))

        self.line = Line2D(xtmp, ytmp, marker='o', markerfacecolor='r',
                           color='y', animated=True)
        self.ax.add_line(self.line)

        self.poly.add_callback(self.poly_changed)
        self._ind = None  # the active vert

        self.canvas.mpl_connect('button_press_event',
                                self.button_press_callback)
        self.canvas.mpl_connect('button_release_event',
                                self.button_release_callback)
        self.canvas.mpl_connect('motion_notify_event',
                                self.motion_notify_callback)

    def draw_callback(self):
        """ Draw callback """
        self.background = self.canvas.copy_from_bbox(self.ax.bbox)
        QtWidgets.QApplication.processEvents()

        self.canvas.restore_region(self.background)
        self.ax.draw_artist(self.poly)
        self.ax.draw_artist(self.line)
        self.canvas.update()

    def new_poly(self, npoly):
        """ New Polygon """
        self.poly.set_xy(npoly)
        self.line.set_data(list(zip(*self.poly.xy)))

        self.canvas.draw()
        self.update_plots()

    def poly_changed(self, poly):
        """ Changed Polygon """
        # this method is called whenever the polygon object is called
        # only copy the artist props to the line (except visibility)
        vis = self.line.get_visible()
        Artist.update_from(self.line, poly)
        self.line.set_visible(vis)  # don't use the poly visibility state

    def get_ind_under_point(self, event):
        """get the index of vertex under point if within epsilon tolerance"""

        # display coords
        xytmp = np.asarray(self.poly.xy)
        xyt = self.poly.get_transform().transform(xytmp)
        xtt, ytt = xyt[:, 0], xyt[:, 1]
        dtt = np.sqrt((xtt - event.x) ** 2 + (ytt - event.y) ** 2)
        indseq = np.nonzero(np.equal(dtt, np.amin(dtt)))[0]
        ind = indseq[0]

        if dtt[ind] >= self.epsilon:
            ind = None

        return ind

    def button_press_callback(self, event):
        """whenever a mouse button is pressed"""
        if event.inaxes is None:
            return
        if event.button != 1:
            return
        self._ind = self.get_ind_under_point(event)

        if self._ind is None:
            xys = self.poly.get_transform().transform(self.poly.xy)
            ptmp = event.x, event.y  # display coords

            if len(xys) == 1:
                self.poly.xy = np.array(
                    [(event.xdata, event.ydata)] +
                    [(event.xdata, event.ydata)])
                self.line.set_data(list(zip(*self.poly.xy)))

                self.canvas.restore_region(self.background)
                self.ax.draw_artist(self.poly)
                self.ax.draw_artist(self.line)
                self.canvas.update()
                return
            dmin = -1
            imin = -1
            for i in range(len(xys) - 1):
                s0tmp = xys[i]
                s1tmp = xys[i + 1]
                dtmp = dist_point_to_segment(ptmp, s0tmp, s1tmp)
                if dmin == -1:
                    dmin = dtmp
                    imin = i
                elif dtmp < dmin:
                    dmin = dtmp
                    imin = i
            i = imin
            self.poly.xy = np.array(list(self.poly.xy[:i + 1]) +
                                    [(event.xdata, event.ydata)] +
                                    list(self.poly.xy[i + 1:]))
            self.line.set_data(list(zip(*self.poly.xy)))

            self.canvas.restore_region(self.background)
            self.ax.draw_artist(self.poly)
            self.ax.draw_artist(self.line)
            self.canvas.update()

    def button_release_callback(self, event):
        """Whenever a mouse button is released"""
        if event.button != 1:
            return
        self._ind = None
        self.update_plots()

    def update_plots(self):
        """ Update Plots """
        polymask = Path(self.poly.xy).contains_points(self.pntxy)
        self.polyi_changed.emit(polymask.tolist())

    def motion_notify_callback(self, event):
        """on mouse movement"""
        if self._ind is None:
            return
        if event.inaxes is None:
            return
        if event.button != 1:
            return
        xtmp, ytmp = event.xdata, event.ydata

        self.poly.xy[self._ind] = xtmp, ytmp
        if self._ind == 0:
            self.poly.xy[-1] = xtmp, ytmp

        self.line.set_data(list(zip(*self.poly.xy)))

        self.canvas.restore_region(self.background)
        self.ax.draw_artist(self.poly)
        self.ax.draw_artist(self.line)
        self.canvas.update()
Ejemplo n.º 12
0
m.drawparallels(np.arange(20,80,5),labels=[1,0,0,0],fmt=lat2str(), dashes=[2,0], linewidth=0.5)
m.drawmeridians(np.arange(-20,60,5),labels=[0,0,0,1],fmt=lon2str(), dashes=[2,0], linewidth=0.5)

shp_info = m.readshapefile('cities','cities')
x, y = zip(*m.cities)
m.scatter(x,y,15,marker='o',edgecolors='k',color='none',zorder=10)

print m.proj4string

shp_info = m.readshapefile('polygon','sectors',drawbounds=True, color='r')

ax = plt.gca() # get current axes instance
for nshape,seg in enumerate(m.sectors):
    color = "#F9966B"
    poly = Polygon(seg,facecolor=color,edgecolor=color)
    poly.set_alpha(0.75)
    ax.add_patch(poly)

# m.drawlsmask(ocean_color='0.3', lakes=True)
m.fillcontinents(color='0.9', zorder=0)

plt.savefig('008_map_laea.png', dpi=72)
plt.savefig('008_map_laea_big.png', dpi=108)

# create new figure
fig=plt.figure(figsize=(8,5))

# setup oblique mercator basemap.
m = Basemap(projection='cyl',llcrnrlat=35,urcrnrlat=65,\
             llcrnrlon=-10,urcrnrlon=45,resolution='l')