예제 #1
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)
예제 #2
0
파일: suntrack.py 프로젝트: mrayson/soda
    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)
예제 #3
0
파일: sunboundary.py 프로젝트: mrayson/soda
    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.
예제 #4
0
파일: ugridgen.py 프로젝트: mrayson/soda
def curv_ugrid_gen(X,Y,suntanspath=None,maskpoly=None):
    """
    Creates a curvilinear mesh from grid corners points stored
    in arrays X and Y.
    """

    ny,nx = X.shape

    XY = np.vstack((X.ravel(),Y.ravel())).T
    if not maskpoly is None:
        mask = inpolygon(XY,maskpoly)
        mask = mask.reshape((ny,nx))
    else:
        mask = np.ones((ny,nx),dtype=np.bool) # all false

    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])
            xp.append(X[jj,ii])
            yp.append(Y[jj,ii])

    for jj in range(ny-1):
        for ii in range(nx-1):
            if mask[jj,ii] and mask[jj+1,ii] and mask[jj+1,ii+1] and mask[jj,ii+1]:
                cells.append([pntindx(jj,ii,nx), pntindx(jj+1,ii,nx),\
                    pntindx(jj+1,ii+1,nx),pntindx(jj,ii+1,nx)])
            
    Nc = len(cells)
    nfaces = 4*np.ones((Nc,),np.int)

    cells = np.array(cells,dtype=np.int32)
    # Convert to a suntans grid
    grd = HybridGrid(np.array(xp),np.array(yp),cells,nfaces=nfaces)

    if not suntanspath is None:
        grd.write2suntans(suntanspath)

    return grd
예제 #5
0
파일: ugridgen.py 프로젝트: rustychris/soda
def curv_ugrid_gen(X,Y,suntanspath=None,maskpoly=None):
    """
    Creates a curvilinear mesh from grid corners points stored
    in arrays X and Y.
    """

    ny,nx = X.shape

    XY = np.vstack((X.ravel(),Y.ravel())).T
    if not maskpoly is None:
        mask = inpolygon(XY,maskpoly)
        mask = mask.reshape((ny,nx))
    else:
        mask = np.ones((ny,nx),dtype=np.bool) # all false

    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])
            xp.append(X[jj,ii])
            yp.append(Y[jj,ii])

    for jj in range(ny-1):
        for ii in range(nx-1):
            if mask[jj,ii] and mask[jj+1,ii] and mask[jj+1,ii+1] and mask[jj,ii+1]:
                cells.append([pntindx(jj,ii,nx), pntindx(jj+1,ii,nx),\
                    pntindx(jj+1,ii+1,nx),pntindx(jj,ii+1,nx)])

    Nc = len(cells)
    nfaces = 4*np.ones((Nc,),np.int)

    cells = np.array(cells,dtype=np.int32)
    # Convert to a suntans grid
    grd = HybridGrid(np.array(xp),np.array(yp),cells,nfaces=nfaces)

    if not suntanspath is None:
        grd.write2suntans(suntanspath)

    return grd
예제 #6
0
파일: gridsearch.py 프로젝트: gorsol/soda
    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)
예제 #7
0
파일: gridsearch.py 프로젝트: mrayson/soda
    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)
예제 #8
0
파일: gridsearch.py 프로젝트: gorsol/soda
    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
예제 #9
0
파일: gridsearch.py 프로젝트: mrayson/soda
    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
예제 #10
0
파일: sunboundary.py 프로젝트: mrayson/soda
def modifyBCmarker(suntanspath, bcfile, saveplot=False):
    """
    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
    if saveplot:
        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 '#######################################################'
예제 #11
0
파일: suntrack.py 프로젝트: mrayson/soda
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
예제 #12
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