Example #1
0
def construct_hex_grid(XYs, tiles_x, tiles_y):
    """
    Build hexagon grid over study area with user-defined number of tiles.
    
    Parameters
    ----------
    XYs : Geoseries series
        Series containing X and Y coordinates.
    tiles_x : integer
        Integer declaring number of tiles along X axis.
    tiles_y : integer
        Integer declaring number of tiles along Y axis.
        
    Returns
    -------
    grid : GeoDataFrame Dataframe
        GeoDataFrame with hexagon grids as shapely polygons.
    
    """
    minx, miny, maxx, maxy = XYs.total_bounds
    padding = 1.e-9 * (maxx - minx)
    minx -= padding
    maxx += padding
    dx = (maxx - minx) / tiles_x
    dy = (maxy - miny) / tiles_y

    tiles_x1 = tiles_x + 1
    tiles_y1 = tiles_y + 1
    n = tiles_x1 * tiles_y1 + tiles_x * tiles_y

    offsets = np.zeros((n, 2), float)
    offsets[:tiles_x1 * tiles_y1, 0] = np.repeat(np.arange(tiles_x1), tiles_y1)
    offsets[:tiles_x1 * tiles_y1, 1] = np.tile(np.arange(tiles_y1), tiles_x1)
    offsets[tiles_x1 * tiles_y1:,
            0] = np.repeat(np.arange(tiles_x) + 0.5, tiles_y)
    offsets[tiles_x1 * tiles_y1:,
            1] = np.tile(np.arange(tiles_y), tiles_x) + 0.5

    offsets[:, 0] *= dx
    offsets[:, 1] *= dy
    offsets[:, 0] += minx
    offsets[:, 1] += miny

    polygon = [dx, dy / 3] * np.array([[.5, -.5], [.5, .5], [0., 1.],
                                       [-.5, .5], [-.5, -.5], [0., -1.]])

    collection = PolyCollection([polygon], offsets=offsets)
    hex_polys = collection.get_paths()[0].vertices
    hex_array = []
    for xs, ys in collection.get_offsets():
        hex_x = np.add(hex_polys[:, 0], xs)
        hex_y = np.add(hex_polys[:, 1], ys)
        hex_array.append(Polygon(np.vstack([hex_x, hex_y]).T))

    hex_grid = gpd.GeoDataFrame({'geometry': hex_array})

    return hex_grid
def test_poly_collection_2d_to_3d_empty():
    poly = PolyCollection([])
    art3d.poly_collection_2d_to_3d(poly)
    assert isinstance(poly, art3d.Poly3DCollection)
    assert poly.get_paths() == []

    fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
    ax.add_artist(poly)
    minz = poly.do_3d_projection()
    assert np.isnan(minz)

    # Ensure drawing actually works.
    fig.canvas.draw()
    def zoom_in_area(self, fill_area: PolyCollection):
        paths = fill_area.get_paths()
        verts = paths[0].vertices
        beginning = np.min(verts[:, 0])
        end = np.max(verts[:, 0])
        # print(beginning, end)
        indmin, indmax = 0, 0
        if self.use_dates:
            indmin, indmax = self.get_index_from_datetime(beginning, end)
        else:
            indmin, indmax = np.searchsorted(self.x, (int(beginning), int(end)))
            indmax = min(len(self.x) - 1, indmax)

        thisx = self.x[indmin:indmax]
        thisy = self.y[indmin:indmax]
        self.line2.set_data(thisx, thisy)
        ax2.set_xlim(thisx[0], thisx[-1])
        ax2.set_ylim(thisy.min(), thisy.max())
def test_poly_collection_2d_to_3d_empty():
    poly = PolyCollection([])
    art3d.poly_collection_2d_to_3d(poly)
    assert isinstance(poly, art3d.Poly3DCollection)
    assert poly.get_paths() == []
Example #5
0
def test_poly_collection_2d_to_3d_empty():
    poly = PolyCollection([])
    art3d.poly_collection_2d_to_3d(poly)
    assert isinstance(poly, art3d.Poly3DCollection)
    assert poly.get_paths() == []
Example #6
0
    def plotCurrent(self, dtfrom, fnamebase):
        
        
        #self.figure.clf()
        #self.canvas.draw()

        #self.loadModel()
        
        self.progressBar.setValue(51)
        frmDate = self.dtFrom.dateTime()


        #print 'Plotting till date: ' + dtfrom.date().toString()
        # get velocity nearest to current time
        ##dtnow = dt.datetime.utcnow() + dt.timedelta(hours=0)
        
        day = dtfrom.date().day()
        month = dtfrom.date().month()
        year = dtfrom.date().year()
        hour = dtfrom.time().hour()
        minute = dtfrom.time().minute()
        second = dtfrom.time().second()
        msecond = dtfrom.time().msec()
        
        #print dir(dtnow)
        #print dtnow.time()
        
        
        startdt = dt.datetime(year, month, day, hour, minute, second, msecond)
        #print startdt
        
        #print start
        istart = netCDF4.date2index(startdt,self.time_var,select=self.interp_method)
        layer = 0 # surface layer
        u = self.nc.variables[self.uvar][istart, layer, :]
        v = self.nc.variables[self.vvar][istart, layer, :]
        mag = numpy.sqrt((u*u)+(v*v)) 
        
        #print start
        #print istart
               
        self.progressBar.setValue(63)
        
        # Now try plotting speed and vectors with Basemap using a PolyCollection
        m = Basemap(projection='merc',  llcrnrlat=self.lat.min(), urcrnrlat=self.lat.max(), 
                                        llcrnrlon=self.lon.min(), urcrnrlon=self.lon.max(), 
                                        lat_ts=self.lat.mean(), resolution=None)

        # project from lon,lat to mercator
        xnode, ynode = m(self.lon, self.lat) 
        xc, yc = m(self.lonc, self.latc) 

        nv = self.nc.variables[self.nvvar][:].T - 1
        # create a TRI object with projected coordinates
        tri = Tri.Triangulation(xnode, ynode, triangles=nv)

        self.progressBar.setValue(77)
        sig_lay = self.nc.variables['siglay']
        zeta = self.nc.variables['zeta']
        
        # make a PolyCollection using triangles
        verts = concatenate((tri.x[tri.triangles][..., None],
              tri.y[tri.triangles][..., None]), axis=2)

        colorlut = []
        fid = 0
        for poly in verts:
            fid = fid + 1
       

        collection = PolyCollection(verts)
        collection.set_edgecolor('none')

        self.progressBar.setValue(81)

        timestamp=startdt.strftime('%Y-%m-%d %H:%M:%S')


        # set the magnitude of the polycollection to the speed
        collection.set_array(mag)

        
        #sys.exit(1)    
        collection.norm.vmin=0
        collection.norm.vmax=0.5


        #for path in collection.get_paths():

        cmap =collection.cmap
        featurecount = fid
        
        redArray =  matplotlib.colors.makeMappingArray(featurecount,cmap._segmentdata['red'], 1.0)            
        greenArray =  matplotlib.colors.makeMappingArray(featurecount,cmap._segmentdata['green'], 1.0)  
        blueArray =  matplotlib.colors.makeMappingArray(featurecount,cmap._segmentdata['blue'], 1.0)                
                        
        fid = 0    
        for path in collection.get_paths():
            tricolor = self.makehexcolor(redArray[fid], greenArray[fid], blueArray[fid])
            ##print tricolor
            name = "polygon#" + str(fid)
            colorlut.append(tricolor)
            #self.dbcur.execute("insert into polystyle values(?,?)",[name,str(tricolor) ])
            fid = fid + 1

        ds, lyr = self.init_vector(fnamebase)
        fid = 0
        for poly in verts:
            #print "polygon"
            linecoords = []
            feat = ogr.Feature( lyr.GetLayerDefn())
            feat.SetField( "idd", "idd1" )
            name = "polygon#" + str(fid)
            feat.SetField( "name", name )
            feat.SetField( "color", colorlut[fid] )
            fid = fid + 1
            path = ogr.Geometry(ogr.wkbPolygon)    
            extring = ogr.Geometry(ogr.wkbLinearRing)
            #path.getExteriorRing();
        
            for coord in poly:
                ##print coord
                cc = m(coord[0],coord[1],inverse=True)
                #print cc
                x = cc[0]
                y = cc[1]
                pt = fid
                tstamp = startdt.strftime('%Y-%m-%d %H:%M:%S')
                z = 0
                #z = sig_lay[pt:pt] * (zeta[pt:pt] - self.nc.variables[self.hvar][pt:pt])
                #print (zeta[tstamp,pt]) # - self.nc.variables[self.hvar][pt])
                #print zeta[:pt]
                #sys.exit(1)
                extring.AddPoint(x, y,z)
                
            extring.CloseRings()    
            polygon = ogr.Geometry(ogr.wkbPolygon)
            polygon.AddGeometry(extring)
            feat.SetGeometry(polygon)
            if lyr.CreateFeature(feat) != 0:
                print "Failed to create feature in shapefile.\n"
                sys.exit( 1 )
            ##else:
                ##print 'creaating feature' + str(feat.GetFID());

            feat.Destroy()
            lyr.SyncToDisk()          
        
        ax2=self.figure.add_subplot(111)
        coll = m.drawmapboundary(fill_color='0.3')
        
        
        self.progressBar.setValue(89)
        
        #m.drawcoastlines()
        #m.fillcontinents()
        # add the speed as colored triangles 
        ax2.add_collection(collection) # add polygons to axes on basemap instance
        # add the vectors
        #Q = m.quiver(xc,yc,u,v,scale=30)
        Q = m.quiver(xc, yc, u, v, scale=100);
        
        ##self.progressBar.setValue(94)
        # add a key for the vectors
        qk = plt.quiverkey(Q,0.1,0.1,0.20,'0.2 m/s',labelpos='W')
        title('FVCOM Surface Current speed at %s UTC' % timestamp)
  
        # refresh canvas
        self.progressBar.setValue(97)
        
        self.canvas.draw()
        
        self.progressBar.setValue(100)
        
        self.animate(False)

        print "returning..."
        outfile = fnamebase + ".shp"
        return outfile
Example #7
0
    def set_data(self, zname=None, zdata=None, zcolor=None, plot_type="poly"):
        if zdata != None:
            if plot_type is "poly":
                if zname not in self.clts:  #plottables['plotted']:#self.pd.list_data():
                    clt = PolyCollection(
                        [], alpha=0.5, antialiased=True
                    )  #, rasterized=False, antialiased=False)
                    if zcolor is not None:
                        clt.set_color(colorConverter.to_rgba(zcolor))
                    self.clts[zname] = clt
                    self.axe.add_collection(self.clts[zname])
                self.clts[zname].set_verts(zdata)

            elif plot_type is "line":
                if zname not in self.clts:
                    clt = LineCollection(
                        zdata)  #, linewidths=(0.5, 1, 1.5, 2),
                    #linestyles='solid', colors=("red", "blue", "green"))
                    if zcolor is not None:
                        clt.set_color(zcolor)
                    else:
                        clt.set_array(arange(len(zdata)))
                else:
                    self.clts[zname].set_verts(zdata)
                    #self.set_xlim(x.min(), x.max())
                    #self.set_ylim(ys.min(), ys.max())

            elif plot_type is "scatter":
                self.axe.scatter(zdata, zdata)
            elif plot_type is "colormap":
                self.axe.pcolormesh(x, y, z)

        if 0:
            x = arange(3)
            ys = array([x + i for i in arange(5)])
            #xdata=arange(len(getattr(self, zname)))

            data = [list(zip(x, y)) for y in ys]
            line_segments = LineCollection(data,
                                           linewidths=1,
                                           linestyles='solid',
                                           colors=mycolors)
            print data
            print len(data)
            #print line_segments.properties()
            #print line_segments.set_hatch("O")
            #print dir(self.axe)

            print[p.vertices for p in line_segments.get_paths()]  #)
            print line_segments.get_segments()
            line_segments.set_array(arange(len(data)))

            x = arange(3)
            ys = array([x + i for i in arange(2)])
            #xdata=arange(len(getattr(self, zname)))

            data = [list(zip(x, y)) for y in ys]

            line_segments.set_verts(data)
            #self.axe.add_collection(line_segments, autolim=True)

            clt = self.axe.scatter(x, x)
            #clt.set_linestyle("solid")
            print dir(clt)
            print clt.get_paths()
        if 0:
            #clt=QuadMesh(0, 0, [1])

            n = 12
            x = linspace(-1.5, 1.5, n)
            y = linspace(-1.5, 1.5, n * 2)
            X, Y = meshgrid(x, y)
            print X
            Qx = cos(Y) - cos(X)
            Qz = sin(Y) + sin(X)
            Qx = (Qx + 1.1)
            Z = sqrt(X**2 + Y**2) / 5
            Z = (Z - Z.min()) / (Z.max() - Z.min())
            Zm = ma.masked_where(fabs(Qz) < 0.5 * amax(Qz), Z)

            #ax = fig.add_subplot(121)
            #self.axe.set_axis_bgcolor("#bdb76b")
            clt = self.axe.pcolormesh(Z)
            #print dir(clt)
            self.axe.set_title('Without masked values')