def plot_stuff(xe, ye, H, cmap, grid, shelf_depth, ax, levels=np.linspace(0,100,11), extend='max'): ''' Do the main plotting stuff. ''' XE, YE = np.meshgrid(op.resize(xe, 0), op.resize(ye, 0)) # Try with pcolor too #pdb.set_trace() mappable = ax.contourf(XE, YE, H, cmap=cmap, levels=levels, extend=extend) ax.contour(grid['xr'], grid['yr'], grid['h'], [shelf_depth], colors='0.1', linewidth=3) return mappable
tracpy.plotting.background(grid=grid, ax=ax, mers=np.arange(-100, -80, 2)) ax.set_title('Winter') Files = glob.glob('tracks/20??-0[1,2]-*gc.nc') elif i==1: tracpy.plotting.background(grid=grid, ax=ax, parslabels=[0,0,0,0], mers=np.arange(-100, -80, 2)) ax.set_title('Summer') Files = glob.glob('tracks/20??-0[7,8]-*gc.nc') if not os.path.exists(fname): for File in Files: # print File d = netCDF.Dataset(File) # pdb.set_trace() U = d.variables['U'][:]; V = d.variables['V'][:] d.close() Stemp = np.sqrt(op.resize(U, 1)**2 + op.resize(V, 0)**2) S[i,:,:] = S[i,:,:] + Stemp # locator = ticker.MaxNLocator(11) # locator.create_dummy_axis() # locator.set_bounds(0, 1) # levels = locator() # extend = 'max' # H = H/Hmax Smax = 1. else: d = np.load(fname); S = d['S']; d.close() Smax = S.max() if howplot=='log':
# w = netCDF.Dataset('/atch/raid1/zhangxq/Projects/narr_txla/txla_blk_narr_' + str(year) + '.nc') # Wind time period to use unitsWind = (w.variables['time'].units).replace('/','-') datesWind = netCDF.num2date(w.variables['time'][:], unitsWind) # datesWind = datesModel wdx = 25; wdy = 40 # in indices ## ## River forcing ## r1 = netCDF.Dataset('/rho/raid/home/kthyng/txla/TXLA_river_4dyes_2012.nc') # use for through 2011 r2 = netCDF.Dataset('/rho/raid/home/kthyng/txla/TXLA_river_4dyes_2012_2014.nc') # use for 2012-2014 # River timing tr1 = r1.variables['river_time'] tunitsr1 = tr1.units # interpolate times for this data file since at the 12 hours mark instead of beginning of the day tr1 = op.resize(tr1, 0) datesr1 = netCDF.num2date(tr1[:], tunitsr1) tr2 = r2.variables['river_time'] datesr2 = netCDF.num2date(tr2[:], tr2.units) # all of river input Q1 = np.abs(r1.variables['river_transport'][:]).sum(axis=1)*2.0/3.0 # interpolate this like for time Q1 = op.resize(Q1, 0) Q2 = np.abs(r2.variables['river_transport'][:]).sum(axis=1)*2.0/3.0 # Combine river info into one dataset iend1 = find(datesr1<datetime(2012,1,1,0,0,0))[-1] # ending index for file 1 tRiver = np.concatenate((tr1[:iend1], tr2[:]), axis=0) datesRiver = np.concatenate((datesr1[:iend1], datesr2)) R = np.concatenate((Q1[:iend1], Q2)) r1.close(); r2.close() # start and end indices in time for river discharge
def readfields(tind,grid,nc,z0=None,zpar=None): ''' readfields() Kristen Thyng, March 2013 Reads in model output in order to calculate fluxes and z grid properties to send into step.f95. Should be called initially and then subsequently each time loop. All arrays are changed to Fortran ordering (from Python ordering) and to tracmass variables ordering from ROMS ordering i.e. from [t,k,j,i] to [i,j,k,t] right away after reading in. Input: tind Single time index for model output to read in grid Dictionary containing all necessary time-independent grid fields nc NetCDF object for relevant files z0 (optional) if doing 2d isoslice, z0 contains string saying which kind zpar (optional) if doing 2d isoslice, zpar is the depth/level/density at which we are to get the level Output: uflux1 Zonal (x) flux at tind vflux1 Meriodional (y) flux at tind dzt Height of k-cells in 3 dim in meters on rho vertical grid. [imt,jmt,km] zrt Time-dependent depths of cells on vertical rho grid (meters). For the isoslice case, zrt ends up with 1 vertical level which contains the depths for the vertical center of the cell for that level. zwt Time-dependent depths of cells on vertical w grid (meters). zwt always contains the depths at the vertical cell edges for the whole 3D grid and the correct depths can be accessed using the drifter indices. Array descriptions: u,v Zonal (x) and meridional (y) velocities [imt,jmt,km] (m/s) ssh Free surface [imt,jmt] (m) dz Height of k-cells in 1 dim [km] From coord.f95: z coordinates (z>0 going up) for layers in meters bottom layer: k=0; surface layer: k=KM and zw=0 dz = layer thickness zt Depths (negative) in meters of w vertical grid [imt,jmt,km+1] dzt Height of k-cells in 3 dim in meters on rho vertical grid. [imt,jmt,km] dzt0 Height of k-cells in 2 dim. [imt,jmt] dzu Height of each u grid cell [imt-1,jmt,km] dzv Height of each v grid cell [imt,jmt-1,km] uflux1 Zonal (x) fluxes [imt-1,jmt,km] (m^3/s)? vflux1 Meriodional (y) fluxes [imt,jmt-1,km] (m^3/s)? ''' # tic_temp = time.time() # Read in model output for index tind if z0 == 's': # read in less model output to begin with, to save time u = nc.variables['u'][tind,zpar,:,:] v = nc.variables['v'][tind,zpar,:,:] ssh = nc.variables['zeta'][tind,:,:] # [t,j,i], ssh in tracmass else: u = nc.variables['u'][tind,:,:,:] v = nc.variables['v'][tind,:,:,:] ssh = nc.variables['zeta'][tind,:,:] # [t,j,i], ssh in tracmass # time_read = time.time()-tic_temp # tic_temp = time.time() # # make arrays in same order as is expected in the fortran code # # ROMS expects [time x k x j x i] but tracmass is expecting [i x j x k x time] # # change these arrays to be fortran-directioned instead of python # # u = u.T.copy(order='f') # # v = v.T.copy(order='f') # # ssh = ssh.T.copy(order='f') # # # Flip vertical dimension because in ROMS surface is at k=-1 # # # and in tracmass surface is at 1 # # u = np.flipud(u) # # v = np.flipud(v) # time_flip1 = time.time()-tic_temp # This is code from tracmass itself, which is being replaced by Rob's octant code # # Copy calculations from rutgersNWA/readfields.f95 # dzt = np.ones((grid['imt'],grid['jmt'],grid['km']))*np.nan # dzu = np.ones((grid['imt']-1,grid['jmt'],grid['km']))*np.nan # dzv = np.ones((grid['imt'],grid['jmt']-1,grid['km']))*np.nan # for k in xrange(grid['km']): # dzt0 = (grid['sc_r'][k]-grid['Cs_r'][k])*grid['hc'] \ # + grid['Cs_r'][k]*grid['h'] # dzt[:,:,k] = dzt0 + ssh*(1.+dzt0/grid['h']) # dzt0 = dzt[:,:,grid['km']-1] # dzt[:,:,0:grid['km']-1] = dzt[:,:,1:grid['km']] - dzt[:,:,0:grid['km']-1] # dzt[:,:,grid['km']-1] = ssh - dzt0 # tic_temp = time.time() h = grid['h'].T.copy(order='c') # Use octant to calculate depths for the appropriate vertical grid parameters # have to transform a few back to ROMS coordinates and python ordering for this zwt = octant.depths.get_zw(1, 1, grid['km']+1, grid['theta_s'], grid['theta_b'], h, grid['hc'], zeta=ssh, Hscale=3) # Change dzt to tracmass/fortran ordering # zwt = zwt.T.copy(order='f') # dzt = zwt[:,:,1:] - zwt[:,:,:-1] dzt = zwt[1:,:,:] - zwt[:-1,:,:] # pdb.set_trace() # time_zw = time.time()-tic_temp # tic_temp = time.time() # also want depths on rho grid zrt = octant.depths.get_zrho(1, 1, grid['km'], grid['theta_s'], grid['theta_b'], h, grid['hc'], zeta=ssh, Hscale=3) # Change dzt to tracmass/fortran ordering # zrt = zrt.T.copy(order='f') # time_zr = time.time()-tic_temp # tic_temp = time.time() dzu = .5*(dzt[:,:,0:grid['imt']-1] + dzt[:,:,1:grid['imt']]) dzv = .5*(dzt[:,0:grid['jmt']-1,:] + dzt[:,1:grid['jmt'],:]) # dzu = .5*(dzt[0:grid['imt']-1,:,:] + dzt[1:grid['imt'],:,:]) # dzv = .5*(dzt[:,0:grid['jmt']-1,:] + dzt[:,1:grid['jmt'],:]) # dzu = dzt[0:grid['imt']-1,:,:]*0.5 + dzt[1:grid['imt'],:,:]*0.5 # dzv = dzt[:,0:grid['jmt']-1,:]*0.5 + dzt[:,1:grid['jmt'],:]*0.5 # dzu[0:grid['imt']-1,:,:] = dzt[0:grid['imt']-1,:,:]*0.5 + dzt[1:grid['imt'],:,:]*0.5 # dzv[:,0:grid['jmt']-1,:] = dzt[:,0:grid['jmt']-1,:]*0.5 + dzt[:,1:grid['jmt'],:]*0.5 # pdb.set_trace() # time_interp = time.time()-tic_temp # tic_temp = time.time() # Change order back to ROMS/python for this calculation # u = u.T.copy(order='c') # v = v.T.copy(order='c') # dzu = dzu.T.copy(order='c') # dzv = dzv.T.copy(order='c') # dzt = dzt.T.copy(order='c') dyu = grid['dyu'].T.copy(order='c') dxv = grid['dxv'].T.copy(order='c') # zrt = zrt.T.copy(order='c') # time_flip2 = time.time()-tic_temp # pdb.set_trace() # tic_temp = time.time() # I think I can avoid this loop for the isoslice case if z0 == None: # 3d case uflux1 = u*dzu*dyu vflux1 = v*dzv*dxv elif z0 == 's': # want a specific s level zpar uflux1 = u*dzu[zpar,:,:]*dyu vflux1 = v*dzv[zpar,:,:]*dxv dzt = dzt[zpar,:,:] zrt = zrt[zpar,:,:] elif z0 == 'rho' or z0 == 'salt' or z0 == 'temp': # the vertical setup we're selecting an isovalue of vert = nc.variables[z0][tind,:,:,:] # pdb.set_trace() # Calculate flux and then take slice uflux1 = octant.tools.isoslice(u*dzu*dyu,op.resize(vert,2),zpar) vflux1 = octant.tools.isoslice(v*dzv*dxv,op.resize(vert,1),zpar) dzt = octant.tools.isoslice(dzt,vert,zpar) zrt = octant.tools.isoslice(zrt,vert,zpar) # pdb.set_trace() elif z0 == 'z': # Calculate flux and then take slice uflux1 = octant.tools.isoslice(u*dzu*dyu,op.resize(zrt,2),zpar) vflux1 = octant.tools.isoslice(v*dzv*dxv,op.resize(zrt,1),zpar) dzt = octant.tools.isoslice(dzt,zrt,zpar) zrt = np.ones(uflux1.shape)*zpar # array of the input desired depth # time_flux = time.time()-tic_temp # tic_temp = time.time() # Change all back to tracmass/fortran ordering if being used again # tic = time.time() # uflux1 = uflux1.T.copy(order='f') # vflux1 = vflux1.T.copy(order='f') # dzt = dzt.T.copy(order='f') # zrt = zrt.T.copy(order='f') # ssh = ssh.T.copy(order='f') # zwt = zwt.T.copy(order='f') # print "copy time",time.time()-tic # tic = time.time() # This is faster than copying arrays # Don't bother changing order of these arrays since I have to change it in # run.py anyway (concatenate appears not to preserve ordering) uflux1 = uflux1.T vflux1 = vflux1.T dzt = np.asfortranarray(dzt.T) # uflux1 = np.asfortranarray(uflux1.T) # vflux1 = np.asfortranarray(vflux1.T) # dzt = np.asfortranarray(dzt.T) zrt = np.asfortranarray(zrt.T) ssh = np.asfortranarray(ssh.T) zwt = np.asfortranarray(zwt.T) # print "fortran time",time.time()-tic # time_flip3 = time.time()-tic_temp # tic_temp = time.time() # make sure that all fluxes have a placeholder for depth if is_string_like(z0): uflux1 = uflux1.reshape(np.append(uflux1.shape,1)) vflux1 = vflux1.reshape(np.append(vflux1.shape,1)) dzt = dzt.reshape(np.append(dzt.shape,1)) zrt = zrt.reshape(np.append(zrt.shape,1)) # time_reshape = time.time()-tic_temp # # Flip vertical dimension because in ROMS surface is at k=-1 # # and in tracmass surface is at 1 # # This is not true. In tracmass, surface is at k=KM # uflux1 = uflux1[:,:,::-1] # vflux1 = vflux1[:,:,::-1] # dzt = dzt[:,:,::-1] # uflux1 = np.flipud(uflux1) # vflux1 = np.flipud(vflux1) # dzt = np.flipud(dzt) # print "time to read=",time_read # # print "time to flip=",time_flip1 # print "time to get zw=",time_zw # print "time to get zr=",time_zr # print "time to interp=",time_interp # print "time to flip2=",time_flip2 # print "time to flux=",time_flux # print "time to flip3=",time_flip3 # print "time to reshape=",time_reshape return uflux1, vflux1, dzt, zrt, zwt
def transport(name, fmod=None, Title=None, dmax=None, N=7, extraname=None, llcrnrlon=-98.5, llcrnrlat=22.5, urcrnrlat=31.0, urcrnrlon=-87.5, colormap='Blues'): ''' Make plot of zoomed-in area near DWH spill of transport of drifters over time. FILL IN Inputs: name U V lon0 lat0 T0 ''' # (name=None, U, V, lon0, lat0, T0, dmax, extraname, Title, N, # llcrnrlon, llcrnrlat, urcrnrlat, urcrnrlon, colormap): # Load in transport information U, V, lon0, lat0, T0 = inout.loadtransport(name,fmod=fmod) # Smaller basemap parameters. loc = 'http://barataria.tamu.edu:8080/thredds/dodsC/NcML/txla_nesting6.nc' grid = inout.readgrid(loc, llcrnrlon=llcrnrlon, llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, urcrnrlon=urcrnrlon) S = np.sqrt(op.resize(U,1)**2+op.resize(V,0)**2) Splot = (S/T0)*100 if dmax is None: dmax = Splot.max() else: dmax = dmax # from http://matplotlib.1069221.n5.nabble.com/question-about-contours-and-clim-td21111.html locator = ticker.MaxNLocator(N) # if you want no more than 10 contours locator.create_dummy_axis() locator.set_bounds(0,dmax)#d.min(),d.max()) levs = locator() fig = figure(figsize=(12,10)) background(grid=grid) c = contourf(grid['xpsi'], grid['ypsi'], Splot, cmap=colormap, extend='max', levels=levs) title(Title) # Add initial drifter location (all drifters start at the same location) lon0 = lon0.mean() lat0 = lat0.mean() x0, y0 = grid['basemap'](lon0, lat0) plot(x0, y0, 'go', markersize=10) # Inlaid colorbar cax = fig.add_axes([0.49, 0.25, 0.39, 0.02]) # cax = fig.add_axes([0.5, 0.2, 0.35, 0.02]) cb = colorbar(cax=cax,orientation='horizontal') cb.set_label('Normalized drifter transport (%)') if extraname is None: savefig('figures/' + name + '/transport', bbox_inches='tight') else: savefig('figures/' + name + '/transport' + extraname, bbox_inches='tight')
def transport(name, fmod=None, Title=None, dmax=None, N=7, extraname=None, llcrnrlon=-98.5, llcrnrlat=22.5, urcrnrlat=31.0, urcrnrlon=-87.5, colormap='Blues', fig=None, ax=None): ''' Make plot of zoomed-in area near DWH spill of transport of drifters over time. FILL IN Inputs: name U V lon0 lat0 T0 ''' # (name=None, U, V, lon0, lat0, T0, dmax, extraname, Title, N, # llcrnrlon, llcrnrlat, urcrnrlat, urcrnrlon, colormap): # Load in transport information U, V, lon0, lat0, T0 = inout.loadtransport(name, fmod=fmod) # Smaller basemap parameters. loc = 'http://barataria.tamu.edu:8080/thredds/dodsC/NcML/txla_nesting6.nc' grid = inout.readgrid(loc, llcrnrlon=llcrnrlon, llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, urcrnrlon=urcrnrlon) S = np.sqrt(op.resize(U, 1)**2 + op.resize(V, 0)**2) Splot = (S / T0) * 100 if dmax is None: dmax = Splot.max() else: dmax = dmax # from http://matplotlib.1069221.n5.nabble.com/question-about-contours-and-clim-td21111.html locator = ticker.MaxNLocator(N) # if you want no more than 10 contours locator.create_dummy_axis() locator.set_bounds(0, dmax) #d.min(),d.max()) levs = locator() if fig is None: fig = figure(figsize=(11, 10)) else: fig = fig background(grid=grid) c = contourf(grid['xpsi'], grid['ypsi'], Splot, cmap=colormap, extend='max', levels=levs) title(Title) # # Add initial drifter location (all drifters start at the same location) # lon0 = lon0.mean() # lat0 = lat0.mean() # x0, y0 = grid['basemap'](lon0, lat0) # plot(x0, y0, 'go', markersize=10) if ax is None: ax = gca() else: ax = ax # Want colorbar at the given location relative to axis so this works regardless of # of subplots, # so convert from axis to figure coordinates # To do this, first convert from axis to display coords # transformations: http://matplotlib.org/users/transforms_tutorial.html ax_coords = [0.35, 0.25, 0.6, 0.02] # axis: [x_left, y_bottom, width, height] disp_coords = ax.transAxes.transform([ (ax_coords[0], ax_coords[1]), (ax_coords[0] + ax_coords[2], ax_coords[1] + ax_coords[3]) ]) # display: [x_left,y_bottom,x_right,y_top] inv = fig.transFigure.inverted( ) # inverter object to go from display coords to figure coords fig_coords = inv.transform( disp_coords) # figure: [x_left,y_bottom,x_right,y_top] # actual desired figure coords. figure: [x_left, y_bottom, width, height] fig_coords = [ fig_coords[0, 0], fig_coords[0, 1], fig_coords[1, 0] - fig_coords[0, 0], fig_coords[1, 1] - fig_coords[0, 1] ] # Inlaid colorbar cax = fig.add_axes(fig_coords) # cax = fig.add_axes([0.39, 0.25, 0.49, 0.02]) # cax = fig.add_axes([0.49, 0.25, 0.39, 0.02]) cb = colorbar(cax=cax, orientation='horizontal') cb.set_label('Normalized drifter transport (%)') if extraname is None: savefig('figures/' + name + '/transport', bbox_inches='tight') else: savefig('figures/' + name + '/' + extraname + 'transport', bbox_inches='tight')
latv = grid.variables['lat_v'][:] xv, yv = basemap(lonv,latv) hfull = grid.variables['h'][:] lonr = grid.variables['lon_rho'][:]#[1:-1,1:-1] latr = grid.variables['lat_rho'][:]#[1:-1,1:-1] xr, yr = basemap(lonr,latr) lonpsi = grid.variables['lon_psi'][:] latpsi = grid.variables['lat_psi'][:] xpsi, ypsi = basemap(lonpsi,latpsi) maskr = grid.variables['mask_rho'][:]#[1:-1,1:-1] X, Y = np.meshgrid(np.arange(xr.shape[1]),np.arange(yr.shape[0])) # grid in index coordinates, without ghost cells tri = delaunay.Triangulation(X.flatten(),Y.flatten()) # Angle on rho grid theta = grid.variables['angle'][:] # Interpolate theta to be on psi grid theta = op.resize(op.resize(theta,0),1) pm = grid.variables['pm'][:] # 1/dx pn = grid.variables['pn'][:] # 1/dy # The following are for setting up z array on u (v) grids for calculating u (v) fluxes # Want h only within domain in y (x) direction (no ghost cells) and interpolated onto cell # walls in x (y) direction hu = op.resize(grid.variables['h'][1:-1,:],1) hv = op.resize(grid.variables['h'][:,1:-1],0) loc = '/Users/kthyng/Documents/research/postdoc/' # for model outputs files = np.sort(glob.glob(loc + 'ocean_his_*.nc')) # sorted list of file names filesfull = np.sort(glob.glob(loc + 'ocean_his_*.nc')) #full path of files # Find the list of files that cover the desired time period for i,name in enumerate(files): # Loop through files nctemp = netCDF.Dataset(name)
# interpolation constant for each time step r2 = np.linspace(0, 1, t1[istart_dates1:].size) r1 = 1. - r2 # Linearly combine model output in overlap region # pdb.set_trace() uin2[:iend_dates2] = (r1.reshape(r1.size,1,1)*uin1[istart_dates1:] + r2.reshape(r1.size,1,1)*uin2[:iend_dates2]) del(uin1) # Cut off end part uin2 = uin2[:istart_dates2] t = t2[:istart_dates2] # Update time dimension nt = uin2.shape[0] # u and v are on rho grid to start uin2 = op.resize(uin2, 2); # onto staggered grid uin2 = uin2.reshape((nt, 1, yu, xu)).repeat(zl,axis=1) # Make new file rootgrp = netCDF.Dataset('ocean_his_' + str(i+1).zfill(4) + '.nc','w',format='NETCDF3_64BIT') rootgrp.createDimension('xu',xu) rootgrp.createDimension('yu',yu) rootgrp.createDimension('xv',xv) rootgrp.createDimension('yv',yv) rootgrp.createDimension('zl',zl) # Change time dimension to be unlimited for aggregation later rootgrp.createDimension('nt',None) ocean_time = rootgrp.createVariable('ocean_time','f8',('nt')) # 64-bit floating point u = rootgrp.createVariable('u','f4',('nt','zl','yu','xu')) # 64-bit floating point v = rootgrp.createVariable('v','f4',('nt','zl','yv','xv')) # 64-bit floating point u[:] = uin2; ocean_time[:] = t;
Smax = 0 for i,fmod in enumerate(fmods): ## Read in transport info ## Files = glob.glob('tracks/' + fmod + '-*') U = 0; V = 0 for File in Files: d = netCDF.Dataset(File) U += d.variables['U'][:] V += d.variables['V'][:] d.close # S is at cell centers, minus ghost points Stemp = np.sqrt(op.resize(U[:,1:-1],0)**2 + op.resize(V[1:-1,:],1)**2) S.append(Stemp) Smax = max((Smax,Stemp.max())) ## Plot ## fig = plt.figure(figsize=(12,4.8))#, dpi=150) fig.suptitle('Surface transport', fontsize=18) for i in xrange(len(S)): ax = fig.add_subplot(2,4,i+1) ax.set_frame_on(False) # kind of like it without the box if i==0:
def readfields(tind, grid, nc, z0=None, zpar=None, zparuv=None): """ readfields() Kristen Thyng, March 2013 Reads in model output in order to calculate fluxes and z grid properties to send into step.f95. Should be called initially and then subsequently each time loop. All arrays are changed to Fortran ordering (from Python ordering) and to tracmass variables ordering from ROMS ordering i.e. from [t,k,j,i] to [i,j,k,t] right away after reading in. Args: tind: Single time index for model output to read in grid: Dictionary containing all necessary time-independent grid fields nc: NetCDF object for relevant files z0 (Optional): if doing 2d isoslice, z0 contains string saying which kind zpar (Optional): if doing 2d isoslice, zpar is the depth/level/density at which we are to get the level zparuv (Optional): Use this if the k index for the model output fields (e.g, u, v) is different from the k index in the grid. This might happen if, for example, only the surface current were saved, but the model run originally did have many layers. This parameter represents the k index for the u and v output, not for the grid. Returns: * uflux1 - Zonal (x) flux at tind * vflux1 - Meriodional (y) flux at tind * dzt - Height of k-cells in 3 dim in meters on rho vertical grid. [imt,jmt,km] * zrt - Time-dependent depths of cells on vertical rho grid (meters). For the isoslice case, zrt ends up with 1 vertical level which contains the depths for the vertical center of the cell for that level. * zwt - Time-dependent depths of cells on vertical w grid (meters). zwt always contains the depths at the vertical cell edges for the whole 3D grid and the correct depths can be accessed using the drifter indices. Array descriptions: * u,v - Zonal (x) and meridional (y) velocities [imt,jmt,km] (m/s) * ssh - Free surface [imt,jmt] (m) * dz - Height of k-cells in 1 dim [km] From coord.f95: z coordinates (z>0 going up) for layers in meters bottom layer: k=0; surface layer: k=KM and zw=0 dz = layer thickness * zt - Depths (negative) in meters of w vertical grid [imt,jmt,km+1] * dzt - Height of k-cells in 3 dim in meters on rho vertical grid. [imt,jmt,km] * dzt0 - Height of k-cells in 2 dim. [imt,jmt] * dzu - Height of each u grid cell [imt-1,jmt,km] * dzv - Height of each v grid cell [imt,jmt-1,km] * uflux1 - Zonal (x) fluxes [imt-1,jmt,km] (m^3/s)? * vflux1 - Meriodional (y) fluxes [imt,jmt-1,km] (m^3/s)? """ # this parameter is in case there is less model output available # vertically than was actually run on the grid if zparuv is None: zparuv = zpar # tic_temp = time.time() # Read in model output for index tind if z0 == 's': # read in less model output to begin with, to save time u = nc.variables['u'][tind, zparuv, :, :] v = nc.variables['v'][tind, zparuv, :, :] if 'zeta' in nc.variables: # [t,j,i], ssh in tracmass ssh = nc.variables['zeta'][tind, :, :] sshread = True else: sshread = False else: u = nc.variables['u'][tind, :, :, :] v = nc.variables['v'][tind, :, :, :] if 'zeta' in nc.variables: # [t,j,i], ssh in tracmass ssh = nc.variables['zeta'][tind, :, :] sshread = True else: sshread = False # Use octant to calculate depths for the appropriate vertical grid # parameters have to transform a few back to ROMS coordinates and python # ordering for this if sshread: zwt = octant.depths.get_zw(grid.Vtransform, grid.Vstretching, grid.km+1, grid.theta_s, grid.theta_b, grid.h, grid.hc, zeta=ssh, Hscale=3) else: # if ssh isn't available, approximate as 0 zwt = octant.depths.get_zw(grid.Vtransform, grid.Vstretching, grid.km+1, grid.theta_s, grid.theta_b, grid.h, grid.hc, zeta=0, Hscale=3) # Change dzt to tracmass/fortran ordering dzt = zwt[1:, :, :] - zwt[:-1, :, :] # also want depths on rho grid if sshread: zrt = octant.depths.get_zrho(grid.Vtransform, grid.Vstretching, grid.km, grid.theta_s, grid.theta_b, grid.h, grid.hc, zeta=ssh, Hscale=3) else: zrt = octant.depths.get_zrho(grid.Vtransform, grid.Vstretching, grid.km, grid.theta_s, grid.theta_b, grid.h, grid.hc, zeta=0, Hscale=3) dzu = .5*(dzt[:, :, 0:grid.imt-1] + dzt[:, :, 1:grid.imt]) dzv = .5*(dzt[:, 0:grid.jmt-1, :] + dzt[:, 1:grid.jmt, :]) # I think I can avoid this loop for the isoslice case if z0 is None: # 3d case uflux1 = u*dzu*grid.dyu vflux1 = v*dzv*grid.dxv elif z0 == 's': # want a specific s level zpar uflux1 = u*dzu[zpar, :, :]*grid.dyu vflux1 = v*dzv[zpar, :, :]*grid.dxv dzt = dzt[zpar, :, :] zrt = zrt[zpar, :, :] elif z0 == 'rho' or z0 == 'salt' or z0 == 'temp': # the vertical setup we're selecting an isovalue of vert = nc.variables[z0][tind, :, :, :] # Calculate flux and then take slice uflux1 = octant.tools.isoslice(u*dzu*grid.dyu, op.resize(vert, 2), zpar) vflux1 = octant.tools.isoslice(v*dzv*grid.dxv, op.resize(vert, 1), zpar) dzt = octant.tools.isoslice(dzt, vert, zpar) zrt = octant.tools.isoslice(zrt, vert, zpar) elif z0 == 'z': # Calculate flux and then take slice uflux1 = octant.tools.isoslice(u*dzu*grid.dyu, op.resize(zrt, 2), zpar) vflux1 = octant.tools.isoslice(v*dzv*grid.dxv, op.resize(zrt, 1), zpar) dzt = octant.tools.isoslice(dzt, zrt, zpar) zrt = np.ones(uflux1.shape)*zpar # array of the input desired depth # make sure that all fluxes have a placeholder for depth if isinstance(z0, str): uflux1 = uflux1.reshape(np.append(1, uflux1.shape)) vflux1 = vflux1.reshape(np.append(1, vflux1.shape)) dzt = dzt.reshape(np.append(1, dzt.shape)) zrt = zrt.reshape(np.append(1, zrt.shape)) return uflux1, vflux1, dzt, zrt, zwt
ax1b.plot([x[n], 891975], [y[n], 146818], '-', color='0.2', lw=0.5) ax1b.text(891975-10000, 146818-10000, 'Ship track', color='0.1') if gradient: cax1b = fig.add_axes([0.38, 0.94, 0.065, 0.015]) # colorbar axes else: cax1b = fig.add_axes([0.55, 0.94, 0.1, 0.015]) # colorbar axes cb1b = fig.colorbar(map1b, cax=cax1b, orientation='horizontal') cb1b.set_label('Free surface [m]', color='0.2') cb1b.ax.tick_params(labelsize=10, length=2, color='0.2', labelcolor='0.2') cb1b.set_ticks(np.arange(-0.1, 0.2, 0.1)) if gradient: ## TXLA Plot of top half of domain - gradients grad1 = (ssh[1:,:] - ssh[:-1,:])/(yr[1:,:] - yr[:-1,:]) grad2 = (ssh[:,1:] - ssh[:,:-1])/(xr[:,1:] - xr[:,:-1]) grad = abs(np.sqrt(op.resize(grad1,1)**2 + op.resize(grad2,0)**2)) tracpy.plotting.background(grid, ax=ax1c, outline=[0, 0, 0, 0], mers=np.arange(-96, -86, 2), parslabels=[0,0,0,0], hlevs=[0]) map1c = ax1c.pcolormesh(xr, yr, grad, cmap=cmo.matter, vmin=0, vmax=0.000008) ax1c.set_frame_on(False) # kind of like it without the box ax1c.text(0.9, 0.01, 'c', color='0.1', transform=ax1c.transAxes, fontsize=12) # Label subplot # Temperature, in jet cmap = cm.jet data = d[:, var.index('temp')] # http://matplotlib.org/1.2.1/examples/pylab_examples/hist_colormapped.html # we need to normalize the data to 0..1 for the full range of the colormap fracs = data[1:][iup] # /data[1:][iup].max() norm = colors.Normalize(fracs.min(), fracs.max()) # loop through the voronoi regions by data point and associated color fraction for frac, point_region in zip(fracs, vor.point_region): color = cmap(norm(frac)) # which color in cmap to use
# loc = 'http://barataria.tamu.edu:6060/thredds/dodsC/NcML/txla_nesting6.nc' # grid = tracpy.inout.readgrid(loc, usebasemap=True) # grid_filename = '/atch/raid1/zhangxq/Projects/txla_nesting6/txla_grd_v4_new.nc' # vert_filename='/atch/raid1/zhangxq/Projects/txla_nesting6/ocean_his_0001.nc' # grid = tracpy.inout.readgrid(grid_filename, vert_filename=vert_filename, usebasemap=True) proj = tracpy.tools.make_proj('nwgom', usebasemap=True) # grid = tracpy.inout.readgrid('../../grid.nc', proj) grid = tracpy.inout.readgrid('grid.nc', proj) if whichtime == 'seasonal': # Load in histogram d = np.load('figures/cross/seasonal100H.npz') H = d['H'] X, Y = np.meshgrid(op.resize(d['xe'],0), op.resize(d['ye'],0)) fh = grid['trir'].nn_interpolator(grid['h'].flatten()) depths = fh(X,Y) ishallow = depths < shelf_depth ideep = depths > shelf_depth # winter offshore = np.nansum(H[0,ishallow])/ishallow.sum() # likelihood per histogram bin onshore = np.nansum(H[0,ideep])/ideep.sum() elif whichtime == 'interannual': if whichseason == 'winter':
lonv = grid.variables['lon_v'][:,1:-1] latv = grid.variables['lat_v'][:,1:-1] xv, yv = basemap(lonv,latv) hfull = grid.variables['h'][:] lonr = grid.variables['lon_rho'][1:-1,1:-1] latr = grid.variables['lat_rho'][1:-1,1:-1] xr, yr = basemap(lonr,latr) lonpsi = grid.variables['lon_psi'][:] latpsi = grid.variables['lat_psi'][:] xpsi, ypsi = basemap(lonpsi,latpsi) X, Y = np.meshgrid(np.arange(latpsi.shape[0]),np.arange(latpsi.shape[1])) tri = delaunay.Triangulation(X.flatten(),Y.flatten()) # Angle on rho grid theta = grid.variables['angle'][:] # Interpolate theta to be on psi grid theta = op.resize(op.resize(theta,0),1) grid.close() nc = netCDF.Dataset('/Users/kthyng/Documents/research/postdoc/ocean_his_0150.nc') t = nc.variables['ocean_time'][0:0+2] # Some grid metrics s = nc.variables['s_w'][:] # sigma coords, 31 layers cs = nc.variables['Cs_w'][:] # stretching curve in sigma coords, 31 layers nc.close() xl = xpsi.shape[1] yl = xpsi.shape[0] zl = len(cs)-1 tl = 3 # three time outputs dt = 4*3600 # 4 hours between outputs # pdb.set_trace()
# w = netCDF.Dataset('/atch/raid1/zhangxq/Projects/narr_txla/txla_blk_narr_' + str(year) + '.nc') # Wind time period to use unitsWind = (w.variables['time'].units).replace('/','-') datesWind = netCDF.num2date(w.variables['time'][:], unitsWind) # datesWind = datesModel wdx = 25; wdy = 30 # in indices ## ## River forcing ## r1 = netCDF.Dataset('/rho/raid/home/kthyng/txla/TXLA_river_4dyes_2012.nc') # use for through 2011 r2 = netCDF.Dataset('/rho/raid/home/kthyng/txla/TXLA_river_4dyes_2012_2014.nc') # use for 2012-2014 # River timing tr1 = r1.variables['river_time'] tunitsr1 = tr1.units # interpolate times for this data file since at the 12 hours mark instead of beginning of the day tr1 = op.resize(tr1, 0) datesr1 = netCDF.num2date(tr1[:], tunitsr1) tr2 = r2.variables['river_time'] datesr2 = netCDF.num2date(tr2[:], tr2.units) # all of river input Q1 = np.abs(r1.variables['river_transport'][:]).sum(axis=1)*2.0/3.0 # interpolate this like for time Q1 = op.resize(Q1, 0) Q2 = np.abs(r2.variables['river_transport'][:]).sum(axis=1)*2.0/3.0 # Combine river info into one dataset iend1 = find(datesr1<datetime(2012,1,1,0,0,0))[-1] # ending index for file 1 tRiver = np.concatenate((tr1[:iend1], tr2[:]), axis=0) datesRiver = np.concatenate((datesr1[:iend1], datesr2)) R = np.concatenate((Q1[:iend1], Q2)) r1.close(); r2.close() # start and end indices in time for river discharge
def readfields(tind,grid,nc,z0=None, zpar=None, zparuv=None): ''' readfields() Kristen Thyng, March 2013 Reads in model output in order to calculate fluxes and z grid properties to send into step.f95. Should be called initially and then subsequently each time loop. All arrays are changed to Fortran ordering (from Python ordering) and to tracmass variables ordering from ROMS ordering i.e. from [t,k,j,i] to [i,j,k,t] right away after reading in. Input: tind Single time index for model output to read in grid Dictionary containing all necessary time-independent grid fields nc NetCDF object for relevant files z0 (optional) if doing 2d isoslice, z0 contains string saying which kind zpar (optional) if doing 2d isoslice, zpar is the depth/level/density at which we are to get the level zparuv (optional) Use this if the k index for the model output fields (e.g, u, v) is different from the k index in the grid. This might happen if, for example, only the surface current were saved, but the model run originally did have many layers. This parameter represents the k index for the u and v output, not for the grid. Output: uflux1 Zonal (x) flux at tind vflux1 Meriodional (y) flux at tind dzt Height of k-cells in 3 dim in meters on rho vertical grid. [imt,jmt,km] zrt Time-dependent depths of cells on vertical rho grid (meters). For the isoslice case, zrt ends up with 1 vertical level which contains the depths for the vertical center of the cell for that level. zwt Time-dependent depths of cells on vertical w grid (meters). zwt always contains the depths at the vertical cell edges for the whole 3D grid and the correct depths can be accessed using the drifter indices. Array descriptions: u,v Zonal (x) and meridional (y) velocities [imt,jmt,km] (m/s) ssh Free surface [imt,jmt] (m) dz Height of k-cells in 1 dim [km] From coord.f95: z coordinates (z>0 going up) for layers in meters bottom layer: k=0; surface layer: k=KM and zw=0 dz = layer thickness zt Depths (negative) in meters of w vertical grid [imt,jmt,km+1] dzt Height of k-cells in 3 dim in meters on rho vertical grid. [imt,jmt,km] dzt0 Height of k-cells in 2 dim. [imt,jmt] dzu Height of each u grid cell [imt-1,jmt,km] dzv Height of each v grid cell [imt,jmt-1,km] uflux1 Zonal (x) fluxes [imt-1,jmt,km] (m^3/s)? vflux1 Meriodional (y) fluxes [imt,jmt-1,km] (m^3/s)? ''' # this parameter is in case there is less model output available vertically than # was actually run on the grid # pdb.set_trace() if zparuv is None: zparuv = zpar # tic_temp = time.time() # Read in model output for index tind if z0 == 's': # read in less model output to begin with, to save time u = nc.variables['u'][tind,zparuv,:,:] v = nc.variables['v'][tind,zparuv,:,:] if 'zeta' in nc.variables: ssh = nc.variables['zeta'][tind,:,:] # [t,j,i], ssh in tracmass sshread = True else: sshread = False else: u = nc.variables['u'][tind,:,:,:] v = nc.variables['v'][tind,:,:,:] if 'zeta' in nc.variables: ssh = nc.variables['zeta'][tind,:,:] # [t,j,i], ssh in tracmass sshread = True else: sshread = False h = grid['h'].T.copy(order='c') # Use octant to calculate depths for the appropriate vertical grid parameters # have to transform a few back to ROMS coordinates and python ordering for this if sshread: zwt = octant.depths.get_zw(grid['Vtransform'], grid['Vstretching'], grid['km']+1, grid['theta_s'], grid['theta_b'], h, grid['hc'], zeta=ssh, Hscale=3) else: # if ssh isn't available, approximate as 0 zwt = octant.depths.get_zw(grid['Vtransform'], grid['Vstretching'], grid['km']+1, grid['theta_s'], grid['theta_b'], h, grid['hc'], zeta=0, Hscale=3) # Change dzt to tracmass/fortran ordering dzt = zwt[1:,:,:] - zwt[:-1,:,:] # also want depths on rho grid if sshread: zrt = octant.depths.get_zrho(grid['Vtransform'], grid['Vstretching'], grid['km'], grid['theta_s'], grid['theta_b'], h, grid['hc'], zeta=ssh, Hscale=3) else: zrt = octant.depths.get_zrho(grid['Vtransform'], grid['Vstretching'], grid['km'], grid['theta_s'], grid['theta_b'], h, grid['hc'], zeta=0, Hscale=3) dzu = .5*(dzt[:,:,0:grid['imt']-1] + dzt[:,:,1:grid['imt']]) dzv = .5*(dzt[:,0:grid['jmt']-1,:] + dzt[:,1:grid['jmt'],:]) # Change order back to ROMS/python for this calculation dyu = grid['dyu'].T.copy(order='c') dxv = grid['dxv'].T.copy(order='c') # I think I can avoid this loop for the isoslice case if z0 == None: # 3d case uflux1 = u*dzu*dyu vflux1 = v*dzv*dxv elif z0 == 's': # want a specific s level zpar uflux1 = u*dzu[zpar,:,:]*dyu vflux1 = v*dzv[zpar,:,:]*dxv dzt = dzt[zpar,:,:] zrt = zrt[zpar,:,:] elif z0 == 'rho' or z0 == 'salt' or z0 == 'temp': # the vertical setup we're selecting an isovalue of vert = nc.variables[z0][tind,:,:,:] # Calculate flux and then take slice uflux1 = octant.tools.isoslice(u*dzu*dyu,op.resize(vert,2),zpar) vflux1 = octant.tools.isoslice(v*dzv*dxv,op.resize(vert,1),zpar) dzt = octant.tools.isoslice(dzt,vert,zpar) zrt = octant.tools.isoslice(zrt,vert,zpar) elif z0 == 'z': # Calculate flux and then take slice uflux1 = octant.tools.isoslice(u*dzu*dyu,op.resize(zrt,2),zpar) vflux1 = octant.tools.isoslice(v*dzv*dxv,op.resize(zrt,1),zpar) dzt = octant.tools.isoslice(dzt,zrt,zpar) zrt = np.ones(uflux1.shape)*zpar # array of the input desired depth # Change all back to tracmass/fortran ordering if being used again # This is faster than copying arrays # Don't bother changing order of these arrays since I have to change it in # run.py anyway (concatenate appears not to preserve ordering) uflux1 = uflux1.T vflux1 = vflux1.T dzt = np.asfortranarray(dzt.T) zrt = np.asfortranarray(zrt.T) if sshread: ssh = np.asfortranarray(ssh.T) zwt = np.asfortranarray(zwt.T) # make sure that all fluxes have a placeholder for depth if is_string_like(z0): uflux1 = uflux1.reshape(np.append(uflux1.shape,1)) vflux1 = vflux1.reshape(np.append(vflux1.shape,1)) dzt = dzt.reshape(np.append(dzt.shape,1)) zrt = zrt.reshape(np.append(zrt.shape,1)) return uflux1, vflux1, dzt, zrt, zwt
.isel(s_rho=-1, eta_rho=slice(1, -1), xi_rho=slice(1, -1)) .data.mean(axis=0) ) salt = np.asarray(salt).mean(axis=0) # salt = np.squeeze(m.variables['salt'][itmodel,-1,1:-1,1:-1]) # Surface currents over domain, use psi grid for common locations u = [] for year in years: u.append(ds["u"].loc[str(year) + "-" + start : str(year) + "-" + stop].isel(s_rho=-1).data.mean(axis=0)) u = np.asarray(u).mean(axis=0) v = [] for year in years: v.append(ds["v"].loc[str(year) + "-" + start : str(year) + "-" + stop].isel(s_rho=-1).data.mean(axis=0)) v = np.asarray(v).mean(axis=0) u = op.resize(u, 0) v = op.resize(v, 1) anglev = ds["angle"].data u, v = rot2d(u, v, op.resize(op.resize(anglev, 0), 1)) if var == "speed": salt = np.sqrt(u ** 2 + v ** 2) # wind stress sustr = [] for year in years: sustr.append(ds["sustr"].loc[str(year) + "-" + start : str(year) + "-" + stop].data.mean(axis=0)) sustr = np.asarray(sustr).mean(axis=0) svstr = [] for year in years: svstr.append(ds["svstr"].loc[str(year) + "-" + start : str(year) + "-" + stop].data.mean(axis=0))
# reading in a subset of indices from the beginning is prohibitively slow xg = d.variables['xg'][:]; xg = xg[ind[::ddi],:] yg = d.variables['yg'][:]; yg = yg[ind[::ddi],:] xp, yp, _ = tracpy.tools.interpolate2d(xg, yg, grid, 'm_ij2xy') nind = xg==-1 del(xg,yg) # xg[nind] = np.nan; yg[nind] = np.nan xp[nind] = np.nan; yp[nind] = np.nan d.close() # Calculate and accumulate histograms of starting locations of drifters that cross shelf # Htemp, xe, ye = np.histogram2d(xg.flatten(), yg.flatten(), bins=bins, range=[[XGrange[0], XGrange[1]], [YGrange[0], YGrange[1]]]) Htemp, xe, ye = np.histogram2d(xp.flatten(), yp.flatten(), bins=bins, range=[[XPrange[0], XPrange[1]], [YPrange[0], YPrange[1]]]) H = np.nansum( np.vstack((H[np.newaxis,:,:], Htemp[np.newaxis,:,:])), axis=0) XE, YE = np.meshgrid(op.resize(xe, 0), op.resize(ye, 0)) hist, bin_edges = np.histogram(H.flat, bins=100) # find # of occurrences of histogram bin values n = np.cumsum(hist) Hmax = bin_edges[find(n<(n.max()-n.min())*.8+n.min())[-1]] # take the 80% of histogram occurrences as the max instead of actual max since too high locator = ticker.MaxNLocator(11) locator.create_dummy_axis() locator.set_bounds(0, 1) levels = locator() extend = 'max' H = H/Hmax mappable = ax.contourf(XE, YE, H.T, cmap=cmap, levels=levels, extend=extend) ax.contour(grid['xr'], grid['yr'], grid['h'], [shelf_depth], colors='0.1', linewidth=3) # outline the area where drifters started d = np.load('calcs/winter-contour-pts.npz') ax.plot(d['x'], d['y'], 'k', lw=3)
nc = netCDF.Dataset(loc) # for wind t = nc.variables['ocean_time'] datesw = netCDF.num2date(t[:], t.units) # Surface stress sustr = nc.variables['sustr']; svstr = nc.variables['svstr'] ## River forcing ## # r1 = netCDF.Dataset('/atch/raid1/zhangxq/Projects/txla_nesting6/TXLA_river_4dyes_2011.nc') r1 = netCDF.Dataset('/rho/raid/home/kthyng/txla/TXLA_river_4dyes_2012.nc') # use for through 2011 r2 = netCDF.Dataset('/rho/raid/home/kthyng/txla/TXLA_river_4dyes_2012_2014.nc') # use for 2012-2014 # River timing tr1 = r1.variables['river_time'] tunitsr1 = tr1.units # interpolate times for this data file since at the 12 hours mark instead of beginning of the day tr1 = op.resize(tr1, 0) datesr1 = netCDF.num2date(tr1[:], tunitsr1) tr2 = r2.variables['river_time'] datesr2 = netCDF.num2date(tr2[:], tr2.units) # all of river input Q1 = np.abs(r1.variables['river_transport'][:]).sum(axis=1)*2.0/3.0 # interpolate this like for time Q1 = op.resize(Q1, 0) Q2 = np.abs(r2.variables['river_transport'][:]).sum(axis=1)*2.0/3.0 # pdb.set_trace() # Combine river info into one dataset iend1 = find(datesr1<datetime(2012,1,1,0,0,0))[-1] # ending index for file 1 tr = np.concatenate((tr1[:iend1], tr2[:]), axis=0) datesr = np.concatenate((datesr1[:iend1], datesr2)) Q = np.concatenate((Q1[:iend1], Q2))
for i, File in enumerate(Files): datestr = File.split('/')[-1].split('gc')[0] fig = plt.figure(figsize=(6.8375, 6.6125)) fig.subplots_adjust(left=0.04, bottom=0.15, right=1.0, top=0.96, wspace=0.07, hspace=0.04) ax = fig.add_subplot(111) tracpy.plotting.background(grid=grid, ax=ax, mers=np.arange(-100, -80, 2)) ax.set_title('Simulation starting ' + datestr) if not os.path.exists(fname): d = netCDF.Dataset(File) U = d.variables['U'][:]; V = d.variables['V'][:] d.close() S[i,:,:] = np.sqrt(op.resize(U, 1)**2 + op.resize(V, 0)**2) # S[i,:,:] = S[i,:,:] + Stemp # locator = ticker.MaxNLocator(11) # locator.create_dummy_axis() # locator.set_bounds(0, 1) # levels = locator() # extend = 'max' # H = H/Hmax Smax = 1. else: d = np.load(fname); S = d['S']; d.close() Smax = S.max() if howplot=='log':
def transport( name, fmod=None, Title=None, dmax=None, N=7, extraname=None, llcrnrlon=-98.5, llcrnrlat=22.5, urcrnrlat=31.0, urcrnrlon=-87.5, colormap="Blues", fig=None, ax=None, ): """ Make plot of zoomed-in area near DWH spill of transport of drifters over time. FILL IN Args: name U V lon0 lat0 T0 """ # Load in transport information U, V, lon0, lat0, T0 = inout.loadtransport(name, fmod=fmod) # Smaller basemap parameters. loc = "http://barataria.tamu.edu:8080/thredds/dodsC/NcML/txla_nesting6.nc" grid = inout.readgrid(loc, llcrnrlon=llcrnrlon, llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, urcrnrlon=urcrnrlon) S = np.sqrt(op.resize(U, 1) ** 2 + op.resize(V, 0) ** 2) Splot = (S / T0) * 100 if dmax is None: dmax = Splot.max() else: dmax = dmax # from http://matplotlib.1069221.n5.nabble.com/question-about-contours-and-clim-td21111.html locator = ticker.MaxNLocator(N) # if you want no more than 10 contours locator.create_dummy_axis() locator.set_bounds(0, dmax) # d.min(),d.max()) levs = locator() if fig is None: fig = plt.figure(figsize=(11, 10)) else: fig = fig background(grid=grid) c = fig.contourf(grid.xpsi, grid.ypsi, Splot, cmap=colormap, extend="max", levels=levs) plt.title(Title) # # Add initial drifter location (all drifters start at the same location) # lon0 = lon0.mean() # lat0 = lat0.mean() # x0, y0 = grid['basemap'](lon0, lat0) # plot(x0, y0, 'go', markersize=10) if ax is None: ax = plt.gca() else: ax = ax # Want colorbar at the given location relative to axis so this works # regardless of # of subplots, # so convert from axis to figure coordinates # To do this, first convert from axis to display coords # transformations: http://matplotlib.org/users/transforms_tutorial.html ax_coords = [0.35, 0.25, 0.6, 0.02] # axis: [x_left, y_bottom, width, height] # display: [x_left,y_bottom,x_right,y_top] disp_coords = ax.transAxes.transform( [(ax_coords[0], ax_coords[1]), (ax_coords[0] + ax_coords[2], ax_coords[1] + ax_coords[3])] ) # inverter object to go from display coords to figure coords inv = fig.transFigure.inverted() # figure: [x_left,y_bottom,x_right,y_top] fig_coords = inv.transform(disp_coords) # actual desired figure coords. figure: [x_left, y_bottom, width, height] fig_coords = [ fig_coords[0, 0], fig_coords[0, 1], fig_coords[1, 0] - fig_coords[0, 0], fig_coords[1, 1] - fig_coords[0, 1], ] # Inlaid colorbar cax = fig.add_axes(fig_coords) # cax = fig.add_axes([0.39, 0.25, 0.49, 0.02]) # cax = fig.add_axes([0.49, 0.25, 0.39, 0.02]) cb = fig.colorbar(cax=cax, orientation="horizontal") cb.set_label("Normalized drifter transport (%)") if extraname is None: fig.savefig("figures/" + name + "/transport", bbox_inches="tight") else: fig.savefig("figures/" + name + "/" + extraname + "transport", bbox_inches="tight")
def hist(lonp, latp, fname, tind='final', which='contour', vmax=None, fig=None, ax=None, \ bins=(40,40), N=10, grid=None, xlims=None, ylims=None, C=None, Title=None, weights=None, Label='Final drifter location (%)', isll=True, binscale=None): """ Plot histogram of given track data at time index tind. Inputs: lonp,latp Drifter track positions in lon/lat [time x ndrifters] fname Plot name to save tind (optional) Default is 'final', in which case the final position of each drifter in the array is found and plotted. Alternatively, a time index can be input and drifters at that time will be plotted. Note that once drifters hit the outer numerical boundary, they are nan'ed out so this may miss some drifters. which (optional) 'contour', 'pcolor', 'hexbin', 'hist2d' for type of plot used. Default 'hexbin'. bins (optional) Number of bins used in histogram. Default (15,25). N (optional) Number of contours to make. Default 10. grid (optional) grid as read in by inout.readgrid() xlims (optional) value limits on the x axis ylims (optional) value limits on the y axis isll Default True. Inputs are in lon/lat. If False, assume they are in projected coords. Note: Currently assuming we are plotting the final location of each drifter regardless of tind. """ if grid is None: loc = 'http://barataria.tamu.edu:8080/thredds/dodsC/NcML/txla_nesting6.nc' grid = inout.readgrid(loc) if isll: # if inputs are in lon/lat, change to projected x/y # Change positions from lon/lat to x/y xp, yp = grid['basemap'](lonp, latp) # Need to retain nan's since basemap changes them to values ind = np.isnan(lonp) xp[ind] = np.nan yp[ind] = np.nan else: xp = lonp yp = latp if fig is None: fig = figure(figsize=(11, 10)) else: fig = fig background(grid) # Plot coastline and such # pdb.set_trace() if tind == 'final': # Find final positions of drifters xpc, ypc = tools.find_final(xp, yp) elif is_numlike(tind): xpc = xp[:, tind] ypc = yp[:, tind] else: # just plot what is input if some other string xpc = xp.flatten() ypc = yp.flatten() if which == 'contour': # Info for 2d histogram H, xedges, yedges = np.histogram2d(xpc, ypc, range=[[grid['xr'].min(), \ grid['xr'].max()], \ [grid['yr'].min(), \ grid['yr'].max()]], bins=bins) # Contour Plot XE, YE = np.meshgrid(op.resize(xedges, 0), op.resize(yedges, 0)) d = (H / H.sum()) * 100 # # from http://matplotlib.1069221.n5.nabble.com/question-about-contours-and-clim-td21111.html # locator = ticker.MaxNLocator(50) # if you want no more than 10 contours # locator.create_dummy_axis() # locator.set_bounds(0,1)#d.min(),d.max()) # levs = locator() con = contourf(XE, YE, d.T, N) #,levels=levs)#(0,15,30,45,60,75,90,105,120)) con.set_cmap('YlOrRd') if Title is not None: set_title(Title) # Horizontal colorbar below plot cax = fig.add_axes([0.3725, 0.25, 0.48, 0.02]) #colorbar axes cb = colorbar(con, cax=cax, orientation='horizontal') cb.set_label('Final drifter location (percent)') # Save figure into a local directory called figures. Make directory if it doesn't exist. if not os.path.exists('figures'): os.makedirs('figures') savefig('figures/' + fname + 'histcon.png', bbox_inches='tight') # savefig('figures/' + fname + 'histcon.pdf',bbox_inches='tight') elif which == 'pcolor': # Info for 2d histogram H, xedges, yedges = np.histogram2d(xpc, ypc, range=[[grid['xr'].min(), \ grid['xr'].max()], \ [grid['yr'].min(), \ grid['yr'].max()]], bins=bins, weights=weights) # print H.T.max() # pdb.set_trace() # Pcolor plot # C is the z value plotted, and is normalized by the total number of drifters if C is None: C = (H.T / H.sum()) * 100 else: # or, provide some other weighting C = (H.T / C) * 100 p = pcolor(xedges, yedges, C, cmap='YlOrRd') if Title is not None: set_title(Title) # Set x and y limits # pdb.set_trace() if xlims is not None: xlim(xlims) if ylims is not None: ylim(ylims) # Horizontal colorbar below plot cax = fig.add_axes([0.3775, 0.25, 0.48, 0.02]) #colorbar axes cb = colorbar(p, cax=cax, orientation='horizontal') cb.set_label('Final drifter location (percent)') # Save figure into a local directory called figures. Make directory if it doesn't exist. if not os.path.exists('figures'): os.makedirs('figures') savefig('figures/' + fname + 'histpcolor.png', bbox_inches='tight') # savefig('figures/' + fname + 'histpcolor.pdf',bbox_inches='tight') elif which == 'hexbin': if ax is None: ax = gca() else: ax = ax if C is None: # C with the reduce_C_function as sum is what makes it a percent C = np.ones(len(xpc)) * (1. / len(xpc)) * 100 else: C = C * np.ones(len(xpc)) * 100 hb = hexbin(xpc, ypc, C=C, cmap='YlOrRd', gridsize=bins[0], extent=(grid['xpsi'].min(), grid['xpsi'].max(), grid['ypsi'].min(), grid['ypsi'].max()), reduce_C_function=sum, vmax=vmax, axes=ax, bins=binscale) # Set x and y limits # pdb.set_trace() if xlims is not None: xlim(xlims) if ylims is not None: ylim(ylims) if Title is not None: ax.set_title(Title) # Want colorbar at the given location relative to axis so this works regardless of # of subplots, # so convert from axis to figure coordinates # To do this, first convert from axis to display coords # transformations: http://matplotlib.org/users/transforms_tutorial.html ax_coords = [0.35, 0.25, 0.6, 0.02] # axis: [x_left, y_bottom, width, height] disp_coords = ax.transAxes.transform([ (ax_coords[0], ax_coords[1]), (ax_coords[0] + ax_coords[2], ax_coords[1] + ax_coords[3]) ]) # display: [x_left,y_bottom,x_right,y_top] inv = fig.transFigure.inverted( ) # inverter object to go from display coords to figure coords fig_coords = inv.transform( disp_coords) # figure: [x_left,y_bottom,x_right,y_top] # actual desired figure coords. figure: [x_left, y_bottom, width, height] fig_coords = [ fig_coords[0, 0], fig_coords[0, 1], fig_coords[1, 0] - fig_coords[0, 0], fig_coords[1, 1] - fig_coords[0, 1] ] # Inlaid colorbar cax = fig.add_axes(fig_coords) # # Horizontal colorbar below plot # cax = fig.add_axes([0.3775, 0.25, 0.48, 0.02]) #colorbar axes cb = colorbar(cax=cax, orientation='horizontal') cb.set_label(Label) # pdb.set_trace() # Save figure into a local directory called figures. Make directory if it doesn't exist. if not os.path.exists('figures'): os.makedirs('figures') savefig('figures/' + fname + 'histhexbin.png', bbox_inches='tight') # savefig('figures/' + fname + 'histhexbin.pdf',bbox_inches='tight') elif which == 'hist2d': # pdb.set_trace() hist2d(xpc, ypc, bins=40, range=[[grid['xr'].min(), grid['xr'].max()], [grid['yr'].min(), grid['yr'].max()]], normed=True) set_cmap('YlOrRd') # Set x and y limits # pdb.set_trace() if xlims is not None: xlim(xlims) if ylims is not None: ylim(ylims) # Horizontal colorbar below plot cax = fig.add_axes([0.3775, 0.25, 0.48, 0.02]) #colorbar axes cb = colorbar(cax=cax, orientation='horizontal') cb.set_label('Final drifter location (percent)') # Save figure into a local directory called figures. Make directory if it doesn't exist. if not os.path.exists('figures'): os.makedirs('figures') savefig('figures/' + fname + 'hist2d.png', bbox_inches='tight')
def hist( lonp, latp, fname, tind="final", which="contour", vmax=None, fig=None, ax=None, bins=(40, 40), N=10, grid=None, xlims=None, ylims=None, C=None, Title=None, weights=None, Label="Final drifter location (%)", isll=True, binscale=None, ): """ Plot histogram of given track data at time index tind. Args: lonp,latp: Drifter track positions in lon/lat [time x ndrifters] fname: Plot name to save tind (Optional): Default is 'final', in which case the final position of each drifter in the array is found and plotted. Alternatively, a time index can be input and drifters at that time will be plotted. Note that once drifters hit the outer numerical boundary, they are nan'ed out so this may miss some drifters. which (Optional[str]): 'contour', 'pcolor', 'hexbin', 'hist2d' for type of plot used. Default 'hexbin'. bins (Optional): Number of bins used in histogram. Default (15,25). N (Optional[int]): Number of contours to make. Default 10. grid (Optional): grid as read in by inout.readgrid() xlims (Optional): value limits on the x axis ylims (Optional): value limits on the y axis isll: Default True. Inputs are in lon/lat. If False, assume they are in projected coords. Note: Currently assuming we are plotting the final location of each drifter regardless of tind. """ if grid is None: loc = "http://barataria.tamu.edu:8080/thredds/dodsC/NcML/txla_nesting6.nc" grid = inout.readgrid(loc) if isll: # if inputs are in lon/lat, change to projected x/y # Change positions from lon/lat to x/y xp, yp = grid.proj(lonp, latp) # Need to retain nan's since basemap changes them to values ind = np.isnan(lonp) xp[ind] = np.nan yp[ind] = np.nan else: xp = lonp yp = latp if fig is None: fig = plt.figure(figsize=(11, 10)) else: fig = fig background(grid) # Plot coastline and such if tind == "final": # Find final positions of drifters xpc, ypc = tools.find_final(xp, yp) elif isinstance(tind, int): xpc = xp[:, tind] ypc = yp[:, tind] else: # just plot what is input if some other string xpc = xp.flatten() ypc = yp.flatten() if which == "contour": # Info for 2d histogram H, xedges, yedges = np.histogram2d( xpc, ypc, range=[[grid.x_rho.min(), grid.x_rho.max()], [grid.y_rho.min(), grid.y_rho.max()]], bins=bins ) # Contour Plot XE, YE = np.meshgrid(op.resize(xedges, 0), op.resize(yedges, 0)) d = (H / H.sum()) * 100 # # from http://matplotlib.1069221.n5.nabble.com/question-about-contours-and-clim-td21111.html # locator = ticker.MaxNLocator(50) # if you want no more than 10 contours # locator.create_dummy_axis() # locator.set_bounds(0,1)#d.min(),d.max()) # levs = locator() con = fig.contourf(XE, YE, d.T, N) # ,levels=levs)#(0,15,30,45,60,75,90,105,120)) con.set_cmap("YlOrRd") if Title is not None: plt.set_title(Title) # Horizontal colorbar below plot cax = fig.add_axes([0.3725, 0.25, 0.48, 0.02]) # colorbar axes cb = fig.colorbar(con, cax=cax, orientation="horizontal") cb.set_label("Final drifter location (percent)") # Save figure into a local directory called figures. Make directory # if it doesn't exist. if not os.path.exists("figures"): os.makedirs("figures") fig.savefig("figures/" + fname + "histcon.png", bbox_inches="tight") elif which == "pcolor": # Info for 2d histogram H, xedges, yedges = np.histogram2d( xpc, ypc, range=[[grid.x_rho.min(), grid.x_rho.max()], [grid.y_rho.min(), grid.y_rho.max()]], bins=bins, weights=weights, ) # Pcolor plot # C is the z value plotted, and is normalized by the total number of # drifters if C is None: C = (H.T / H.sum()) * 100 else: # or, provide some other weighting C = (H.T / C) * 100 p = plt.pcolor(xedges, yedges, C, cmap="YlOrRd") if Title is not None: plt.set_title(Title) # Set x and y limits if xlims is not None: plt.xlim(xlims) if ylims is not None: plt.ylim(ylims) # Horizontal colorbar below plot cax = fig.add_axes([0.3775, 0.25, 0.48, 0.02]) # colorbar axes cb = fig.colorbar(p, cax=cax, orientation="horizontal") cb.set_label("Final drifter location (percent)") # Save figure into a local directory called figures. Make directory # if it doesn't exist. if not os.path.exists("figures"): os.makedirs("figures") fig.savefig("figures/" + fname + "histpcolor.png", bbox_inches="tight") # savefig('figures/' + fname + 'histpcolor.pdf',bbox_inches='tight') elif which == "hexbin": if ax is None: ax = plt.gca() else: ax = ax if C is None: # C with the reduce_C_function as sum is what makes it a percent C = np.ones(len(xpc)) * (1.0 / len(xpc)) * 100 else: C = C * np.ones(len(xpc)) * 100 hb = plt.hexbin( xpc, ypc, C=C, cmap="YlOrRd", gridsize=bins[0], extent=(grid.x_psi.min(), grid.x_psi.max(), grid.y_psi.min(), grid.y_psi.max()), reduce_C_function=sum, vmax=vmax, axes=ax, bins=binscale, ) # Set x and y limits if xlims is not None: plt.xlim(xlims) if ylims is not None: plt.ylim(ylims) if Title is not None: ax.set_title(Title) # Want colorbar at the given location relative to axis so this works # regardless of # of subplots, so convert from axis to figure # coordinates. To do this, first convert from axis to display coords # transformations: # http://matplotlib.org/users/transforms_tutorial.html # axis: [x_left, y_bottom, width, height] ax_coords = [0.35, 0.25, 0.6, 0.02] # display: [x_left,y_bottom,x_right,y_top] disp_coords = ax.transAxes.transform( [(ax_coords[0], ax_coords[1]), (ax_coords[0] + ax_coords[2], ax_coords[1] + ax_coords[3])] ) # inverter object to go from display coords to figure coords inv = fig.transFigure.inverted() # figure: [x_left,y_bottom,x_right,y_top] fig_coords = inv.transform(disp_coords) # actual desired figure coords. figure: # [x_left, y_bottom, width, height] fig_coords = [ fig_coords[0, 0], fig_coords[0, 1], fig_coords[1, 0] - fig_coords[0, 0], fig_coords[1, 1] - fig_coords[0, 1], ] # Inlaid colorbar cax = fig.add_axes(fig_coords) # # Horizontal colorbar below plot # cax = fig.add_axes([0.3775, 0.25, 0.48, 0.02]) # colorbar axes cb = fig.colorbar(hb, cax=cax, orientation="horizontal") cb.set_label(Label) # Save figure into a local directory called figures. Make directory # if it doesn't exist. if not os.path.exists("figures"): os.makedirs("figures") fig.savefig("figures/" + fname + "histhexbin.png", bbox_inches="tight") # savefig('figures/' + fname + 'histhexbin.pdf',bbox_inches='tight') elif which == "hist2d": plt.hist2d( xpc, ypc, bins=40, range=[[grid.x_rho.min(), grid.x_rho.max()], [grid.y_rho.min(), grid.y_rho.max()]], normed=True, ) plt.set_cmap("YlOrRd") # Set x and y limits if xlims is not None: xlim(xlims) if ylims is not None: ylim(ylims) # Horizontal colorbar below plot cax = fig.add_axes([0.3775, 0.25, 0.48, 0.02]) # colorbar axes cb = fig.colorbar(cax=cax, orientation="horizontal") cb.set_label("Final drifter location (percent)") # Save figure into a local directory called figures. Make directory # if it doesn't exist. if not os.path.exists("figures"): os.makedirs("figures") fig.savefig("figures/" + fname + "hist2d.png", bbox_inches="tight")
def hist(lonp, latp, fname, tind='final', which='contour', \ bins=(40,40), N=10, grid=None, xlims=None, ylims=None): """ Plot histogram of given track data at time index tind. Inputs: lonp,latp Drifter track positions in lon/lat [time x ndrifters] fname Plot name to save tind (optional) Default is 'final', in which case the final position of each drifter in the array is found and plotted. Alternatively, a time index can be input and drifters at that time will be plotted. Note that once drifters hit the outer numerical boundary, they are nan'ed out so this may miss some drifters. which (optional) 'contour', 'pcolor', 'hexbin', 'hist2d' for type of plot used. Default 'hexbin'. bins (optional) Number of bins used in histogram. Default (15,25). N (optional) Number of contours to make. Default 10. grid (optional) grid as read in by inout.readgrid() xlims (optional) value limits on the x axis ylims (optional) value limits on the y axis Note: Currently assuming we are plotting the final location of each drifter regardless of tind. """ if grid is None: loc = 'http://barataria.tamu.edu:8080/thredds/dodsC/NcML/txla_nesting6.nc' grid = inout.readgrid(loc) # Change positions from lon/lat to x/y xp, yp = grid['basemap'](lonp, latp) # Need to retain nan's since basemap changes them to values ind = np.isnan(lonp) xp[ind] = np.nan yp[ind] = np.nan fig = figure(figsize=(12,10)) background(grid) # Plot coastline and such # pdb.set_trace() if tind == 'final': # Find final positions of drifters xpc, ypc = tools.find_final(xp, yp) elif is_numlike(tind): xpc = xp[:,tind] ypc = yp[:,tind] else: # just plot what is input if some other string xpc = xp.flatten() ypc = yp.flatten() if which == 'contour': # Info for 2d histogram H, xedges, yedges = np.histogram2d(xpc, ypc, range=[[grid['xr'].min(), \ grid['xr'].max()], \ [grid['yr'].min(), \ grid['yr'].max()]], bins=bins) # Contour Plot XE, YE = np.meshgrid(op.resize(xedges,0), op.resize(yedges,0)) d = (H/H.sum())*100 # # from http://matplotlib.1069221.n5.nabble.com/question-about-contours-and-clim-td21111.html # locator = ticker.MaxNLocator(50) # if you want no more than 10 contours # locator.create_dummy_axis() # locator.set_bounds(0,1)#d.min(),d.max()) # levs = locator() con = contourf(XE, YE, d.T, N)#,levels=levs)#(0,15,30,45,60,75,90,105,120)) con.set_cmap('YlOrRd') # Horizontal colorbar below plot cax = fig.add_axes([0.3725, 0.25, 0.48, 0.02]) #colorbar axes cb = colorbar(con, cax=cax, orientation='horizontal') cb.set_label('Final drifter location (percent)') # Save figure into a local directory called figures. Make directory if it doesn't exist. if not os.path.exists('figures'): os.makedirs('figures') savefig('figures/' + fname + 'histcon.png',bbox_inches='tight') # savefig('figures/' + fname + 'histcon.pdf',bbox_inches='tight') elif which == 'pcolor': # Info for 2d histogram H, xedges, yedges = np.histogram2d(xpc, ypc, range=[[grid['xr'].min(), \ grid['xr'].max()], \ [grid['yr'].min(), \ grid['yr'].max()]], bins=bins) # Pcolor plot p = pcolor(xedges, yedges, (H.T/H.sum())*100, cmap='YlOrRd') # Set x and y limits # pdb.set_trace() if xlims is not None: xlim(xlims) if ylims is not None: ylim(ylims) # Horizontal colorbar below plot cax = fig.add_axes([0.3775, 0.25, 0.48, 0.02]) #colorbar axes cb = colorbar(p, cax=cax, orientation='horizontal') cb.set_label('Final drifter location (percent)') # Save figure into a local directory called figures. Make directory if it doesn't exist. if not os.path.exists('figures'): os.makedirs('figures') savefig('figures/' + fname + 'histpcolor.png', bbox_inches='tight') # savefig('figures/' + fname + 'histpcolor.pdf',bbox_inches='tight') elif which == 'hexbin': # C with the reduce_C_function as sum is what makes it a percent C = np.ones(len(xpc))*(1./len(xpc))*100 hb = hexbin(xpc, ypc, C=C, cmap='YlOrRd', gridsize=bins[0], extent=(grid['xr'].min(), grid['xr'].max(), grid['yr'].min(), grid['yr'].max()), reduce_C_function=sum) # Set x and y limits # pdb.set_trace() if xlims is not None: xlim(xlims) if ylims is not None: ylim(ylims) # Horizontal colorbar below plot cax = fig.add_axes([0.3775, 0.25, 0.48, 0.02]) #colorbar axes cb = colorbar(cax=cax, orientation='horizontal') cb.set_label('Final drifter location (percent)') # pdb.set_trace() # Save figure into a local directory called figures. Make directory if it doesn't exist. if not os.path.exists('figures'): os.makedirs('figures') savefig('figures/' + fname + 'histhexbin.png', bbox_inches='tight') # savefig('figures/' + fname + 'histhexbin.pdf',bbox_inches='tight') elif which == 'hist2d': # pdb.set_trace() hist2d(xpc, ypc, bins=40, range=[[grid['xr'].min(), grid['xr'].max()], [grid['yr'].min(), grid['yr'].max()]], normed=True) set_cmap('YlOrRd') # Set x and y limits # pdb.set_trace() if xlims is not None: xlim(xlims) if ylims is not None: ylim(ylims) # Horizontal colorbar below plot cax = fig.add_axes([0.3775, 0.25, 0.48, 0.02]) #colorbar axes cb = colorbar(cax=cax,orientation='horizontal') cb.set_label('Final drifter location (percent)') # Save figure into a local directory called figures. Make directory if it doesn't exist. if not os.path.exists('figures'): os.makedirs('figures') savefig('figures/' + fname + 'hist2d.png',bbox_inches='tight')
def readfields(tind, grid, nc, z0=None, zpar=None, zparuv=None): """ readfields() Kristen Thyng, March 2013 Reads in model output in order to calculate fluxes and z grid properties to send into step.f95. Should be called initially and then subsequently each time loop. All arrays are changed to Fortran ordering (from Python ordering) and to tracmass variables ordering from ROMS ordering i.e. from [t,k,j,i] to [i,j,k,t] right away after reading in. Args: tind: Single time index for model output to read in grid: Dictionary containing all necessary time-independent grid fields nc: NetCDF object for relevant files z0 (Optional): if doing 2d isoslice, z0 contains string saying which kind zpar (Optional): if doing 2d isoslice, zpar is the depth/level/density at which we are to get the level zparuv (Optional): Use this if the k index for the model output fields (e.g, u, v) is different from the k index in the grid. This might happen if, for example, only the surface current were saved, but the model run originally did have many layers. This parameter represents the k index for the u and v output, not for the grid. Returns: * uflux1 - Zonal (x) flux at tind * vflux1 - Meriodional (y) flux at tind * dzt - Height of k-cells in 3 dim in meters on rho vertical grid. [imt,jmt,km] * zrt - Time-dependent depths of cells on vertical rho grid (meters). For the isoslice case, zrt ends up with 1 vertical level which contains the depths for the vertical center of the cell for that level. * zwt - Time-dependent depths of cells on vertical w grid (meters). zwt always contains the depths at the vertical cell edges for the whole 3D grid and the correct depths can be accessed using the drifter indices. Array descriptions: * u,v - Zonal (x) and meridional (y) velocities [imt,jmt,km] (m/s) * ssh - Free surface [imt,jmt] (m) * dz - Height of k-cells in 1 dim [km] From coord.f95: z coordinates (z>0 going up) for layers in meters bottom layer: k=0; surface layer: k=KM and zw=0 dz = layer thickness * zt - Depths (negative) in meters of w vertical grid [imt,jmt,km+1] * dzt - Height of k-cells in 3 dim in meters on rho vertical grid. [imt,jmt,km] * dzt0 - Height of k-cells in 2 dim. [imt,jmt] * dzu - Height of each u grid cell [imt-1,jmt,km] * dzv - Height of each v grid cell [imt,jmt-1,km] * uflux1 - Zonal (x) fluxes [imt-1,jmt,km] (m^3/s)? * vflux1 - Meriodional (y) fluxes [imt,jmt-1,km] (m^3/s)? """ # this parameter is in case there is less model output available # vertically than was actually run on the grid if zparuv is None: zparuv = zpar # tic_temp = time.time() # Read in model output for index tind if z0 == 's': # read in less model output to begin with, to save time if nc.variables['u'].ndim == 4: u = nc.variables['u'][tind, zparuv, :, :] v = nc.variables['v'][tind, zparuv, :, :] elif nc.variables['u'].ndim == 3: u = nc.variables['u'][tind, :, :] v = nc.variables['v'][tind, :, :] if 'zeta' in nc.variables: # [t,j,i], ssh in tracmass ssh = nc.variables['zeta'][tind, :, :] sshread = True else: sshread = False else: u = nc.variables['u'][tind, :, :, :] v = nc.variables['v'][tind, :, :, :] if 'zeta' in nc.variables: # [t,j,i], ssh in tracmass ssh = nc.variables['zeta'][tind, :, :] sshread = True else: sshread = False # Use octant to calculate depths for the appropriate vertical grid # parameters have to transform a few back to ROMS coordinates and python # ordering for this if sshread: zwt = octant.depths.get_zw(grid.Vtransform, grid.Vstretching, grid.km + 1, grid.theta_s, grid.theta_b, grid.h, grid.hc, zeta=ssh, Hscale=3) else: # if ssh isn't available, approximate as 0 zwt = octant.depths.get_zw(grid.Vtransform, grid.Vstretching, grid.km + 1, grid.theta_s, grid.theta_b, grid.h, grid.hc, zeta=0, Hscale=3) # Change dzt to tracmass/fortran ordering dzt = zwt[1:, :, :] - zwt[:-1, :, :] # also want depths on rho grid if sshread: zrt = octant.depths.get_zrho(grid.Vtransform, grid.Vstretching, grid.km, grid.theta_s, grid.theta_b, grid.h, grid.hc, zeta=ssh, Hscale=3) else: zrt = octant.depths.get_zrho(grid.Vtransform, grid.Vstretching, grid.km, grid.theta_s, grid.theta_b, grid.h, grid.hc, zeta=0, Hscale=3) dzu = .5 * (dzt[:, :, 0:grid.imt - 1] + dzt[:, :, 1:grid.imt]) dzv = .5 * (dzt[:, 0:grid.jmt - 1, :] + dzt[:, 1:grid.jmt, :]) # I think I can avoid this loop for the isoslice case if z0 is None: # 3d case uflux1 = u * dzu * grid.dyu vflux1 = v * dzv * grid.dxv elif z0 == 's': # want a specific s level zpar uflux1 = u * dzu[zpar, :, :] * grid.dyu vflux1 = v * dzv[zpar, :, :] * grid.dxv dzt = dzt[zpar, :, :] zrt = zrt[zpar, :, :] elif z0 == 'rho' or z0 == 'salt' or z0 == 'temp': # the vertical setup we're selecting an isovalue of vert = nc.variables[z0][tind, :, :, :] # Calculate flux and then take slice uflux1 = octant.tools.isoslice(u * dzu * grid.dyu, op.resize(vert, 2), zpar) vflux1 = octant.tools.isoslice(v * dzv * grid.dxv, op.resize(vert, 1), zpar) dzt = octant.tools.isoslice(dzt, vert, zpar) zrt = octant.tools.isoslice(zrt, vert, zpar) elif z0 == 'z': # Calculate flux and then take slice uflux1 = octant.tools.isoslice(u * dzu * grid.dyu, op.resize(zrt, 2), zpar) vflux1 = octant.tools.isoslice(v * dzv * grid.dxv, op.resize(zrt, 1), zpar) dzt = octant.tools.isoslice(dzt, zrt, zpar) zrt = np.ones(uflux1.shape) * zpar # array of the input desired depth # make sure that all fluxes have a placeholder for depth if isinstance(z0, str): uflux1 = uflux1.reshape(np.append(1, uflux1.shape)) vflux1 = vflux1.reshape(np.append(1, vflux1.shape)) dzt = dzt.reshape(np.append(1, dzt.shape)) zrt = zrt.reshape(np.append(1, zrt.shape)) return uflux1, vflux1, dzt, zrt, zwt
import pdb import op seed = "C" loccalcs = "calcs/" loctracks = "tracks/" # Loop through tracks files and run calculations Files = glob.glob(loctracks + seed + "*.nc") # Highest res case for comparison dc = netCDF.Dataset(loctracks + seed + "_dx250_V25.nc") # control case Uc = dc.variables["U"][:] Vc = dc.variables["V"][:] Sc = np.sqrt(op.resize(Uc, 1) ** 2 + op.resize(Vc, 0) ** 2) dc.close() # lonpc = dc.variables['lonp'][:]; latpc = dc.variables['latp'][:]; tpc = dc.variables['tp'][:]; loc = "http://barataria.tamu.edu:8080/thredds/dodsC/NcML/txla_nesting6.nc" grid = tracpy.inout.readgrid(loc) # grid file, Gulf model domain # grid = tracpy.inout.readgrid(loc[1], vert_filename=loc[0], llcrnrlon=llcrnrlon, urcrnrlon=urcrnrlon, # llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat) # grid file, Gulf model domain for File in Files: print File # Read in tracks d = netCDF.Dataset(File)