def get_full(fn): # gets v_dict for the full extent of one history file ds = nc.Dataset(fn) G, S, T = zrfun.get_basic_info(fn) # extract needed info from history file v_dict = dict() if print_info: print('\nINPUT Variable Info:') for vn in ['alkalinity', 'TIC', 'salt', 'temp','rho']: v = ds[vn][:] v = fillit(v) v_dict[vn] = v # create depth, pressure, and in situ temperature h = ds['h'][:] h = fillit(h) lat = G['lat_rho'][:] z_rho = zrfun.get_z(h, 0*h, S, only_rho=True) depth = -z_rho pres = sw.pres(depth, lat) v_dict['pres'] = pres temp = sw.ptmp(v_dict['salt'], v_dict['temp'], 0, v_dict['pres']) v_dict['temp'] = temp # convert from umol/L to umol/kg using in situ dentity v_dict['alkalinity'] = 1000 * v_dict['alkalinity'] / (v_dict['rho'] + 1000) v_dict['TIC'] = 1000 * v_dict['TIC'] / (v_dict['rho'] + 1000) # clean up v_dict.pop('rho') # no longer needed, so don't pass to worker ds.close() return v_dict
def _fix_data(xr_time, var): """Specific data fixes for different variables.""" logger.info("Fixing data ...") if var == 'thetao': depth3d = np.zeros(xr_time.temp.shape[1:]) for i in range(xr_time.depth.shape[0]): depth3d[i, :, :] = xr_time.depth[i] ptemp = sw.ptmp(xr_time.salt[0, :], xr_time.temp[0, :], depth3d) ptemp = np.expand_dims(ptemp, axis=0) temp_new = xr.DataArray(ptemp + 273.15, coords={ 'time': xr_time.temp.coords['time'], 'depth': xr_time.temp.coords['depth'], 'lat': xr_time.temp.coords['lat'], 'lon': xr_time.temp.coords['lon'], }, dims=['time', 'depth', 'lat', 'lon']) temp_new.attrs = OrderedDict([('standard_name', 'sea_water_potential_temperature'), ('units', 'K')]) cube = temp_new.to_iris() return cube.copy() elif var == 'so': cube = xr_time.salt.to_iris() return cube.copy() elif var == 'areacello': cube = _fix_fx_areacello(xr_time, var) return cube.copy() return None
def pottemp_calculation(salinity, temperature, pressure, depth, no_press=False): """ Calculate Potenital Temperature - Following EOS-80 standards (ITS-90 temp and PSS-78 sal)""" if (pressure == -9999.).any() | (no_press): history = "ITS90 Pot. Temp calculated using nominal depth" pot_temp = sw.ptmp(salinity, temperature, pressure * 0 + depth) pot_temp[np.isnan(pot_temp)] = 1e35 else: history = "ITS90 Pot. Temp calculated using P_1 (recorded pressure)" pot_temp = sw.ptmp(salinity, temperature, pressure) return (pot_temp, history)
def __init__(self, path, fname, var='temp'): self.path = path self.fname = fname self.var = var #__________________________________________________________________# ncid = Dataset(path + fname, 'r') #__________________________________________________________________# self.lon = np.copy(ncid.variables['lon'][:]) self.lat = np.copy(ncid.variables['lat'][:]) self.depth = np.copy(ncid.variables['depth'][:]) #______________________________________________________________________# # load WOA 2005 data if 'woa' in self.fname: self.descript = 'WOA' valueT = np.copy(ncid.variables['t00an1'][:, :, :, :]).squeeze() valueS = np.copy(ncid.variables['s00an1'][:, :, :, :]).squeeze() elif self.fname == 'phc3.0_annual.nc': self.descript = 'PHC3' valueT = np.copy(ncid.variables['temp'][:, :, :]).squeeze() valueS = np.copy(ncid.variables['salt'][:, :, :]).squeeze() ncid.close() #__________________________________________________________________# # convert missing value to nan valueT[np.abs(valueT) >= 100] = np.nan valueS[np.abs(valueS) >= 100] = np.nan #__________________________________________________________________# # shift coordinates from 0...360 --> -180...180 if self.lon.max() > 180: valueT, dum = shiftgrid(180.0, valueT, self.lon, start=False, cyclic=359) valueS, self.lon = shiftgrid(180.0, valueS, self.lon, start=False, cyclic=359) #__________________________________________________________________# # calculate potential temperature if var == 'temp': self.value = valueT elif var == 'ptemp': depth3d = np.zeros(valueS.shape) for di in range(0, self.depth.size): depth3d[di, :, :] = self.depth[di] self.value = sw.ptmp(valueS, valueT, depth3d) elif var == 'salt': self.value = valueS else: print(' --> this variable is not supported for this climatology')
def calcs(self, S, T, P): self['gpan'] = sw.gpan(S, T, P) self['pt'] = sw.ptmp(S, T, P) self['psigma0'] = sw.pden(S, T, P, 0) - 1000 self['psigma1'] = sw.pden(S, T, P, 1000) - 1000 self['psigma2'] = sw.pden(S, T, P, 2000) - 1000 return self
def clim_load_data(data): #__________________________________________________________________# ncid = Dataset(data.path + data.fname, 'r') #__________________________________________________________________# data.lon = np.copy(ncid.variables['lon'][:]) data.lat = np.copy(ncid.variables['lat'][:]) data.zlev = np.copy(ncid.variables['depth'][:]) #______________________________________________________________________# # load WOA 2005 data if 'woa' in data.fname: if '2005' in data.fname: data.descript = 'WOA05' if '2018' in data.fname: data.descript = 'WOA18' valueT = np.copy(ncid.variables['t00an1'][:, :, :, :]).squeeze() valueS = np.copy(ncid.variables['s00an1'][:, :, :, :]).squeeze() elif data.fname == 'phc3.0_annual.nc': data.descript = 'PHC3.0 annual' valueT = np.copy(ncid.variables['temp'][:, :, :]).squeeze() valueS = np.copy(ncid.variables['salt'][:, :, :]).squeeze() ncid.close() #__________________________________________________________________# # convert missing value to nan valueT[np.abs(valueT) >= 100] = np.nan valueS[np.abs(valueS) >= 100] = np.nan #__________________________________________________________________# # shift coordinates from 0...360 --> -180...180 if data.lon.max() > 180: valueT, dum = shiftgrid(180.0, valueT, data.lon, start=False, cyclic=359) valueS, data.lon = shiftgrid(180.0, valueS, data.lon, start=False, cyclic=359) #__________________________________________________________________# # calculate potential temperature if data.var == 'temp': data.value = valueT elif data.var == 'ptemp': depth3d = np.zeros(valueS.shape) for di in range(0, data.depth.size): depth3d[di, :, :] = data.depth[di] data.value = sw.ptmp(valueS, valueT, depth3d) elif data.var == 'salt': data.value = valueS else: print(' --> this variable is not supported for this climatology') return data
def PVort(S,T,P,U,V): theta=np.zeros(np.shape(S)) for ii in range(0,np.shape(S)[1]): for jj in range(0,np.shape(S)[2]): theta[:,ii,jj]=sw.ptmp(S[:,ii,jj],T[:,ii,jj],P) rho=sw.dens(S,T,P) omega=7.2921159*10**(-5) zeta=2*omega+curl(U,V) Q=(1/rho)*(zeta)*np.gradient(theta)
def plt_TS(ds, fig=None, s=0.2, c='k', pr=0): if fig is None: fig, ax = plt.subplots() if isinstance(ds, dict): # Non-interpolated data comes in a dictionary of datasets. S, T, p = np.array([]), np.array([]), np.array([]) for dsi in ds.values(): try: S = np.concatenate((S, dsi['PSAL_ADJUSTED'].values.ravel())) except KeyError: S = np.concatenate((S, dsi['PSAL'].values.ravel())) try: T = np.concatenate((T, dsi['TEMP_ADJUSTED'].values.ravel())) except KeyError: T = np.concatenate((T, dsi['TEMP'].values.ravel())) p = np.concatenate((p, dsi['p'].values.ravel())) else: try: S = ds['PSAL_ADJUSTED'].values.ravel() except KeyError: S = ds['PSAL'].values.ravel() try: T = ds['TEMP_ADJUSTED'].values.ravel() except KeyError: T = ds['TEMP'].values.ravel() p = ds['p'].values.ravel() T = ptmp(S, T, p, pr=pr) ax.scatter(S, T, s=s, c=c, zorder=9) Sx = np.linspace(np.nanmin(S)-0.5, np.nanmax(S)+0.5, 1000) Ty = np.linspace(np.nanmin(T)-0.5, np.nanmax(T)+0.5, 1000) Sx, Ty = np.meshgrid(Sx, Ty) sigi = dens(Sx, Ty, pr) - 1000 cc = ax.contour(Sx, Ty, sigi, levels=np.arange(0, 40, 0.1), colors='gray', zorder=-9) ax.clabel(cc, manual=False, fmt='%.1f', inline_spacing=0.01) ax.set_xlabel(r'Practical Salinity [unitless]') ax.set_ylabel(r'Potential Temperature [$^o$C]') ax.set_xlim((np.nanmin(S)-0.05, np.nanmax(S)+0.05)) ax.set_ylim((np.nanmin(T)-0.2, np.nanmax(T)+0.2)) return fig, ax
def makeTSPlot(float_data, units, cmax=500, close_all=False): if close_all: plt.close('all') # ymin = np.floor(min(float_data['Temperature'])) # ymax = np.ceil(max(float_data['Temperature'])) ymin = -2 ymax = 15 xmin = 33.5 xmax = 35.5 # pmin = np.floor(min(float_data['Density'])) # pmax = np.ceil(max(float_data['Density'])) pmin = 25 pmax = 28.5 #plot sample data plt.figure() pres = sw.pres(float_data['Depth'], float_data['Lat']) ptemp = sw.ptmp(float_data['Salinity'], float_data['Temperature'], pres, 0) plt.scatter(float_data['Salinity'], ptemp, c=float_data['Depth'], lw=0, cmap=plt.cm.rainbow, vmin=0, vmax=cmax) plt.ylabel('Pot. Temperature (%s)' %units['Temperature']) plt.xlabel('Salinity (PSS)') plt.title("T vs. S for SOCCOM float '%s'" %float_data['Cruise'][0]) plt.clim(cmax, 0) plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) cbar = plt.colorbar(extend='max') cbar.ax.set_ylabel('Depth (%s)' %units['Depth']) #add density lines temps = np.arange(ymin, ymax,0.1) sals = np.arange(xmin, xmax, 0.1) sal_grid, temp_grid = np.meshgrid(np.ma.masked_invalid(sals), np.ma.masked_invalid(temps)) pdens_grid= sw.dens(sal_grid, temp_grid, 0)-1000 plvls = np.arange(pmin, pmax, 0.2) cs = plt.contour(sal_grid, temp_grid, pdens_grid, plvls, colors='0.5',linewidth=0.5) plt.clabel(cs, inline=1, fontsize=10,fmt='%1.1f',inline_spacing=10) plt.show()
def __init__(self, path): # if climname=='phc': ncfile = Dataset(path) self.T = np.copy(ncfile.variables['temp'][:,:,:]) x=np.copy(ncfile.variables['lon'][:]) x[x>180]=x[x>180]-360 ind=[i[0] for i in sorted(enumerate(x), key=lambda x:x[1])] x=np.sort(x) self.x=x self.y=ncfile.variables['lat'][:] self.z=ncfile.variables['depth'][:] self.T[:,:,:]=self.T[:,:,ind] self.S=np.copy(ncfile.variables['salt'][:,:,:]) self.S[:,:,:]=self.S[:,:,ind] depth3d = np.zeros(self.S.shape) for i in range(self.z.shape[0]): depth3d[i, :, :] = self.z[i] ptemp = sw.ptmp(self.S, self.T, depth3d) self.T = ptemp ncfile.close() self.Tyz=nanmean(self.T, 2) self.Syz=nanmean(self.S, 2)
def get_extrapolated(in_fn, L, M, N, X, Y, lon, lat, z, Ldir, add_CTD=False): b = pickle.load(open(in_fn, 'rb')) vn_list = list(b.keys()) # check that things are the expected shape def check_coords(shape_tuple, arr_shape): if arr_shape != shape_tuple: print('WARNING: array shape mismatch') for vn in vn_list: if vn == 'dt': pass elif vn == 'ssh': check_coords((M, L), b[vn].shape) else: check_coords((N, M, L), b[vn].shape) # creat output array and add dt to it. vn_list.remove('dt') V = dict() for vn in vn_list: V[vn] = np.nan + np.ones(b[vn].shape) V['dt'] = b['dt'] # extrapolate ssh vn = 'ssh' v = b[vn] vv = extrap_nearest_to_masked(X, Y, v) V[vn] = vv vn_list.remove('ssh') # extrapolate 3D fields for vn in vn_list: v = b[vn] if vn == 't3d': v0 = np.nanmin(v) elif vn == 's3d': v0 = np.nanmax(v) if vn in ['t3d', 's3d']: print(' -- extrapolating ' + vn) if add_CTD==False: for k in range(N): fld = v[k, :, :] fldf = extrap_nearest_to_masked(X, Y, fld, fld0=v0) V[vn][k, :, :] = fldf elif add_CTD==True: print(vn + ' Adding CTD data before extrapolating') Cast_dict, sta_df = Ofun_CTD.get_casts(Ldir) for k in range(N): fld = v[k, :, :] zz = z[k] xyorig, fldorig = Ofun_CTD.get_orig(Cast_dict, sta_df, X, Y, fld, lon, lat, zz, vn) fldf = Ofun_CTD.extrap_nearest_to_masked_CTD(X,Y,fld, xyorig=xyorig,fldorig=fldorig,fld0=v0) V[vn][k, :, :] = fldf elif vn in ['u3d', 'v3d']: print(' -- extrapolating ' + vn) vv = v.copy() vv = np.ma.masked_where(np.isnan(vv), vv) vv[vv.mask] = 0 V[vn] = vv.data # Create ubar and vbar. # Note: this is slightly imperfect because the z levels are at the same # position as the velocity levels. dz = np.nan * np.ones((N, 1, 1)) dz[1:, 0, 0]= np.diff(z) dz[0, 0, 0] = dz[1, 0, 0] # account for the fact that the new hycom fields do not show up masked u3d = np.ma.masked_where(np.isnan(b['u3d']),b['u3d']) v3d = np.ma.masked_where(np.isnan(b['v3d']),b['v3d']) dz3 = dz * np.ones_like(u3d) # make dz a masked array b['ubar'] = np.sum(u3d*dz3, axis=0) / np.sum(dz3, axis=0) b['vbar'] = np.sum(v3d*dz3, axis=0) / np.sum(dz3, axis=0) for vn in ['ubar', 'vbar']: v = b[vn] vv = v.copy() vv = np.ma.masked_where(np.isnan(vv), vv) vv[vv.mask] = 0 V[vn] = vv.data # calculate potential temperature press_db = -z.reshape((N,1,1)) V['theta'] = seawater.ptmp(V['s3d'], V['t3d'], press_db) return V
no3_qf = infil[:, 18] si = infil[:, 19] si_qf = infil[:, 20] po4 = infil[:, 21] po4_qf = infil[:, 22] pH_obs = infil[:, 23] pH_obs_qf = infil[:, 24] #============================================================================# # CALCULATE DERIVED PROPERTIES # #============================================================================# # density vector and sigma theta dens = sw.dens(S, T, P) sigmaT = 1000. - dens ptmp = sw.ptmp(S, T, P, 0.) dens_ze = sw.dens(S, ptmp, 0.) sigma_theta = dens_ze - 1000. # unit conversions raw data - all to umol/kg ox_kg = ox / 0.0223916 / dens * 1000. no3_kg = no3 / dens * 1000. si_kg = si / dens * 1000. po4_kg = po4 / dens * 1000. #============================================================================# # CREATE DATA MASKS # #============================================================================# ox_qc = ((ox_qf == 2) | (ox_qf == 6)) & (ox > 0.0) dic_qc = ((dic_qf == 2) | (dic_qf == 6) | (dic_qf == 10)) & (dic > 0.0)
nc = Dataset(fnamen) try: U = nc.variables['UVEL'][0, ...][:, :fcap, :] * cm2m V = nc.variables['VVEL'][0, ...][:, :fcap, :] * cm2m T = nc.variables['TEMP'][0, ...][:, :fcap, :] S = nc.variables['SALT'][0, ...][:, :fcap, :] SHF = nc.variables['SHF'][0, ...][:fcap, :][msk] except KeyError: print("Skipping corrupted file: %s" % fnamen) continue t.append(ti) Ssec = S[:, ii, ji] # Practical salinity. Tfm = Tinsitu_freezing_eos80(Ssec, p[:, np.newaxis]) Tfm = ptmp( Ssec, Tfm, p[:, np.newaxis], pr=0 ) # In situ temperature of freezing to potential temperature of freezing (which is the model variable). fisob = z > -isob # Only down to the depth of the middle isobath. Tfmin = Tfm[fisob, :].min() print("") print("[%s] Minimum freezing T along %d m isobath: %.3f degC" % (ti, isob, Tfmin)) if CALC_minimumTf_ONLY: Tfmins.append(Tfmin) continue eta = nc.variables['SSH'][0, :fcap, :] * cm2m srfcvol_fac = np.ones((ny, nx)) csi = eta / DZT0[0, :, :] srfcvol_fac = srfcvol_fac + csi
def __init__(self, path, climname='woa05', record=0): if climname == 'woa05': ncfile = Dataset(os.path.join(path, 'woa2005TS.nc')) self.T = np.copy(ncfile.variables['t00an1'][0, :, :, :]) x = np.copy(ncfile.variables['lon'][:]) x[x > 180] = x[x > 180] - 360 ind = [i[0] for i in sorted(enumerate(x), key=lambda x: x[1])] x = np.sort(x) self.x = x self.y = ncfile.variables['lat'][:] self.z = ncfile.variables['depth'][:] self.T[:, :, :] = self.T[:, :, ind] self.S = np.copy(ncfile.variables['s00an1'][0, :, :, :]) self.S[:, :, :] = self.S[:, :, ind] depth3d = np.zeros(self.S.shape) for i in range(self.z.shape[0]): depth3d[i, :, :] = self.z[i] ptemp = sw.ptmp(self.S, self.T, depth3d) self.T = ptemp ncfile.close() self.Tyz = nanmean(self.T, 2) self.Syz = nanmean(self.S, 2) self.T = np.ma.masked_greater(self.T, 1000) self.S = np.ma.masked_greater(self.S, 1000) if climname == 'phc': ncfile = Dataset(os.path.join(path, 'phc3.0_annual.nc')) self.T = np.copy(ncfile.variables['temp'][:, :, :]) x = np.copy(ncfile.variables['lon'][:]) x[x > 180] = x[x > 180] - 360 ind = [i[0] for i in sorted(enumerate(x), key=lambda x: x[1])] x = np.sort(x) self.x = x self.y = ncfile.variables['lat'][:] self.z = ncfile.variables['depth'][:] self.T[:, :, :] = self.T[:, :, ind] self.S = np.copy(ncfile.variables['salt'][:, :, :]) self.S[:, :, :] = self.S[:, :, ind] depth3d = np.zeros(self.S.shape) for i in range(self.z.shape[0]): depth3d[i, :, :] = self.z[i] ptemp = sw.ptmp(self.S, self.T, depth3d) self.T = ptemp ncfile.close() self.Tyz = nanmean(self.T, 2) self.Syz = nanmean(self.S, 2) if climname == 'gdem': ncfile = Dataset(os.path.join(path, 'gdemv3s_tm.nc')) self.T = np.copy(ncfile.variables['water_temp'][0, :, :, :]) x = np.copy(ncfile.variables['lon'][:]) x[x > 180] = x[x > 180] - 360 ind = [i[0] for i in sorted(enumerate(x), key=lambda x: x[1])] x = np.sort(x) self.x = x self.y = ncfile.variables['lat'][:] self.z = ncfile.variables['depth'][:] self.T[:, :, :] = self.T[:, :, ind] self.S = np.copy(ncfile.variables['salinity'][0, :, :, :]) self.S[:, :, :] = self.S[:, :, ind] depth3d = np.zeros(self.S.shape) for i in range(self.z.shape[0]): depth3d[i, :, :] = self.z[i] ptemp = sw.ptmp(self.S, self.T, depth3d) self.T = ptemp ncfile.close() self.Tyz = nanmean(self.T, 2) self.Syz = nanmean(self.S, 2) self.T = np.ma.masked_less(self.T, -1000) self.S = np.ma.masked_less(self.S, -1000) if climname == 'en4': ncfile = Dataset(os.path.join(path, 'en4_monthly.nc')) self.T = np.copy(ncfile.variables['temperature'][record, :, :, :]) x = np.copy(ncfile.variables['lon'][:]) x[x > 180] = x[x > 180] - 360 ind = [i[0] for i in sorted(enumerate(x), key=lambda x: x[1])] x = np.sort(x) self.x = x self.y = ncfile.variables['lat'][:] self.z = ncfile.variables['depth'][:] self.T[:, :, :] = self.T[:, :, ind] self.T[:, :, :] = self.T[:, :, :] - 273.15 self.S = np.copy(ncfile.variables['salinity'][record, :, :, :]) self.S[:, :, :] = self.S[:, :, ind] depth3d = np.zeros(self.S.shape) for i in range(self.z.shape[0]): depth3d[i, :, :] = self.z[i] ptemp = sw.ptmp(self.S, self.T, depth3d) self.T = ptemp ncfile.close() self.Tyz = nanmean(self.T, 2) self.Syz = nanmean(self.S, 2) self.T = np.ma.masked_less(self.T, -1000) self.S = np.ma.masked_less(self.S, -1000)
def test(fileout='python-test.txt'): r"""Copy of the Matlab test. Modifications: Phil Morgan 03-12-12. Lindsay Pender, Converted to ITS-90. """ f = open(fileout, 'w') asterisks = '*' * 76 f.write(asterisks) f.write('\n TEST REPORT ') f.write('\n') f.write('\n SEA WATER LIBRARY %s' % sw.__version__) f.write('\n') # Show some info about this Python. f.write('\npython version: %s' % sys.version) f.write('\n on %s computer %s' % (uname()[0], uname()[-1])) f.write('\n') f.write('\n') f.write(asctime(localtime())) f.write('\n') f.write('\n') # Test main module ptmp. f.write('\n%s' % asterisks) f.write('\n** TESTING MODULE: ptmp') f.write('\n** and SUB-MODULE: adtg') f.write('\n%s' % asterisks) f.write('\n') f.write('\n') # Test 1 - data from Unesco 1983 p45. T = np.array([[0, 0, 0, 0, 0, 0], [10, 10, 10, 10, 10, 10], [20, 20, 20, 20, 20, 20], [30, 30, 30, 30, 30, 30], [40, 40, 40, 40, 40, 40]]) T = T / 1.00024 S = np.array([[25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35]]) P = np.array([[0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000]]) Pr = np.array([0, 0, 0, 0, 0, 0]) UN_ptmp = np.array([[0, -0.3061, -0.9667, 0, -0.3856, -1.0974], [10, 9.3531, 8.4684, 10, 9.2906, 8.3643], [20, 19.0438, 17.9426, 20, 18.9985, 17.8654], [30, 28.7512, 27.4353, 30, 28.7231, 27.3851], [40, 38.4607, 36.9254, 40, 38.4498, 36.9023]]) PT = sw.ptmp(S, T, P, Pr) * 1.00024 # Display results. f.write('\n') f.write('\n%s' % asterisks) f.write('\nComparison of accepted values from UNESCO 1983 ') f.write('\n (Unesco Tech. Paper in Marine Sci. No. 44, p45)') f.write('\n%s' % asterisks) f.write('\n') m, n = S.shape # TODO: so many loops there must be a better way. for icol in range(0, n): f.write('\n Sal Temp Press PTMP ptmp') f.write('\n (psu) (C) (db) (C) (C)\n') result = np.vstack((S[:, icol], T[:, icol], P[:, icol], UN_ptmp[:, icol], PT[:, icol])) for iline in range(0, m): f.write(" %4.0f %4.0f %5.0f %8.4f %11.5f\n" % tuple(result[:, iline])) # Test main module svan. f.write('\n%s' % asterisks) f.write('\n** TESTING MODULE: svan') f.write('\n** and SUB-MODULE: dens dens0 smow seck pden ptmp') f.write('\n%s' % asterisks) # Test data FROM: Unesco Tech. Paper in Marine Sci. No. 44, p22. s = np.array([0, 0, 0, 0, 35, 35, 35, 35]) p = np.array([0, 10000, 0, 10000, 0, 10000, 0, 10000]) t = np.array([0, 0, 30, 30, 0, 0, 30, 30]) / 1.00024 UN_svan = np.array([2749.54, 2288.61, 3170.58, 3147.85, 0.0, 0.00, 607.14, 916.34]) SVAN = sw.svan(s, t, p) # DISPLAY RESULTS f.write('\n') f.write('\n%s' % asterisks) f.write('\n') f.write('\nComparison of accepted values from UNESCO 1983') f.write('\n (Unesco Tech. Paper in Marine Sci. No. 44, p22)') f.write('\n%s' % asterisks) f.write('\n') f.write('\n Sal Temp Press SVAN svan') f.write('\n (psu) (C) (db) (1e-8*m3/kg) (1e-8*m3/kg)\n') result = np.vstack([s, t, p, UN_svan, 1e+8 * SVAN]) for iline in range(0, len(SVAN)): f.write(" %4.0f %4.0f %5.0f %11.2f %11.3f\n" % tuple(result[:, iline])) # Test main module salt. f.write('\n%s' % asterisks) f.write('\n** TESTING MODULE: salt') f.write('\n** and SUB-MODULE: salrt salrp sals') f.write('\n%s' % asterisks) f.write('\n') # Test 1 - data from Unesco 1983 p9. R = np.array([1, 1.2, 0.65]) # cndr = R. T = np.array([15, 20, 5]) / 1.00024 P = np.array([0, 2000, 1500]) #Rt = np.array([ 1, 1.0568875, 0.81705885]) UN_S = np.array([35, 37.245628, 27.995347]) S = sw.salt(R, T, P) # Display results. f.write('\n') f.write('\n%s' % asterisks) f.write('\nComparison of accepted values from UNESCO 1983 ') f.write('\n(Unesco Tech. Paper in Marine Sci. No. 44, p9)') f.write('\n%s' % asterisks) f.write('\n') f.write('\n Temp Press R S salt') f.write('\n (C) (db) (no units) (psu) (psu)\n') table = np.vstack([T, P, R, UN_S, S]) m, n = table.shape for iline in range(0, n): f.write(" %4.0f %4.0f %8.2f %11.6f %14.7f\n" % tuple(table[:, iline])) # Test main module cndr. f.write('\n%s' % asterisks) f.write('\n** TESTING MODULE: cndr') f.write('\n** and SUB-MODULE: salds') f.write('\n%s' % asterisks) # Test 1 - data from Unesco 1983 p9. T = np.array([0, 10, 0, 10, 10, 30]) / 1.00024 P = np.array([0, 0, 1000, 1000, 0, 0]) S = np.array([25, 25, 25, 25, 40, 40]) UN_R = np.array([0.498088, 0.654990, 0.506244, 0.662975, 1.000073, 1.529967]) R = sw.cndr(S, T, P) # Display results. f.write('\n') f.write('\n%s' % asterisks) f.write('\nComparison of accepted values from UNESCO 1983 ') f.write('\n (Unesco Tech. Paper in Marine Sci. No. 44, p14)') f.write('\n%s' % asterisks) f.write('\n') f.write('\n') f.write('\n Temp Press S cndr cndr') f.write('\n (C) (db) (psu) (no units) (no units)\n') table = np.vstack([T, P, S, UN_R, R]) m, n = table.shape for iline in range(0, n): f.write(" %4.0f %4.0f %8.6f %11.6f %14.8f\n" % tuple(table[:, iline])) # Test main module depth. f.write('\n%s' % asterisks) f.write('\n** TESTING MODULE: depth') f.write('\n%s' % asterisks) # Test data - matrix "pressure", vector "lat" Unesco 1983 data p30. lat = np.array([0, 30, 45, 90]) P = np.array([[500, 500, 500, 500], [5000, 5000, 5000, 5000], [10000, 10000, 10000, 10000]]) UN_dpth = np.array([[496.65, 496.00, 495.34, 494.03], [4915.04, 4908.56, 4902.08, 4889.13], [9725.47, 9712.65, 9699.84, 9674.23]]) dpth = sw.dpth(P, lat) # Display results. f.write('\n') f.write('\n%s' % asterisks) f.write('\nComparison of accepted values from Unesco 1983 ') f.write('\n(Unesco Tech. Paper in Marine Sci. No. 44, p28)') f.write('\n%s' % asterisks) f.write('\n') f.write('\n') for irow in range(0, 3): f.write('\n Lat Press DPTH dpth') f.write('\n (degree) (db) (meter) (meter)\n') table = np.vstack([lat, P[irow, :], UN_dpth[irow, :], dpth[irow, :]]) m, n = table.shape for iline in range(0, n): f.write(" %6.3f %6.0f %8.2f %8.3f\n" % tuple(table[:, iline])) # Test main module fp. f.write('\n%s' % asterisks) f.write('\n** TESTING MODULE: fp') f.write('\n%s' % asterisks) # Test 1 - UNESCO data p.30. S = np.array([[5, 10, 15, 20, 25, 30, 35, 40], [5, 10, 15, 20, 25, 30, 35, 40]]) P = np.array([[0, 0, 0, 0, 0, 0, 0, 0], [500, 500, 500, 500, 500, 500, 500, 500]]) UN_fp = np.array([[-0.274, -0.542, -0.812, -1.083, -1.358, -1.638, -1.922, -2.212], [-0.650, -0.919, -1.188, -1.460, -1.735, -2.014, -2.299, -2.589]]) FP = sw.fp(S, P) # Display results. f.write('\n') f.write('\n%s' % asterisks) f.write('\nComparison of accepted values from UNESCO 1983 ') f.write('\n (Unesco Tech. Paper in Marine Sci. No. 44, p30)') f.write('\n%s' % asterisks) f.write('\n') f.write('\n') for irow in range(0, 2): f.write('\n Sal Press fp fp') f.write('\n (psu) (db) (C) (C)\n') table = np.vstack([S[irow, :], P[irow, :], UN_fp[irow, :], FP[irow, :]]) m, n = table.shape for iline in range(0, n): f.write(" %4.0f %5.0f %8.3f %11.4f\n" % tuple(table[:, iline])) # Test main module cp. f.write('\n%s' % asterisks) f.write('\n** TESTING MODULE: cp') f.write('\n%s' % asterisks) # Test 1. # Data from Pond and Pickard Intro. Dynamical Oceanography 2nd ed. 1986 T = np.array([[0, 0, 0, 0, 0, 0], [10, 10, 10, 10, 10, 10], [20, 20, 20, 20, 20, 20], [30, 30, 30, 30, 30, 30], [40, 40, 40, 40, 40, 40]]) / 1.00024 S = np.array([[25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35]]) P = np.array([[0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000]]) UN_cp = np.array([[4048.4, 3896.3, 3807.7, 3986.5, 3849.3, 3769.1], [4041.8, 3919.6, 3842.3, 3986.3, 3874.7, 3804.4], [4044.8, 3938.6, 3866.7, 3993.9, 3895.0, 3828.3], [4049.1, 3952.0, 3883.0, 4000.7, 3909.2, 3844.3], [4051.2, 3966.1, 3905.9, 4003.5, 3923.9, 3868.3]]) CP = sw.cp(S, T, P) # Display results. f.write('\n') f.write('\n%s' % asterisks) f.write('\nComparison of accepted values from UNESCO 1983 ') f.write('\n (Unesco Tech. Paper in Marine Sci. No. 44, p37)') f.write('\n%s' % asterisks) f.write('\n') m, n = S.shape f.write('\n') for icol in range(0, n): f.write('\n Sal Temp Press Cp cp') f.write('\n (psu) (C) (db) (J/kg.C) (J/kg.C)\n') result = np.vstack([S[:, icol], T[:, icol], P[:, icol], UN_cp[:, icol], CP[:, icol]]) for iline in range(0, m): f.write(" %4.0f %4.0f %5.0f %8.1f %11.2f\n" % tuple(result[:, iline])) # Test main module svel. f.write('\n%s' % asterisks) f.write('\n** TESTING MODULE: svel') f.write('\n%s' % asterisks) # Test 1. # Data from Pond and Pickard Intro. Dynamical Oceanography 2nd ed. 1986 T = np.array([[0, 0, 0, 0, 0, 0], [10, 10, 10, 10, 10, 10], [20, 20, 20, 20, 20, 20], [30, 30, 30, 30, 30, 30], [40, 40, 40, 40, 40, 40]]) / 1.00024 S = np.array([[25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35]]) P = np.array([[0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000]]) UN_svel = np.array([[1435.8, 1520.4, 1610.4, 1449.1, 1534.0, 1623.2], [1477.7, 1561.3, 1647.4, 1489.8, 1573.4, 1659.0], [1510.3, 1593.6, 1676.8, 1521.5, 1604.5, 1687.2], [1535.2, 1619.0, 1700.6, 1545.6, 1629.0, 1710.1], [1553.4, 1638.0, 1719.2, 1563.2, 1647.3, 1727.8]]) SVEL = sw.svel(S, T, P) # Display results. f.write('\n') f.write('\n%s' % asterisks) f.write('\nComparison of accepted values from UNESCO 1983 ') f.write('\n (Unesco Tech. Paper in Marine Sci. No. 44, p50)') f.write('\n%s' % asterisks) f.write('\n') m, n = SVEL.shape f.write('\n') for icol in range(0, n): f.write('\n Sal Temp Press SVEL svel') f.write('\n (psu) (C) (db) (m/s) (m/s)\n') result = np.vstack([S[:, icol], T[:, icol], P[:, icol], UN_svel[:, icol], SVEL[:, icol]]) for iline in range(0, m): f.write(" %4.0f %4.0f %5.0f %8.1f %11.3f\n" % tuple(result[:, iline])) # Test submodules alpha beta aonb. f.write('\n%s' % asterisks) f.write('\n** and SUB-MODULE: alpha beta aonb') f.write('\n%s' % asterisks) # Data from McDouogall 1987. s = 40 PT = 10 p = 4000 beta_lit = 0.72088e-03 aonb_lit = 0.34763 alpha_lit = aonb_lit * beta_lit BETA = sw.beta(s, PT, p, pt=True) ALPHA = sw.alpha(s, PT, p, pt=True) AONB = sw.aonb(s, PT, p, pt=True) # Display results. f.write('\n') f.write('\n%s' % asterisks) f.write('\nComparison of accepted values from MCDOUGALL 1987 ') f.write('\n%s' % asterisks) f.write('\n') f.write('\n') f.write('\n Sal Temp Press BETA beta') f.write('\n (psu) (C) (db) (psu^-1) (psu^-1)\n') table = np.hstack([s, PT, p, beta_lit, BETA]) f.write(" %4.0f %4.0f %5.0f %11.4e %11.5e\n" % tuple(table)) f.write('\n Sal Temp Press AONB aonb') f.write('\n (psu) (C) (db) (psu C^-1) (psu C^-1)\n') table = np.hstack([s, PT, p, aonb_lit, AONB]) f.write(" %4.0f %4.0f %5.0f %8.5f %11.6f\n" % tuple(table)) f.write('\n Sal Temp Press ALPHA alpha') f.write('\n (psu) (C) (db) (psu^-1) (psu^-1)\n') table = np.hstack([s, PT, p, alpha_lit, ALPHA]) f.write(" %4.0f %4.0f %5.0f %11.4e %11.4e\n" % tuple(table)) # Test main moduleS satO2 satN2 satAr. f.write('\n%s' % asterisks) f.write('\n** TESTING MODULE: satO2 satN2 satAr') f.write('\n%s' % asterisks) f.write('\n') # Data from Weiss 1970. T = np.array([[-1, -1], [10, 10], [20, 20], [40, 40]]) / 1.00024 S = np.array([[20, 40], [20, 40], [20, 40], [20, 40]]) lit_O2 = np.array([[9.162, 7.984], [6.950, 6.121], [5.644, 5.015], [4.050, 3.656]]) lit_N2 = np.array([[16.28, 14.01], [12.64, 11.01], [10.47, 9.21], [7.78, 6.95]]) lit_Ar = np.array([[0.4456, 0.3877], [0.3397, 0.2989], [0.2766, 0.2457], [0.1986, 0.1794]]) O2 = sw.satO2(S, T) N2 = sw.satN2(S, T) Ar = sw.satAr(S, T) # Display results. f.write('\n') f.write('\n%s' % asterisks) f.write('\nComparison of accepted values from Weiss, R.F. 1979 ') f.write('\n"The solubility of nitrogen, oxygen and argon in water') f.write('\n and seawater." Deep-Sea Research., 1970, Vol 17, pp721-735.') f.write('\n%s' % asterisks) f.write('\n') m, n = S.shape f.write('\n') for icol in range(0, n): f.write('\n Sal Temp O2 satO2') f.write('\n (psu) (C) (ml/l) (ml/l)\n') result = np.vstack([S[:, icol], T[:, icol], lit_O2[:, icol], O2[:, icol]]) for iline in range(0, m): f.write(" %4.0f %4.0f %8.2f %9.3f\n" % tuple(result[:, iline])) for icol in range(0, n): f.write('\n Sal Temp N2 satN2') f.write('\n (psu) (C) (ml/l) (ml/l)\n') result = np.vstack([S[:, icol], T[:, icol], lit_N2[:, icol], N2[:, icol]]) for iline in range(0, m): f.write(" %4.0f %4.0f %8.2f %9.3f\n" % tuple(result[:, iline])) for icol in range(0, n): f.write('\n Sal Temp Ar satAr') f.write('\n (psu) (C) (ml/l) (ml/l)\n') result = np.vstack([S[:, icol], T[:, icol], lit_Ar[:, icol], Ar[:, icol]]) for iline in range(0, m): f.write(" %4.0f %4.0f %8.4f %9.4f\n" % tuple(result[:, iline]))
import seawater import numpy as np # artemis dirwoa = '/local/data/artemis/workspace/rdussin/Observations/WOA13/' dirgrid = '/local/data/artemis/workspace/rdussin/ASTE/GRID/' dirout = '/local/data/artemis/workspace/rdussin/Observations/WOA13/interp_ASTE/' woa_global = xr.open_mfdataset(dirwoa + 'woa13_decav_[t,s]??_01.nc', decode_times=False) # compute pot temperature pres = np.zeros(woa_global['s_an'].values.shape) for k in np.arange(woa_global['depth'].shape[0]): pres[:, k, :, :] = woa_global['depth'].values[k] woa_global['theta'] = xr.DataArray(seawater.ptmp(woa_global['s_an'], woa_global['t_an'], pres), coords=woa_global['s_an'].coords, dims=woa_global['s_an'].dims) variables2regrid = ['theta'] #--------------- FACET 1 --------------------- aste_grid1 = xr.open_dataset(dirgrid + 'ASTE_FACET1.nc') Regrid2ASTE1 = Regrid2MITgcm(aste_grid1) interpolated1 = Regrid2ASTE1.regrid(woa_global, variables2regrid, 'lon', 'lat', depthvarname='depth', method='bilinear', blend_missing=False, periodicity=0,
ax.set_title(f"Vertical Salinity section for float {prof.PLATFORM_NUMBER[0].astype(str).values}") ax.set_xlabel(f"{prof.JULD.standard_name}") ax.set_ylabel(f"{prof.PRES.long_name}") cbar=fig.colorbar(cs,ax=ax) or a TS diagram using the hydrographic data in `TEMP` and `PSAl` import seawater as sw temp=prof.TEMP.values.flatten() psal=prof.PSAL.values.flatten() pres=prof.PRES.values.flatten() ptmp=sw.ptmp(psal, temp, pres, pr=0) t_bins = np.linspace(2, 25, 200) s_bins = np.linspace(35, 37.25, 200) hist, xedges, yedges = np.histogram2d(psal, ptmp, (s_bins, t_bins)) xidx = np.clip(np.digitize(psal, xedges), 0, hist.shape[0]-1) yidx = np.clip(np.digitize(ptmp, yedges), 0, hist.shape[1]-1) c = hist[xidx, yidx] fig, ax = plt.subplots(figsize=(10,10)) sc=ax.scatter(psal, ptmp, c=c,alpha=0.5, cmap="RdBu_r",vmin=0, vmax=10) ax.set_title(f"T/S diagram for float {prof.PLATFORM_NUMBER[0].astype(str).values}") ax.set_ylabel("potential temperature") ax.set_xlabel(f"{prof.PSAL.long_name}") fig.colorbar(sc,extend='both');
MP['lat']) MP['z_mid'] = gsw.z_from_p(MP['P_mid'], MP['lat']) MP['ual'], MP['uac'] = rotate_overflow(MP['u'], MP['v'], MP['sig4'], sig4max) print('- Calculating the overflow integrated velocity') ual_ = MP['ual'].copy() uac_ = MP['uac'].copy() mask = MP['sig4'] < sig4max ual_[mask] = np.nan uac_[mask] = np.nan MP['uoal'] = utils.nantrapz(ual_, x=MP['z'], axis=0, xave=True) MP['uoac'] = utils.nantrapz(uac_, x=MP['z'], axis=0, xave=True) print('- Calculating neutral density') MP['PT0'] = seawater.ptmp(MP['S'], MP['T'], MP['P']) # Flatten variables for analysis. S = MP['S'].flatten() T = MP['PT0'].flatten() P = MP['P'].flatten() LO = MP['lon'] * np.ones_like(S) LA = MP['lat'] * np.ones_like(S) gamman = gamma_GP_from_SP_pt(S, T, P, LO, LA) MP['gamman'] = np.reshape(gamman, MP['S'].shape) + 1000. MP['gamman_sorted'] = utils.nansort(MP['gamman'], axis=0) MP['gammanm'] = np.nanmean(MP['gamman']) MP['N2_sorted'] = -MP['g']*np.gradient(MP['sig4_sorted'], axis=0) \ / (MP['sig4m']*np.gradient(MP['z'], axis=0)) print('- Calculating dissipation rate')
def test(fileout='python-test.txt'): r"""Copy of the Matlab test. Modifications: Phil Morgan 03-12-12. Lindsay Pender, Converted to ITS-90. """ f = open(fileout, 'w') asterisks = '*' * 76 f.write(asterisks) f.write('\n TEST REPORT ') f.write('\n') f.write('\n SEA WATER LIBRARY %s' % sw.__version__) f.write('\n') # Show some info about this Python. f.write('\npython version: %s' % sys.version) f.write('\n on %s computer %s' % (uname()[0], uname()[-1])) f.write('\n') f.write('\n') f.write(asctime(localtime())) f.write('\n') f.write('\n') # Test main module ptmp. f.write('\n%s' % asterisks) f.write('\n** TESTING MODULE: ptmp') f.write('\n** and SUB-MODULE: adtg') f.write('\n%s' % asterisks) f.write('\n') f.write('\n') # Test 1 - data from Unesco 1983 p45. T = np.array([[0, 0, 0, 0, 0, 0], [10, 10, 10, 10, 10, 10], [20, 20, 20, 20, 20, 20], [30, 30, 30, 30, 30, 30], [40, 40, 40, 40, 40, 40]]) T = T / 1.00024 S = np.array([[25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35]]) P = np.array([[0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000]]) Pr = np.array([0, 0, 0, 0, 0, 0]) UN_ptmp = np.array([[0, -0.3061, -0.9667, 0, -0.3856, -1.0974], [10, 9.3531, 8.4684, 10, 9.2906, 8.3643], [20, 19.0438, 17.9426, 20, 18.9985, 17.8654], [30, 28.7512, 27.4353, 30, 28.7231, 27.3851], [40, 38.4607, 36.9254, 40, 38.4498, 36.9023]]) PT = sw.ptmp(S, T, P, Pr) * 1.00024 # Display results. f.write('\n') f.write('\n%s' % asterisks) f.write('\nComparison of accepted values from UNESCO 1983 ') f.write('\n (Unesco Tech. Paper in Marine Sci. No. 44, p45)') f.write('\n%s' % asterisks) f.write('\n') m, n = S.shape # TODO: so many loops there must be a better way. for icol in range(0, n): f.write('\n Sal Temp Press PTMP ptmp') f.write('\n (psu) (C) (db) (C) (C)\n') result = np.vstack( (S[:, icol], T[:, icol], P[:, icol], UN_ptmp[:, icol], PT[:, icol])) for iline in range(0, m): f.write(" %4.0f %4.0f %5.0f %8.4f %11.5f\n" % tuple(result[:, iline])) # Test main module svan. f.write('\n%s' % asterisks) f.write('\n** TESTING MODULE: svan') f.write('\n** and SUB-MODULE: dens dens0 smow seck pden ptmp') f.write('\n%s' % asterisks) # Test data FROM: Unesco Tech. Paper in Marine Sci. No. 44, p22. s = np.array([0, 0, 0, 0, 35, 35, 35, 35]) p = np.array([0, 10000, 0, 10000, 0, 10000, 0, 10000]) t = np.array([0, 0, 30, 30, 0, 0, 30, 30]) / 1.00024 UN_svan = np.array( [2749.54, 2288.61, 3170.58, 3147.85, 0.0, 0.00, 607.14, 916.34]) SVAN = sw.svan(s, t, p) # DISPLAY RESULTS f.write('\n') f.write('\n%s' % asterisks) f.write('\n') f.write('\nComparison of accepted values from UNESCO 1983') f.write('\n (Unesco Tech. Paper in Marine Sci. No. 44, p22)') f.write('\n%s' % asterisks) f.write('\n') f.write('\n Sal Temp Press SVAN svan') f.write('\n (psu) (C) (db) (1e-8*m3/kg) (1e-8*m3/kg)\n') result = np.vstack([s, t, p, UN_svan, 1e+8 * SVAN]) for iline in range(0, len(SVAN)): f.write(" %4.0f %4.0f %5.0f %11.2f %11.3f\n" % tuple(result[:, iline])) # Test main module salt. f.write('\n%s' % asterisks) f.write('\n** TESTING MODULE: salt') f.write('\n** and SUB-MODULE: salrt salrp sals') f.write('\n%s' % asterisks) f.write('\n') # Test 1 - data from Unesco 1983 p9. R = np.array([1, 1.2, 0.65]) # cndr = R. T = np.array([15, 20, 5]) / 1.00024 P = np.array([0, 2000, 1500]) #Rt = np.array([ 1, 1.0568875, 0.81705885]) UN_S = np.array([35, 37.245628, 27.995347]) S = sw.salt(R, T, P) # Display results. f.write('\n') f.write('\n%s' % asterisks) f.write('\nComparison of accepted values from UNESCO 1983 ') f.write('\n(Unesco Tech. Paper in Marine Sci. No. 44, p9)') f.write('\n%s' % asterisks) f.write('\n') f.write('\n Temp Press R S salt') f.write('\n (C) (db) (no units) (psu) (psu)\n') table = np.vstack([T, P, R, UN_S, S]) m, n = table.shape for iline in range(0, n): f.write(" %4.0f %4.0f %8.2f %11.6f %14.7f\n" % tuple(table[:, iline])) # Test main module cndr. f.write('\n%s' % asterisks) f.write('\n** TESTING MODULE: cndr') f.write('\n** and SUB-MODULE: salds') f.write('\n%s' % asterisks) # Test 1 - data from Unesco 1983 p9. T = np.array([0, 10, 0, 10, 10, 30]) / 1.00024 P = np.array([0, 0, 1000, 1000, 0, 0]) S = np.array([25, 25, 25, 25, 40, 40]) UN_R = np.array( [0.498088, 0.654990, 0.506244, 0.662975, 1.000073, 1.529967]) R = sw.cndr(S, T, P) # Display results. f.write('\n') f.write('\n%s' % asterisks) f.write('\nComparison of accepted values from UNESCO 1983 ') f.write('\n (Unesco Tech. Paper in Marine Sci. No. 44, p14)') f.write('\n%s' % asterisks) f.write('\n') f.write('\n') f.write('\n Temp Press S cndr cndr') f.write('\n (C) (db) (psu) (no units) (no units)\n') table = np.vstack([T, P, S, UN_R, R]) m, n = table.shape for iline in range(0, n): f.write(" %4.0f %4.0f %8.6f %11.6f %14.8f\n" % tuple(table[:, iline])) # Test main module depth. f.write('\n%s' % asterisks) f.write('\n** TESTING MODULE: depth') f.write('\n%s' % asterisks) # Test data - matrix "pressure", vector "lat" Unesco 1983 data p30. lat = np.array([0, 30, 45, 90]) P = np.array([[500, 500, 500, 500], [5000, 5000, 5000, 5000], [10000, 10000, 10000, 10000]]) UN_dpth = np.array([[496.65, 496.00, 495.34, 494.03], [4915.04, 4908.56, 4902.08, 4889.13], [9725.47, 9712.65, 9699.84, 9674.23]]) dpth = sw.dpth(P, lat) # Display results. f.write('\n') f.write('\n%s' % asterisks) f.write('\nComparison of accepted values from Unesco 1983 ') f.write('\n(Unesco Tech. Paper in Marine Sci. No. 44, p28)') f.write('\n%s' % asterisks) f.write('\n') f.write('\n') for irow in range(0, 3): f.write('\n Lat Press DPTH dpth') f.write('\n (degree) (db) (meter) (meter)\n') table = np.vstack([lat, P[irow, :], UN_dpth[irow, :], dpth[irow, :]]) m, n = table.shape for iline in range(0, n): f.write(" %6.3f %6.0f %8.2f %8.3f\n" % tuple(table[:, iline])) # Test main module fp. f.write('\n%s' % asterisks) f.write('\n** TESTING MODULE: fp') f.write('\n%s' % asterisks) # Test 1 - UNESCO data p.30. S = np.array([[5, 10, 15, 20, 25, 30, 35, 40], [5, 10, 15, 20, 25, 30, 35, 40]]) P = np.array([[0, 0, 0, 0, 0, 0, 0, 0], [500, 500, 500, 500, 500, 500, 500, 500]]) UN_fp = np.array( [[-0.274, -0.542, -0.812, -1.083, -1.358, -1.638, -1.922, -2.212], [-0.650, -0.919, -1.188, -1.460, -1.735, -2.014, -2.299, -2.589]]) FP = sw.fp(S, P) # Display results. f.write('\n') f.write('\n%s' % asterisks) f.write('\nComparison of accepted values from UNESCO 1983 ') f.write('\n (Unesco Tech. Paper in Marine Sci. No. 44, p30)') f.write('\n%s' % asterisks) f.write('\n') f.write('\n') for irow in range(0, 2): f.write('\n Sal Press fp fp') f.write('\n (psu) (db) (C) (C)\n') table = np.vstack( [S[irow, :], P[irow, :], UN_fp[irow, :], FP[irow, :]]) m, n = table.shape for iline in range(0, n): f.write(" %4.0f %5.0f %8.3f %11.4f\n" % tuple(table[:, iline])) # Test main module cp. f.write('\n%s' % asterisks) f.write('\n** TESTING MODULE: cp') f.write('\n%s' % asterisks) # Test 1. # Data from Pond and Pickard Intro. Dynamical Oceanography 2nd ed. 1986 T = np.array([[0, 0, 0, 0, 0, 0], [10, 10, 10, 10, 10, 10], [20, 20, 20, 20, 20, 20], [30, 30, 30, 30, 30, 30], [40, 40, 40, 40, 40, 40]]) / 1.00024 S = np.array([[25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35]]) P = np.array([[0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000]]) UN_cp = np.array([[4048.4, 3896.3, 3807.7, 3986.5, 3849.3, 3769.1], [4041.8, 3919.6, 3842.3, 3986.3, 3874.7, 3804.4], [4044.8, 3938.6, 3866.7, 3993.9, 3895.0, 3828.3], [4049.1, 3952.0, 3883.0, 4000.7, 3909.2, 3844.3], [4051.2, 3966.1, 3905.9, 4003.5, 3923.9, 3868.3]]) CP = sw.cp(S, T, P) # Display results. f.write('\n') f.write('\n%s' % asterisks) f.write('\nComparison of accepted values from UNESCO 1983 ') f.write('\n (Unesco Tech. Paper in Marine Sci. No. 44, p37)') f.write('\n%s' % asterisks) f.write('\n') m, n = S.shape f.write('\n') for icol in range(0, n): f.write('\n Sal Temp Press Cp cp') f.write('\n (psu) (C) (db) (J/kg.C) (J/kg.C)\n') result = np.vstack( [S[:, icol], T[:, icol], P[:, icol], UN_cp[:, icol], CP[:, icol]]) for iline in range(0, m): f.write(" %4.0f %4.0f %5.0f %8.1f %11.2f\n" % tuple(result[:, iline])) # Test main module svel. f.write('\n%s' % asterisks) f.write('\n** TESTING MODULE: svel') f.write('\n%s' % asterisks) # Test 1. # Data from Pond and Pickard Intro. Dynamical Oceanography 2nd ed. 1986 T = np.array([[0, 0, 0, 0, 0, 0], [10, 10, 10, 10, 10, 10], [20, 20, 20, 20, 20, 20], [30, 30, 30, 30, 30, 30], [40, 40, 40, 40, 40, 40]]) / 1.00024 S = np.array([[25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35], [25, 25, 25, 35, 35, 35]]) P = np.array([[0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000], [0, 5000, 10000, 0, 5000, 10000]]) UN_svel = np.array([[1435.8, 1520.4, 1610.4, 1449.1, 1534.0, 1623.2], [1477.7, 1561.3, 1647.4, 1489.8, 1573.4, 1659.0], [1510.3, 1593.6, 1676.8, 1521.5, 1604.5, 1687.2], [1535.2, 1619.0, 1700.6, 1545.6, 1629.0, 1710.1], [1553.4, 1638.0, 1719.2, 1563.2, 1647.3, 1727.8]]) SVEL = sw.svel(S, T, P) # Display results. f.write('\n') f.write('\n%s' % asterisks) f.write('\nComparison of accepted values from UNESCO 1983 ') f.write('\n (Unesco Tech. Paper in Marine Sci. No. 44, p50)') f.write('\n%s' % asterisks) f.write('\n') m, n = SVEL.shape f.write('\n') for icol in range(0, n): f.write('\n Sal Temp Press SVEL svel') f.write('\n (psu) (C) (db) (m/s) (m/s)\n') result = np.vstack([ S[:, icol], T[:, icol], P[:, icol], UN_svel[:, icol], SVEL[:, icol] ]) for iline in range(0, m): f.write(" %4.0f %4.0f %5.0f %8.1f %11.3f\n" % tuple(result[:, iline])) # Test submodules alpha beta aonb. f.write('\n%s' % asterisks) f.write('\n** and SUB-MODULE: alpha beta aonb') f.write('\n%s' % asterisks) # Data from McDouogall 1987. s = 40 PT = 10 p = 4000 beta_lit = 0.72088e-03 aonb_lit = 0.34763 alpha_lit = aonb_lit * beta_lit BETA = sw.beta(s, PT, p, pt=True) ALPHA = sw.alpha(s, PT, p, pt=True) AONB = sw.aonb(s, PT, p, pt=True) # Display results. f.write('\n') f.write('\n%s' % asterisks) f.write('\nComparison of accepted values from MCDOUGALL 1987 ') f.write('\n%s' % asterisks) f.write('\n') f.write('\n') f.write('\n Sal Temp Press BETA beta') f.write('\n (psu) (C) (db) (psu^-1) (psu^-1)\n') table = np.hstack([s, PT, p, beta_lit, BETA]) f.write(" %4.0f %4.0f %5.0f %11.4e %11.5e\n" % tuple(table)) f.write('\n Sal Temp Press AONB aonb') f.write('\n (psu) (C) (db) (psu C^-1) (psu C^-1)\n') table = np.hstack([s, PT, p, aonb_lit, AONB]) f.write(" %4.0f %4.0f %5.0f %8.5f %11.6f\n" % tuple(table)) f.write('\n Sal Temp Press ALPHA alpha') f.write('\n (psu) (C) (db) (psu^-1) (psu^-1)\n') table = np.hstack([s, PT, p, alpha_lit, ALPHA]) f.write(" %4.0f %4.0f %5.0f %11.4e %11.4e\n" % tuple(table)) # Test main moduleS satO2 satN2 satAr. f.write('\n%s' % asterisks) f.write('\n** TESTING MODULE: satO2 satN2 satAr') f.write('\n%s' % asterisks) f.write('\n') # Data from Weiss 1970. T = np.array([[-1, -1], [10, 10], [20, 20], [40, 40]]) / 1.00024 S = np.array([[20, 40], [20, 40], [20, 40], [20, 40]]) lit_O2 = np.array([[9.162, 7.984], [6.950, 6.121], [5.644, 5.015], [4.050, 3.656]]) lit_N2 = np.array([[16.28, 14.01], [12.64, 11.01], [10.47, 9.21], [7.78, 6.95]]) lit_Ar = np.array([[0.4456, 0.3877], [0.3397, 0.2989], [0.2766, 0.2457], [0.1986, 0.1794]]) O2 = sw.satO2(S, T) N2 = sw.satN2(S, T) Ar = sw.satAr(S, T) # Display results. f.write('\n') f.write('\n%s' % asterisks) f.write('\nComparison of accepted values from Weiss, R.F. 1979 ') f.write('\n"The solubility of nitrogen, oxygen and argon in water') f.write('\n and seawater." Deep-Sea Research., 1970, Vol 17, pp721-735.') f.write('\n%s' % asterisks) f.write('\n') m, n = S.shape f.write('\n') for icol in range(0, n): f.write('\n Sal Temp O2 satO2') f.write('\n (psu) (C) (ml/l) (ml/l)\n') result = np.vstack( [S[:, icol], T[:, icol], lit_O2[:, icol], O2[:, icol]]) for iline in range(0, m): f.write(" %4.0f %4.0f %8.2f %9.3f\n" % tuple(result[:, iline])) for icol in range(0, n): f.write('\n Sal Temp N2 satN2') f.write('\n (psu) (C) (ml/l) (ml/l)\n') result = np.vstack( [S[:, icol], T[:, icol], lit_N2[:, icol], N2[:, icol]]) for iline in range(0, m): f.write(" %4.0f %4.0f %8.2f %9.3f\n" % tuple(result[:, iline])) for icol in range(0, n): f.write('\n Sal Temp Ar satAr') f.write('\n (psu) (C) (ml/l) (ml/l)\n') result = np.vstack( [S[:, icol], T[:, icol], lit_Ar[:, icol], Ar[:, icol]]) for iline in range(0, m): f.write(" %4.0f %4.0f %8.4f %9.4f\n" % tuple(result[:, iline]))
for lev in levs: x = m["t"][fix[:, lev], lev] xp = m["t"][~fix[:, lev], lev] for var in varl: fp = m[var][~fix[:, lev], lev] m[var][fix[:, lev], lev] = np.interp(x, xp, fp) # Re-estimate thermodynamic quantities. m["SA"] = gsw.SA_from_SP(m["S"], m["P"], m["lon"], m["lat"]) m["CT"] = gsw.CT_from_t(m["SA"], m["T"], m["P"]) print("Calculating neutral density.") # Estimate the neutral density for m in moorings: # Compute potential temperature using the 1983 UNESCO EOS. m["PT0"] = seawater.ptmp(m["S"], m["T"], m["P"]) # Flatten variables for analysis. lons = m["lon"] * np.ones_like(m["P"]) lats = m["lat"] * np.ones_like(m["P"]) S_ = m["S"].flatten() T_ = m["PT0"].flatten() P_ = m["P"].flatten() LO_ = lons.flatten() LA_ = lats.flatten() gamman = gamma_GP_from_SP_pt(S_, T_, P_, LO_, LA_) m["gamman"] = np.reshape(gamman, m["P"].shape) + 1000.0 print("Calculating slice gradients at C.") # Want gradient of density/vel to be local, no large central differences. slices = [slice(0, 4), slice(4, 6), slice(6, 10), slice(10, 12)] cc["dgdz"] = np.empty((cc["N_data"], cc["N_levels"]))
TY["vo"] = utils.nantrapz(v_, x=TY["z"], axis=0, xave=True) # Need the minus here because otherwise we get the wrong way around... TY["UT"] = -utils.nantrapz(u_, x=TY["z"], axis=0, xave=False) TY["VT"] = -utils.nantrapz(v_, x=TY["z"], axis=0, xave=False) TY["zo"] = utils.nan_interp(sig4max, TY["sig4_sorted"], TY["z"], axis=0) # Density difference 200 m above the interface. TY["dsig4"] = utils.nan_interp( -TY["zo"] - 100., TY["depth"], TY["sig4_sorted"], axis=0)[0, :] - sig4max TY["HKE"] = utils.nantrapz(0.5 * (u_**2 + v_**2), x=TY["z"], axis=0, xave=True) print("- Calculating neutral density") TY["PT0"] = seawater.ptmp(TY["S"], TY["T"], TY["P"]) # Flatten variables for analysis. nans = np.isnan(TY["lon"].flatten()) S = TY["S"].flatten()[~nans] T = TY["PT0"].flatten()[~nans] P = TY["P"].flatten()[~nans] LO = TY["lon"].flatten()[~nans] LA = TY["lat"].flatten()[~nans] gamman = np.full_like(TY["lon"].flatten(), np.nan) gamman[~nans] = gamma_GP_from_SP_pt(S, T, P, LO, LA) TY["gamman"] = np.reshape(gamman, TY["S"].shape) + 1000.0 TY["gamman_sorted"] = utils.nansort(TY["gamman"], axis=0) TY["gammanm"] = np.nanmean(TY["gamman"]) TY["N2_sorted"] = (-TY["g"] * np.gradient(TY["sig4_sorted"], axis=0) / (TY["sig4m"] * np.gradient(TY["z"], axis=0)))
def get_extrapolated(in_fn, L, M, N, X, Y, lon, lat, z, Ldir, add_CTD=False, fix_NSoG=False): b = pickle.load(open(in_fn, 'rb')) vn_list = list(b.keys()) # check that things are the expected shape def check_coords(shape_tuple, arr_shape): if arr_shape != shape_tuple: print('WARNING: array shape mismatch') for vn in vn_list: if vn == 'dt': pass elif vn == 'ssh': check_coords((M, L), b[vn].shape) else: check_coords((N, M, L), b[vn].shape) # creat output array and add dt to it. vn_list.remove('dt') V = dict() for vn in vn_list: V[vn] = np.nan + np.ones(b[vn].shape) V['dt'] = b['dt'] # extrapolate ssh vn = 'ssh' v = b[vn] if fix_NSoG: print(' ^^ Fixing NSoG ^^') # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # (a) Mouth of Strait of Juan de Fuca i0, i1, fr = zfun.get_interpolant(np.array([-124.7, -124.5]), lon, extrap_nan=False) j0, j1, fr = zfun.get_interpolant(np.array([48.4, 48.6]), lat, extrap_nan=False) zeta_jdf = v[j0[0]:j1[1] + 1, i0[0]:i1[1] + 1] # # (b) Northern Strait of Georgia i0, i1, fr = zfun.get_interpolant(np.array([-125.5, -124.5]), lon, extrap_nan=False) j0, j1, fr = zfun.get_interpolant(np.array([50.15, 50.45]), lat, extrap_nan=False) v[j0[0]:j1[1] + 1, i0[0]:i1[1] + 1] = np.nanmean(zeta_jdf) + 0.1 # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ vv = extrap_nearest_to_masked(X, Y, v) V[vn] = vv vn_list.remove('ssh') # extrapolate 3D fields for vn in vn_list: v = b[vn] if vn == 't3d': v0 = np.nanmin(v) elif vn == 's3d': v0 = np.nanmax(v) if vn in ['t3d', 's3d']: print(' -- extrapolating ' + vn) if add_CTD == False: for k in range(N): fld = v[k, :, :] fldf = extrap_nearest_to_masked(X, Y, fld, fld0=v0) V[vn][k, :, :] = fldf elif add_CTD == True: print(vn + ' Adding CTD data before extrapolating') Cast_dict, sta_df = Ofun_CTD.get_casts(Ldir) for k in range(N): fld = v[k, :, :] zz = z[k] xyorig, fldorig = Ofun_CTD.get_orig( Cast_dict, sta_df, X, Y, fld, lon, lat, zz, vn) fldf = Ofun_CTD.extrap_nearest_to_masked_CTD( X, Y, fld, xyorig=xyorig, fldorig=fldorig, fld0=v0) V[vn][k, :, :] = fldf elif vn in ['u3d', 'v3d']: print(' -- extrapolating ' + vn) vv = v.copy() vv = np.ma.masked_where(np.isnan(vv), vv) vv[vv.mask] = 0 V[vn] = vv.data # Create ubar and vbar. # Note: this is slightly imperfect because the z levels are at the same # position as the velocity levels. dz = np.nan * np.ones((N, 1, 1)) dz[1:, 0, 0] = np.diff(z) dz[0, 0, 0] = dz[1, 0, 0] # account for the fact that the new hycom fields do not show up masked u3d = np.ma.masked_where(np.isnan(b['u3d']), b['u3d']) v3d = np.ma.masked_where(np.isnan(b['v3d']), b['v3d']) dz3 = dz * np.ones_like(u3d) # make dz a masked array b['ubar'] = np.sum(u3d * dz3, axis=0) / np.sum(dz3, axis=0) b['vbar'] = np.sum(v3d * dz3, axis=0) / np.sum(dz3, axis=0) for vn in ['ubar', 'vbar']: v = b[vn] vv = v.copy() vv = np.ma.masked_where(np.isnan(vv), vv) vv[vv.mask] = 0 V[vn] = vv.data # calculate potential temperature press_db = -z.reshape((N, 1, 1)) V['theta'] = seawater.ptmp(V['s3d'], V['t3d'], press_db) return V
def spice(s, t, p): """Compute sea spiciness as defined by Flament (2002). .. math:: \pi(\theta,s) = \sum^5_{i=0} \sum^4_{j=0} b_{ij}\theta^i(s-35)^i Parameters ---------- s(p) : array_like salinity [psu (PSS-78)] t(p) : array_like temperature [:math:`^\\circ` C (ITS-90)] p : array_like pressure [db] Returns ------- sp : array_like :math:`\pi` [kg m :sup:`3`] See Also -------- pressure is not used... should the input be theta instead of t? Go read the paper! Notes ----- Spiciness, just like potential density, is only useful over limited vertical excursions near the pressure to which they are referenced; for large vertical ranges, the slope of the isopycnals and spiciness isopleths vary significantly with pressure, and generalization of the polynomial expansion to include a reference pressure dependence is needed. Examples -------- >>> from oceans import sw_extras as swe >>> swe.spice(33, 15, 0) array(0.5445864137500002) References ---------- .. [1] A state variable for characterizing water masses and their diffusive stability: spiciness. Prog. in Oceanography Volume 54, 2002, Pages 493-501. http://www.satlab.hawaii.edu/spice/spice.m Modifications: 2011/03/15. Filipe Fernandes, python translation. """ s, t, p = list(map(np.asanyarray, (s, t, p))) # FIXME: I'm not sure about this. pt = sw.ptmp(s, t, p) B = np.zeros((6, 5)) B[0, 0] = 0. B[0, 1] = 7.7442e-001 B[0, 2] = -5.85e-003 B[0, 3] = -9.84e-004 B[0, 4] = -2.06e-004 B[1, 0] = 5.1655e-002 B[1, 1] = 2.034e-003 B[1, 2] = -2.742e-004 B[1, 3] = -8.5e-006 B[1, 4] = 1.36e-005 B[2, 0] = 6.64783e-003 B[2, 1] = -2.4681e-004 B[2, 2] = -1.428e-005 B[2, 3] = 3.337e-005 B[2, 4] = 7.894e-006 B[3, 0] = -5.4023e-005 B[3, 1] = 7.326e-006 B[3, 2] = 7.0036e-006 B[3, 3] = -3.0412e-006 B[3, 4] = -1.0853e-006 B[4, 0] = 3.949e-007 B[4, 1] = -3.029e-008 B[4, 2] = -3.8209e-007 B[4, 3] = 1.0012e-007 B[4, 4] = 4.7133e-008 B[5, 0] = -6.36e-010 B[5, 1] = -1.309e-009 B[5, 2] = 6.048e-009 B[5, 3] = -1.1409e-009 B[5, 4] = -6.676e-010 sp = np.zeros_like(pt) T = np.ones_like(pt) s -= 35 r, c = B.shape for i in range(r): S = np.ones_like(pt) for j in range(c): sp += B[i, j] * T * S S *= s T *= pt return sp
def do_load_mfdata(mesh, data, fname_list, var_list, sel_timeidx, sel_levidx, \ nsi, ndi, do_tmean, do_output,): if ndi!=0: #_______________________________________________________________________ # select time+depth range + compute time mean if do_tmean: data.value = MFDataset(fname_list[0],'r').variables[var_list[0]][sel_timeidx,:,sel_levidx].mean(axis=0) if len(fname_list[1]): data.value2 = MFDataset(fname_list[1],'r').variables[var_list[1]][sel_timeidx,:,sel_levidx].mean(axis=0) if len(fname_list[2]): data.value3 = MFDataset(fname_list[2],'r').variables[var_list[2]][sel_timeidx,:,sel_levidx].mean(axis=0) else: data.value = MFDataset(fname_list[0],'r').variables[var_list[0]][sel_timeidx,:,sel_levidx] if len(fname_list[1]): data.value2 = MFDataset(fname_list[1],'r').variables[var_list[1]][sel_timeidx,:,sel_levidx] if len(fname_list[2]): data.value3 = MFDataset(fname_list[2],'r').variables[var_list[2]][sel_timeidx,:,sel_levidx] #_______________________________________________________________________ # compute potential density & temperatur if selected if any(x in data.var for x in ['pdens','ptemp','sigma']): dep = np.matlib.repmat(mesh.zmid[sel_levidx],nsi,1) lat = np.matlib.repmat(mesh.nodes_2d_yg[0:mesh.n2dn],len(sel_levidx),1).transpose() press = sw.pres(dep,lat) press_ref = 0 if '0' in data.var : press_ref=0 elif '1' in data.var : press_ref=1000 elif '2' in data.var : press_ref=2000 elif '3' in data.var : press_ref=3000 elif '4' in data.var : press_ref=4000 elif '5' in data.var : press_ref=5000 if 'sigma' in data.var: data.lname = '$\sigma_{'+str(int(press_ref/1000))+'}$ '+data.lname del dep,lat if do_tmean: if 'ptemp' in data.var: data.value = sw.ptmp(data.value2,data.value,press,press_ref) if any(x in data.var for x in ['pdens','sigma']): data.value = sw.pden(data.value2,data.value,press,press_ref)-1000.025 else: for it in range(0,data.value.shape[0]): if 'ptemp' in data.var: data.value[it,:,:] = sw.ptmp(data.value2[it,:,:],data.value[it,:,:],press,press_ref) if any(x in data.var for x in ['pdens','sigma']): data.value[it,:,:] = sw.pden(data.value2[it,:,:],data.value[it,:,:],press,press_ref)-1000.025 fname_list[1]=[] #_______________________________________________________________________ # compute depth mean + linear interpolation to selected depth levels if do_tmean: data.value = do_zinterp(mesh, data.value, data.depth, ndi, data.value.shape[0], sel_levidx,do_output) if len(fname_list[1]): data.value2 = do_zinterp(mesh, data.value2, data.depth, ndi, data.value2.shape[0], sel_levidx,do_output) if len(fname_list[2]): data.value3 = do_zinterp(mesh, data.value3, data.depth, ndi, data.value3.shape[0], sel_levidx,do_output) else: data.value = do_zinterp(mesh, data.value, data.depth, ndi, data.value.shape[1], sel_levidx,do_output) if len(fname_list[1]): data.value2 = do_zinterp(mesh, data.value2, data.depth, ndi, data.value2.shape[1], sel_levidx,do_output) if len(fname_list[2]): data.value3 = do_zinterp(mesh, data.value3, data.depth, ndi, data.value3.shape[1], sel_levidx,do_output) # 2D data: else: if do_tmean: data.value = MFDataset(fname_list[0],'r').variables[var_list[0]][sel_timeidx,:].mean(axis=0) if len(fname_list[1]): data.value2 = MFDataset(fname_list[1],'r').variables[var_list[1]][sel_timeidx,:].mean(axis=0) if len(fname_list[2]): data.value3 = MFDataset(fname_list[2],'r').variables[var_list[2]][sel_timeidx,:].mean(axis=0) else: data.value = MFDataset(fname_list[0],'r').variables[var_list[0]][sel_timeidx,:] if len(fname_list[1]): data.value2 = MFDataset(fname_list[1],'r').variables[var_list[1]][sel_timeidx,:] if len(fname_list[2]): data.value3 = MFDataset(fname_list[2],'r').variables[var_list[2]][sel_timeidx,:] # kickout single array dimension data.value = data.value.squeeze() if len(fname_list[1]): data.value2 = data.value2.squeeze() if len(fname_list[2]): data.value3 = data.value3.squeeze() return(data)
def spice(s, t, p): """ Compute sea spiciness as defined by Flament (2002). .. math:: \pi(\theta,s) = \sum^5_{i=0} \sum^4_{j=0} b_{ij}\theta^i(s-35)^i Parameters ---------- s(p) : array_like salinity [psu (PSS-78)] t(p) : array_like temperature [:math:`^\\circ` C (ITS-90)] p : array_like pressure [db] Returns ------- sp : array_like :math:`\pi` [kg m :sup:`3`] See Also -------- pressure is not used... should the input be theta instead of t? Go read the paper! Notes ----- Spiciness, just like potential density, is only useful over limited vertical excursions near the pressure to which they are referenced; for large vertical ranges, the slope of the isopycnals and spiciness isopleths vary significantly with pressure, and generalization of the polynomial expansion to include a reference pressure dependence is needed. Examples -------- >>> from oceans import sw_extras as swe >>> swe.spice(33, 15, 0) array(0.5445864137500002) References ---------- .. [1] A state variable for characterizing water masses and their diffusive stability: spiciness. Prog. in Oceanography Volume 54, 2002, Pages 493-501. http://www.satlab.hawaii.edu/spice/spice.m """ s, t, p = list(map(np.asanyarray, (s, t, p))) # FIXME: I'm not sure about this. pt = sw.ptmp(s, t, p) B = np.zeros((6, 5)) B[0, 0] = 0. B[0, 1] = 7.7442e-001 B[0, 2] = -5.85e-003 B[0, 3] = -9.84e-004 B[0, 4] = -2.06e-004 B[1, 0] = 5.1655e-002 B[1, 1] = 2.034e-003 B[1, 2] = -2.742e-004 B[1, 3] = -8.5e-006 B[1, 4] = 1.36e-005 B[2, 0] = 6.64783e-003 B[2, 1] = -2.4681e-004 B[2, 2] = -1.428e-005 B[2, 3] = 3.337e-005 B[2, 4] = 7.894e-006 B[3, 0] = -5.4023e-005 B[3, 1] = 7.326e-006 B[3, 2] = 7.0036e-006 B[3, 3] = -3.0412e-006 B[3, 4] = -1.0853e-006 B[4, 0] = 3.949e-007 B[4, 1] = -3.029e-008 B[4, 2] = -3.8209e-007 B[4, 3] = 1.0012e-007 B[4, 4] = 4.7133e-008 B[5, 0] = -6.36e-010 B[5, 1] = -1.309e-009 B[5, 2] = 6.048e-009 B[5, 3] = -1.1409e-009 B[5, 4] = -6.676e-010 sp = np.zeros_like(pt) T = np.ones_like(pt) s = s - 35 r, c = B.shape for i in range(r): S = np.ones_like(pt) for j in range(c): sp += B[i, j] * T * S S *= s T *= pt return sp
def do_load_dataloop(mesh, data, fname_list, var_list, sel_timeidx, sel_levidx, \ nti, nsi, ndi, do_tmean, do_output,): if ndi!=0: #_______________________________________________________________________ # initialize data.value array if do_tmean: data.value = np.zeros((nsi,len(sel_levidx)),dtype='float32') if len(fname_list[1]): data.value2 = np.zeros((nsi,len(sel_levidx)),dtype='float32') if len(fname_list[1]): data.value3 = np.zeros((nsi,len(sel_levidx)),dtype='float32') else: data.value = np.zeros((nti,nsi,len(sel_levidx))) if len(fname_list[1]): data.value2 = np.zeros((nti*len(fname_list),nsi,len(sel_levidx)),dtype='float32') if len(fname_list[1]): data.value3 = np.zeros((nti*len(fname_list),nsi,len(sel_levidx)),dtype='float32') #_______________________________________________________________________ # select time+depth range + compute time mean for it in range(0,len(fname_list[0])): if do_tmean: data.value = data.value + Dataset(fname_list[0][it],'r').variables[var_list[0]][sel_timeidx,:,sel_levidx].mean(axis=0) if len(fname_list[1]): data.value2 = data.value2 + Dataset(fname_list[1][it],'r').variables[var_list[1]][sel_timeidx,:,sel_levidx].mean(axis=0) if len(fname_list[2]): data.value3 = data.value3 + Dataset(fname_list[2][it],'r').variables[var_list[2]][sel_timeidx,:,sel_levidx].mean(axis=0) else: t_idx = sel_timeidx+nti*it data.value[t_idx,:,:] = data.value[t_idx,:,:] + Dataset(fname_list[0][it],'r').variables[var_list[0]][sel_timeidx,:,sel_levidx] if len(fname_list[1]): data.value2[t_idx,:,:] = data.value2[t_idx,:,:] + Dataset(fname_list[1][it],'r').variables[var_list[1]][sel_timeidx,:,sel_levidx] if len(fname_list[2]): data.value3[t_idx,:,:] = data.value3[t_idx,:,:] + Dataset(fname_list[2][it],'r').variables[var_list[2]][sel_timeidx,:,sel_levidx] # divide by loaded file number --> to final time mean if do_tmean: data.value = data.value/len(fname_list[0]) if len(fname_list[1]): data.value2 = data.value2/len(fname_list[1]) if len(fname_list[2]): data.value3 = data.value2/len(fname_list[2]) #_______________________________________________________________________ # compute potential density & temperatur if selected if any(x in data.var for x in ['pdens','ptemp','sigma']): dep = np.matlib.repmat(mesh.zmid[sel_levidx],nsi,1) lat = np.matlib.repmat(mesh.nodes_2d_yg[0:mesh.n2dn],nsi,1).transpose() press = sw.pres(dep,lat) press_ref= 0 if '0' in data.var : press_ref=0 elif '1' in data.var : press_ref=1000 elif '2' in data.var : press_ref=2000 elif '3' in data.var : press_ref=3000 elif '4' in data.var : press_ref=4000 elif '5' in data.var : press_ref=5000 if press_ref!=0: data.lname = '$\sigma_{'+str(int(press_ref/1000))+'}$ '+data.lname del dep,lat if do_tmean: if 'ptemp' in data.var: data.value = sw.ptmp(data.value2,data.value,press,press_ref) if any(x in data.var for x in ['pdens','sigma']): data.value = sw.pden(data.value2,data.value,press,press_ref)-1000.025 else: for it in range(0,data.value.shape[0]): if 'ptemp' in data.var: data.value[it,:,:] = sw.ptmp(data.value2[it,:,:],data.value[it,:,:],press,press_ref) if any(x in data.var for x in ['pdens','sigma']): data.value[it,:,:] = sw.pden(data.value2[it,:,:],data.value[it,:,:],press,press_ref)-1000.025 fname_list[1]=[] #_______________________________________________________________________ # compute depth mean + linear interpolation to selected depth levels data.value = do_zinterp(mesh, data.value, data.depth, ndi, nsi, sel_levidx,do_output) if len(fname_list[1]): data.value2 = do_zinterp(mesh, data.value2, data.depth, ndi, nsi, sel_levidx,do_output) if len(fname_list[2]): data.value3 = do_zinterp(mesh, data.value3, data.depth, ndi, nsi, sel_levidx,do_output) # 2D data: else: #_______________________________________________________________________ # initialize data.value array if do_tmean: data.value = np.zeros((nsi,)) if len(fname_list[1]): data.value2 = np.zeros((nsi,)) if len(fname_list[1]): data.value3 = np.zeros((nsi,)) else: data.value = np.zeros((nti,nsi)) if len(fname_list[1]): data.value2 = np.zeros((nti*len(fname_list),nsi)) if len(fname_list[1]): data.value3 = np.zeros((nti*len(fname_list),nsi)) #_______________________________________________________________________ # select time+depth range + compute time mean for it in range(0,len(fname_list[0])): if do_tmean: data.value = data.value + Dataset(fname_list[0][it],'r').variables[var_list[0]][sel_timeidx,:].mean(axis=0) if len(fname_list[1]): data.value2 = data.value2 + Dataset(fname_list[1][it],'r').variables[var_list[1]][sel_timeidx,:].mean(axis=0) if len(fname_list[2]): data.value3 = data.value3 + Dataset(fname_list[2][it],'r').variables[var_list[2]][sel_timeidx,:].mean(axis=0) else: t_idx = sel_timeidx+nti*it data.value[t_idx,:] = data.value[t_idx,:] + Dataset(fname_list[0][it],'r').variables[var_list[0]][sel_timeidx,:] if len(fname_list[1]): data.value2[t_idx,:] = data.value2[t_idx,:] + Dataset(fname_list[1][it],'r').variables[var_list[1]][sel_timeidx,:] if len(fname_list[2]): data.value3[t_idx,:] = data.value3[t_idx,:] + Dataset(fname_list[2][it],'r').variables[var_list[2]][sel_timeidx,:] # divide by loaded file number --> to final time mean if do_tmean: data.value = data.value/len(fname_list[0]) if len(fname_list[1]): data.value2 = data.value2/len(fname_list[1]) if len(fname_list[2]): data.value3 = data.value2/len(fname_list[2]) return(data)
def ctdproc(lista, temp_name='t068C', lathint='Latitude =', lonhint='Longitude =', cond_name='c0S/m', press_name='prDM', down_cast=True, looped=True, hann_f=False, hann_block=20, hann_times=2, latline=[], lonline=[]): ''' This function do the basic proccess to all .cnv CTD data from given list. ''' for fname in lista: lon, lat, data = ctdread(fname, press_name=press_name, down_cast=down_cast, lathint=lathint, lonhint=lonhint, lonline=lonline, latline=latline) if looped: data = loopedit(data) dataname = basename(fname)[1] if (data.shape[0] < 101) & ( data.shape[0] > 10): # se o tamanho do perfil for com menos de 101 medidas if (data.shape[0] / 2) % 2 == 0: # caso a metade dos dados seja par blk = (data.shape[0] / 2) + 1 # bloco = a metade +1 else: blk = data.shape[0] / 2 # se for impar o bloco e a metade # remove spikes dos perfis de temperatura e condutividade data = despike(data, propname=temp_name, block=blk, wgth=2) data = despike(data, propname=cond_name, block=blk, wgth=2) elif data.shape[0] >= 101: # para perfis com mais de 101 medidas, utiliza-se blocos de 101 data = despike(data, propname=temp_name, block=101, wgth=2) data = despike(data, propname=cond_name, block=101, wgth=2) else: print('radial muito rasa') # realiza média em caixa de 1 metro data = binning(data, delta=1.) if temp_name == 't068C': data['t090C'] = gsw.t90_from_t68(data['t068C']) data['sp'] = gsw.SP_from_C(data[cond_name] * 10, data['t090C'], data.index.values) if hann_f: times = 0 while times < hann_times: data = hann_filter(data, 't090C', hann_block) data = hann_filter(data, 'sp', hann_block) times += 1 data['pt'] = sw.ptmp(data['sp'], data['t090C'], data.index.values) #data['ct'] = gsw.CT_from_pt(data['sa'],data['pt']) data['psigma0'] = sw.pden( data['sp'], data['t090C'], data.index.values, pr=0) - 1000 data['psigma1'] = sw.pden( data['sp'], data['t090C'], data.index.values, pr=1000) - 1000 data['psigma2'] = sw.pden( data['sp'], data['t090C'], data.index.values, pr=2000) - 1000 data['gpan'] = sw.gpan(data['sp'], data['t090C'], data.index.values) data['lat'] = lat data['lon'] = lon data.to_pickle( os.path.split(fname)[0] + '/' + os.path.splitext(os.path.split(fname)[1])[0]) print(dataname)
def __init__(self, path, climname='woa05'): if climname == 'woa05': ncfile = Dataset(os.path.join(path, 'woa2005TS.nc')) self.T = np.copy(ncfile.variables['t00an1'][0, :, :, :]) x = np.copy(ncfile.variables['lon'][:]) x[x > 180] = x[x > 180] - 360 ind = [i[0] for i in sorted(enumerate(x), key=lambda x: x[1])] x = np.sort(x) self.x = x self.y = ncfile.variables['lat'][:] self.z = ncfile.variables['depth'][:] self.T[:, :, :] = self.T[:, :, ind] self.S = np.copy(ncfile.variables['s00an1'][0, :, :, :]) self.S[:, :, :] = self.S[:, :, ind] depth3d = np.zeros(self.S.shape) for i in range(self.z.shape[0]): depth3d[i, :, :] = self.z[i] ptemp = sw.ptmp(self.S, self.T, depth3d) self.T = ptemp ncfile.close() self.Tyz = nanmean(self.T, 2) self.Syz = nanmean(self.S, 2) self.T = np.ma.masked_greater(self.T, 1000) self.S = np.ma.masked_greater(self.S, 1000) if climname == 'phc': ncfile = Dataset(os.path.join(path, 'phc3.0_annual.nc')) self.T = np.copy(ncfile.variables['temp'][:, :, :]) x = np.copy(ncfile.variables['lon'][:]) x[x > 180] = x[x > 180] - 360 ind = [i[0] for i in sorted(enumerate(x), key=lambda x: x[1])] x = np.sort(x) self.x = x self.y = ncfile.variables['lat'][:] self.z = ncfile.variables['depth'][:] self.T[:, :, :] = self.T[:, :, ind] self.S = np.copy(ncfile.variables['salt'][:, :, :]) self.S[:, :, :] = self.S[:, :, ind] depth3d = np.zeros(self.S.shape) for i in range(self.z.shape[0]): depth3d[i, :, :] = self.z[i] ptemp = sw.ptmp(self.S, self.T, depth3d) self.T = ptemp ncfile.close() self.Tyz = nanmean(self.T, 2) self.Syz = nanmean(self.S, 2) if climname == 'gdem': ncfile = Dataset(os.path.join(path, 'gdemv3s_tm.nc')) self.T = np.copy(ncfile.variables['water_temp'][0, :, :, :]) x = np.copy(ncfile.variables['lon'][:]) x[x > 180] = x[x > 180] - 360 ind = [i[0] for i in sorted(enumerate(x), key=lambda x: x[1])] x = np.sort(x) self.x = x self.y = ncfile.variables['lat'][:] self.z = ncfile.variables['depth'][:] self.T[:, :, :] = self.T[:, :, ind] self.S = np.copy(ncfile.variables['salinity'][0, :, :, :]) self.S[:, :, :] = self.S[:, :, ind] depth3d = np.zeros(self.S.shape) for i in range(self.z.shape[0]): depth3d[i, :, :] = self.z[i] ptemp = sw.ptmp(self.S, self.T, depth3d) self.T = ptemp ncfile.close() self.Tyz = nanmean(self.T, 2) self.Syz = nanmean(self.S, 2) self.T = np.ma.masked_less(self.T, -1000) self.S = np.ma.masked_less(self.S, -1000) # def fesom_2_clim(data, depth, mesh, climatology, verbose=True, radius_of_influence=100000): # ''' # Interpolation of fesom data to grid of the climatology. # Parameters # ---------- # data : array # 1d array of FESOM 2d data slice # depth : depth of the slice # mesh : mesh object # FESOM mesh object # climatology: climatology object # FESOM climatology object # Returns # ------- # iz : the index of the closest depth in climatology to the input depth # xx : 2d array longitudes # yy : 2d array latitudes # out_data : 2d array # array with data interpolated to climatology level # ''' # xx,yy = np.meshgrid(climatology.x, climatology.y) # out_data=np.copy(climatology.T) # distances, inds = create_indexes_and_distances(mesh, xx, yy,\ # k=10, n_jobs=2) # #import pdb # #pdb.set_trace() # iz=abs(abs(climatology.z)-abs(depth)).argmin() # print('the model depth is: ', depth, '; the closest depth in climatology is: ', climatology.z[iz]) # out_data=fesom2regular(data, mesh, xx, yy, distances=distances, inds=inds, radius_of_influence=radius_of_influence) # out_data[np.isnan(climatology.T[iz,:,:])]=np.nan # return iz, xx, yy, out_data