def test_xarray_with_coords():
    pytest.importorskip('dask')
    SA_chunk = SA.chunk(chunks={'y': 1, 't': 1})
    CT_chunk = CT.chunk(chunks={'y': 1, 't': 1})
    lat_chunk = lat.chunk(chunks={'y': 1})

    # Dimensions and cordinates match:
    expected = gsw.sigma0(SA_vals, CT_vals)
    xarray = gsw.sigma0(SA, CT)
    chunked = gsw.sigma0(SA_chunk, CT_chunk)
    assert_allclose(xarray, expected)
    assert_allclose(chunked, expected)

    # Broadcasting along dimension required (dimensions known)
    expected = gsw.alpha(SA_vals, CT_vals, p_vals[np.newaxis, :, np.newaxis])
    xarray = gsw.alpha(SA, CT, p)
    chunked = gsw.alpha(SA_chunk, CT_chunk, p)
    assert_allclose(xarray, expected)
    assert_allclose(chunked, expected)

    # Broadcasting along dimension required (dimensions unknown/exclusive)
    expected = gsw.z_from_p(p_vals[:, np.newaxis], lat_vals[np.newaxis, :])
    xarray = gsw.z_from_p(p, lat)
    chunked = gsw.z_from_p(p, lat_chunk)
    assert_allclose(xarray, expected)
    assert_allclose(chunked, expected)
    def interpolate(self):
        self.ipres = range(int(min(self.pres)),int(max(self.pres)))
        if len(self.pres)>4:

            self.isals = np.interp(self.ipres,self.pres,self.sals)
            self.itemps = np.interp(self.ipres,self.pres,self.temps)
            if hasattr(self,"knownu"):
                self.iknownu = np.interp(self.ipres,self.pres,self.knownu)
                self.iknownv = np.interp(self.ipres,self.pres,self.knownv)
            if hasattr(self,"knownpsi"):
                self.iknownpsi = np.interp(self.ipres,self.pres,self.knownpsi)

            if hasattr(self,"kapredi"):
                self.ikapredi = np.interp(self.ipres,self.pres,self.kapredi)
                self.idiffkr = np.interp(self.ipres,self.pres,self.diffkr)
                self.ikapgm = np.interp(self.ipres,self.pres,self.kapgm)
            #plt.plot(self.temps,self.pres)
            #plt.plot(self.itemps,self.ipres)
            #plt.show()
            self.ialpha = gsw.alpha(self.isals,self.itemps,self.ipres)
            self.ibeta = gsw.beta(self.isals,self.itemps,self.ipres)
            self.idalphadtheta = gsw.cabbeling(self.isals,self.itemps,self.ipres)
            self.idalphadp = gsw.thermobaric(self.isals,self.itemps,self.ipres)

            ###using gsw
            self.n2 = gsw.Nsquared(self.isals,self.itemps,self.ipres,self.maplat)[0]
Exemple #3
0
def calc_buoyancyflux(ds,xv,yv):
    import gsw
    
    # Calculate buoyancy flux
    r0 = gsw.rho(ds.variables['vosaline'][0,0,yv,xv],ds.variables['votemper'][0,0,yv,xv],0)
    alpha = gsw.alpha(ds.variables['vosaline'][0,0,yv,xv],ds.variables['votemper'][0,0,yv,xv],0)
    beta = gsw.beta(ds.variables['vosaline'][0,0,yv,xv],ds.variables['votemper'][0,0,yv,xv],0)
    D_T = -(alpha/gsw.cp0)*ds.variables['sohefldo'][0,yv,xv]
    D_S = r0*beta*ds.variables['vosaline'][0,0,yv,xv]*ds.variables['sowaflup'][0,yv,xv]/1000
    
    return D_T + D_S
def _main(args):
    """Run the command line program."""

    temperature_cube, temperature_history = gio.combine_files(args.temperature_file, args.temperature_var, checks=True)
    salinity_cube, salinity_history = gio.combine_files(args.salinity_file, 'sea_water_salinity', checks=True)
   
    assert 'c' in str(temperature_cube.units).lower(), "Input temperature units must be in celsius"
#    if not 'C' in str(bigthetao_cube.units):
#        bigthetao_cube.data = bigthetao_cube.data - 273.15
#        data_median = np.ma.median(bigthetao_cube.data)
#        assert data_median < 100
#        assert data_median > -10
#        bigthetao_cube.units = 'C'

    target_shape = temperature_cube.shape[1:]
    depth = temperature_cube.coord('depth').points * -1
    broadcast_depth = uconv.broadcast_array(depth, 0, target_shape)
    broadcast_longitude = uconv.broadcast_array(temperature_cube.coord('longitude').points, [1, 2], target_shape)
    broadcast_latitude = uconv.broadcast_array(temperature_cube.coord('latitude').points, [1, 2], target_shape)
    pressure = gsw.p_from_z(broadcast_depth, broadcast_latitude)

    absolute_salinity = gsw.SA_from_SP(salinity_cube.data, pressure, broadcast_longitude, broadcast_latitude)
    if args.temperature_var == 'sea_water_conservative_temperature':
        conservative_temperature = temperature_cube.data
    elif args.temperature_var == 'sea_water_potential_temperature':  
        conservative_temperature = gsw.CT_from_pt(absolute_salinity, temperature_cube.data)
    else:
        raise ValueError('Invalid temperature variable')

    if args.coefficient == 'alpha':
        coefficient_data = gsw.alpha(absolute_salinity, conservative_temperature, pressure)
        var_name = 'alpha'
        standard_name = 'thermal_expansion_coefficient'
        long_name = 'thermal expansion coefficient'
        units = '1/K'
    elif args.coefficient == 'beta':
        coefficient_data = gsw.beta(absolute_salinity, conservative_temperature, pressure)
        var_name = 'beta'
        standard_name = 'saline_contraction_coefficient'
        long_name = 'saline contraction coefficient'
        units = 'kg/g'
    else:
        raise ValueError('Coefficient must be alpha or beta')

    iris.std_names.STD_NAMES[standard_name] = {'canonical_units': units}
    coefficient_cube = temperature_cube.copy()
    coefficient_cube.data = coefficient_data
    coefficient_cube.standard_name = standard_name    
    coefficient_cube.long_name = long_name
    coefficient_cube.var_name = var_name
    coefficient_cube.units = units

    coefficient_cube.attributes['history'] = cmdprov.new_log(git_repo=repo_dir)
    iris.save(coefficient_cube, args.outfile)
    def get_alpha(self):
        """
        Get alpha
        
        Requires absolute salinity and conservative temperature to have been
        calculated already
        """
        if not hasattr(self, 'CT'): self.get_CT()
        if not hasattr(self, 'SA'): self.get_SA()

        self.alpha = gsw.alpha(self.SA, self.CT, self.pressure)
        return self.alpha
Exemple #6
0
def plot_RTS_profile(ax, z, R, T, S):
    """ plot density (R) temperature (T) and salinity (S) profiles in common axis
      with correctly scaled axis"""

    col = plt.get_cmap("tab10")

    # create axis tripplett
    ax1 = [ax]
    ax1.append(ax.twiny())
    ax1.append(ax.twiny())
    # right, left, top, bottom
    ax1[2].spines['top'].set_position(('outward', 40))

    i = -1
    i += 1  # density
    ax1[i].plot(R, z, color=col(i), Linewidth=1, Linestyle='-', Label=r'')
    ax1[i].xaxis.label.set_color(color=col(i))
    ax1[i].tick_params(axis='x', colors=col(i))
    ax1[i].set_xlabel(r'$\langle\rho\rangle_t$  (kg/m$^3$)', fontsize=12)

    i += 1  # temperature
    ax1[i].plot(T, z, color=col(i), Linewidth=1, Linestyle='-', Label=r'')
    ax1[i].xaxis.label.set_color(color=col(i))
    ax1[i].tick_params(axis='x', colors=col(i))
    ax1[i].set_xlabel(r'$\langle T \rangle_t$  ($^\circ$C)', fontsize=12)

    i += 1  # salinity
    ax1[i].plot(S, z, color=col(i), Linewidth=1, Linestyle='-', Label=r'')
    ax1[i].xaxis.label.set_color(color=col(i))
    ax1[i].tick_params(axis='x', colors=col(i))
    ax1[i].set_xlabel(r'$\langle S \rangle_t$  (g/kg)', fontsize=12)

    #---------------set correct lims-----------------
    rho_lims = ax1[0].get_xlim()
    T_lims = ax1[1].get_xlim()
    S_lims = ax1[2].get_xlim()
    import gsw  # sea water tool box
    Tcenter = np.mean(T_lims)
    Scenter = np.mean(S_lims)
    rho0 = 1015
    alpha = -gsw.alpha(Scenter, Tcenter, 1)
    T_lims = Tcenter + np.array([-1, 1
                                 ]) * np.diff(rho_lims) * .5 / alpha / rho0
    beta = gsw.beta(Scenter, Tcenter, 1)
    S_lims = Scenter + np.array([-1, 1]) * np.diff(rho_lims) * .5 / beta / rho0

    ax1[1].set_xlim(T_lims)
    ax1[2].set_xlim(S_lims)
Exemple #7
0
    def interpolate(self):
        self.ipres = range(int(min(self.pres)), int(max(self.pres)))
        if len(self.pres) > 4:

            self.isals = np.interp(self.ipres, self.pres, self.sals)
            self.itemps = np.interp(self.ipres, self.pres, self.temps)
            self.igamma = np.interp(self.ipres, self.pres, self.gamma)
            self.ialpha = gsw.alpha(self.isals, self.itemps, self.ipres)
            self.ibeta = gsw.beta(self.isals, self.itemps, self.ipres)
            self.idalphadtheta = gsw.cabbeling(self.isals, self.itemps,
                                               self.ipres)
            self.idalphadp = gsw.thermobaric(self.isals, self.itemps,
                                             self.ipres)

            ###using gsw
            self.n2 = gsw.Nsquared(self.isals, self.itemps, self.ipres,
                                   self.lat)[0]
Exemple #8
0
def turner(datadir, filename):
    """
    compute turner angle for data contained in filename
    """
    data = xr.open_dataset(os.path.join(datadir, filename))
    T = data.ptemp.values
    S = data.ab_sal.values
    lon = data.lon.values[np.isreal(data.lon.values)][0]
    lat = data.lat.values[np.isreal(data.lat.values)][0]
    p = data.DEPTH.values
    alpha = gsw.alpha(S, T, p)
    beta = gsw.beta(S, T, p)
    ta = turner_angle(np.gradient(T, -p), np.gradient(S, -p), alpha, beta)
    colorcycle = [i['color'] for i in rcParams['axes.prop_cycle']]
    c = np.array([colorcycle[0] for i in ta])
    c[ta > 0] = colorcycle[1]
    plt.scatter(p, ta, c=c, s=2)
    return ([i for i in p], [i for i in ta])
Exemple #9
0
def extractPointSurfaces(fname,fields={}):
    if len(fields.keys())<1:
        fields = {"lat":"lat","lon":"lon","pres":"P_gamma",\
            "s":"NS_S","ct":"NS_CT","pv":"PV","psi":"accpo","dthetads":"dCTdS"}
    ctddata = sio.loadmat(fname)
    lats = np.asarray(ctddata[fields["lat"]])[0]
    lons = np.asarray(ctddata[fields["lon"]])[0]
    nspres = np.asarray(ctddata[fields["pres"]]).T
    PV = np.asarray(ctddata[fields["pv"]]).T
    NS_CT = np.asarray(ctddata[fields["ct"]]).T
    dCTdS = np.asarray(ctddata[fields["dthetads"]]).T
    NS_S = np.asarray(ctddata[fields["s"]]).T
    ACCPO = np.asarray(ctddata[fields["psi"]]).T
    ns = np.asarray(ctddata["P_gref"])
    profiles = []
    surfaces = {}

    for j in Bar("surface").iter(range(len(ns))):
        tempSurf = nstools.emptySurface()
        tempSurf["data"]["psi"] = []
        tempSurf["data"]["dthetads"] = []
        tempSurf["data"]["dalphadp"] = []
        tempSurf["data"]["dalphadtheta"] = []
        for p in range(len(lats)):
            if lats[p]>20 and lons[p]<0 or lons[p] > 170:
                tempSurf["lats"].append(lats[p])
                tempSurf["lons"].append(lons[p])
                tempSurf["ids"].append(p)
                tempSurf["data"]["pres"].append(nspres[p][j])
                tempSurf["data"]["t"].append(NS_CT[p][j])
                tempSurf["data"]["s"].append(NS_S[p][j])
                tempSurf["data"]["psi"].append(ACCPO[p][j])

                tempSurf["data"]["pv"].append(PV[p][j])
                tempSurf["data"]["n^2"].append(np.nan)
                tempSurf["data"]["dalphadp"].append(gsw.thermobaric(NS_S[p][j],NS_CT[p][j],nspres[p][j]))
                tempSurf["data"]["dalphadtheta"].append(gsw.cabbeling(NS_S[p][j],NS_CT[p][j],nspres[p][j]))
                tempSurf["data"]["alpha"].append(gsw.alpha(NS_S[p][j],NS_CT[p][j],nspres[p][j]))
                tempSurf["data"]["beta"].append(gsw.beta(NS_S[p][j],NS_CT[p][j],nspres[p][j]))
                tempSurf["data"]["dthetads"].append(dCTdS[p][j])
        surfaces[ns[j][0]] = tempSurf
    return surfaces
Exemple #10
0
    def derive(self,property):
        """

        Derives seawater properties as salinity, buoyancy frequency squared etc.
        Args:
            ST:
            N2:
        """

        try:
            gsw
        except:
            logger.warning('GSW toolbox missing, derive will not work, doing nothing')
            return
        
        if(property == 'ST'):
            # Poor mans check if the variables exist
            sensor_pair0 = False
            sensor_pair1 = False
            try:
                tmp1 = self.data['cond0']
                tmp1 = self.data['temp0']
                tmp1 = self.data['p']
                sensor_pair0 = True
            except:
                sensor_pair0 = False

            try:
                tmp1 = self.data['cond1']
                tmp1 = self.data['temp1']
                tmp1 = self.data['p']
                sensor_pair1 = True
            except:
                sensor_pair1 = False                
                
                
            if(sensor_pair0):
                logger.debug('Calculating PSU0/SA11/CT11/rho11')
                SP = gsw.SP_from_C(self.data['cond0'],self.data['temp0'],self.data['p'])
                self.derived['SP00'] = SP
                SA = gsw.SA_from_SP(SP,self.data['p'],self.header['lon'],self.header['lat'])
                self.derived['SA00'] = SA
                CT = gsw.CT_from_t(SA,self.data['temp0'],self.data['p'])
                self.derived['CT00'] = CT
                rho = gsw.rho_CT_exact(SA,CT,self.data['p'])
                self.derived['rho00'] = rho
            if(sensor_pair1):
                logger.debug('Calculating PSU1/SA11/CT11/rho11') 
                SP = gsw.SP_from_C(self.data['cond1'],self.data['temp1'],self.data['p'])
                self.derived['SP11'] = SP
                SA = gsw.SA_from_SP(SP,self.data['p'],self.header['lon'],self.header['lat'])
                self.derived['SA11'] = SA
                CT = gsw.CT_from_t(SA,self.data['temp1'],self.data['p'])
                self.derived['CT11'] = CT
                rho = gsw.rho_CT_exact(SA,CT,self.data['p'])
                self.derived['rho11'] = rho                
                
                
        if(property == 'N2'):
            # Poor mans check if the variables exist
            sensor_pair0 = False
            sensor_pair1 = False
            try:
                tmp1 = self.derived['SA00']
                tmp1 = self.derived['CT00']                
                tmp1 = self.data['p']
                sensor_pair0 = True
            except:
                logger.info('Did not find absolute salinities and temperature, do first a .derive("ST")')
                sensor_pair0 = False

            try:
                tmp1 = self.derived['SA11']
                tmp1 = self.derived['CT11']                
                tmp1 = self.data['p']
                sensor_pair1 = True
            except:
                logger.info('Did not find absolute salinities and temperature, do first a .derive("ST")')
                sensor_pair1 = False

            if(sensor_pair0):
                logger.debug('Calculating Nsquared00')
                [N2,p_mid] = gsw.Nsquared(self.derived['SA00'],self.derived['CT00'],self.data['p'])
                self.derived['Nsquared00'] = interp(self.data['p'],p_mid,N2)
            if(sensor_pair1):
                logger.debug('Calculating Nsquared11')                
                [N2,p_mid] = gsw.Nsquared(self.derived['SA11'],self.derived['CT11'],self.data['p'])
                self.derived['Nsquared11'] = interp(self.data['p'],p_mid,N2)
                
                
        if(property == 'alphabeta'):
            # Poor mans check if the variables exist
            sensor_pair0 = False
            sensor_pair1 = False
            try:
                tmp1 = self.derived['SA00']
                tmp1 = self.derived['CT00']                
                tmp1 = self.data['p']
                sensor_pair0 = True
            except:
                logger.info('Did not find absolute salinities and temperature, do first a .derive("ST")')
                sensor_pair0 = False

            try:
                tmp1 = self.derived['SA11']
                tmp1 = self.derived['CT11']                
                tmp1 = self.data['p']
                sensor_pair1 = True
            except:
                logger.info('Did not find absolute salinities and temperature, do first a .derive("ST")')
                sensor_pair1 = False
                

            if(sensor_pair0):
                logger.debug('Calculating Nsquared00')
                alpha = gsw.alpha(self.derived['SA00'],self.derived['CT00'],self.data['p'])
                beta = gsw.beta(self.derived['SA00'],self.derived['CT00'],self.data['p'])
                self.derived['alpha00'] = alpha
                self.derived['beta00'] = beta
            if(sensor_pair1):
                logger.debug('Calculating Nsquared11')                
                alpha = gsw.alpha(self.derived['SA11'],self.derived['CT11'],self.data['p'])
                beta = gsw.beta(self.derived['SA11'],self.derived['CT11'],self.data['p'])
                self.derived['alpha11'] = alpha
                self.derived['beta11'] = beta
Exemple #11
0
def alphabeta(S, T, P):
    SA = gsw.SA_from_SP(S, P, 6., 42.)
    CT = gsw.CT_from_t(SA, T, P)
    return gsw.alpha(SA, CT, P), gsw.beta(SA, CT, P)