Esempio n. 1
0
def readThenReduce(grid, ndrift, fileloc='projects/driftcards/Deployment_data.txt'):

    startdate, startlon, startlat, idnum = read(ndrift, fileloc)
    # startdate, startlon, startlat, enddate, endlon, endlat, idnum = read(ndrift)

    # If covering the whole domain, need to exclude points outside domain.
    # Use info just inside domain so points aren't right at the edge.
    xvert = np.hstack((np.flipud(grid['lonr'][1,:]),grid['lonr'][:,1],
        grid['lonr'][-2,:],np.flipud(grid['lonr'][:,-2])))
    yvert = np.hstack((np.flipud(grid['latr'][1,:]),grid['latr'][:,1],
        grid['latr'][-2,:],np.flipud(grid['latr'][:,-2])))
    verts = np.vstack((xvert,yvert))
    # Form path
    path = Path(verts.T)
    # nan out all drifters that do not start within the TXLA model domain
    for i in xrange(ndrift):
        if not path.contains_point(np.vstack((startlon[i], startlat[i]))):
            startlon[i] = np.nan
            startlat[i] = np.nan
            startdate[i] = np.nan
            # endlon[i] = np.nan
            # endlat[i] = np.nan

    # # nan out drifters that have not been found yet
    # for i in xrange(ndrift):
    #     if np.isnan(enddate[i]):
    #         startlon[i] = np.nan
    #         startlat[i] = np.nan
    #         startdate[i] = np.nan
    # pdb.set_trace()
    # Eliminate nan'ed entries (only save non-nan'ed entries)
    ind = ~np.isnan(startlon)
    startlon = startlon[ind]
    startlat = startlat[ind]
    startdate = startdate[ind]
    idnum = idnum[ind]
  
    return startdate, startlon, startlat, idnum
Esempio n. 2
0
def check_points(lon0, lat0, grid, z0=None, nobays=False):
    """
    Eliminate starting locations for drifters that are outside numerical
    domain and that are masked out. If provided an array of starting vertical
    locations in z0, it checks whether these points are at least 1m above the
    bottom.

    Args:
        lon0,lat0: Starting locations for drifters in lon/lat
        z0: Starting locations for drifters in z
        grid: Grid made from readgrid.py
        nobays: Whether to use points in bays or not. Default is False.

    Returns:
        * lon0,lat0 - Fixed lon0,lat0
        * z0 - Fixed z0
    """

    lonr = grid.lon_rho
    latr = grid.lat_rho

    # make interpolation function for water depth h.
    # Used to check if float is above the bottom
    if z0 is not None:
        from scipy.interpolate import interp2d
        h = grid.h
        hint = interp2d(lonr[:, 1], latr[1, :], h.T, fill_value=np.nan)

    # If covering the whole domain, need to exclude points outside domain.
    # Use info just inside domain so points aren't right at the edge.
    xvert = np.hstack(
        (np.flipud(lonr[1, :]), lonr[:, 1], lonr[-2, :], np.flipud(lonr[:,
                                                                        -2])))
    yvert = np.hstack(
        (np.flipud(latr[1, :]), latr[:, 1], latr[-2, :], np.flipud(latr[:,
                                                                        -2])))
    verts = np.vstack((xvert, yvert))
    # Form path
    path = Path(verts.T)
    # Loop through particle tracks to eliminate drifters that start outside
    # the domain
    if lon0.ndim == 2:
        for jd in range(lon0.shape[0]):  # loop through drifters
            for it in range(lon0.shape[1]):
                # if drifter is not inside path, nan out this and all
                # subsequent points
                if not path.contains_point(
                        np.vstack((lon0[jd, it], lat0[jd, it]))):
                    lon0[jd, it] = np.nan
                    lat0[jd, it] = np.nan
                    if z0 is not None:
                        z0[jd, it] = np.nan

                if z0 is not None:
                    # check that the drifter starts above the bottom
                    if z0[jd, it] <= -1 * hint(lon0[jd, it], lat0[jd, it]):
                        lon0[jd, it] = np.nan
                        lat0[jd, it] = np.nan
                        if z0 is not None:
                            z0[jd, it] = np.nan

    elif lon0.ndim == 1:
        for jd in range(lon0.shape[0]):  # loop through drifters
            # if drifter is not inside path, nan out this and all
            # subsequent points
            if not path.contains_point(np.vstack((lon0[jd], lat0[jd]))):
                lon0[jd] = np.nan
                lat0[jd] = np.nan
                if z0 is not None:
                    z0[jd] = np.nan

            if z0 is not None:
                # check that the drifter starts above the bottom
                if z0[jd] <= -1 * hint(lon0[jd], lat0[jd]):
                    lon0[jd] = np.nan
                    lat0[jd] = np.nan
                    z0[jd] = np.nan

    # Also nan out points that are masked
    fmask = mtri.LinearTriInterpolator(grid.trirllrho, grid.mask.flatten())
    mask0 = fmask(lon0, lat0)  # mask for lon0/lat0 points
    ind1 = (mask0 == 1.)  # indices select out where points are masked

    # If nobays, eliminate points with shallow bathymetry
    if nobays:
        fh = grid.trirllrho.nn_interpolator(grid.h.flatten())
        h0 = fh(lon0, lat0)
        ind2 = (h0 > 10.)
    else:
        ind2 = np.ones(ind1.shape).astype(bool)

    ind2 = ~np.isnan(lon0) * ind1 * ind2

    L = len(ind2.ravel())
    Lnan = sum(ind2.ravel())
    print L - Lnan, '/', L, ' drifters NaN-ed out.'

    lon0 = lon0[ind2].flatten()
    lat0 = lat0[ind2].flatten()

    if z0 is not None:
        z0 = z0[ind2].flatten()

    if z0 is None:
        return lon0, lat0
    else:
        return lon0, lat0, z0
Esempio n. 3
0
    #     continue

    # Get necessary info from File
    # d = np.load(File)
    # xg = d['xg']; yg = d['yg']; tg = d['tg']
    d = netCDF.Dataset(File)
    xg = d.variables['xg'][:]
    yg = d.variables['yg'][:]
    tg = d.variables['tp'][:]
    d.close()

    # Load in coastline region info
    # Mexico
    dconn = np.load('calcs/MXpts.npz')
    xp = np.asarray(dconn['MX'])[:,0]; yp = np.asarray(dconn['MX'])[:,1]
    MXpath = Path(np.vstack((xp, yp)).T)
    dconn.close()
    # S Texas
    dconn = np.load('calcs/STXpts.npz')
    xp = np.asarray(dconn['STX'])[:,0]; yp = np.asarray(dconn['STX'])[:,1]
    STXpath = Path(np.vstack((xp, yp)).T)
    dconn.close()
    # N Texas
    dconn = np.load('calcs/NTXpts.npz')
    xp = np.asarray(dconn['NTX'])[:,0]; yp = np.asarray(dconn['NTX'])[:,1]
    NTXpath = Path(np.vstack((xp, yp)).T)
    dconn.close()
    # Chenier
    dconn = np.load('calcs/CHpts.npz')
    xp = np.asarray(dconn['CH'])[:,0]; yp = np.asarray(dconn['CH'])[:,1]
    CHpath = Path(np.vstack((xp, yp)).T)
def init(name):
    '''
    Initialization for the simulation.
    '''

    # loc = 'http://barataria.tamu.edu:6060/thredds/dodsC/NcML/txla_nesting6.nc'

    time_units = 'seconds since 1970-01-01'

    # horizontal_diffusivity project showed that relative dispersion did not
    # change between nsteps=25 and 50, but does between nsteps=5 and 25, and
    # interim numbers have not been tested yet.
    nsteps = 25 # in-between tracks: 12 # old tracks: 25 

    # Number of steps to divide model output for outputting drifter location
    N = 1 # not interested in drifter locations

    # Number of days
    ndays = 30

    # This is a backward-moving simulation
    ff = -1 

    # Time between outputs
    tseas = 4*3600 # 4 hours between outputs, in seconds, time between model outputs 
    ah = 0. # old tracks: 5.
    av = 0. # m^2/s

    # surface drifters
    z0 = 's'  
    zpar = 29 

    # for 3d flag, do3d=0 makes the run 2d and do3d=1 makes the run 3d
    do3d = 0
    doturb = 0

    # Flag for streamlines.
    dostream = 1

    # Initialize Tracpy class
    tp = Tracpy(currents_filename, grid_filename=grid_filename, name=name, tseas=tseas, ndays=ndays, nsteps=nsteps, dostream=dostream, savell=False, doperiodic=0, 
                N=N, ff=ff, ah=ah, av=av, doturb=doturb, do3d=do3d, z0=z0, zpar=zpar, 
                time_units=time_units, usebasemap=True, grid=grid, vert_filename=vert_filename)

    # tp._readgrid()

    # Initial lon/lat locations for drifters
    startindsfile = 'NTX-starting-inds.npz'
    if not os.path.exists(startindsfile):
        # get starting drifter locations for this region 
        loc_shelftransport = '/home/kthyng/projects/shelf_transport/'
        NTX = np.load(loc_shelftransport + 'calcs/NTXpts.npz')['NTX']
        xp = NTX[:,0]; yp = NTX[:,1]
        gpath = Path(np.vstack((xp, yp)).T)
        drifters = netCDF.Dataset(loc_shelftransport + 'tracks/2004-01-01T00gc.nc')
        xg = drifters.variables['xg'][:]; yg = drifters.variables['yg'][:]
        # Change to projected drifter locations now
        nanind = np.isnan(xg) + (xg==-1) # indices where nans are location in xg, yg; for reinstitution of nans
        # pdb.set_trace()
        xp, yp, _ = tracpy.tools.interpolate2d(xg, yg, grid, 'm_ij2xy') 
        xp[nanind] = np.nan; yp[nanind] = np.nan
        del(xg,yg) # don't need grid info anymore
        # save indices of drifters that start in the coastal areas
        inds = gpath.contains_points(np.vstack((xp[:,0].flat, yp[:,0].flat)).T).reshape(xp[:,0].shape)
        np.savez(startindsfile, inds=inds)
    else:
        inds = np.load(startindsfile)['inds']

    startptsfile = 'NTX-starting-ll.npz'
    if not os.path.exists(startptsfile):
        loc_shelftransport = '/home/kthyng/projects/shelf_transport/'
        drifters = netCDF.Dataset(loc_shelftransport + 'tracks/2004-01-01T00gc.nc')
        xg = drifters.variables['xg'][:]; yg = drifters.variables['yg'][:]
        xg = xg[inds,0]; yg = yg[inds,0]
        lon0, lat0, _ = tracpy.tools.interpolate2d(xg, yg, tp.grid, 'm_ij2ll')
        np.savez(startptsfile, lon0=lon0, lat0=lat0)
    else:
        d = np.load(startptsfile)
        lon0 = d['lon0']; lat0 = d['lat0']
        d.close()

    # equal weightings for drifters for transport.
    T0 = np.ones(lon0.size, order='F')

    U = np.ma.zeros(tp.grid['xu'].shape, order='F')
    V = np.ma.zeros(tp.grid['xv'].shape, order='F')

    # pdb.set_trace()
       
    return tp, lon0, lat0, T0, U, V
Esempio n. 5
0
def check_points(lon0, lat0, grid, z0=None, nobays=False):
    """
    Eliminate starting locations for drifters that are outside numerical
    domain and that are masked out. If provided an array of starting vertical
    locations in z0, it checks whether these points are at least 1m above the
    bottom.

    Args:
        lon0,lat0: Starting locations for drifters in lon/lat
        z0: Starting locations for drifters in z
        grid: Grid made from readgrid.py
        nobays: Whether to use points in bays or not. Default is False.

    Returns:
        * lon0,lat0 - Fixed lon0,lat0
        * z0 - Fixed z0
    """

    lonr = grid.lon_rho
    latr = grid.lat_rho

    # make interpolation function for water depth h.
    # Used to check if float is above the bottom
    if z0 is not None:
        from scipy.interpolate import interp2d
        h = grid.h
        hint = interp2d(lonr[:, 1], latr[1, :], h.T, fill_value=np.nan)

    # If covering the whole domain, need to exclude points outside domain.
    # Use info just inside domain so points aren't right at the edge.
    xvert = np.hstack((np.flipud(lonr[1, :]), lonr[:, 1], lonr[-2, :],
                       np.flipud(lonr[:, -2])))
    yvert = np.hstack((np.flipud(latr[1, :]), latr[:, 1], latr[-2, :],
                       np.flipud(latr[:, -2])))
    verts = np.vstack((xvert, yvert))
    # Form path
    path = Path(verts.T)
    # Loop through particle tracks to eliminate drifters that start outside
    # the domain
    if lon0.ndim == 2:
        for jd in range(lon0.shape[0]):  # loop through drifters
            for it in range(lon0.shape[1]):
                # if drifter is not inside path, nan out this and all
                # subsequent points
                if not path.contains_point(np.vstack((lon0[jd, it],
                                                      lat0[jd, it]))):
                    lon0[jd, it] = np.nan
                    lat0[jd, it] = np.nan
                    if z0 is not None:
                        z0[jd, it] = np.nan

                if z0 is not None:
                    # check that the drifter starts above the bottom
                    if z0[jd, it] <= -1*hint(lon0[jd, it], lat0[jd, it]):
                        lon0[jd, it] = np.nan
                        lat0[jd, it] = np.nan
                        if z0 is not None:
                            z0[jd, it] = np.nan

    elif lon0.ndim == 1:
        for jd in range(lon0.shape[0]):  # loop through drifters
            # if drifter is not inside path, nan out this and all
            # subsequent points
            if not path.contains_point(np.vstack((lon0[jd], lat0[jd]))):
                lon0[jd] = np.nan
                lat0[jd] = np.nan
                if z0 is not None:
                    z0[jd] = np.nan

            if z0 is not None:
                # check that the drifter starts above the bottom
                if z0[jd] <= -1*hint(lon0[jd], lat0[jd]):
                    lon0[jd] = np.nan
                    lat0[jd] = np.nan
                    z0[jd] = np.nan

    # Also nan out points that are masked
    fmask = mtri.LinearTriInterpolator(grid.trirllrho, grid.mask.flatten())
    mask0 = fmask(lon0, lat0)  # mask for lon0/lat0 points
    ind1 = (mask0 == 1.)  # indices select out where points are masked

    # If nobays, eliminate points with shallow bathymetry
    if nobays:
        fh = grid.trirllrho.nn_interpolator(grid.h.flatten())
        h0 = fh(lon0, lat0)
        ind2 = (h0 > 10.)
    else:
        ind2 = np.ones(ind1.shape).astype(bool)

    ind2 = ~np.isnan(lon0)*ind1*ind2

    L = len(ind2.ravel())
    Lnan = sum(ind2.ravel())
    print L - Lnan, '/', L, ' drifters NaN-ed out.'

    lon0 = lon0[ind2].flatten()
    lat0 = lat0[ind2].flatten()

    if z0 is not None:
        z0 = z0[ind2].flatten()

    if z0 is None:
        return lon0, lat0
    else:
        return lon0, lat0, z0
Esempio n. 6
0
    # Get necessary info from File
    # d = np.load(File)
    # xg = d['xg']; yg = d['yg']; tg = d['tg']
    d = netCDF.Dataset(File)
    xg = d.variables['xg'][:]
    yg = d.variables['yg'][:]
    tg = d.variables['tp'][:]
    d.close()

    # Load in coastline region info
    # Mexico
    dconn = np.load('calcs/MXpts.npz')
    xp = np.asarray(dconn['MX'])[:, 0]
    yp = np.asarray(dconn['MX'])[:, 1]
    MXpath = Path(np.vstack((xp, yp)).T)
    dconn.close()
    # S Texas
    dconn = np.load('calcs/STXpts.npz')
    xp = np.asarray(dconn['STX'])[:, 0]
    yp = np.asarray(dconn['STX'])[:, 1]
    STXpath = Path(np.vstack((xp, yp)).T)
    dconn.close()
    # N Texas
    dconn = np.load('calcs/NTXpts.npz')
    xp = np.asarray(dconn['NTX'])[:, 0]
    yp = np.asarray(dconn['NTX'])[:, 1]
    NTXpath = Path(np.vstack((xp, yp)).T)
    dconn.close()
    # Chenier
    dconn = np.load('calcs/CHpts.npz')