def get_aspectratio(region,LL=1): """ Takes a region and returns the average aspect ratio of the data. :Parameters: region - a region as defined in regions.py :Optional: LL - if LL is 0 then uses an xy region instead of a region. """ if (LL==0): H=region['regionxy'][3]-region['regionxy'][2] W=region['regionxy'][1]-region['regionxy'][0] else: H1=(sw.dist([region['region'][3], region['region'][2]],[region['region'][0], region['region'][0]],'km'))[0]; H2=(sw.dist([region['region'][3], region['region'][2]],[region['region'][1], region['region'][1]],'km'))[0]; H=1/2*(H1+H2); W1=(sw.dist([region['region'][3], region['region'][3]],[region['region'][0], region['region'][1]],'km'))[0]; W2=(sw.dist([region['region'][2], region['region'][2]],[region['region'][0], region['region'][1]],'km'))[0]; W=1/2*(W1+W2); return H/W
def geovelfield(ssha,lon,lat,mask): ma.filled(ssha,np.nan) distmlon=sw.dist(0,lon,'km')[0][:]*1000 distmlat=sw.dist(0,lat,'km')[0][:]*1000 mlon=np.cumsum(distmlon) mlat=np.cumsum(distmlat) dy=np.gradient(mlat) dx=np.gradient(mlon) detay,detax=np.gradient(ssha) omega = 7.2921e-5 g=9.81 f=2*omega*np.sin(np.deg2rad(lat)) u=np.zeros(np.shape(ssha)) v=np.zeros(np.shape(ssha)) for ii in range(np.shape(ssha)[1]-1): detaxdy=detax[:,ii]/dx[ii] v[:,ii]=(g/f)*(detaxdy) for jj in range(np.shape(ssha)[0]-1): detaydx=detay[jj,:]/dy[jj] u[jj,:]=-(g/f[jj])*(detaydx) u[u>100]=0 v[v>100]=0 u[u<-100]=0 v[v<-100]=0 u= np.ma.masked_array(u, mask) v= np.ma.masked_array(v, mask) return u,v
def okuboweissparm(u,v,lat,lon,z): if z==0: du=np.gradient(u[:,:],axis=1) dv=np.gradient(v[:,:],axis=1) du=np.gradient(u[:,:],axis=0) dv=np.gradient(v[:,:],axis=0) else: du=np.gradient(u[z,:,:],axis=1) dv=np.gradient(v[z,:,:],axis=1) du=np.gradient(u[z,:,:],axis=0) dv=np.gradient(v[z,:,:],axis=0) distmlon=sw.dist(0,lon,'km')[0][:]*1000 distmlat=sw.dist(lat,0,'km')[0][:]*1000 mlon=np.cumsum(distmlon) mlat=np.cumsum(distmlat) mlon = np.hstack((mlon,mlon[-1])) mlat = np.hstack((mlat,mlat[-1])) dy=np.gradient(mlat) dx=np.gradient(mlon) dX,dY = np.meshgrid(dx,dy) du_dx=du/dX du_dy=du/dY dv_dx=dv/dX dv_dy=dv/dY sn=du_dx-dv_dy ss=dv_dx+du_dy w=vorticity2D(u,v,lon,lat) owparm=sn**2+ss**2-w**2 return owparm
def distance(x, y, units="km"): if ma.isMaskedArray(x): x = x.filled(fill_value=np.NaN) if ma.isMaskedArray(y): y = y.filled(fill_value=np.NaN) dist, pha = sw.dist(x, y, units=units) return np.r_[0, np.cumsum(dist)]
def plot_glider(lon,lat,z,tim, data, mask_topo=False, **kw): """Plot glider cube.""" cmap = kw.pop('cmap', plt.cm.rainbow) dist, pha = sw.dist(lat, lon, units='km') dist = np.append(0, np.cumsum(dist)) dist, z = np.broadcast_arrays(dist[..., None], z) """ z_range = [z.min(), z.max()] data_range = [data.min(), data.max()] good = np.logical_and(data >= data_range[0], data <= data_range[1]) data = ma.masked_where(~good, data) condition = np.logical_and(z >= z_range[0], z <= z_range[1]) z = ma.masked_where(~condition, z) """ fig,ax = plt.subplots(figsize=(12,4)) cs = ax.pcolor(dist, z, data, cmap=cmap, **kw) if mask_topo: h = z.max(axis=1) xm, hm = gen_topomask(h, lon, lat, dx=1., kind='linear') ax.plot(xm, hm, color='black', linewidth='1', zorder=3) ax.fill_between(xm, hm, y2=hm.max(), color='0.8', zorbathy_der=3) ax.invert_yaxis() ax.set_title('Glider track from {} to {}'.format(tim[0], tim[-1])) ax.set_ylabel('depth (m)') ax.set_xlabel('alongtrack distance (km)') return fig, ax, cs, dist
def integration(LAT): i = np.abs(scow.latitude-LAT).argmin() Tr = transport[i,:].copy() ibad = np.isnan(Tr) Tr[ibad] = 0. # Closing the eastern boundary at latitudes higher than Cape Town's ibad1 = scow.longitude >= 18 Tr[ibad1] = 0. # Spatial Resolution DX = sw.dist([scow.latitude[i],scow.latitude[i]], [scow.longitude[0],scow.longitude[1]])[0][0]*1000. # Horizontal integration PSI = np.zeros(Tr.shape[0]) for j in xrange(1,Tr.shape[0],1): PSI[-j-1] = np.sum(Tr[-j:]*DX) PSI[ibad] = np.nan PSI[ibad1] = np.nan return PSI
def get_nearest(xi, yi, cube): """Encontra os dados mais próximos aos pontos escolhidos.""" x, y = cube.dim_coords X, Y = np.meshgrid(x.points, y.points) xi = wrap_lon360(xi) tree = KDTree(zip(X.ravel(), Y.ravel())) dist, indices = tree.query(np.array([xi, yi]).T) indices = np.unravel_index(indices, X.shape) lon = X[indices] lat = Y[indices] maskx = np.logical_and(x.points >= min(lon), x.points <= max(lon)) masky = np.logical_and(y.points >= min(lat), y.points <= max(lat)) maxnp = len(np.nonzero(maskx)[0]) + len(np.nonzero(masky)[0]) lons = np.linspace(lon[0], lon[1], maxnp) lats = np.linspace(lat[0], lat[1], maxnp) # Find all x, y, data in that line using the same KDTree obj. dist, indices = tree.query(np.array([lons, lats]).T) indices = np.unique(indices) indices = np.unravel_index(indices, X.shape) lons, lats = X[indices], Y[indices] elvs = cube.data.T[indices] dist, angle = sw.dist(lats, lons, 'km') dist *= 1e3 dist = np.r_[0, dist.cumsum()] return (lons, lats), (elvs, dist, angle)
def vorticity2D(u,v,lon,lat): dv=np.gradient(v[:,:],axis=1) du=np.gradient(u[:,:],axis=0) distmlon=sw.dist(0,lon,'km')[0][:]*1000 distmlat=sw.dist(lat,0,'km')[0][:]*1000 mlon=np.cumsum(distmlon) mlat=np.cumsum(distmlat) mlon = np.hstack((mlon,mlon[-1])) mlat = np.hstack((mlat,mlat[-1])) dy=np.gradient(mlat) dx=np.gradient(mlon) dX,dY = np.meshgrid(dx,dy) dv_dx=dv/dX du_dy=du/dY w=dv_dx-du_dy return w
def plot_glider(cube, mask_topo=False, **kw): """Plot glider cube.""" cmap = kw.pop('cmap', plt.cm.rainbow) lon = cube.coord(axis='X').points.squeeze() lat = cube.coord(axis='Y').points.squeeze() z = cube.coord(axis='Z').points.squeeze() data = cube.data data = ma.masked_invalid(data,copy=True) z = ma.masked_invalid(z,copy=True) t = cube.coord(axis='T') t = t.units.num2date(t.points) dist, pha = sw.dist(lat, lon, units='km') dist = np.r_[0, np.cumsum(dist)] dist, z = np.broadcast_arrays(dist[..., None], z) fig, ax = plt.subplots(figsize=(9, 3.75)) cs = ax.pcolor(dist, z, data, cmap=cmap, snap=True, **kw) plt.colorbar(cs) if mask_topo: h = z.max(axis=1) x = dist[:, 0] ax.plot(x, h, color='black', linewidth='0.5', zorder=3) ax.fill_between(x, h, y2=h.max(), color='0.9', zorder=3) ax.invert_yaxis() ax.set_title('Glider track from {} to {}'.format(t[0], t[-1])) fig.tight_layout() return fig, ax, cs
def format_coord(x, y): lonx,latx=map(x, y, inverse = True) # get the distance dist,ang = seawater.dist(np.array([lat,latx]),np.array([lon,lonx]), units='nm') head=(360-ang+90)%360 return 'lon=%.4f, lat=%.4f,\n dist=%.2f, head=%05.1f'%(lonx,latx,dist,head)
def get_angle(lon, lat): NR, NC = lon.shape theta = np.nan * np.ones_like(lon) for jj in range(NR - 1): junk, theta[jj, :-1] = sw.dist(lat[jj, :], lon[jj, :]) theta[:, -1] = theta[:, -2] ca = np.cos(-np.pi * theta / 180) sa = np.sin(-np.pi * theta / 180) return ca, sa
def gen_topomask(h, lon, lat, dx=1., kind='linear'): """ generate bottom contour, dx in km """ h, lon, lat = map(np.asanyarray, (h, lon, lat)) x = np.append(0, np.cumsum(sw.dist(lon, lat, units='km')[0])) Ih = interp1d(x, h, kind=kind, bounds_error=False, fill_value=h[-1]) xm = np.arange(0, x.max() + dx, dx) hm = Ih(xm) return xm, hm
def select_rad(pts, lon, lat): args = np.array([]) for est in pts: c = [] arg = np.array([0]) for i in np.arange(0, lon.size): c.append(sw.dist([lat[i], est[1]], [lon[i], est[0]])) arg = np.argmin(np.array(c).T[0][0]) args = np.append(args, arg) return args
def get_distance_over_ground(ds): good = ~np.isnan(ds.latitude + ds.longitude) dist, cog = seawater.dist(ds.latitude[good], ds.longitude[good]) dist = np.roll(np.append(dist, 0), 1) dist = np.cumsum(dist) attr = { 'long_name': 'distance over ground flown since mission start', 'method': 'get_distance_over_ground', 'units': 'km', 'sources': 'latitude longitude' } ds['distance_over_ground'] = (('time'), dist, attr) return ds
def extrap_gradient(df, lat=[], lon=[], wgt=0.5): ##if the df is not a pandas.DataFrame #if type(df) <> pd.core.frame.DataFrame: # #raise an Error # raise ValueError('Data is not in the correct format (pandas.DataFrame)') #calculate the distance vector from the first dist = np.hstack((0, np.cumsum(sw.dist(lat, lon)[0]))) #calculate the distance between the points dxs = sw.dist(lat, lon)[0] #calculate the horizontal gradient between the points gradient = ((np.diff(df)) / dxs) * wgt # *1. is to make sure we #are working with float numbers extrap_df = df.copy() #Assuming the points with more nan values is the first #we just read until the second from last column for col in np.arange(extrap_df.shape[1] - 2): #find where is the nan values along the column nans = np.argwhere(np.isnan(extrap_df.iloc[:, col])) if nans.tolist() != []: #the gradient per unit of distance plus the distance #between the column and the next one dif = gradient[nans, col + 1] * dxs[col] #find the next value to apply the coef ref_val = extrap_df.iloc[np.hstack(nans), col + 1] #calculate the new value to the nans in col based on values in col+1 #new_values = ref_val.reshape(dif.shape) - dif new_values = ref_val - dif.squeeze() #replace the nans by the new values #extrap_df.iloc[np.hstack(nans),col] = new_values.reshape(ref_val.shape) extrap_df.iloc[np.hstack(nans), col] = new_values return extrap_df
def rho_dist(RomsFile): """ Use seawater package to compute distance between rho points """ RomsNC = dt(RomsFile, 'r') lat = RomsNC.variables['lat_rho'][:] lon = RomsNC.variables['lon_rho'][:] x_dist = np.empty((lon.shape[0], lon.shape[1] - 1)) x_dist.fill(np.nan) for i in range(lon.shape[0]): for j in range(lon.shape[1] - 1): x_dist[i, j] = sw.dist([lat[i, j], lat[i, j + 1]], [lon[i, j], lon[i, j + 1]])[0] y_dist = np.empty((lat.shape[0] - 1, lat.shape[1])) y_dist.fill(np.nan) for i in range(y_dist.shape[0]): for j in range(y_dist.shape[1]): y_dist[i, j] = sw.dist([lat[i, j], lat[i + 1, j]], [lon[i, j], lon[i + 1, j]]) return x_dist, y_dist
def ll_dist(region,dist): """ Given a region and a distance in meters returns longitude interval approximately equalivent to the distance. NOTE: Clearly this is crude, hacky, and inaccurate over large areas. However, over small areas the error is small. :Parameters: region - The region being plotted, needed for average latitude. dist - The distance in meters to match. """ lat=region['region'][2:4].mean() mlat=sw.dist([lat, lat],[0, 1],'km')[0]*1000 # print mlat # mtest=ll2m([0,lat],[1,lat])[0] # print mtest return dist/mlat
def ll_dist(region, dist): """ Given a region and a distance in meters returns longitude interval approximately equalivent to the distance. NOTE: Clearly this is crude, hacky, and inaccurate over large areas. However, over small areas the error is small. :Parameters: region - The region being plotted, needed for average latitude. dist - The distance in meters to match. """ lat = region['region'][2:4].mean() mlat = sw.dist([lat, lat], [0, 1], 'km')[0] * 1000 # print mlat # mtest=ll2m([0,lat],[1,lat])[0] # print mtest return dist / mlat
def get_wrf_grid(fn): wds = nc.Dataset(fn) lon = wds['XLONG'][:].squeeze() lat = wds['XLAT'][:].squeeze() if False: print('\n** ' + fn.split('/')[-1]) vn_list = [] for vn in wds.variables: vn_list.append(vn) print(vn_list) wds.close() # grid size info NR, NC = lon.shape jj = int(NR/2); ii = int(NC/2) dx_km, dd_deg = sw.dist(lat[jj,ii], [lon[jj,ii], lon[jj+1,ii+1]]) return lon, lat, dx_km
def plot_glider(cube, mask_topo=False, **kw): """Plot glider cube.""" cmap = kw.pop('cmap', plt.cm.rainbow) lon = cube.coord(axis='X').points.squeeze() lat = cube.coord(axis='Y').points.squeeze() z = cube.coord(axis='Z').points.squeeze() data = cube.data t = cube.coord(axis='T') t = t.units.num2date(t.points) dist, pha = sw.dist(lat, lon, units='km') dist = np.r_[0, np.cumsum(dist)] dist, z = np.broadcast_arrays(dist[..., None], z) z_range = cube.coord(axis='Z').attributes['actual_range'] data_range = cube.attributes['actual_range'] condition = np.logical_and(data >= data_range[0], data <= data_range[1]) data = ma.masked_where(~condition, data) condition = np.logical_and(z >= z_range[0], z <= z_range[1]) z = ma.masked_where(~condition, z) from matplotlib import rcParams rcParams['xtick.direction'] = 'in' rcParams['ytick.direction'] = 'in' fig, ax = plt.subplots() cs = ax.pcolor(dist, z, data, cmap=cmap, **kw) if mask_topo: h = z.max(axis=1) xm, hm = gen_topomask(h, lon, lat, dx=1., kind='linear') ax.plot(xm, hm, color='black', linewidth='1', zorder=3) ax.fill_between(xm, hm, y2=hm.max(), color='0.8', zorder=3) ax.invert_yaxis() ax.set_title('Glider track from {} to {}'.format(t[0], t[-1])) ax.set_ylabel('depth (m)') ax.set_xlabel('alongtrack distance (km)') return fig, ax, cs
def integration(LAT): i = np.abs(scow.latitude - LAT).argmin() Tr = transport[i, :].copy() ibad = np.isnan(Tr) Tr[ibad] = 0. # Closing the eastern boundary at latitudes higher than Cape Town's ibad1 = scow.longitude >= 18 Tr[ibad1] = 0. # Spatial Resolution DX = sw.dist([scow.latitude[i], scow.latitude[i]], [scow.longitude[0], scow.longitude[1]])[0][0] * 1000. # Horizontal integration PSI = np.zeros(Tr.shape[0]) for j in xrange(1, Tr.shape[0], 1): PSI[-j - 1] = np.sum(Tr[-j:] * DX) PSI[ibad] = np.nan PSI[ibad1] = np.nan return PSI
def get_gebco15(x, y, topofile='gebco15-40s_30-52w_30seg.nc'): """ Usage ----- H, D, Xo, Yo = get_gebco15(x, y, topofile='gebco/gebco_08_30seg.nc') Description ----------- Finds the depth of points of coordinates 'x','y' using GEBCO data set. Parameters ---------- x : 1D array Array containing longitudes of the points of unknown depth. y : 1D array Array containing latitudes of the points of unknown depth. topofile : string, optional String containing path to the GEBCO netCDF file. Returns ------- H : 1D array Array containing depths of points closest to the input X, Y coordinates. X : 1D array Array of horizontal distance associated with array 'H'. D : 1D array Array containing distances (in km) from the input X, Y coordinates to the data points. Xo : 1D array Array containing longitudes of the data points. Yo : 1D array Array containing latitudes of the data points. NOTES ------- This function reads the entire netCDF file before extracting the wanted data. Therefore, it does not handle the full GEBCO dataset (1.8 GB) efficiently. TODO ------- Make it possible to work with the full gebco dataset, by extracting only the wanted indexes. Code History --------------------------------------- Author of the original Matlab code (ftopo.m, ETOPO2 dataset): Marcelo Andrioni <*****@*****.**> December 2008: Modification performed by Cesar Rocha <*****@*****.**> to handle ETOPO1 dataset. July 2012: Python Translation and modifications performed by André Palóczy Filho <*****@*****.**> to handle GEBCO dataset (30 arc seconds resolution). """ from seawater import dist x, y = list(map(np.asanyarray, (x, y))) # Opening netCDF file and extracting data. grid = Dataset(topofile) yyr = grid.variables['y_range'][:] xxr = grid.variables['x_range'][:] spacing = grid.variables['spacing'][:] dx, dy = spacing[0], spacing[1] # Creating lon and lat 1D arrays. xx = np.arange(xxr[0], xxr[1], dx) xx = xx + dx / 2 yy = np.arange(yyr[0], yyr[1], dy) yy = yy + dy / 2 h = grid.variables['z'][:] grid.close() # Retrieving nearest point for each input coordinate. A = np.asanyarray([]) xx, yy = np.meshgrid(xx, yy) ni, nj = xx.shape[0], yy.shape[1] h = np.reshape(h, (ni, nj)) h = np.flipud(h) Xo = A.copy() Yo = A.copy() H = A.copy() D = A.copy() for I in range(x.size): ix = near(xx[0, :], x[I]) iy = near(yy[:, 0], y[I]) H = np.append(H, h[iy, ix]) # Calculating distance between input and GEBCO points. D = np.append(D, dist([x[I], xx[0, ix]], [y[I], yy[iy, 0]], units='km')[0]) Xo = np.append(Xo, xx[0, ix]) Yo = np.append(Yo, yy[iy, 0]) # Calculating distance axis. X = np.append(0, np.cumsum(dist(Xo, Yo, units='km')[0])) return H, X, D, Xo, Yo
unc_sf2 = cf.unc_sf[inst2] unc_dk2 = cf.unc_dk[inst2] files2 = cf.data_files[inst2] func2 = cf.data_function[inst2] if sca1==sca2: unc_chi1 = 0 unc_chi2 = 0 figure_name = 'bbp_'+inst1+'_'+inst2+'.png' yy = [np.min([cf.max_dep[inst1],cf.max_dep[inst2]]),0] ## Standard variables CENTRAL_LAT = 50.5 CENTRAL_LON = -145 DEG_LAT_TO_KM = sw.dist(CENTRAL_LAT+np.array([-.5,.5]),CENTRAL_LON,units='km')[0][0] DEG_LON_TO_KM = sw.dist(CENTRAL_LAT,CENTRAL_LON+np.array([-.5,.5]),units='km')[0][0] aspect = 1/np.cos(CENTRAL_LAT*np.pi/180) ## Find nearby indices data1_loc = func1(files1,get_data=False) data2_loc = func2(files2,get_data=False) inds1,inds2,dist,dtime = get_bestfit.find_nearby((data1_loc[0],data2_loc[0]), (data1_loc[1],data2_loc[1]), (data1_loc[2],data2_loc[2]), cf.TIME_THRES,cf.DIST_THRES, return_distances=True) if cf.OUTPUT_INFO: with np.printoptions(precision=2,suppress=True): print('%d matches found'%len(inds1))
len_lat = len(pos_lat) time_ltd = time_stp[0:len_lat] speed_ltd = speed_1[0:len_lat] map_df = pd.DataFrame({ 'Time': time_ltd, 'Latitude': pos_lat, 'Longitude': pos_long, 'Speed': speed_ltd }) map_df['Latitude'] = map_df['Latitude'] * (180 / (2**31)) map_df['Longitude'] = map_df['Longitude'] * (180 / (2**31)) #use lat and longitude to get map. Not correctly implemented yet _, angles = sw.dist(map_df['Latitude'], map_df['Longitude']) angles = np.r_[0, np.deg2rad(angles)] # Normalize the speed to use as the length of the arrows r = map_df['Speed'] / map_df['Speed'].max() kw = dict(window_len=31, window='hanning') map_df['u'] = r * np.cos(angles) map_df['v'] = r * np.sin(angles) fig, ax = plt.subplots() map_df = map_df.dropna() ax.plot(map_df['Longitude'], map_df['Latitude'], color='deepskyblue', linewidth=5, alpha=0.5)
tend = tini + timedelta(hours=float(lead_time_pom_oper[-1])) date_end = str(tend) okt = np.logical_and(time_best_track >= tini, time_best_track <= tend) # time forecasted track_exp time_forec_track_oper = np.asarray( [tini + timedelta(hours=float(t)) for t in lead_time_pom_oper]) oktt = [ np.where(t == time_forec_track_oper)[0][0] for t in time_best_track[okt] ] str_time = [str(tt)[5:13] for tt in time_forec_track_oper[oktt]] dist_along_track = np.cumsum( np.append(0, sw.dist(lat_bnd[0], lon_bnd[0], units='km')[0])) lev = np.arange(-9000, 9100, 100) fig, ax = plt.subplots() plt.contourf(bath_lonsub, bath_latsub, bath_elevsub, lev, cmap=cmocean.cm.topo) plt.contourf(bath_lon, bath_lat, bath_elev, [0, 10000], colors='seashell') plt.contour(bath_lon, bath_lat, bath_elev, [0], colors='k') plt.plot(lon_best_track[okt], lat_best_track[okt], 'o-', color='k', label='Best Track') plt.plot(lon_forec_track_pom_oper[oktt], lat_forec_track_pom_oper[oktt],'X-',color='mediumorchid',\ markeredgecolor='k',label='HWRF2019-POM (IC clim.)',markersize=7) plt.plot(lon_forec_track_pom_exp[oktt], lat_forec_track_pom_exp[oktt],'^-',color='teal',\
def getdist(lon0,lat0,lonex,latex): distout=zeros(len(lonex)) for ii in range(len(lonex)): distout[ii]=sw.dist([lat0,latex[ii]],[lon0,lonex[ii]])[0][0] return distout
print(cubes) print('Loading obs from "%s"' % obs['url']) print(' Variable is %s' % obs[variable]['name']) for cube in cubes: if cube.name().lower() == obs[variable]['name']: obs['data'] = cube.data obs['z'] = cube.coord(obs['zname']).points time_coord = cube.coord(axis='T') obs['time'] = time_coord.units.num2date(time_coord.points) elif cube.name().lower() == obs['lonname']: obs['lon'] = cube.data elif cube.name().lower() == obs['latname']: obs['lat'] = cube.data obs['dist'] = np.cumsum(np.r_[0, sw.dist(obs['lat'], obs['lon'], units='km')[0]]) obs[variable]['data'] = obs['data'] obs[variable]['dist'] = obs['dist'] obs[variable]['z'] = obs['z'] tstart = min(obs['time']) tend = max(obs['time']) print(' Time interval of obs:') print(' %s to %s' % (tstart, tend)) # <markdowncell> # # Probably iris will change all this part. No need to define all those parameters. # <markdowncell>
def fwoa(x, y, woafile='woa2009_annual.mat'): r""" Usage ----- T,S,X,D,Xo,Yo = fwoa(x, y, woafile='woa2009_annual.mat') Description ----------- Gets the TS profiles in the World Ocean Atlas (WOA) 2009 data set whose coordinates are closest to the input coordinates 'x', 'y'. Parameters ---------- x : 1D array Array containing longitudes of the points of unknown depth. y : 1D array Array containing latitudes of the points of unknown depth. woafile : string, optional String containing path to the WOA .mat file. Returns ------- T : 2D array Array containing the Temperature profiles closest to the input X, Y coordinates. S : 2D array Array containing the Salinity (PSS-78) profiles closest to the input X,Y coordinates. X : 1D array Array of horizontal distance associated with the TS profiles recovered. D : 1D array Array containing distances (in km) from the input X, Y coordinates to the TS profiles. Xo : 1D array Array containing longitudes of the WOA TS profiles. Yo : 1D array Array containing latitudes of the WOA TS profiles. NOTES ------- This function reads mat files, converted from the original netCDF ones. TODO ------- Implement netCDF file reading (Original WOA 2009 format) Implement option to retrieve linearly interpolated profiles instead of nearest ones. """ x, y = map(np.asanyarray, (x, y)) # Reading .mat file. d = loadmat(woafile) xx = d['lon'] yy = d['lat'] TT = d['temp'] SS = d['salt'] # Retrieving nearest profiles for each input coordinate. A = np.asanyarray([]) B = np.NaN * np.ones((TT.shape[2], x.size)) Xo = A.copy() Yo = A.copy() D = A.copy() T = B.copy() S = B.copy() for I in xrange(x.size): ix = near(xx[0, :], x[I]) iy = near(yy[:, 0], y[I]) T[:, I] = TT[iy, ix, :] S[:, I] = SS[iy, ix, :] # Calculating distance between input and nearest WOA points. D = np.append(D, dist([x[I], xx[0, ix]], [y[I], yy[iy, 0]], units='km')[0]) Xo = np.append(Xo, xx[0, ix]) Yo = np.append(Yo, yy[iy, 0]) # Calculating distance axis. X = np.append(0, np.cumsum(dist(Xo, Yo, units='km')[0])) return T, S, X, D, Xo, Yo
TRY = (TRY_ru - TRY_blank) / TRY_calib; NAP = (NAP_ru - NAP_blank) / NAP_calib; PHE = (PHE_ru - PHE_blank) / PHE_calib; FLU = (FLU_ru - FLU_blank) / FLU_calib; PYR = (PYR_ru - PYR_blank) / PYR_calib; # Other variables SeaExplorer CHL = sx_chlorophyll.values CDOM = sx_cdom.values BB700 = sx_backscatter_700.values ## ---- Projection on definited transect ---- ## import coord_list ## 1. SeaExplorer dist, angle = seawater.dist([origin[0], target[0]], [origin[1], target[1]]) # not used interval = 20.0 #meters azimuth = coord_list.calculateBearing(origin[0], origin[1], target[0], target[1]) # this works but angle above not. coords = np.array(coord_list.main(interval,azimuth,origin[0], origin[1], target[0], target[1])) lats = coords[:,0] lons = coords[:,1] I2 = np.argmin(np.abs(latVec-target[0]) + np.abs(lonVec-target[1])) I1 = np.argmin(np.abs(latVec-origin[0]) + np.abs(lonVec-origin[1])) theIndex = np.arange(np.min([I1, I2]), np.max([I1, I2])) distVec = np.full_like(theIndex, np.nan, dtype=np.double) new_lat = np.full_like(theIndex, np.nan, dtype=np.double) new_lon = np.full_like(theIndex, np.nan, dtype=np.double) for re_idx, idx in enumerate(theIndex): idx_nearest = np.argmin(np.abs(latVec[idx]-lats) + np.abs(lonVec[idx]-lons)) new_lat[re_idx] = coords[idx_nearest,0]
df.head() # To get unsmoothed total height of climbs df['Altitude'].diff()[df['Altitude'].diff() > 0.0].sum() # SMOOTHING df_new = pd.rolling_mean(df[['Longitude', 'Latitude', 'Altitude', 'Speed']], 5, min_periods=1, center=True) df_new['Time'] = df['Time'] # smoothed total of climbs df_new['Altitude'].diff()[df_new['Altitude'].diff() > 0.0].sum() # get angles _, angles = sw.dist(df_new['Latitude'], df_new['Longitude']) angles = np.r_[0, np.deg2rad(angles)] # Normalize the speed to use as the length of the arrows r = df_new['Speed'] / df_new['Speed'].max() kw = dict(window_len=31, window='hanning') df_new['u'] = r * np.cos(angles) df_new['v'] = r * np.sin(angles) # Visualize the data fig, ax = plt.subplots(figsize=(16, 9)) df = df.dropna() ax.plot(df_new['Longitude'], df_new['Latitude'], color='darkorange', linewidth=6, alpha=0.5)
def distance(x, y, units="km"): dist, pha = sw.dist(x, y, units=units) return np.r_[0, np.cumsum(dist)]
plot_profiles(prof, p, t, s, cyy, cmm, cdd) if f_upd == 1: # only make trajectory and section plots if more than 1 profile for the float is available # open trajectory file for this float f1 = open( config.tdir2 + prof.split('_')[0][1:] + '_traj.txt', 'r') tlat, tlon, tkm = ([] for k in range(3)) for line in f1: tlat.append(float(line.split(' ')[1])) tlon.append(float(line.split(' ')[2])) tkm.append(float(line.split(' ')[3])) tkm.append( float( sw.dist((lat[i], tlat[-1]), (lon[i], tlon[-1]), units='km')[0]) + tkm[-1]) tlat.append(lat[i]) tlon.append(lon[i]) f1.close() f1 = open( config.tdir2 + prof.split('_')[0][1:] + '_traj.txt', 'a') f1.write('%02d' % cyy + '%02d' % cmm + '%02d' % cdd + ' ' + str(lat[i]) + ' ' + str(lon[i]) + ' %-5.2f' % tkm[-1] + '\n') f1.close() i = i + 1 # make trajectory plot for this float #print ('making trajectory plot for float '+prof.split('_')[0][1:])
SHIPS_Dorian = np.hstack([SHIPS_Dorian1, SHIPS_Dorian2]) markers = ['X-', '^-', 'H-'] colors = ['mediumorchid', 'teal', 'darkorange'] labels = [ 'HWRF2019-POM (IC clim.) ', 'HWRF2020-POM (IC RTOFS) ', 'HWRF2020-HYCOM (IC RTOFS) ' ] #%% Calculate translation speed from best track file lon_best_track, lat_best_track, time_best_track, _, _, _ = \ read_kmz_file_storm_best_track(kmz_file_Dorian) # Translation Speed dtime = (time_best_track[1] - time_best_track[0]).seconds dr = seawater.dist(lat_best_track,\ lon_best_track,'km')[0] * 1000 best_trans_speed = dr / dtime okt = np.logical_and(time_best_track[1:] >= datetime(2019, 8, 28, 00), time_best_track[1:] <= datetime(2019, 8, 31, 12)) #%% fig, ax1 = plt.subplots(figsize=(10, 5)) plt.title('Shear Magnitude Forecast Dorian Cycle ' + cycle, fontsize=16) plt.ylabel('Shear Magnitude (KT)', fontsize=14) plt.xlabel('Forecast Lead Time (Hours)', fontsize=14) ax1.xaxis.set_major_locator(MultipleLocator(12)) ax1.xaxis.set_major_formatter(FormatStrFormatter('%d')) ax1.xaxis.set_minor_locator(MultipleLocator(3)) for f, file in enumerate(SHIPS_Dorian): print(file)
# In[13]: cube = cubes.extract_strict('sea_water_potential_temperature') print(cube) # In[14]: # Finding the right `num` is tricky. num = 60 xi = np.linspace(A[0], B[0], num=num, endpoint=True) yi = np.linspace(A[1], B[1], num=num, endpoint=True) dist = sw.dist(xi, yi, 'km')[0].cumsum() dist = np.insert(dist, 0, 0) # In[15]: # grab a 3D chunk of data at a specific time step t3d = cube[-1, ...].data # In[16]: # this uses the CF formula terms to compute the z positions in the vertical z3d = cube[-1, ...].coord('sea_surface_height_above_reference_ellipsoid').points
def cross_shore_transect_2d(grid,name,region,vec,npt): data = dt.loadnc('runs/'+grid+'/'+name+'/output/',singlename=grid + '_0001.nc') print('done load') data = dt.ncdatasort(data,trifinder=True) print('done sort') cages=gt.loadcage('runs/'+grid+'/' +name+ '/input/' +grid+ '_cage.dat') if np.shape(cages)!=(): tmparray=[list(zip(data['nodell'][data['nv'][i,[0,1,2,0]],0],data['nodell'][data['nv'][i,[0,1,2,0]],1])) for i in cages ] color='g' lw=.2 ls='solid' vectorstart=np.array(vec[0]) vectorend=np.array(vec[1]) vectorx=np.array([vectorstart[0],vectorend[0]]) vectory=np.array([vectorstart[1],vectorend[1]]) snv=(vectorend-vectorstart)/np.linalg.norm(vectorend-vectorstart) xi=np.linspace(vectorstart[0],vectorend[0],npt) yi=np.linspace(vectorstart[1],vectorend[1],npt) us=data['ua'].shape savepath='data/cross_shore_transect/' if not os.path.exists(savepath): os.makedirs(savepath) plotpath='figures/png/'+grid+'_2d/cross_shore_transect/' if not os.path.exists(plotpath): os.makedirs(plotpath) nidx=dt.get_nodes(data,region) f=plt.figure() ax=f.add_axes([.125,.1,.775,.8]) triax=ax.tripcolor(data['trigrid'],data['h'],vmin=data['h'][nidx].min(),vmax=data['h'][nidx].max()) ax.plot(xi,yi,'k',lw=3) if np.shape(cages)!=(): lseg_t=LC(tmparray,linewidths = lw,linestyles=ls,color=color) coast=ax.add_collection(lseg_t) coast.set_zorder(30) pt.prettyplot_ll(ax,setregion=region,cb=triax,cblabel=r'Depth (m)') f.savefig(plotpath + name+'_'+('%f'%vectorx[0])+'_'+('%f'%vectorx[1])+'_'+('%f'%vectory[0])+'_'+('%f'%vectory[1])+'_'+('%d'%len(xi))+'_line_location.png',dpi=600) plt.close(f) fillarray_u=np.empty((us[0],npt)) fillarray_v=np.empty((us[0],npt)) fillalong=np.empty((us[0],npt)) fillcross=np.empty((us[0],npt)) dist=np.empty((npt,)) h=np.empty((npt,)) print('interp uvw on path') for i in range(0,len(xi)): print(i) fillarray_u[:,i]=interpE_at_loc(data,'ua',[xi[i],yi[i]]) fillarray_v[:,i]=interpE_at_loc(data,'va',[xi[i],yi[i]]) h[i]=interpN_at_loc(data,'h',[xi[i],yi[i]]) print('Calc along path current') for i in range(0,len(xi)): print(i) inner=np.inner(np.vstack([fillarray_u[:,i],fillarray_v[:,i]]).T,snv) along=np.vstack([inner*snv[0],inner*snv[1]]).T tmpa=np.multiply(np.sign(np.arctan2(along[:,1],along[:,0])),np.linalg.norm(along,axis=1)) fillalong[:,i]=tmpa cross=np.vstack([fillarray_u[:,i],fillarray_v[:,i]]).T-along tmpc=np.multiply(np.sign(np.arctan2(cross[:,1],cross[:,0])),np.linalg.norm(cross,axis=1)) fillcross[:,i]=tmpc dist[i]=(sw.dist([vectorstart[1], yi[i]],[vectorstart[0], xi[i]],'km'))[0]*1000; if np.shape(cages)!=(): incage=np.zeros((len(xi),)) host=data['trigrid'].get_trifinder().__call__(xi,yi) incage[np.in1d(host,cages)]=1 savedic={} savedic['u']=fillarray_u savedic['v']=fillarray_v savedic['along']=fillalong savedic['cross']=fillcross savedic['distance']=dist savedic['h']=h savedic['lon']=xi savedic['lat']=yi if np.shape(cages)!=(): savedic['incage']=incage np.save(savepath+grid+'_'+name+'_'+('%f'%vectorx[0])+'_'+('%f'%vectorx[1])+'_'+('%f'%vectory[0])+'_'+('%f'%vectory[1])+'_'+('%d'%len(xi))+'_2d.npy',savedic) sio.savemat(savepath+'matfiles/'+grid+'_'+name+'_'+('%f'%vectorx[0])+'_'+('%f'%vectorx[1])+'_'+('%f'%vectory[0])+'_'+('%f'%vectory[1])+'_'+('%d'%len(xi))+'_2d.mat',mdict=savedic)
def fwoa(x, y, woafile='woa2009_annual.mat'): """ Usage ----- T,S,X,D,Xo,Yo = fwoa(x, y, woafile='woa2009_annual.mat') Description ----------- Gets the TS profiles in the World Ocean Atlas (WOA) 2009 data set whose coordinates are closest to the input coordinates 'x', 'y'. Parameters ---------- x : 1D array Array containing longitudes of the points of unknown depth. y : 1D array Array containing latitudes of the points of unknown depth. woafile : string, optional String containing path to the WOA .mat file. Returns ------- T : 2D array Array containing the Temperature profiles closest to the input X, Y coordinates. S : 2D array Array containing the Salinity (PSS-78) profiles closest to the input X,Y coordinates. X : 1D array Array of horizontal distance associated with the TS profiles recovered. D : 1D array Array containing distances (in km) from the input X, Y coordinates to the TS profiles. Xo : 1D array Array containing longitudes of the WOA TS profiles. Yo : 1D array Array containing latitudes of the WOA TS profiles. NOTES ------- This function reads mat files, converted from the original netCDF ones. TODO ------- Implement netCDF file reading (Original WOA 2009 format) Implement option to retrieve linearly interpolated profiles instead of nearest ones. """ x, y = list(map(np.asanyarray, (x, y))) # Reading .mat file. d = loadmat(woafile) xx = d['lon'] yy = d['lat'] TT = d['temp'] SS = d['salt'] # Retrieving nearest profiles for each input coordinate. A = np.asanyarray([]) B = np.NaN * np.ones((TT.shape[2], x.size)) Xo = A.copy() Yo = A.copy() D = A.copy() T = B.copy() S = B.copy() for I in range(x.size): ix = near(xx[0, :], x[I]) iy = near(yy[:, 0], y[I]) T[:, I] = TT[iy, ix, :] S[:, I] = SS[iy, ix, :] # Calculating distance between input and nearest WOA points. D = np.append( D, dist([x[I], xx[0, ix]], [y[I], yy[iy, 0]], units='km')[0]) Xo = np.append(Xo, xx[0, ix]) Yo = np.append(Yo, yy[iy, 0]) # Calculating distance axis. X = np.append(0, np.cumsum(dist(Xo, Yo, units='km')[0])) return T, S, X, D, Xo, Yo
h[i]=ipt.interpN_at_loc(data,'h',[xi[i],yi[i]]) print 'Calc along path current' for i in range(0,len(xi)): print i inner=np.inner(np.vstack([fillarray_u[:,i],fillarray_v[:,i]]).T,snv) along=np.vstack([inner*snv[0],inner*snv[1]]).T tmpa=np.multiply(np.sign(np.arctan2(along[:,1],along[:,0])),np.linalg.norm(along,axis=1)) fillalong[:,i]=tmpa cross=np.vstack([fillarray_u[:,i],fillarray_v[:,i]]).T-along tmpc=np.multiply(np.sign(np.arctan2(cross[:,1],cross[:,0])),np.linalg.norm(cross,axis=1)) fillcross[:,i]=tmpc dist[i]=(sw.dist([vectorstart[1], yi[i]],[vectorstart[0], xi[i]],'km'))[0]*1000; if cages!=None: incage=np.zeros((len(xi),)) host=data['trigrid'].get_trifinder().__call__(xi,yi) incage[np.in1d(host,cages)]=1 savedic={} savedic['u']=fillarray_u savedic['v']=fillarray_v savedic['along']=fillalong
def cross_shore_transect_2d(grid, name, region, vec, npt): data = dt.loadnc('runs/' + grid + '/' + name + '/output/', singlename=grid + '_0001.nc') print('done load') data = dt.ncdatasort(data, trifinder=True) print('done sort') cages = gt.loadcage('runs/' + grid + '/' + name + '/input/' + grid + '_cage.dat') if np.shape(cages) != (): tmparray = [ list( zip(data['nodell'][data['nv'][i, [0, 1, 2, 0]], 0], data['nodell'][data['nv'][i, [0, 1, 2, 0]], 1])) for i in cages ] color = 'g' lw = .2 ls = 'solid' vectorstart = np.array(vec[0]) vectorend = np.array(vec[1]) vectorx = np.array([vectorstart[0], vectorend[0]]) vectory = np.array([vectorstart[1], vectorend[1]]) snv = (vectorend - vectorstart) / np.linalg.norm(vectorend - vectorstart) xi = np.linspace(vectorstart[0], vectorend[0], npt) yi = np.linspace(vectorstart[1], vectorend[1], npt) us = data['ua'].shape savepath = 'data/cross_shore_transect/' if not os.path.exists(savepath): os.makedirs(savepath) plotpath = 'figures/png/' + grid + '_2d/cross_shore_transect/' if not os.path.exists(plotpath): os.makedirs(plotpath) nidx = dt.get_nodes(data, region) f = plt.figure() ax = f.add_axes([.125, .1, .775, .8]) triax = ax.tripcolor(data['trigrid'], data['h'], vmin=data['h'][nidx].min(), vmax=data['h'][nidx].max()) ax.plot(xi, yi, 'k', lw=3) if np.shape(cages) != (): lseg_t = LC(tmparray, linewidths=lw, linestyles=ls, color=color) coast = ax.add_collection(lseg_t) coast.set_zorder(30) pt.prettyplot_ll(ax, setregion=region, cb=triax, cblabel=r'Depth (m)') f.savefig(plotpath + name + '_' + ('%f' % vectorx[0]) + '_' + ('%f' % vectorx[1]) + '_' + ('%f' % vectory[0]) + '_' + ('%f' % vectory[1]) + '_' + ('%d' % len(xi)) + '_line_location.png', dpi=600) plt.close(f) fillarray_u = np.empty((us[0], npt)) fillarray_v = np.empty((us[0], npt)) fillalong = np.empty((us[0], npt)) fillcross = np.empty((us[0], npt)) dist = np.empty((npt, )) h = np.empty((npt, )) print('interp uvw on path') for i in range(0, len(xi)): print(i) fillarray_u[:, i] = interpE_at_loc(data, 'ua', [xi[i], yi[i]]) fillarray_v[:, i] = interpE_at_loc(data, 'va', [xi[i], yi[i]]) h[i] = interpN_at_loc(data, 'h', [xi[i], yi[i]]) print('Calc along path current') for i in range(0, len(xi)): print(i) inner = np.inner( np.vstack([fillarray_u[:, i], fillarray_v[:, i]]).T, snv) along = np.vstack([inner * snv[0], inner * snv[1]]).T tmpa = np.multiply(np.sign(np.arctan2(along[:, 1], along[:, 0])), np.linalg.norm(along, axis=1)) fillalong[:, i] = tmpa cross = np.vstack([fillarray_u[:, i], fillarray_v[:, i]]).T - along tmpc = np.multiply(np.sign(np.arctan2(cross[:, 1], cross[:, 0])), np.linalg.norm(cross, axis=1)) fillcross[:, i] = tmpc dist[i] = (sw.dist([vectorstart[1], yi[i]], [vectorstart[0], xi[i]], 'km'))[0] * 1000 if np.shape(cages) != (): incage = np.zeros((len(xi), )) host = data['trigrid'].get_trifinder().__call__(xi, yi) incage[np.in1d(host, cages)] = 1 savedic = {} savedic['u'] = fillarray_u savedic['v'] = fillarray_v savedic['along'] = fillalong savedic['cross'] = fillcross savedic['distance'] = dist savedic['h'] = h savedic['lon'] = xi savedic['lat'] = yi if np.shape(cages) != (): savedic['incage'] = incage np.save( savepath + grid + '_' + name + '_' + ('%f' % vectorx[0]) + '_' + ('%f' % vectorx[1]) + '_' + ('%f' % vectory[0]) + '_' + ('%f' % vectory[1]) + '_' + ('%d' % len(xi)) + '_2d.npy', savedic) sio.savemat(savepath + 'matfiles/' + grid + '_' + name + '_' + ('%f' % vectorx[0]) + '_' + ('%f' % vectorx[1]) + '_' + ('%f' % vectory[0]) + '_' + ('%f' % vectory[1]) + '_' + ('%d' % len(xi)) + '_2d.mat', mdict=savedic)
def ftopo(x, y, topofile='gebco15-40s_30-52w_30seg.nc'): r""" Usage ----- H, D, Xo, Yo = ftopo(x, y, topofile='gebco/gebco_08_30seg.nc') Description ----------- Finds the depth of points of coordinates 'x','y' using GEBCO data set. Parameters ---------- x : 1D array Array containing longitudes of the points of unknown depth. y : 1D array Array containing latitudes of the points of unknown depth. topofile : string, optional String containing path to the GEBCO netCDF file. Returns ------- H : 1D array Array containing depths of points closest to the input X, Y coordinates. X : 1D array Array of horizontal distance associated with array 'H'. D : 1D array Array containing distances (in km) from the input X, Y coordinates to the data points. Xo : 1D array Array containing longitudes of the data points. Yo : 1D array Array containing latitudes of the data points. NOTES ------- This function reads the entire netCDF file before extracting the wanted data. Therefore, it does not handle the full GEBCO dataset (1.8 GB) efficiently. TODO ------- Make it possible to work with the full gebco dataset, by extracting only the wanted indexes. Code History --------------------------------------- Author of the original Matlab code (ftopo.m, ETOPO2 dataset): Marcelo Andrioni <*****@*****.**> December 2008: Modification performed by Cesar Rocha <*****@*****.**> to handle ETOPO1 dataset. July 2012: Python Translation and modifications performed by André Palóczy Filho <*****@*****.**> to handle GEBCO dataset (30 arc seconds resolution). """ x, y = map(np.asanyarray, (x, y)) # Opening netCDF file and extracting data. grid = Dataset(topofile) yyr = grid.variables['y_range'][:] xxr = grid.variables['x_range'][:] spacing = grid.variables['spacing'][:] dx, dy = spacing[0], spacing[1] # Creating lon and lat 1D arrays. xx = np.arange(xxr[0], xxr[1], dx) xx = xx + dx / 2 yy = np.arange(yyr[0], yyr[1], dy) yy = yy + dy / 2 h = grid.variables['z'][:] grid.close() # Retrieving nearest point for each input coordinate. A = np.asanyarray([]) xx, yy = np.meshgrid(xx, yy) ni, nj = xx.shape[0], yy.shape[1] h = np.reshape(h, (ni, nj)) h = np.flipud(h) Xo = A.copy() Yo = A.copy() H = A.copy() D = A.copy() for I in xrange(x.size): ix = near(xx[0, :], x[I]) iy = near(yy[:, 0], y[I]) H = np.append(H, h[iy, ix]) # Calculating distance between input and GEBCO points. D = np.append(D, dist([x[I], xx[0, ix]], [y[I], yy[iy, 0]], units='km')[0]) Xo = np.append(Xo, xx[0, ix]) Yo = np.append(Yo, yy[iy, 0]) # Calculating distance axis. X = np.append(0, np.cumsum(dist(Xo, Yo, units='km')[0])) return H, X, D, Xo, Yo
def polcoms_select_domain(bathy, lat, lon, roi, dr): """ This calculates the shelf break :param bathy: This is the input bathymetry data :param lat: Latittude array :param lon: Longitude array :param roi: region of interest array [4] :param dr: shelf break distance :type bathy: numpy array :type lat: numpy array :type lon: numpy array :type roi: python array :type dr: float :return: returns the depth_shelf, h_max :rtype: numpy arrays :Example: """ logger = logging.getLogger(__name__) # dy = 0.1 # dx = 0.1 #create a copy of bathy bathy_copy = bathy.copy() # bathy[bathy>=0] = 0; # bathy = bathy*-1 global_ind = bathy_copy * np.NaN # r = np.ceil(dr/(np.pi/180*6400)/dy) # r = np.ceil(dr/(np.cos(np.radians(lat_ob[idx]))*np.pi*6400*2/360*dy)) # if r > np.max(bathy_copy.shape): # logger.error("Shelf break is larger than the grid") # d1 = bathy_copy.shape[0]-(roi[3]-roi[2])/2.0 # d2 = bathy_copy.shape[1]-(roi[1]-roi[0])/2.0 # r = np.ceil(min(d1,d2)) #just select the box roi # ret_val = np.ones(bathy.shape) # ret_val[roi[2]:roi[3],roi[0]:roi[1]] = -1 # return ret_val == -1 tmp = bathy_copy[roi[2]:roi[3], roi[0]:roi[1]] lat = lat[roi[2]:roi[3], roi[0]:roi[1]] lon = lon[roi[2]:roi[3], roi[0]:roi[1]] nanind = np.isnan(tmp) tmp[nanind] = -1 dummy, lb = gcoms_boundary_masks(tmp, -1, 0) Zshelf, Hmax = gcoms_break_depth(tmp) tmp[tmp > Hmax] = -1 tmp[np.logical_and(np.logical_and(tmp != 0, np.logical_not(np.isnan(tmp))), tmp != -1)] = 1 ob, dummy = gcoms_boundary_masks(tmp, -1, 0) lat_ob = np.ravel(lat, order='F')[np.ravel(ob, order='F')] lon_ob = np.ravel(lon, order='F')[np.ravel(ob, order='F')] print(lat_ob, lon_ob) len_lat = len(lat[:, 0]) len_lon = len(lon[0, :]) lat_lon_index = np.nonzero( np.logical_and(lat == lat_ob[0], lon == lon_ob[0])) for idx in range(0, len(lat_ob)): lat_lon_index = np.nonzero( np.logical_and(lat == lat_ob[idx], lon == lon_ob[idx])) # messy fudge to determine local dx,dy TODO tidy and formalise j_0 = max(lat_lon_index[0], 0) j_e = min(lat_lon_index[0] + 1 + 1, len_lat) i_0 = max(lat_lon_index[1], 0) i_e = min(lat_lon_index[1] + 1 + 1, len_lon) if j_e > len_lat - 2: j_0 = j_0 - 3 j_e = j_0 + 2 if i_e > len_lon - 2: i_0 = i_0 - 3 i_e = i_0 + 2 lat_slice = slice(max(lat_lon_index[0], 0), min(lat_lon_index[0] + 1 + 1, len_lat)) lon_slice = slice(max(lat_lon_index[1], 0), min(lat_lon_index[1] + 1 + 1, len_lon)) print('method2', lon_slice, lat_slice) lat_slice = slice(j_0, j_e) lon_slice = slice(i_0, i_e) print('method1', lon_slice, lat_slice) lat_pts = lat[lat_slice, lon_slice] lon_pts = lon[lat_slice, lon_slice] print(lat_pts, lon_pts) print(lat_lon_index[0], lat_lon_index[1]) print(len_lon, len_lat, lat_lon_index[0], lat_lon_index[1]) dy, py = seawater.dist(lat_pts[:, 0], lon_pts[:, 0]) dx, px = seawater.dist(lat_pts[0, :], lon_pts[0, :]) r = np.rint(np.ceil(dr / np.amax([dx, dy]))) print(dx, dy, r) lat_slice = slice(max(lat_lon_index[0] - r, 0), min(lat_lon_index[0] + r + 1, len_lat)) lon_slice = slice(max(lat_lon_index[1] - r, 0), min(lat_lon_index[1] + r + 1, len_lon)) lat_pts = lat[lat_slice, lon_slice] lon_pts = lon[lat_slice, lon_slice] lat_pts_shape = lat_pts.shape lat_pts = np.ravel(lat_pts) lon_pts = np.ravel(lon_pts) # NOTE: seawater package calculates the distance from point to the next point in the array # that is the reason to insert reference point before every point lat_pts = np.insert(lat_pts, list(range(0, len(lat_pts))), lat_ob[idx]) lon_pts = np.insert(lon_pts, list(range(0, len(lon_pts))), lon_ob[idx]) distance_pts = seawater.dist(lat_pts, lon_pts) #distances repeat themselves so only pick every alternative distance distance_pts = distance_pts[0][::2] #Using pyproj #geod = pyproj.Geod(ellps='WGS84') #dummy,dummy, distance_pts = geod.inv(len(lon_pts)*[lon_ob[idx]],len(lat_pts)*[lat_ob[idx]], lon_pts, lat_pts) #distance_pts=distance_pts/1000.0 distance_pts = np.reshape(distance_pts, lat_pts_shape) distance_pts[distance_pts > dr] = np.NaN distance_pts[np.logical_not(np.isnan(distance_pts))] = 1 tmp1 = tmp[lat_slice, lon_slice] tmp1[np.logical_and(tmp1 == -1, distance_pts == 1)] = 1 tmp[lat_slice, lon_slice] = tmp1 lat_lb = lat[lb] lon_lb = lon[lb] for idx in range(0, len(lat_lb)): lat_lon_index = np.nonzero( np.logical_and(lat == lat_lb[idx], lon == lon_lb[idx])) # messy fudge to determine local dx,dy TODO tidy and formalise j_0 = max(lat_lon_index[0], 0) j_e = min(lat_lon_index[0] + 1 + 1, len_lat) i_0 = max(lat_lon_index[1], 0) i_e = min(lat_lon_index[1] + 1 + 1, len_lon) if j_e > len_lat - 2: j_0 = j_0 - 3 j_e = j_0 + 2 if i_e > len_lon - 2: i_0 = i_0 - 3 i_e = i_0 + 2 lat_slice = slice(max(lat_lon_index[0], 0), min(lat_lon_index[0] + 1 + 1, len_lat)) lon_slice = slice(max(lat_lon_index[1], 0), min(lat_lon_index[1] + 1 + 1, len_lon)) print('method2', lon_slice, lat_slice) lat_slice = slice(j_0, j_e) lon_slice = slice(i_0, i_e) print('method1', lon_slice, lat_slice) lat_pts = lat[lat_slice, lon_slice] lon_pts = lon[lat_slice, lon_slice] print(lat_pts, lon_pts) print(lat_lon_index[0], lat_lon_index[1]) print(len_lon, len_lat, lat_lon_index[0], lat_lon_index[1]) dy, py = seawater.dist(lat_pts[:, 0], lon_pts[:, 0]) dx, px = seawater.dist(lat_pts[0, :], lon_pts[0, :]) r = np.rint(np.ceil(dr / np.amax([dx, dy]))) print(dx, dy, r) lat_slice = slice(max(lat_lon_index[0] - r, 0), min(lat_lon_index[0] + r + 1, len_lat)) lon_slice = slice(max(lat_lon_index[1] - r, 0), min(lat_lon_index[1] + r + 1, len_lon)) lat_pts = lat[lat_slice, lon_slice] lon_pts = lon[lat_slice, lon_slice] lat_pts_shape = lat_pts.shape lat_pts = np.ravel(lat_pts) lon_pts = np.ravel(lon_pts) # NOTE: seawater package calculates the distance from point to the next point in the array # that is the reason to insert reference point before every point lat_pts = np.insert(lat_pts, list(range(0, len(lat_pts))), lat_lb[idx]) lon_pts = np.insert(lon_pts, list(range(0, len(lon_pts))), lon_lb[idx]) distance_pts = seawater.dist(lat_pts, lon_pts) #distances repeat themselves so only pick every alternative distance distance_pts = distance_pts[0][::2] #Using pyproj #geod = pyproj.Geod(ellps='WGS84') #dummy,dummy, distance_pts = geod.inv(len(lon_pts)*[lon_lb[idx]],len(lat_pts)*[lat_lb[idx]], lon_pts, lat_pts) #distance_pts=distance_pts/1000.0 distance_pts = np.reshape(distance_pts, lat_pts_shape) distance_pts[distance_pts > dr] = np.NaN distance_pts[np.logical_not(np.isnan(distance_pts))] = 1 tmp1 = tmp[lat_slice, lon_slice] tmp1[np.logical_and(tmp1 == -1, distance_pts == 1)] = 1 tmp[lat_slice, lon_slice] = tmp1 #Only select largest sub region tmp[nanind] = np.NaN ret_val = np.ones(bathy.shape) ret_val[roi[2]:roi[3], roi[0]:roi[1]] = tmp return ret_val == 1
# <codecell> print ncv['ctd_temp'] # <codecell> data = ma.masked_invalid(data,copy=True) z = ma.masked_invalid(z,copy=True) # <codecell> data.min() # <codecell> dist, pha = sw.dist(lat, lon, units='km') # <codecell> dist.min() # <codecell> def plot_glider(lon,lat,z,tim, data, mask_topo=False, **kw): """Plot glider cube.""" cmap = kw.pop('cmap', plt.cm.rainbow) dist, pha = sw.dist(lat, lon, units='km') dist = np.append(0, np.cumsum(dist)) dist, z = np.broadcast_arrays(dist[..., None], z)