Exemplo n.º 1
0
    def inpolygon(self):
        """
        Inpolygon logical test
        """
        xy = np.vstack((self.X,self.Y)).T

        return inpolygon(xy, self.agepoly)
Exemplo n.º 2
0
    def inpolygon(self):
        """
        Inpolygon logical test
        """
        xy = np.vstack((self.X, self.Y)).T

        return inpolygon(xy, self.agepoly)
Exemplo n.º 3
0
    def CalcAge(self):
        """     
        Calculate the age of a particle inside of the age polygon
        """
        #print '\t\tCalculating the particle age...'
        #inpoly = nxutils.points_inside_poly(np.vstack((self.particles['X'],self.particles['Y'])).T,self.agepoly)
        inpoly = inpolygon(np.vstack((self.particles['X'],self.particles['Y'])).T,self.agepoly)

        self.particles['age'][inpoly] = self.particles['age'][inpoly] + self.dt
        self.particles['age'][inpoly==False]=0.0

        # Update the agemax attribute
        self.particles['agemax'] = np.max([self.particles['age'],self.particles['agemax']],axis=0)
Exemplo n.º 4
0
    def setAgeSource(self,shpfile):
        """
        Sets the age source term using a polygon shapefile
        """
        # Read the shapefile
        XY,tmp = readShpPoly(shpfile,FIELDNAME=None)
        if len(XY)<1:
            raise Exception, ' could not find any polygons in shapefile: %s'%shpfile

        for xpoly in XY:
            xycells = np.asarray([self.xv,self.yv])
            #ind1 = nxutils.points_inside_poly(xycells.T,xpoly)
            ind1 = inpolygon(xycells.T,xpoly)
            # Sets all vertical layers for now...
            self.agesource[:,ind1] = 1.
Exemplo n.º 5
0
def maskPoly(X,Y,XYpoly):
    """
    Mask a region based on a polygon
    """
    # Reshape the input array
    sz = X.shape
    X = X.ravel()
    Y = Y.ravel()
        
    #ind = nxutils.points_inside_poly(np.vstack((X,Y)).T,XYpoly)
    ind = inpolygon(np.vstack((X,Y)).T,XYpoly)
    
    mask = np.zeros(sz,dtype=np.int)
    ind = ind.reshape(sz)
    mask[ind]=1

    return mask
Exemplo n.º 6
0
def maskPoly(X, Y, XYpoly):
    """
    Mask a region based on a polygon
    """
    # Reshape the input array
    sz = X.shape
    X = X.ravel()
    Y = Y.ravel()

    #ind = nxutils.points_inside_poly(np.vstack((X,Y)).T,XYpoly)
    ind = inpolygon(np.vstack((X, Y)).T, XYpoly)

    mask = np.zeros(sz, dtype=np.int)
    ind = ind.reshape(sz)
    mask[ind] = 1

    return mask
Exemplo n.º 7
0
    def inCell(self, cellind, xy):
        """
        Check whether a point is inside a cell

        Basically a wrapper for points_inside_polyo function        
        """

        xyverts = np.zeros((4, 2))
        xyverts[:,0]= [self.xp[self.cells[cellind,0]],\
                        self.xp[self.cells[cellind,1]],\
                        self.xp[self.cells[cellind,2]],\
                        self.xp[self.cells[cellind,0]]]
        xyverts[:,1]= [self.yp[self.cells[cellind,0]],\
                        self.yp[self.cells[cellind,1]],\
                        self.yp[self.cells[cellind,2]],\
                        self.yp[self.cells[cellind,0]] ]

        #return points_inside_poly(xy.reshape(1,2),xyverts)
        return inpolygon(xy.reshape(1, 2), xyverts)
Exemplo n.º 8
0
    def inCell(self,cellind,xy):
        """
        Check whether a point is inside a cell

        Basically a wrapper for points_inside_polyo function        
        """
        
        xyverts=np.zeros((4,2))                
        xyverts[:,0]= [self.x[self.triangles[cellind,0]],\
                        self.x[self.triangles[cellind,1]],\
                        self.x[self.triangles[cellind,2]],\
                        self.x[self.triangles[cellind,0]]]
        xyverts[:,1]= [self.y[self.triangles[cellind,0]],\
                        self.y[self.triangles[cellind,1]],\
                        self.y[self.triangles[cellind,2]],\
                        self.y[self.triangles[cellind,0]] ]
                        
        #return points_inside_poly(xy.reshape(1,2),xyverts)
        return inpolygon(xy.reshape(1,2),xyverts)
Exemplo n.º 9
0
    def inCellVecOld(self, cellinds, x, y):
        """
        Check whether a point is inside a cell

        Basically a wrapper for points_inside_poly function        
        """

        nx = x.shape[0]
        xyvertsall = np.zeros((nx, 4, 2))
        xyvertsall[:, 0, 0] = self.xp[self.cells[cellinds, 0]]
        xyvertsall[:, 1, 0] = self.xp[self.cells[cellinds, 1]]
        xyvertsall[:, 2, 0] = self.xp[self.cells[cellinds, 2]]
        xyvertsall[:, 3, 0] = self.xp[self.cells[cellinds, 0]]
        xyvertsall[:, 0, 1] = self.yp[self.cells[cellinds, 0]]
        xyvertsall[:, 1, 1] = self.yp[self.cells[cellinds, 1]]
        xyvertsall[:, 2, 1] = self.yp[self.cells[cellinds, 2]]
        xyvertsall[:, 3, 1] = self.yp[self.cells[cellinds, 0]]

        xyverts = np.zeros((4, 2))

        def _xyverts(ii):
            xyverts[:, :] = xyvertsall[ii, :, :]
            return xyverts

        xy = np.zeros((1, 2))

        def _xy(ii):
            xy[0, 0] = x[ii]
            xy[0, 1] = y[ii]
            return xy

        nx = x.shape[0]
        inpoly = np.zeros((x.shape), dtype=np.bool)
        for ii in range(nx):
            #inpoly[ii] = points_inside_poly(_xy(ii),_xyverts(ii))
            inpoly[ii] = inpolygon(_xy(ii), _xyverts(ii))

        return inpoly
Exemplo n.º 10
0
    def inCellVec(self,cellinds,x,y):
        """
        Check whether a point is inside a cell

        Basically a wrapper for points_inside_poly function        
        """
        
        nx = x.shape[0]
        xyvertsall=np.zeros((nx,4,2))  
        xyvertsall[:,0,0]= self.x[self.triangles[cellinds,0]]
        xyvertsall[:,1,0]= self.x[self.triangles[cellinds,1]]
        xyvertsall[:,2,0]= self.x[self.triangles[cellinds,2]]
        xyvertsall[:,3,0]= self.x[self.triangles[cellinds,0]]
        xyvertsall[:,0,1]= self.y[self.triangles[cellinds,0]]
        xyvertsall[:,1,1]= self.y[self.triangles[cellinds,1]]
        xyvertsall[:,2,1]= self.y[self.triangles[cellinds,2]]
        xyvertsall[:,3,1]= self.y[self.triangles[cellinds,0]] 
        
        
        xyverts=np.zeros((4,2))    
        def _xyverts(ii):
            xyverts[:,:] = xyvertsall[ii,:,:]
            return xyverts            
                            
        xy = np.zeros((1,2))
        def _xy(ii):
            xy[0,0]=x[ii]
            xy[0,1]=y[ii]
            return xy
            
        nx = x.shape[0]          
        inpoly = np.zeros((x.shape),dtype=np.bool)
        for ii in range(nx):
            #inpoly[ii] = points_inside_poly(_xy(ii),_xyverts(ii))
            inpoly[ii] = inpolygon(_xy(ii),_xyverts(ii))

        
        return inpoly
Exemplo n.º 11
0
def modifyBCmarker(suntanspath,bcfile):
    """
    Modifies SUNTANS boundary markers with a shapefile

    The shapefile must contain polygons with the integer-type field "marker"
    """
    
    print '#######################################################'
    print '     Modifying the boundary markers for grid in folder:'
    print '         %s'%suntanspath

    # Load the grid into an object
    grd = sunpy.Grid(suntanspath)
    
    # Find the edge points
    xe = np.mean(grd.xp[grd.edges],axis=1)
    ye = np.mean(grd.yp[grd.edges],axis=1)
    
    # Read the shapefile
    if not bcfile==None:
        XY,newmarker = readShpPoly(bcfile,FIELDNAME='marker')
        if len(XY)<1:
            print 'Error - could not find any polygons with the field name "marker" in shapefile: %s'%bcfile
            return
        
        XY,edge_id = readShpPoly(bcfile,FIELDNAME='edge_id')
        if len(XY)<1:
            print 'Error - could not find any polygons with the field name "edge_id" in shapefile: %s'%bcfile
            return
    else:
        XY=[]
        newmarker=[]
        edge_id=[]
    
    # Plot before updates
    #plt.figure()
    #grd.plotBC()
    #plt.plot(XY[0][:,0],XY[0][:,1],'m',linewidth=2)
    #plt.show()
    
    # Reset all markers to one (closed)
    ind0 = grd.mark>0
    grd.mark[ind0]=1
        
    # Find the points inside each of the polygon and assign new bc
    grd.edge_id = grd.mark*0 # Flag to identify linked edges/segments (marker=4 only)
    for xpoly, bctype,segmentID in zip(XY,newmarker,edge_id):
        ind0 = grd.mark>0
        edges = np.asarray([xe[ind0],ye[ind0]])
        mark = grd.mark[ind0]
        
        #ind1 = nxutils.points_inside_poly(edges.T,xpoly)
        ind1 = inpolygon(edges.T,xpoly)
        if bctype==4:
            eflag = grd.edge_id[ind0]
            eflag[ind1]=segmentID
            grd.edge_id[ind0]=eflag
            bctype=2
        mark[ind1]=bctype
        grd.mark[ind0]=mark
    
    # Save the new markers to edges.dat
    edgefile = suntanspath+'/edges.dat'
    grd.saveEdges(edgefile)
    print 'Updated markers written to: %s'%(edgefile)
    
    # Plot the markers
    plt.figure()
    grd.plotBC()
    if len(XY)>0:
        plt.plot(XY[0][:,0],XY[0][:,1],'m',linewidth=2)
    figfile = suntanspath+'/BoundaryMarkerTypes.pdf'
    plt.savefig(figfile)
    
    print 'Marker plot saved to: %s'%(figfile)
    print 'Done.'
    print '#######################################################'
Exemplo n.º 12
0

# Create the grid outline
xlims = [x.min(),x.max()]
ylims = [y.min(),y.max()]

xgrd = np.arange(xlims[0]-scale/2,xlims[1]+1.5*scale,scale)
ygrd = np.arange(ylims[0]-scale/2,ylims[1]+1.5*scale,scale)

nx = xgrd.shape[0]
ny = ygrd.shape[0]

# Create a mask polygon
X,Y = np.meshgrid(xgrd,ygrd)
XY = np.vstack((X.ravel(),Y.ravel())).T
mask = inpolygon(XY,xypoly)
mask = mask.reshape((ny,nx))

cells=[]
xp = []
yp = []

def pntindx(j,i,nrows):
    return j*nrows + i

for jj in range(ny):
    for ii in range(nx):
        #if mask[jj,ii]:
        xp.append(xgrd[ii])
        yp.append(ygrd[jj])
Exemplo n.º 13
0
def GridParticles(grdfile,dx,dy,nz,xypoly=None,splitvec=1):
    """
    Returns the locations of particles on a regular grid inside of suntans grid

    Inputs:
    	grdfile - netcdf filename containing the suntans grid
	dx,dy - resolution in x and y component respectively.
	nz - number of particles in the vertical. Particles are arranged in sigma layers.
	xypoly - [optional] coordinates of an additional bounding polygon [Nx2 array]
    """
    
    # Load the suntans grid
    sun = Grid(grdfile)

    # Load a trisearch object    
    tri = GridSearch(sun.xp,sun.yp,sun.cells,nfaces=sun.nfaces,verbose=False)
    
    if xypoly == None:
        xlims = [sun.xlims[0],sun.xlims[1]]
        ylims = [sun.ylims[0],sun.ylims[1]]
    else:
        xlims = [xypoly[:,0].min(),xypoly[:,0].max()]
        ylims = [xypoly[:,1].min(),xypoly[:,1].max()]

    # Construct a 2D mesh of particles
    x = np.arange(xlims[0],xlims[1],dx)
    y = np.arange(ylims[0],ylims[1],dy)
    
    X,Y = np.meshgrid(x,y)
    
    X=X.ravel()
    Y=Y.ravel()
    # Check which particles are inside the grid 
    cellind = tri(X,Y)
    mask = cellind!=-1

    # Check which particles are also inside of the polygon
    if not xypoly == None:
        inpoly = inpolygon(np.vstack((X,Y)).T,xypoly)
        mask = operator.and_(mask,inpoly)

    xout = X[mask]
    yout = Y[mask]
    
    nx = xout.shape[0]
    
    # Construct the 3D mesh
    xout = np.repeat(xout.reshape((nx,1)),nz,axis=1)
    yout = np.repeat(yout.reshape((nx,1)),nz,axis=1)
    
    zout = np.linspace(0.05,0.95,nz)
    zout = np.repeat(zout.reshape((nz,1)),nx,axis=1)
        
    zout *= -sun.dv[cellind[mask]]
    zout = zout.T
    
    xout = xout.ravel()
    yout = yout.ravel()
    zout = zout.ravel()

    # Rearrange the vectors to avoid clustering (this helps even the MPI workload)
    #xout_split=[]
    #yout_split=[]
    #zout_split=[]
    #for start in range(splitvec):
    #    xout_split.append(xout[start::splitvec])
    #    yout_split.append(yout[start::splitvec])
    #    zout_split.append(zout[start::splitvec])

    #xout = np.hstack(xout_split)
    #yout = np.hstack(yout_split)
    #zout = np.hstack(zout_split)
    

    return xout, yout, zout
Exemplo n.º 14
0
xypoly = [(x[ii], y[ii]) for ii in range(x.shape[0])]

# Create the grid outline
xlims = [x.min(), x.max()]
ylims = [y.min(), y.max()]

xgrd = np.arange(xlims[0] - scale / 2, xlims[1] + 1.5 * scale, scale)
ygrd = np.arange(ylims[0] - scale / 2, ylims[1] + 1.5 * scale, scale)

nx = xgrd.shape[0]
ny = ygrd.shape[0]

# Create a mask polygon
X, Y = np.meshgrid(xgrd, ygrd)
XY = np.vstack((X.ravel(), Y.ravel())).T
mask = inpolygon(XY, xypoly)
mask = mask.reshape((ny, nx))

cells = []
xp = []
yp = []


def pntindx(j, i, nrows):
    return j * nrows + i


for jj in range(ny):
    for ii in range(nx):
        #if mask[jj,ii]:
        xp.append(xgrd[ii])