def SWdensityFromCTD(SA, t, p, potential=False): """Calculate seawater density at CTD depth Args ---- SA: ndarray Absolute salinity, g/kg t: ndarray In-situ temperature (ITS-90), degrees C p: ndarray Sea pressure (absolute pressure minus 10.1325 dbar), dbar Returns ------- rho: ndarray Seawater density, in-situ or potential, kg/m^3 """ import numpy import gsw CT = gsw.CT_from_t(SA, t, p) # Calculate potential density (0 bar) instead of in-situ if potential: p = numpy.zeros(len(SA)) return gsw.rho(SA, CT, p)
def compute_mass_adjustment(self, f, w=None, **kwargs): """ \delta_m = V \delta \rho_w + \rho_w \delta V """ if w is not None: z = -self.pressure water_temperature = w.get_temp(z) water_salinity = w.get_s(z) lon, lat = w.lon, w.lat else: water_temperature = kwargs['temperature'] water_salinity = kwargs['salinity'] lon, lat = kwargs['lon'], kwargs['lat'] SA = gsw.SA_from_SP(water_salinity, self.pressure, lon, lat) CT = gsw.CT_from_t(SA, water_temperature, self.pressure) rho_water = gsw.density.rho(SA, CT, self.pressure) # new in situ density for name, b in self._d.items(): delta_rho_water = rho_water - b['rho_water'] # f.m = b['mass_in_air']*1e-3 # need to convert to kg f.piston.update_d(b['piston_displacement']*1e-2) # need to convert to m f.piston_update_vol() f.V = b['V'] - f.v V = f.volume(p=self.pressure, temp=water_temperature) delta_V = V - b['V'] # delta_m = V * delta_rho_water + rho_water * delta_V print('According to balast %s, you need add %.1f g' %(name, delta_m*1e3))
def calculate_n2(T, p, C, lat, long): """Calculates the buoyancy frequency N^2 All parameters and output are float or array-like. :param T: temperature (deg C) :param p: pressure (bar) :param C: conductivity (S/m) :param lat: latitude (decimal deg) :param long: longitude (decimal deg) :return: buoyancy (i.e. brunt-vaisala) frequency N^2 (s^-2) """ # pressure in dbars = pressure * 10 p_dbar = p * 10 # conductivity in mS/cm = conductivity * 10 C_mScm = C * 10 print(T.count()) print(p.count()) print(C.count()) print(lat.count()) print(long.count()) # calculate SP from conductivity (mS/cm), in-situ temperature (deg C), and gauge pressure (dbar) SP = gsw.SP_from_C(C_mScm, T, p_dbar) # calculate SA from SP (unitless), gauge pressure (dbar), longitude and latitude (decimal degrees) SA = gsw.SA_from_SP(SP, p_dbar, long, lat) # calculate CT from SA (g/kg), in-situ temperature (deg C), and gauge pressure (dbar) CT = gsw.CT_from_t(SA, T, p_dbar) # calculate N^2 nsquared, p_mid = gsw.Nsquared(SA, CT, p_dbar, lat=lat) return nsquared
def o2pl2pkg(p_col, t_col, sal_col, dopl_col, dopkg_col, lat_col, lon_col, inMat): """o2pl2pkg convert ml/l dissolved oxygen to umol/kg Input: - t_col, temperature column header deg c. - sal_col, salinity column header psu. - dopl_col, dissolved column header ml/l. - dopkg_col, dissolved column header umol/kg - lat_col, latitude for entire cast deg. - lon_col, longitude for entire cast deg. - inMat, dtype ndarray processed ctd time data. Output: - Converted Oxygen column umol/kg Example: >>> # linear interpolation of NaNs >>> outArray = o2pl2kg(inArr) """ pkg = np.ndarray(shape=len(inMat), dtype=[(dopkg_col, np.float)]) # Absolute sailinity from Practical salinity. SA = gsw.SA_from_SP(inMat[sal_col], inMat[p_col], inMat[lat_col], inMat[lon_col]) # Conservative temperature from insitu temperature. CT = gsw.CT_from_t(SA, inMat[t_col], inMat[p_col]) s0 = gsw.sigma0( SA, CT ) # Potential density from Absolute Salinity g/Kg Conservative temperature deg C. # Convert DO ml/l to umol/kg for i in range(0, len(inMat[dopl_col])): pkg[i] = inMat[dopl_col][i] * 44660 / (s0[i] + 1000) return pkg
def compute_alpha_beta(data, temperature_var='SST', salinity_var='SSS'): p = 0 * data['lon'] SA = gsw.SA_from_SP(data[salinity_var], p, data['lon'], data['lat']) CT = gsw.CT_from_t(SA, data[temperature_var], p) rho, alpha, beta = gsw.rho_alpha_beta(SA, CT, p) return data.assign(alpha=xr.DataArray(alpha, dims='time'), beta=xr.DataArray(beta, dims='time'))
def add_density(netCDFfile): # loads the netcdf file ds = Dataset(netCDFfile, 'a') if 'DENSITY' in list(ds.variables): ds.close() return "file already contains density" # extracts the variables from the netcdf var_temp = ds.variables["TEMP"] var_psal = ds.variables["PSAL"] var_pres = ds.variables["PRES"] var_lon = ds.variables["LONGITUDE"] var_lat = ds.variables["LATITUDE"] # extracts the data from the variables t = var_temp[:] psal = var_psal[:] p = var_pres[:] lon = var_lon[:] lat = var_lat[:] # calculates absolute salinity SA = gsw.SA_from_SP(psal, p, lon, lat) # calculates conservative temperature CT = gsw.CT_from_t(SA, t, p) # calculates density density = gsw.rho(SA, CT, p) # generates a new variable 'DENSITY' in the netcdf ncVarOut = ds.createVariable( "DENSITY", "f4", ("TIME", ), fill_value=np.nan, zlib=True) # fill_value=nan otherwise defaults to max # assigns the calculated densities to the DENSITY variable, sets the units as kg/m^3, and comments on the variable's origin ncVarOut[:] = density ncVarOut.units = "kg/m^3" ncVarOut.long_name = "sea_water_density" ncVarOut.standard_name = "sea_water_density" ncVarOut.valid_max = np.float32( 1100 ) # https://oceanobservatories.org/wp-content/uploads/2015/09/1341-10004_Data_Product_SPEC_GLBLRNG_OOI.pdf ncVarOut.valid_min = np.float32(1000) ncVarOut.comment = "calculated using gsw-python https://teos-10.github.io/GSW-Python/index.html" # update the history attribute try: hist = ds.history + "\n" except AttributeError: hist = "" ds.setncattr( 'history', hist + datetime.utcnow().strftime("%Y-%m-%d") + " : added DENSITY from TEMP, PSAL, PRES, LAT, LON") ds.close()
def derive_variables(dbase, which_ones='all'): """ Also include density, potential temp and density; and uncertainties!! """ SA_dat = [ gsw.SA_from_SP(dbase['sal'][n], dbase['pres'][n], dbase['lon'][n], dbase['lat'][n]) for n in range(0, len(dbase)) ] CT_dat = [ gsw.CT_from_t(SA_dat[n], dbase['temp'][n], dbase['pres'][n]) for n in range(0, len(dbase)) ] N2_dat = [ gsw.Nsquared( SA_dat[n], CT_dat[n], dbase['pres'][n], dbase['lat'][n], alphabeta=True, ) for n in range(0, len(dbase)) ] if which_ones == 'all': return SA_dat, CT_dat, N2_dat elif which_ones == 'N2': return N2_dat
def rho(SP, t, p, lon=-45.401666, lat=-23.817233): """ Calculates in situ density from practical salinity, in situ temperature and pressure (depth). Parameters ---------- SP : array like Salinity (PSS-78) [1e-3] t : array like Temperature (ITS-90) [degC] p : array like Pressure [dbar] lon : array like, float, optional Longitude, decimal degrees east lat : array like, float, optional Latitude, decimal degrees north Returns ------- rho : array like In situ density [kg m-3] """ # Calculates Absolute Salinity from Practical Salinity SA = gsw.SA_from_SP(SP, p, lon, lat) # Calcualtes Conservative Temperature from in situ temperature CT = gsw.CT_from_t(SA, t, p) # Calculates and returns density return gsw.rho(SA, CT, p)
def water_properties(sp, t, p, lon=0.0, lat=0.0): """ Calculates seawater density and sound speed using the TEOS-10 equations. Uses the gsw toolbox, which is an implementation of the TEOS-10 equations. Args: :sp: Practical salinity [PSU] :t: Temperature [degC] :p: Pressure [dbar] :lon: Longitude (optional - use named parameters) [decimal degrees] :lat: Latitude (optional - use named parameters) [decimal degrees] Returns: :c: speed of sound in water [m/s] :rho: density of water [kg/m^3] Notes: The accuracy of sound speed and density that we need is such that it doesn't matter what latitude and longitude is used. """ sa = gsw.SA_from_SP(sp, p, lon, lat) ct = gsw.CT_from_t(sa, t, p) c = gsw.sound_speed(sa, ct, p) rho = gsw.rho(sa, ct, p) return c, rho
def get_hydro(my_file): f = Dataset(my_file, mode='r') eps = f.variables['EPSILON'][:] eps = remove_bad_eps(eps) lat = f.variables['LATITUDE'][:] lon = f.variables['LONGITUDE'][:] p = f.variables['PRESSURE'][:] SP = f.variables['PSAL'][:] T = f.variables['TEMPERATURE'][:] z = gsw.z_from_p(p, lat) # m SA = gsw.SA_from_SP(SP, p, lon, lat) # g/kg, absolute salinity CT = gsw.CT_from_t(SA, T, p) # C, conservative temperature SA = remove_bad_SA(SA) CT = remove_bad_CT(CT) [N2_mid, p_mid] = gsw.Nsquared(SA, CT, p, lat) z_mid = gsw.z_from_p(p_mid, lat) N2 = interp_to_edges(N2_mid, z, z_mid, 4) N2 = np.append(np.append(N2, [np.nan]), [np.nan]) N2 = remove_bad_N2(N2) return N2, SA, CT, eps, z
def _update_eos(self): assert hasattr(self, 'd_depth'), \ 'You need to run clean_and_depth_bin first' d = self.d_depth d['SA'] = gsw.SA_from_SP(d.salinity, d.index, d.longitude, d.latitude) d['CT'] = gsw.CT_from_t(d.SA, d.temperature, d.index) d['sound_speed'] = gsw.sound_speed(d.SA, d.CT, d.index)
def __init__(self, lon, lat, name=None): self._woa=True # self._tfile = 'woa13_decav_t00_01v2.nc' nc = Dataset(self._tfile,'r') # glon = nc.variables['lon'][:] glat = nc.variables['lat'][:] ilon = np.argmin(np.abs(lon-glon)) ilat = np.argmin(np.abs(lat-glat)) self.lon = glon[ilon] self.lat = glat[ilat] # self.z = -nc.variables['depth'][:] self.p = gsw.p_from_z(self.z,self.lat) # self.temp = nc.variables['t_an'][0,:,ilat,ilon] nc.close() # self._sfile = 'woa13_decav_s00_01v2.nc' nc = Dataset(self._sfile,'r') self.s = nc.variables['s_an'][0,:,ilat,ilon] nc.close() # derive absolute salinity and conservative temperature self.SA = gsw.SA_from_SP(self.s, self.p, self.lon, self.lat) self.CT = gsw.CT_from_t(self.SA, self.temp, self.p) # isopycnal displacement self.eta=0. # if name is None: self.name = 'WOA water profile at lon=%.0f, lat=%.0f'%(self.lon,self.lat)
def sound_speed_teos10(lats, lons, z, t, SP): """ Compute sound speed from temperature, salinity, and depth for a given latitude and longitude using the Thermodynamic Equation of Seawater 2010. https://teos-10.github.io/GSW-Python/ Args: lats: numpy array Latitudes (-90 to 90 degrees) lons: numpy array Longitudes (-180 to 180 degrees) z: numpy array Depths (meters) t: numpy array In-situ temperature (Celsius) SP: numpy array Practical Salinity (psu) Returns: c: numpy array Sound speed (m/s) """ p = gsw.p_from_z(z=-z, lat=lats) # sea pressure (gsw uses negative z below sea surface) SA = gsw.SA_from_SP(SP, p, lons, lats) # absolute salinity CT = gsw.CT_from_t(SA, t, p) # conservative temperature c = gsw.density.sound_speed(SA=SA, CT=CT, p=p) return c
def _load_from_pts(self, pressure, temperature, salinity, lon, lat, name): self._pts = True # if all([ isinstance(i, float) for i in [pressure, temperature, salinity, lon, lat] ]): #pressure = np.array([-1, 1e4]) #temperature = np.array([temperature, temperature]) #salinity = np.array([salinity, salinity]) #lon = np.array([lon,lon]) #lat = np.array([lat,lat]) pressure = [-1, 1e4] temperature = [temperature, temperature] salinity = [salinity, salinity] lon = [lon, lon] lat = [lat, lat] # self.lon, self.lat = lon, lat # self.p = pressure self.z = gsw.z_from_p(self.p, self.lat) # self.temp, self.s = temperature, salinity # derive absolute salinity and conservative temperature self.SA = gsw.SA_from_SP(self.s, self.p, self.lon, self.lat) self.CT = gsw.CT_from_t(self.SA, self.temp, self.p) # isopycnal displacement and velocity self.eta = 0. self.detadt = 0. # if name is None: self.name = 'Provided water profile at lon=%.0f, lat=%.0f' % ( self.lon, self.lat)
def aaoptode_sternvolmer(foil_coef, optode_phase, tempc, salin, press): # %%%%%%%%%%%%%%%%%%%%%%%%%%%% # %% AAOPTODE_STERNVOLMER: For Aanderaa optode 4XXX series, to interpret # % calphase measurements based on the Stern Volmer equation. To be used in # % combination with aaoptode_salpresscorr, which handles salinity and # % pressure corrections. # # %% INPUTS # % foil_coef: Struct of calibration coefficients # % optode_phase: vector of optode phase measurements (calphase or dphase) # % tempc: temperature in deg C # % salin: Salinity # % press: pressure (db) for pressure correction # # %% OUTPUTS # % optode_uM: Oxygen concentration in uM # % optode_umolkg: Oxygen concentration in umol/kg # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # % H. Palevsky, 8/6/2019, based on sg_aaoptode.m # % Uchida et al. 2008 Stern-Volmer based calbration mode C = foil_coef; Ksv = C[0] + C[1]*tempc+C[2]*tempc**2; P0 = C[3] + C[4]*tempc; PC = C[5] + C[6]*optode_phase; optode_uM = ((P0/PC)-1)/Ksv; # % note - this uses SR, reference salinity SA = 35.16504/35*salin; CT = gsw.CT_from_t(SA,tempc,press); optode_umolkg = 1000*optode_uM/(1000+ gsw.sigma0(SA,CT)); return optode_uM, optode_umolkg
def common_thermodynamics(depth, lon, lat, SP, t): """Wrapper for various thermodynamic calculations. Assumes input data is 1D with size N or M, or 2D with size N*M, where M denotes profiles and N depths. Parameters ---------- depth : numpy array Depth (m), size N. lon : numpy array Longitude, size M. lat : numpy array Latitude, size M. SP : numpy array Practical salinity, size N*M. t : numpy array Temperature, size N*M. """ p = gsw.p_from_z(-depth, np.mean(lat)) SA = gsw.SA_from_SP(SP, p[:, np.newaxis], lon[np.newaxis, :], lat[np.newaxis, :]) CT = gsw.CT_from_t(SA, t, p[:, np.newaxis]) sig0 = gsw.pot_rho_t_exact(SA, t, p[:, np.newaxis], 0) N2, p_mid = gsw.Nsquared(SA, CT, p[:, np.newaxis], lat[np.newaxis, :]) return p, SA, CT, sig0, p_mid, N2
def calculate_density(T, p, C, lat, long): """Calculates density from temp, pressure, conductivity, and lat/long. All parameters and output are float or array-like. :param T: temperature (deg C) :param p: pressure (bar) :param C: conductivity (S/m) :param lat: latitude (decimal deg) :param long: longitude (decimal deg) :return: density (kg/m^3) """ # pressure in dbars = pressure * 10 if type(p) == float: p_dbar = p * 10 else: p_dbar = [pi * 10 for pi in p] # conductivity in mS/cm = conductivity * 10 if type(C) == float: C_mScm = C * 10 else: C_mScm = [Ci * 10 for Ci in C] # calculate SP from conductivity (mS/cm), in-situ temperature (deg C), and gauge pressure (dbar) SP = gsw.SP_from_C(C_mScm, T, p_dbar) # calculate SA from SP (unitless), gauge pressure (dbar), longitude and latitude (decimal degrees) SA = gsw.SA_from_SP(SP, p_dbar, long, lat) # calculate CT from SA (g/kg), in-situ temperature (deg C), and gauge pressure (dbar) CT = gsw.CT_from_t(SA, T, p_dbar) # calculate density return gsw.rho(SA, CT, p_dbar)
def convertToDictionary(refdata): ## gamma_n goes lon, lat, pres data = {} data["lats"] = np.asarray(refdata["lat_ref"]) data["lons"] = np.asarray(refdata["long_ref"]) p_ref = np.empty((91, 45, 33)) for i in range(p_ref.shape[0]): for j in range(p_ref.shape[1]): p_ref[i][j] = np.asarray(refdata["p_ref"]).flatten() data["s"] = [] data["t"] = [] data["p"] = [] for j in range(refdata["SP_ref"].shape[0]): data["s"].append( np.asarray( gsw.SA_from_SP(np.asarray(refdata["SP_ref"][j]), p_ref[j], np.full_like(data["lats"], data["lons"][j]), data["lats"]))) data["t"].append( np.asarray( gsw.CT_from_t(data["s"][-1], np.asarray(refdata["t_ref"][j]), p_ref[j]))) data["p"].append(p_ref[j]) data["t"] = np.asarray(data["t"]) print(data["t"].shape) data["p"] = np.asarray(refdata["p_ref"]).flatten() data["lats"] = np.asarray(refdata["lat_ref"]).flatten() data["lons"] = np.asarray(refdata["long_ref"]).flatten() data["gamma"] = np.asarray(refdata["gamma_n_ref"]) return data
def add_ctd_params(df_in: MutableMapping[str, Sequence], cfg: Mapping[str, Any], lon=16.7, lat=55.2): """ Calculate all parameters from 'sigma0', 'depth', 'soundV', 'SA' that is specified in cfg['out']['data_columns'] :param df_in: DataFrame with columns: 'Pres', 'Temp90' or 'Temp', and may be others: 'Lat', 'Lon': to use instead cfg['in']['lat'] and lat and -//- lon :param cfg: dict with fields: ['out']['data_columns'] - list of columns in output dataframe ['in'].['b_temp_on_its90'] - optional :param lon: # 54.8707 # least priority values :param lon: # 19.3212 :return: DataFrame with only columns specified in cfg['out']['data_columns'] """ ctd = df_in params_to_calc = set(cfg['out']['data_columns']).difference(ctd.columns) params_coord_needed_for = params_to_calc.intersection( ('depth', 'sigma0', 'SA', 'soundV')) # need for all cols? if any(params_coord_needed_for): # todo: load from nav: if np.any(ctd.get('Lat')): lat = ctd['Lat'] lon = ctd['Lon'] else: if 'lat' in cfg['in']: lat = cfg['in']['lat'] lon = cfg['in']['lon'] else: print( 'Calc', '/'.join(params_coord_needed_for), f'using MANUAL INPUTTED coordinates: lat={lat}, lon={lon}') if 'Temp90' not in ctd.columns: if cfg['in'].get('b_temp_on_its90'): ctd['Temp90'] = ctd['Temp'] else: ctd['Temp90'] = gsw.conversions.t90_from_t68(df_in['Temp']) ctd['SA'] = gsw.SA_from_SP( ctd['Sal'], ctd['Pres'], lat=lat, lon=lon) # or Sstar_from_SP() for Baltic where SA=S* # Val['Sal'] = gsw.SP_from_C(Val['Cond'], Val['Temp'], Val['P']) if 'soundV' in params_to_calc: ctd['soundV'] = gsw.sound_speed_t_exact(ctd['SA'], ctd['Temp90'], ctd['Pres']) if 'depth' in params_to_calc: ctd['depth'] = np.abs(gsw.z_from_p(np.abs(ctd['Pres']), lat)) if 'sigma0' in params_to_calc: CT = gsw.CT_from_t(ctd['SA'], ctd['Temp90'], ctd['Pres']) ctd['sigma0'] = gsw.sigma0(ctd['SA'], CT) # ctd = pd.DataFrame(ctd, columns=cfg['out']['data_columns'], index=df_in.index) if 'Lat' in params_to_calc and not 'Lat' in ctd.columns: ctd['Lat'] = lat ctd['Lon'] = lon return ctd[cfg['out']['data_columns']]
def derive_csv(data): density = gsw.z_from_p(cast[6].values,lat) absolute_sal=gsw.SA_from_SP(cast[10].values,density,lon,lat) reference_sal=gsw.SR_from_SP(absolute_sal) conservative_temp=gsw.CT_from_t(absolute_sal,cast[8],density) potential_density=gsw.sigma0(absolute_sal,conservative_temp) return density,absolute_sal,reference_sal,conservative_temp,potential_density
def insitu_to_absolute(Tis, SP, p, lon, lat, zref): """Transform in situ variables to TEOS10 variables :rtype: float, float, float""" # SP is in p.s.u. SA = gsw.SA_from_SP(SP, p, lon, lat) CT = gsw.CT_from_t(SA, Tis, p) z = -gsw.z_from_p(p, lat) return (CT, SA, z)
def brunt_vaisala(SP, t, p, lon=-45.401666, lat=-23.817233, interpolate=True, result='frequency'): """ Returns Brunt-Väisäla (or buoyancy) frequency/period from practical salinity, in situ temperature and pressure (depth). Parameters ---------- SP : array like Salinity (PSS-78) [1e-3] t : array like Temperature (ITS-90) [degC] p : array like Pressure [dbar] lon : array like, float, optional Longitude, decimal degrees east lat : array like, float, optional Latitude, decimal degrees north interpolate : boolean, optional If True, interpolates calculated frequency to original pressure (depth) levels. If False, returns results at mid pressure between pressugre grid. result : {'freuency', 'period'}, optional Sets whether to return `frequency` [in Returns ------- N : array like Brunt-Väisälä frequency [s-1] or period [s]. p : array like Pressure levels [dbar]. """ # Calculates Absolute Salinity from Practical Salinity SA = gsw.SA_from_SP(SP, p, lon, lat) # Calcualtes Conservative Temperature from in situ temperature CT = gsw.CT_from_t(SA, t, p) # N2, p_mid = gsw.Nsquared(SA, CT, p, lat=lat) N2[N2 < 0] = 0 # if interpolate: N2 = interp(p, p_mid, N2) # if result == 'frequency': return N2**0.5, p_mid elif result == 'period': return 1. / N2**0.5, p_mid else: raise ValueError('Invalid result type {}.'.format(result))
def _update_eos(self): # derive absolute salinity and conservative temperature self.SA = gsw.SA_from_SP(self.s, self.p, self.lon, self.lat) self.CT = gsw.CT_from_t(self.SA, self.temp, self.p) # derive N2 self.N2, self.p_mid = gsw.Nsquared(self.SA, self.CT, self.p, lat=self.lat) self.z_mid = gsw.z_from_p(self.p_mid, self.lat)
def sigma0FromCTD(S, T, p, lon, lat): """ Rho from measured salinity and temperature values """ SA = gsw.SA_from_SP(S, p, lon, lat) CT = gsw.CT_from_t(SA, T, p) rho = gsw.density.sigma0(SA, CT) return rho
def dens0(S, T, P): # ctd file contain in situ temperature and practical salinity # CT= conservative temperature # SA= absolute salinity # p is sea pressure (dbar) SA = gsw.SA_from_SP(S, P, 6., 42.) CT = gsw.CT_from_t(SA, T, P) # sound speed #C = gsw.sound_speed(SA, CT, P) return gsw.sigma0(SA, CT) + 1000.
def compute_density(data): p = 0 * data['lon'] SA = gsw.SA_from_SP(data['SSS'], p, data['lon'], data['lat']) CT = gsw.CT_from_t(SA, data['SST'], p) rho, alpha, beta = gsw.rho_alpha_beta(SA, CT, p) #b = 9.81 * (1 - rho / 1025.) data['SSS'].data = SA data['SST'].data = CT return data.assign(SSrho=xr.DataArray(rho, dims='time'), SSalpha=xr.DataArray(alpha, dims='time'), SSbeta=xr.DataArray(beta, dims='time'))
def sigma0(S, T, p, lat=None, lon=None): ones = xr.ones_like(S) p = ones * S['p'] if lat is None: lat = ones * S['lat'] if lon is None: lon = ones * S['lon'] SA = gsw.SA_from_SP(S, p, lon, lat) CT = gsw.CT_from_t(SA, T, p) rho = gsw.sigma0(SA, CT) return rho
def Nsquared(S, T, p, lat=None, lon=None, dim='p'): ones = xr.ones_like(S) p = ones * S[dim] if lat is None: lat = ones * S['lat'] if lon is None: lon = ones * S['lon'] SA = gsw.SA_from_SP(S, p, lon, lat) CT = gsw.CT_from_t(SA, T, p) N2, pmid = gsw.Nsquared(SA, CT, p, axis=S.get_axis_num(dim)) return N2, pmid
def test(self): sal = np.array([0.1, 0.1]) # temp = np.array([4., 21.]) # Celsius pres = np.array([10., 20.]) rho = gsw.rho(sal, temp, pres) print("density", rho) lat = [43.2, 43.2] CT = gsw.CT_from_t(sal, temp, pres) N2, p_mid = gsw.Nsquared(sal, CT, pres, lat=lat) print("N2", N2) print("p_mid", p_mid)
def density_profile(Hydro_Dataframe): for index, row in Hydro_Dataframe.iterrows(): t = row["CTDTMP"] #ITS-90 SP = row["CTDSAL"] # PSS-78 p = row["CTDPRS"] # decibar lon = [row["LON"]]*t.size lat = [row["LAT"]]*t.size SA = gsw.SA_from_SP(SP, p, lon, lat) #gsw.SA_from_SP(SP, p, lon, lat) CT = gsw.CT_from_t(SA,t,p) # gsw.CT_from_t(SA, t, p) D = gsw.density.sigma0(SA, CT)# gsw.density.sigma0(SA, CT) plt.plot(D+1000,-p,marker='.',linestyle='None',markersize=1) plt.show()