Example #1
0
    def oceanmodel2ic(self,ncfile,\
            convert2utm=True,setUV=False,seth=False,zmax=6000.,name='HYCOM'):
        """
        Interpolate data from a downloaded netcdf file to the initial condition

        """
        print 'Loading initial condition data from ocean model netcdf file:\n\t%s...'%ncfile
        dt = timedelta(days=0.5)
        trange = [self.time - dt, self.time + 3*dt]

        # Get the temperature data and coordinate data
        temp, nc = get_metocean_local(ncfile,'temp',name=name, trange=trange)

        # Convert to utm
        if nc.X.ndim==1:
            X, Y = np.meshgrid(nc.X, nc.Y)
        else:
            X, Y = nc.X, nc.Y

        ll = np.vstack([X.ravel(),Y.ravel()]).T
        if convert2utm:
            xy = ll2utm(ll,self.utmzone,north=self.isnorth)
        else:
            xy = ll

        # Construct a 3D mask
        mask3d = temp.mask
        mask3d = mask3d[0,...]
        mask3d = mask3d.reshape((nc.nz,xy.shape[0]))

        # Ensure that the bottom cell of the ocean model is deeper than the suntans grid
        nc.Z[-1] = zmax

        # Construct the 4D interp class
        F4d =\
            Interp4D(xy[:,0],xy[:,1],nc.Z, nc.localtime,\
                self.xv,self.yv,self.z_r,self.time,mask=mask3d,**self.interpdict)

        tempnew = F4d(temp)
        self.T[:] = tempnew

        salt, nc = get_metocean_local(ncfile,'salt', name=name, trange=trange)
        saltnew = F4d(salt)
        self.S[:] = saltnew

        if seth:
            # Construct the 3D interp class for surface height
            ssh, nc = get_metocean_local(ncfile,'ssh', name=name, trange=trange)
            mask2d = ssh.mask
            mask2d = mask2d[0,...].ravel()

            F3d = Interp4D(xy[:,0],xy[:,1],None,nc.time,\
                self.xv,self.yv,None,self.time,mask=mask2d,**self.interpdict)
            sshnew = F3d(ssh)
            self.h[:] = sshnew
Example #2
0
    def oceanmodel2bdy(self,ncfile,\
        convert2utm=True,setUV=True,seth=True, zmax=6000., name='HYCOM'):
        """
        Interpolate data from a downloaded netcdf file to the open boundaries

        """
        print 'Loading boundary data from ocean model netcdf file:\n\t%s...'%ncfile

        dt = timedelta(days=0.5)
        trange = [self.time[0] - dt, self.time[-1] + dt]

        # Load the temperature salinity data and coordinate data
        temp, nc = get_metocean_local(ncfile,'temp', name=name, trange=trange)
        salt, nc = get_metocean_local(ncfile,'salt', name=name, trange=trange)

        if nc.X.ndim==1:
            X, Y = np.meshgrid(nc.X, nc.Y)
        else:
            X, Y = nc.X, nc.Y

        # Convert to utm
        ll = np.vstack([X.ravel(),Y.ravel()]).T
        if convert2utm:
            xy = ll2utm(ll,self.utmzone,north=self.isnorth)
        else:
            xy = ll

        # Construct a 3D mask
        mask3d = temp.mask
        mask3d = mask3d[0,...]
        mask3d = mask3d.reshape((nc.nz,xy.shape[0]))

        # Ensure that the bottom cell of the ocean model is deeper than the suntans grid
        nc.Z[-1] = zmax

        # Type 3 cells
        if self.N3>0:
            # Construct the 4D interp class
            F4d =\
                Interp4D(xy[:,0],xy[:,1],nc.Z,nc.localtime,\
                    self.xv,self.yv,self.z,self.time,mask=mask3d,**self.interpdict)

            tempnew = F4d(temp)
            self.T[:] = tempnew

            saltnew = F4d(salt)
            self.S[:] = saltnew

            # Never do this for type-3
            #if setUV:
            #    unew = F4d(u)
            #    self.u[:] += unew
            #    vnew = F4d(v)
            #    self.v[:] += vnew

            if seth:
                # Construct the 3D interp class for surface height
                ssh, nc2d = get_metocean_local(ncfile,'ssh', name=name, trange=trange)
                mask2d = ssh.mask
                mask2d = mask2d[0,...].ravel()

                F3d = Interp4D(xy[:,0],xy[:,1],None,nc2d.localtime,\
                    self.xv,self.yv,None,self.time,mask=mask2d,**self.interpdict)
                sshnew = F3d(ssh)
                self.h[:] += sshnew

        # Type 2 cells : no free-surface
        if self.N2>0:
            # Construct the 4D interp class
            F4d =\
             Interp4D(xy[:,0], xy[:,1], nc.Z, nc.localtime,\
                 self.xe,self.ye,self.z,self.time,mask=mask3d,**self.interpdict)

            tempnew = F4d(temp)
            self.boundary_T[:] = tempnew

            del temp

            saltnew = F4d(salt)
            self.boundary_S[:] = saltnew

            del salt

            if setUV:
                u, nc = get_metocean_local(ncfile,'u', name=name, trange=trange)
                unew = F4d(u)
                self.boundary_u[:] += unew

                del u

                v, nc = get_metocean_local(ncfile,'v', name=name, trange=trange)
                vnew = F4d(v)
                self.boundary_v[:] += vnew

                del v
Example #3
0
    def __init__(self, **kwargs):

        self.__dict__.update(kwargs)

        # Check if the input file is not a list
        T = type(self.infile)

        if T != list:
            self.multifile = False

            # Parse the data file into two vectors
            print "Reading data from: %s..." % self.infile
            if self.infile[-3:] == ".gz":
                LL, self.Zin = read_xyz_gz(self.infile)

            elif self.infile[-3:] == "txt":
                LL, self.Zin = read_xyz(self.infile)

            elif self.infile[-3:] == "shp":
                LL, self.Zin = readShpBathy(self.infile)

            elif self.infile[-3:] == "dem":
                LL, self.Zin = readDEM(self.infile, True)

            elif self.infile[-3:] == ".nc":
                self.loadnc(fv=2)
                LL = self._returnXY()
                self.Zin = np.ravel(self.Zin)

            elif self.infile[-3:] in [".h5", "hdf"]:
                LL, self.Zin = self.load_hdf(self.infile, self.h5groups)

            # rescale the data
            self.Zin = self.scale * self.Zin

            # Convert the coordinates
            self.npt = len(self.Zin)
            if self.convert2utm:

                if self.bbox == None:
                    # Work out the domain limits from the input file
                    self.bbox = [LL[:, 0].min(), LL[:, 0].max(), LL[:, 1].min(), LL[:, 1].max()]
                # else:
                #    # Clip the points outside of the domain
                #    print 'Clipping points outside of the bounding box...'
                #    LL=self.clipPoints(LL)

                # Convert the coordinates
                print "Transforming the coordinates to UTM..."
                self.XY = ll2utm(LL, self.utmzone, self.CS, self.isnorth)

            else:
                self.XY = LL

        else:  # Multiple files
            self.multifile = True

        # Print out some details before processing
        print 72 * "#"
        print "Grid bounds: "
        print "\tX: ", self.bbox[0:2]
        print "\tY: ", self.bbox[2:4]
        print "Data bounds:"
        print "X min = %f, X max = %f" % (self.XY[:, 0].min(), self.XY[:, 0].max())
        print "Y min = %f, Y max = %f" % (self.XY[:, 1].min(), self.XY[:, 1].max())
        print 72 * "#"

        # Create the grid object
        self.grd = Grid(
            self.bbox,
            self.dx,
            self.dx,
            utmzone=self.utmzone,
            CS=self.CS,
            isnorth=self.isnorth,
            convert2utm=self.convert2utm,
        )
Example #4
0
    def build(self):

        tic = time.clock()
        if self.multifile == False:
            if self.interptype == "nn":
                print "Building DEM with Nearest Neighbour interpolation..."
                self.nearestNeighbour()

            elif self.interptype == "blockavg":
                print "Building DEM with Block Averaging..."
                self.blockAvg()

            elif self.interptype == "idw":
                print "Building DEM with Inverse Distance Weighted Interpolation..."
                self.invdistweight()

            elif self.interptype == "kriging":
                print "Building DEM with Kriging Interpolation..."
                self.krig()
            elif self.interptype == "griddata":
                print "Building DEM using griddata..."
                self.griddata()

            elif self.interptype == "curvmin":
                print "Building DEM using curvmin..."
                self.curvmin()

            else:
                print "Error - Unknown interpolation type: %s." % self.interptype
        else:  # Multiple file interpolation
            print 'Multiple input files detected - setting "interptype" to "blockavg".'
            self.interptype = "blockavg"
            self.Z = np.zeros((self.grd.ny, self.grd.nx))
            self.N = np.zeros((self.grd.ny, self.grd.nx))
            ctr = 0
            for f in self.infile:
                ctr += 1
                # Read in the array
                print "Reading data file (%d of %d): %s..." % (ctr, len(self.infile), f)
                if f[-3:] == ".gz":
                    LL, self.Zin = read_xyz_gz(f)
                if f[-3:] == "txt":
                    LL, self.Zin = read_xyz(f)
                elif f[-3:] == "shp":
                    LL, self.Zin = readShpBathy(f)
                elif f[-3:] == "dem":
                    LL, self.Zin = readDEM(f, True)

                self.npt = len(self.Zin)

                if self.convert2utm:

                    # Clip the points outside of the domain
                    # print 'Clipping points outside of the bounding box...'
                    # LL=self.clipPoints(LL)

                    # Convert the coordinates
                    print "Transforming the coordinates to UTM..."
                    self.XY = ll2utm(LL, self.utmzone, self.CS, self.isnorth)
                else:
                    self.XY = LL

                del LL
                # Interpolate
                print "Building DEM with Block Averaging..."
                self.blockAvgMulti()

                # Memory cleanup
                del self.XY
                del self.Zin

            # Compute the block average for all of the files
            self.Z = np.divide(self.Z, self.N)

        toc = time.clock()
        print "Elapsed time %10.3f seconds." % (toc - tic)
Example #5
0
    def __init__(self, **kwargs):

        self.__dict__.update(kwargs)

        # Check if the input file is not a list
        T = type(self.infile)

        if T != list:
            self.multifile = False

            # Parse the data file into two vectors
            print('Reading data from: %s...' % self.infile)
            if self.infile[-3:] == '.gz':
                LL, self.Zin = read_xyz_gz(self.infile)

            elif self.infile[-3:] == 'txt':
                LL, self.Zin = read_xyz(self.infile)

            elif self.infile[-3:] == 'shp':
                LL, self.Zin = readShpBathy(self.infile)

            elif self.infile[-3:] == 'dem':
                LL, self.Zin = readDEM(self.infile, True)

            elif self.infile[-3:] == '.nc':
                self.loadnc(fv=2)
                LL = self._returnXY()
                self.Zin = np.ravel(self.Zin)

            elif self.infile[-3:] in ['.h5', 'hdf']:
                LL, self.Zin = self.load_hdf(self.infile, self.h5groups)

            # rescale the data
            self.Zin = self.scale * self.Zin

            # Convert the coordinates
            self.npt = len(self.Zin)
            if self.convert2utm:

                if self.bbox == None:
                    # Work out the domain limits from the input file
                    self.bbox = [
                        LL[:, 0].min(), LL[:, 0].max(), LL[:, 1].min(),
                        LL[:, 1].max()
                    ]
                #else:
                #    # Clip the points outside of the domain
                #    print 'Clipping points outside of the bounding box...'
                #    LL=self.clipPoints(LL)

                # Convert the coordinates
                print('Transforming the coordinates to UTM...')
                self.XY = ll2utm(LL, self.utmzone, self.CS, self.isnorth)

            else:
                self.XY = LL

        else:  # Multiple files
            self.multifile = True

        # Print out some details before processing
        print(72 * '#')
        print('Grid bounds: ')
        print('\tX: ', self.bbox[0:2])
        print('\tY: ', self.bbox[2:4])
        print('Data bounds:')
        print('X min = %f, X max = %f' %
              (self.XY[:, 0].min(), self.XY[:, 0].max()))
        print('Y min = %f, Y max = %f' %
              (self.XY[:, 1].min(), self.XY[:, 1].max()))
        print(72 * '#')

        # Create the grid object
        self.grd = Grid(self.bbox,self.dx,self.dx,\
                utmzone=self.utmzone,\
                CS=self.CS,\
                isnorth=self.isnorth,
                convert2utm= self.convert2utm)
Example #6
0
    def build(self):

        tic = time.clock()
        if self.multifile == False:
            if self.interptype == 'nn':
                print('Building DEM with Nearest Neighbour interpolation...')
                self.nearestNeighbour()

            elif self.interptype == 'blockavg':
                print('Building DEM with Block Averaging...')
                self.blockAvg()

            elif self.interptype == 'idw':
                print(
                    'Building DEM with Inverse Distance Weighted Interpolation...'
                )
                self.invdistweight()

            elif self.interptype == 'kriging':
                print('Building DEM with Kriging Interpolation...')
                self.krig()
            elif self.interptype == 'griddata':
                print('Building DEM using griddata...')
                self.griddata()

            elif self.interptype == 'curvmin':
                print('Building DEM using curvmin...')
                self.curvmin()

            else:
                print('Error - Unknown interpolation type: %s.' %
                      self.interptype)
        else:  # Multiple file interpolation
            print(
                'Multiple input files detected - setting "interptype" to "blockavg".'
            )
            self.interptype = 'blockavg'
            self.Z = np.zeros((self.grd.ny, self.grd.nx))
            self.N = np.zeros((self.grd.ny, self.grd.nx))
            ctr = 0
            for f in self.infile:
                ctr += 1
                # Read in the array
                print('Reading data file (%d of %d): %s...' %
                      (ctr, len(self.infile), f))
                if f[-3:] == '.gz':
                    LL, self.Zin = read_xyz_gz(f)
                if f[-3:] == 'txt':
                    LL, self.Zin = read_xyz(f)
                elif f[-3:] == 'shp':
                    LL, self.Zin = readShpBathy(f)
                elif f[-3:] == 'dem':
                    LL, self.Zin = readDEM(f, True)

                self.npt = len(self.Zin)

                if self.convert2utm:

                    # Clip the points outside of the domain
                    #print 'Clipping points outside of the bounding box...'
                    #LL=self.clipPoints(LL)

                    # Convert the coordinates
                    print('Transforming the coordinates to UTM...')
                    self.XY = ll2utm(LL, self.utmzone, self.CS, self.isnorth)
                else:
                    self.XY = LL

                del LL
                # Interpolate
                print('Building DEM with Block Averaging...')
                self.blockAvgMulti()

                # Memory cleanup
                del self.XY
                del self.Zin

            # Compute the block average for all of the files
            self.Z = np.divide(self.Z, self.N)

        toc = time.clock()
        print('Elapsed time %10.3f seconds.' % (toc - tic))