def test_prepareForSimulation(): """ Test initial steps to get ready for a simulation. """ # Get projection object proj = tracpy.tools.make_proj(setup="galveston", usebasemap=False) # Read in grid grid_filename = os.path.join(here, "input", "grid.nc") currents_filename = os.path.join(here, "input", "ocean_his_0001.nc") grid = tracpy.inout.readgrid(grid_filename, proj, vert_filename=currents_filename) tp = Tracpy(currents_filename, grid) date = datetime.datetime(2013, 12, 19, 0) lon0 = [-123.0, -123.0] lat0 = [48.55, 48.75] tinds, nc, t0save, xend, yend, zend, zp, ttend, flag = tp.prepare_for_model_run(date, lon0, lat0) assert True assert tp.uf is not None assert np.sum(np.isnan(tp.uf[0, :, :, :])) == tp.uf[0, :, :, :].size
def test_prepareForSimulation(): ''' Test initial steps to get ready for a simulation. ''' # Get projection object proj = tracpy.tools.make_proj(setup='galveston', usebasemap=False) # Read in grid grid_filename = os.path.join(here, 'input', 'grid.nc') currents_filename = os.path.join(here, 'input', 'ocean_his_0001.nc') grid = tracpy.inout.readgrid(grid_filename, proj, vert_filename=currents_filename) tp = Tracpy(currents_filename, grid) date = datetime.datetime(2013, 12, 19, 0) lon0 = [-123., -123.] lat0 = [48.55, 48.75] tinds, nc, t0save, xend, yend, zend, zp, ttend, flag \ = tp.prepare_for_model_run(date, lon0, lat0) assert True assert tp.uf is not None assert np.sum(np.isnan(tp.uf[0, :, :, :])) == tp.uf[0, :, :, :].size
def init(name, grid_filename, currents_filename): ''' Initialize parameters for idealized eddy simulations. Initialization for seeding drifters at all shelf model grid points to be run forward. ''' time_units = 'seconds since 0001-01-01 00:00:00' # 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 = 19 # to approximate the output timing of the TXLA model 25 # Number of steps to divide model output for outputting drifter location N = 4 # to approximate the output timing of the TXLA model # 5 # Number of days ndays = 7 # This is a forward-moving simulation ff = 1 # Time between outputs tseas = 10800.0 # time between output in seconds ah = 0. av = 0. # m^2/s # surface drifters z0 = 's' zpar = 29 # 30 layers # for 3d flag, do3d=0 makes the run 2d and do3d=1 makes the run 3d do3d = 0 doturb = 0 # for periodic boundary conditions in the x direction doperiodic = 1 # Flag for streamlines. All the extra steps right after this are for streamlines. dostream = 0 # Initialize Tracpy class tp = Tracpy(currents_filename, grid_filename, name=name, tseas=tseas, ndays=ndays, nsteps=nsteps, N=N, ff=ff, ah=ah, av=av, doturb=doturb, do3d=do3d, z0=z0, zpar=zpar, time_units=time_units, usespherical=False, savell=False, doperiodic=doperiodic) # force grid reading tp._readgrid() # Start uniform array of drifters across domain using x,y coords x0 = tp.grid['xr'][1:-1,1:-1] y0 = tp.grid['yr'][1:-1,1:-1] return tp, x0, y0
def test_readgrid(): ''' Test for initializing grid without vertical grid information. ''' tp = Tracpy(os.path.join(here, 'input', 'grid.nc')) tp._readgrid() assert True assert tp.grid
def test_readgridWithVertical(): ''' Test for initializing grid and saving vertical grid information. ''' tp = Tracpy(os.path.join(here, 'input', 'ocean_his_0001.nc'), os.path.join(here, 'input', 'grid.nc')) tp._readgrid() assert True assert tp.grid assert tp.grid['Vtransform'] # make sure vertical info is in there
def __init__( self, currents_filename, grid_filename=None, nsteps=1, ndays=1, ff=1, tseas=3600., ah=0., av=0., z0='s', zpar=1, do3d=0, doturb=0, name='test', dostream=0, N=1, time_units='seconds since 1970-01-01', dtFromTracmass=None, zparuv=None, tseas_use=None **kwargs ): """ tracpy_mover (velocity) create a tracpy_mover instance :param velocity: a (u, v, w) triple -- in meters per second Remaining kwargs are passed onto Mover's __init__ using super. See Mover documentation for remaining valid kwargs. """ # self.velocity = np.asarray(velocity, # dtype=basic_types.mover_type).reshape((3, # )) # use this, to be compatible with whatever we are using for location # self.uncertainty_scale = uncertainty_scale # initializes Tracpy class self.tp = Tracpy(currents_filename, grid_filename=grid_filename, nsteps=nsteps, ndays=ndays, ff=ff, tseas=tseas, ah=ah, av=av, z0=z0, zpar=zpar, do3d=do3d, doturb=doturb, name=name, dostream=dostream, N=N, time_units=time_units, dtFromTracmass=dtFromTracmass, zparuv=zparuv, tseas_use=tseas_use) # calls Mover class super(TracpyMover, self).__init__(**kwargs)
def test_prepareForSimulation(): ''' Test initial steps to get ready for a simulation. ''' date = datetime.datetime(2013, 12, 19, 0) lon0 = [-123., -123.] lat0 = [48.55, 48.75] tp = Tracpy(os.path.join(here, 'input', 'ocean_his_0001.nc'), grid_filename=os.path.join(here, 'input', 'grid.nc')) tinds, nc, t0save, xend, yend, zend, zp, ttend, flag = tp.prepare_for_model_run(date, lon0, lat0) assert True assert tp.uf is not None assert np.sum(np.isnan(tp.uf[:,:,:,0])) == tp.uf[:,:,:,0].size
def test_init(): ''' Make sure that we can initialize the class. ''' tp = Tracpy(os.path.join(here, 'input', 'ocean_his_0001.nc')) assert True
def test_initWithGridSource(): ''' Make sure we can initialize with a grid source location ''' tp = Tracpy(os.path.join(here, 'input', 'ocean_his_0001.nc'), grid_filename=os.path.join(here, 'input', 'grid.nc')) assert True
def test_prepareForSimulation(): ''' Test initial steps to get ready for a simulation. ''' date = datetime.datetime(2013, 12, 19, 0) lon0 = [-123., -123.] lat0 = [48.55, 48.75] tp = Tracpy(os.path.join(here, 'input', 'ocean_his_0001.nc'), grid_filename=os.path.join(here, 'input', 'grid.nc')) tinds, nc, t0save, xend, yend, zend, zp, ttend, flag = tp.prepare_for_model_run( date, lon0, lat0) assert True assert tp.uf is not None assert np.sum(np.isnan(tp.uf[:, :, :, 0])) == tp.uf[:, :, :, 0].size
def test_readgridWithVertical(): ''' Test for initializing grid and saving vertical grid information. ''' # Get projection object proj = tracpy.tools.make_proj(setup='galveston', usebasemap=False) # Read in grid grid_filename = os.path.join(here, 'input', 'grid.nc') currents_filename = os.path.join(here, 'input', 'ocean_his_0001.nc') grid = tracpy.inout.readgrid(grid_filename, proj, vert_filename=currents_filename) tp = Tracpy(currents_filename, grid) assert True assert tp.grid # make sure there is a value for a vertical grid parameter assert hasattr(grid, 'sc_r')
def test_init(): ''' Initialize class without vertical grid information. Make sure that we can initialize the class with a grid and without vertical grid information. ''' # Get projection object proj = tracpy.tools.make_proj(setup='galveston', usebasemap=False) # Read in grid grid_filename = os.path.join(here, 'input', 'grid.nc') currents_filename = os.path.join(here, 'input', 'ocean_his_0001.nc') grid = tracpy.inout.readgrid(grid_filename, proj) tp = Tracpy(currents_filename, grid) assert True assert tp.grid # make sure there isn't a value for a vertical grid parameter assert not hasattr(grid, 'sc_r')
def init(name, lonsink, latsink, sinkarrows): ''' Initialization for the simulation. ''' 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 = 5 # interpolation forced between model output # Number of steps to divide model output for outputting drifter location N = 1 # Number of days ndays = 30 # This is a forward-moving simulation ff = 1 # Time between outputs tseas = 3 * 3600 # 3 hours between outputs, in seconds, time between model outputs ah = 0. # old tracks: 5. av = 0. # m^2/s # surface drifters z0 = 's' zpar = 0 zparuv = 0 # for 3d flag, do3d=0 makes the run 2d and do3d=1 makes the run 3d do3d = 0 doturb = 0 # Flag for streamlines. dostream = 0 # Initialize Tracpy class tp = Tracpy(loc, grid=grid, 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, sinkarrows=sinkarrows) # initial separation distance of drifters, in meters, from sensitivity project dx = 100 seedsfile = 'calcs/seeds_lon0_%2.2f_lat0_%2.2f.npz' % (abs(lonsink), latsink) if os.path.exists(seedsfile): seeds = np.load(seedsfile) lon0 = seeds['lon0'] lat0 = seeds['lat0'] seeds.close() else: # Initial lon/lat locations for drifters # Start uniform array of drifters across domain using x,y coords llcrnrlon = lonsink - 0.1 urcrnrlon = lonsink + 0.1 llcrnrlat = latsink - 0.1 urcrnrlat = latsink + 0.1 xcrnrs, ycrnrs = tp.grid.proj([llcrnrlon, urcrnrlon], [llcrnrlat, urcrnrlat]) X, Y = np.meshgrid(np.arange(xcrnrs[0], xcrnrs[1], dx), np.arange(ycrnrs[0], ycrnrs[1], dx)) lon0, lat0 = tp.grid.proj(X, Y, inverse=True) # save starting locations for future use np.savez(seedsfile, lon0=lon0, lat0=lat0) return tp, lon0, lat0
def init(rootdir, ndrifters): ''' Initialize simulation. ''' name = os.path.join(rootdir, 'tracks') # Where to find simulation information currents_filename = os.path.join(rootdir, 'ocean_his_0001.nc') grid_filename = os.path.join(rootdir, 'grid.nc') time_units = 'seconds since 1970-01-01' num_layers = 3 nsteps = 5 # Number of steps to divide model output for outputting drifter location N = 4 # This is a forward-moving simulation ff = 1 # Time between outputs tseas = 4 * 3600. # 4 hours between outputs, in seconds ah = 0. av = 0. # m^2/s # Number of days ndays = tseas * 9. / (3600. * 24) # surface drifters z0 = 's' zpar = num_layers - 1 # top layer # for 3d flag, do3d=0 makes the run 2d and do3d=1 makes the run 3d do3d = 0 doturb = 0 # for periodic boundary conditions in the x direction doperiodic = 1 # Flag for streamlines. All the extra steps right after this are for streamlines. dostream = 0 # Initialize Tracpy class tp = Tracpy(currents_filename, grid_filename, name=name, tseas=tseas, ndays=ndays, nsteps=nsteps, N=N, ff=ff, ah=ah, av=av, doturb=doturb, do3d=do3d, z0=z0, zpar=zpar, time_units=time_units, savell=False, doperiodic=0, usespherical=False) # one particle starting position times however many drifters x0 = np.ones(ndrifters) * 12000. y0 = np.ones(ndrifters) * 31000. return tp, x0, y0
def init(name): '''Initialize tracpy simulation''' time_units = 'seconds since 0001-01-01 00:00:00' nsteps = 25 # Number of steps to divide model output for outputting drifter location N = 1 # Number of days # 165 seconds max or less as simulations step forward in time # name accounts for start time stepping forward in time each simulation if len(name) == 19: startdate = datetime.strptime(name, '%Y-%m-%dT%H:%M:%S') elif len(name) > 19: startdate = datetime.strptime(name, '%Y-%m-%dT%H:%M:%S.%f') starttime = netCDF.date2num(startdate, time_units) ndays = (220. - starttime - dt) / 86400 # This is a forward-moving simulation ff = 1 # Time between outputs tseas = dt # time between output in seconds ah = 0. av = 0. # m^2/s # surface drifters z0 = 's' zpar = 0 # 1 layer # for 3d flag, do3d=0 makes the run 2d and do3d=1 makes the run 3d do3d = 0 doturb = 0 # for periodic boundary conditions in the x direction doperiodic = 0 # Flag for streamlines. All the extra steps right after this are for streamlines. dostream = 0 # import pdb; pdb.set_trace() proj = tracpy.tools.make_proj(setup='galveston') loc = 'model/model.nc' grid = tracpy.inout.readgrid(loc, proj, usespherical=False) # Start uniform array of drifters across domain using x,y coords # z0temp = tracpy.op.resize(np.linspace(-1,0,7), 0) # s_rho # z0 = np.concatenate((z0temp, z0temp)) # x0temp = [7.435, 7.435] # x0 = np.concatenate((x0temp[0]*np.ones(z0temp.size), x0temp[1]*np.ones(z0temp.size))) # y0temp = [2.3945, 2.968] # y0 = np.concatenate((y0temp[0]*np.ones(z0temp.size), y0temp[1]*np.ones(z0temp.size))) x0 = [7.435, 7.435] y0 = [2.3945, 2.968] # Initialize Tracpy class tp = Tracpy(loc, grid, name='tracks/tracks_' + name, tseas=tseas, ndays=ndays, nsteps=nsteps, N=N, ff=ff, ah=ah, av=av, doturb=doturb, do3d=do3d, z0=z0, zpar=zpar, time_units=time_units, usespherical=False, savell=True, doperiodic=doperiodic) # force grid reading # tp._readgrid() return tp, x0, y0
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 = 5 # Number of days ndays = 50 # This is a forward-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 = 0 # Initialize Tracpy class tp = Tracpy(currents_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) # 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() if os.path.exists('calcs/seeds.npz'): seeds = np.load('calcs/seeds.npz') lon0 = seeds['lon0']; lat0 = seeds['lat0'] seeds.close() else: llcrnrlon = -93.8; urcrnrlon = -92.2; llcrnrlat = 28; urcrnrlat = 29.2; # New xcrnrs, ycrnrs = grid['basemap']([llcrnrlon, urcrnrlon], [llcrnrlat, urcrnrlat]) X, Y = np.meshgrid(np.arange(xcrnrs[0], xcrnrs[1], 700), np.arange(ycrnrs[0], ycrnrs[1], 700)) lon0, lat0 = grid['basemap'](X, Y, inverse=True) # Eliminate points that are outside domain or in masked areas lon0, lat0 = tracpy.tools.check_points(lon0, lat0, grid) # save starting locations for future use np.savez('calcs/seeds.npz', lon0=lon0, lat0=lat0) # # 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
def test_run_2d_ll(): """ can we initialize and run tracpy (using rectangle example). Compare final location of drifters with known analytic answer. Using lon/lat coords. """ # some simple example data currents_filename = os.path.join('input', 'ocean_his_0001.nc') grid_filename = os.path.join('input', 'grid.nc') time_units = 'seconds since 1970-01-01' num_layers = 3 name = 'test_run_2d_ll' start = time.time() # grd = tracpy.inout.readgrid(grid_filename, vert_filename=currents_filename) print "building grid took:", time.time() - start # Start date in date time formatting date = datetime.datetime(2013, 12, 19, 0) # Time between outputs tseas = 4 * 3600. # 4 hours between outputs, in seconds # Number of days to run the drifters. ndays = tseas * 9. / (3600. * 24) # Sets a smaller limit than between model outputs for when to force interpolation if hasn't already occurred. nsteps = 5 # Controls the sampling frequency of the drifter tracks. N = 4 # This allows the user to call to TRACMASS for a different period of time than between 2 model outputs dtFromTracmass = tseas / 2. # Just testing to try new loop, should have same behavior as before # Use ff = 1 for forward in time and ff = -1 for backward in time. ff = 1 # will work for ff=1 or ff=-1 since checks by distance traveled ah = 0. # m^2/s av = 0. # m^2/s # turbulence/diffusion flag doturb = 0 # two particles (starting positions) lon0 = [-123., -123.] lat0 = [48.55, 48.75] do3d = 0 # flag to set to 2-d z0 = 's' #'z' #'salt' #'s' zpar = num_layers - 1 # top layer # Initialize Tracpy class tp = Tracpy(currents_filename, grid_filename, name=name, tseas=tseas, ndays=ndays, nsteps=nsteps, N=N, ff=ff, ah=ah, av=av, doturb=doturb, do3d=do3d, z0=z0, zpar=zpar, time_units=time_units, dtFromTracmass=dtFromTracmass) # tp._readgrid() lonp, yp, zp, t, T0, U, V = tracpy.run.run(tp, date, lon0, lat0) ## check the results: print lonp.shape print lonp print yp #eastward current, latitude should not change: assert np.allclose(lat0, yp.T) # current velocity -- 0.1 m/s # position distance = (ndays * 24 * 3600 * 0.1) * ff # better to use pyproj to compute the geodesic geod = pyproj.Geod(ellps='WGS84') end = geod.fwd(lon0, lat0, (90, 90), (distance, distance), radians=False) assert np.allclose(lonp[:, -1], end[0])
days = np.arange(1, 32) for day in days: date = datetime.datetime(year, month, day, 0) name = '%dJuly%d' % (year, day) # 1994July5 if not os.path.exists('tracks/' + name + '.nc') and not os.path.exists('tracks/' + name + 'gc.nc'): print(day) tp = Tracpy(loc, grid, name=name, tseas=tseas, ndays=ndays, nsteps=nsteps, N=N, ff=ff, ah=ah, av=av, doturb=doturb, do3d=do3d, z0=z0, zpar=zpar, time_units=time_units) # evenly spaced surface drifters dx = 1000 # in meters lonsink, latsink = -93.72595, 27.902 # exactly in between outer boundaries of banks from fgb website llcrnrlon = lonsink - 0.2 urcrnrlon = lonsink + 0.2 llcrnrlat = latsink - 0.12 urcrnrlat = latsink + 0.12 xcrnrs, ycrnrs = tp.grid.proj([llcrnrlon, urcrnrlon],
def init(name): '''Initialize tracpy simulation''' time_units = 'seconds since 0001-01-01 00:00:00' nsteps = 25 # Number of steps to divide model output for outputting drifter location N = 1 # Number of days ndays = 150. / 86400 # 150 sec 0.0025 # 220 seconds # This is a forward-moving simulation ff = 1 # Time between outputs tseas = 0.1 # time between output in seconds ah = 0. av = 0. # m^2/s # surface drifters z0 = 's' zpar = 0 # 1 layer # for 3d flag, do3d=0 makes the run 2d and do3d=1 makes the run 3d do3d = 0 doturb = 0 # for periodic boundary conditions in the x direction doperiodic = 0 # Flag for streamlines. All the extra steps right after this are for streamlines. dostream = 0 # import pdb; pdb.set_trace() proj = tracpy.tools.make_proj(setup='galveston') loc = 'model.nc' grid = tracpy.inout.readgrid(loc, proj, usespherical=False) # Initialize Tracpy class tp = Tracpy(loc, grid, name='tracks', tseas=tseas, ndays=ndays, nsteps=nsteps, N=N, ff=ff, ah=ah, av=av, doturb=doturb, do3d=do3d, z0=z0, zpar=zpar, time_units=time_units, usespherical=False, savell=True, doperiodic=doperiodic) # force grid reading # tp._readgrid() # Start uniform array of drifters across domain using x,y coords x0 = grid.x_rho[1:-1:2, 1:-1:2] y0 = grid.y_rho[1:-1:2, 1:-1:2] return tp, x0, y0
def init(name, ndays, grid_filename, currents_filename): ''' Initialization for seeding drifters at all shelf model grid points to be run forward. ''' # 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 = 19 # to approximate the output timing of the TXLA model 25 # Number of steps to divide model output for outputting drifter location N = 4 # to approximate the output timing of the TXLA model # 5 # Number of days # ndays = 30 # This is a forward-moving simulation ff = 1 # Time between outputs tseas = 10800.0 # time between output in seconds ah = 0. av = 0. # m^2/s # Initial lon/lat locations for drifters # The following few lines aren't necessary because the grid cells are uniformly 1km res # # Start uniform array of drifters across domain using x,y coords # dx = 1000 # initial separation distance of drifters, in meters # xcrnrs = np.array([grid['xr'][1:-1,:].min(), grid['xr'][1:-1,:].max()]) # ycrnrs = np.array([grid['yr'][1:-1,:].min(), grid['yr'][1:-1,:].max()]) # X, Y = np.meshgrid(np.arange(xcrnrs[0], xcrnrs[1], dx), np.arange(ycrnrs[0], ycrnrs[1], dx)) # lon0, lat0 = grid['basemap'](X, Y, inverse=True) # surface drifters z0 = 's' zpar = 29 # 30 layers # zpar = grid['km']-1 # for 3d flag, do3d=0 makes the run 2d and do3d=1 makes the run 3d do3d = 0 doturb = 0 # for periodic boundary conditions in the x direction doperiodic = 1 # Flag for streamlines. All the extra steps right after this are for streamlines. dostream = 0 # Initialize Tracpy class tp = Tracpy(currents_filename, grid_filename, name=name, tseas=tseas, ndays=ndays, nsteps=nsteps, N=N, ff=ff, ah=ah, av=av, doturb=doturb, do3d=do3d, z0=z0, zpar=zpar, time_units=time_units, savell=False, doperiodic=1) # force grid reading tp._readgrid() # Start uniform array of drifters across domain using x,y coords x0 = tp.grid['xr'][1:-1, 1:-1] y0 = tp.grid['yr'][1:-1, 1:-1] return tp, x0, y0
def test_run_2d_xy(): """ can we initialize and run tracpy (using rectangle example). Compare final location of drifters with known analytic answer. Using x/y coords for idealized type runs. Made this simulation information from the other test information using: """ # some simple example data currents_filename = os.path.join('input', 'ocean_his_0001.nc') grid_filename = os.path.join('input', 'gridxy.nc') time_units = 'seconds since 1970-01-01' num_layers = 3 name = 'test_run_2d_xy' start = time.time() # grd = tracpy.inout.readgrid(grid_filename, vert_filename=currents_filename) print "building grid took:", time.time() - start # Start date in date time formatting date = datetime.datetime(2013, 12, 19, 0) # Time between outputs tseas = 4 * 3600. # 4 hours between outputs, in seconds # Number of days to run the drifters. ndays = tseas * 9. / (3600. * 24) # Sets a smaller limit than between model outputs for when to force interpolation if hasn't already occurred. nsteps = 5 # Controls the sampling frequency of the drifter tracks. N = 4 # This allows the user to call to TRACMASS for a different period of time than between 2 model outputs dtFromTracmass = tseas / 2. # Just testing to try new loop, should have same behavior as before # Use ff = 1 for forward in time and ff = -1 for backward in time. ff = 1 # will work for ff=1 or ff=-1 since checks by distance traveled ah = 0. # m^2/s av = 0. # m^2/s # turbulence/diffusion flag doturb = 0 # two particles (starting positions) x0 = [22065., 22065.] y0 = [27777., 51587.] do3d = 0 # flag to set to 2-d z0 = 's' #'z' #'salt' #'s' zpar = num_layers - 1 # top layer # Initialize Tracpy class tp = Tracpy(currents_filename, grid_filename, name=name, tseas=tseas, ndays=ndays, nsteps=nsteps, N=N, ff=ff, ah=ah, av=av, doturb=doturb, do3d=do3d, z0=z0, zpar=zpar, time_units=time_units, dtFromTracmass=dtFromTracmass, usespherical=False) # tp._readgrid() xp, yp, zp, t, T0, U, V = tracpy.run.run(tp, date, x0, y0) ## check the results: print xp.shape print xp print yp #eastward current, latitude should not change: assert np.allclose(y0, yp.T) # current velocity -- 0.1 m/s # position distance = (ndays * 24 * 3600 * 0.1) * ff print distance print xp[:, -1] - xp[:, 0] assert np.allclose(xp[:, -1] - xp[:, 0], distance)
class TracpyMover(Mover): """ tracpy_mover """ _state = copy.deepcopy(Mover._state) _state.add(update=['uncertainty_scale', 'velocity'], create=['uncertainty_scale', 'velocity']) def __init__( self, currents_filename, grid_filename=None, nsteps=1, ndays=1, ff=1, tseas=3600., ah=0., av=0., z0='s', zpar=1, do3d=0, doturb=0, name='test', dostream=0, N=1, time_units='seconds since 1970-01-01', dtFromTracmass=None, zparuv=None, tseas_use=None **kwargs ): """ tracpy_mover (velocity) create a tracpy_mover instance :param velocity: a (u, v, w) triple -- in meters per second Remaining kwargs are passed onto Mover's __init__ using super. See Mover documentation for remaining valid kwargs. """ # self.velocity = np.asarray(velocity, # dtype=basic_types.mover_type).reshape((3, # )) # use this, to be compatible with whatever we are using for location # self.uncertainty_scale = uncertainty_scale # initializes Tracpy class self.tp = Tracpy(currents_filename, grid_filename=grid_filename, nsteps=nsteps, ndays=ndays, ff=ff, tseas=tseas, ah=ah, av=av, z0=z0, zpar=zpar, do3d=do3d, doturb=doturb, name=name, dostream=dostream, N=N, time_units=time_units, dtFromTracmass=dtFromTracmass, zparuv=zparuv, tseas_use=tseas_use) # calls Mover class super(TracpyMover, self).__init__(**kwargs) def __repr__(self): return 'TracpyMover(<%s>)' % self.id def prepare_for_model_run(self, date, lon0, lat0): tinds, nc, t0save, xend, yend, zend, zp, ttend, t, flag = self.tp.prepare_for_model_run(date, lon0, lat0) return tinds, nc, t0save, xend, yend, zend, zp, ttend, t, flag def prepare_for_model_step2(self, tind, nc, flag, xend, yend, zend, j): xstart, ystart, zstart = self.tp.prepare_for_model_step(tind, nc, flag, xend, yend, zend, j) # xstart, ystart, zstart = self.tp.prepare_for_model_step(tinds[j+1], nc, flag, xend, yend, zend, j) def get_move( self, spill, time_step, model_time, ): """ moves the particles defined in the spill object :param spill: spill is an instance of the gnome.spill.Spill class :param time_step: time_step in seconds :param model_time: current model time as a datetime object In this case, it uses the: positions status_code data arrays. :returns delta: Nx3 numpy array of movement -- in (long, lat, meters) units """ # Get the data: try: positions = spill['positions'] # Nx3 with lon,lat,z status_codes = spill['status_codes'] except KeyError, err: raise ValueError('The spill does not have the required data arrays\n' + err.message) # which ones should we move? # status codes for things like off map or on beach in_water_mask = status_codes == basic_types.oil_status.in_water # compute the move delta = np.zeros_like(positions) if self.active and self.on: # Old: # delta[in_water_mask] = tracpy. #self.velocity * time_step # Convert from lon/lat to grid coords # Interpolate to get starting positions in grid space xstart, ystart, _ = tracpy.tools.interpolate2d(positions[:,0], positions[:,1], self.tp.grid, 'd_ll2ij') # Call TRACMASS # Since I know I am doing 2d for now, can I essentially ignore the z positions? # FLAG PROBABLY NEEDS TO BE UPDATED FOR STATUS CODES FOR EXITING DRIFTERS? xend,\ yend,\ zend,\ flag,\ ttend, U, V = self.tp.step(xstart, ystart, positions[:,2]) # xend_temp,\ # yend_temp,\ # zend_temp,\ # flag[ind],\ # ttend_temp, U, V = self.tp.step(j, ttend[ind,j*self.tp.N], xstart, ystart, zstart) # Convert back to lon/lat from grid indices and calculate change in lon/lat lon, lat, _ = tracpy.tools.interpolate2d(xend, yend, self.tp.grid, 'm_ij2ll') delta[in_water_mask] = np.hstack((lon-positions[:,0], lat-positions[:,1], positions[:,2])) return delta
def test_run_2d_xy_ssh(): """ Test initialization and running of tracpy with projected coordinates and ssh. can we initialize and run tracpy (using rectangle example). Compare final location of drifters with known analytic answer. Using x/y coords for idealized type runs. Made this simulation information from the other test information using: """ import xarray as xr ds = xr.open_dataset('input/ocean_his_0001.nc') # sine wave in x, fixed in y and t zeta = np.sin(np.linspace(0, 2 * np.pi, ds['xr'].size)) zeta = zeta[np.newaxis, np.newaxis, :].repeat(ds['tl'].size, axis=0).repeat(ds['yr'].size, axis=1) ds['zeta'] = xr.Variable(['tl', 'yr', 'xr'], data=zeta) # ds['zeta'] = xr.Variable(['tl','yr','xr'], # data=10*np.ones((ds['tl'].size, ds['yr'].size, ds['xr'].size))) # ds['zeta'] = xr.Variable(['tl','yr','xr'], # data=np.random.rand(ds['tl'].size, ds['yr'].size, ds['xr'].size)) ds.to_netcdf('input/ocean_his_0002.nc') # some simple example data currents_filename = os.path.join('input', 'ocean_his_0001.nc') grid_filename = os.path.join('input', 'gridxy.nc') time_units = 'seconds since 1970-01-01' num_layers = 3 name = 'test_run_2d_xy_ssh' # Start date in date time formatting date = datetime.datetime(2013, 12, 19, 0) # Time between outputs tseas = 4 * 3600. # 4 hours between outputs, in seconds # Number of days to run the drifters. ndays = tseas * 9. / (3600. * 24) # Sets a smaller limit than between model outputs for when to force # interpolation if hasn't already occurred. nsteps = 5 # Controls the sampling frequency of the drifter tracks. N = 4 # # This allows the user to call to TRACMASS for a different period of time # # than between 2 model outputs # # Just testing to try new loop, should have same behavior as before # dtFromTracmass = tseas/2. # Use ff = 1 for forward in time and ff = -1 for backward in time. ff = 1 # will work for ff=1 or ff=-1 since checks by distance traveled ah = 0. # m^2/s av = 0. # m^2/s # turbulence/diffusion flag doturb = 0 # two particles (starting positions) x0 = [22065., 22065.] y0 = [27777., 51587.] do3d = 0 # flag to set to 2-d z0 = 's' # 'z' 'salt' 's' zpar = num_layers - 1 # top layer usespherical = False # Get projection object proj = tracpy.tools.make_proj(setup='galveston') # Read in grid grid = tracpy.inout.readgrid(grid_filename, proj, vert_filename=currents_filename, usespherical=usespherical) # Initialize Tracpy class tp = Tracpy(currents_filename, grid, name=name, tseas=tseas, ndays=ndays, nsteps=nsteps, N=N, ff=ff, ah=ah, av=av, doturb=doturb, do3d=do3d, z0=z0, zpar=zpar, time_units=time_units, usespherical=usespherical) xp, yp, zp, t, T0, U, V = tracpy.run.run(tp, date, x0, y0) ## check the results: # print xp.shape print(xp) # print yp #eastward current, latitude should not change: assert np.allclose(y0, yp.T) # current velocity -- 0.1 m/s # position distance = (ndays * 24 * 3600 * 0.1) * ff print(distance) print(xp[:, -1] - xp[:, 0]) assert np.allclose(xp[:, -1] - xp[:, 0], distance)