Пример #1
0
    def get_meteo(self,start_time, end_time):

        start = self.df.index.searchsorted(start_time)
        end = self.df.index.searchsorted(end_time)
        # print meteo.columns.tolist()
        cols=[0,1,2,3,6,7,8,9,13,14,15]
        meteo=self.df.ix[start:end,cols].copy()

        ''' pressure '''
        pres = meteo.apres.values
        
        ''' add relative humidity '''
        temp = meteo.atemp.values
        dewp = meteo.dewp.values
        relh = thermo.relative_humidity(C=temp,Dewp=dewp) # [%]
        meteo.loc[:,'relh'] = pd.Series(relh,index=meteo.index)

        ''' mixing ratio '''
        satmixr=thermo.sat_mix_ratio(C=temp,hPa=pres)
        mixr=relh*satmixr/100

        ''' add theta '''
        theta = thermo.theta2(C=temp,hPa=pres,mixing_ratio=mixr)
        meteo.loc[:,'theta'] = pd.Series(theta,index=meteo.index)    

        ''' add thetav '''
        thetav = thermo.virtual_temperature(theta=theta,mixing_ratio=mixr)
        meteo.loc[:,'thetav'] = pd.Series(thetav,index=meteo.index)    

        ''' add thetae '''
        thetaeq = thermo.theta_equiv2(C=temp,hPa=pres,
                                      mixing_ratio=mixr,relh=relh)
        meteo.loc[:,'thetaeq'] = pd.Series(thetaeq,index=meteo.index)    
        
        return meteo
Пример #2
0
def parse_acft_sounding(flight_level_file, req_ini, req_end, return_interp):

    raw = pd.read_table(flight_level_file, engine='python', delimiter='\s*')

    ini_raw = raw['TIME'].iloc[0]
    end_raw = raw['TIME'].iloc[-1]
    timestamp = pd.date_range(
        '2001-01-23 '+ini_raw, '2001-01-24 '+end_raw, freq='s')
    raw.index = timestamp
    raw.drop(['TIME'], axis=1, inplace=True)

    ''' req_ini and req_end are python datatime variables '''
    st = raw.index.searchsorted(req_ini)
    en = raw.index.searchsorted(req_end)
    data = raw[['PRES_ALT', 'AIR_PRESS', 'AIR_TEMP', 'DEW_POINT',
                'WIND_SPD', 'WIND_DIR', 'LAT', 'LON']].ix[st:en]

    x = data['PRES_ALT'].values
    xnew = np.linspace(min(x), max(x), x.size)

    if x[0] > x[-1]:
        descening = True
        data = data.iloc[::-1]

    if return_interp:
        ''' flight sounding might include constant height levels
        or descening trayectories, so we interpolate data to a
        common vertical grid '''
        data2 = data.drop_duplicates(subset='PRES_ALT')
        x2 = data2['PRES_ALT'].values

        ''' interpolate each field '''
        for n in ['AIR_PRESS', 'AIR_TEMP', 'DEW_POINT', 'WIND_SPD', 'WIND_DIR']:
            y = data2[n].values
            # spl = UnivariateSpline(x2,y,k=4)
            # data[n]= spl(xnew)
            rbf = Rbf(x2, y, smooth=1.0)
            ynew = rbf(xnew)
            data[n] = ynew

        '''' update values '''
        data['PRES_ALT'] = xnew

        ''' set index '''
        data = data.set_index('PRES_ALT')

        ''' compute thermo '''
        hgt = data.index.values
        Tc = data['AIR_TEMP']
        Tk = Tc+273.15
        press = data['AIR_PRESS']
        dewp = data['DEW_POINT']
        Rh = tm.relative_humidity(C=Tc, Dewp=dewp)
        Sat_mixr = tm.sat_mix_ratio(C=Tc, hPa=press)
        Mr = Rh*Sat_mixr/100.
        theta = tm.theta2(K=Tk, hPa=press, mixing_ratio=Mr)
        thetaeq = tm.theta_equiv2(K=Tk, hPa=press, relh=Rh, mixing_ratio=Mr)
        data['theta'] = theta.values
        data['thetaeq'] = thetaeq.values
        bvf_dry = tm.bv_freq_dry(
            theta=theta, agl_m=hgt, depth_m=100, centered=True)
        bvf_moist = tm.bv_freq_moist(K=Tk, hPa=press, mixing_ratio=Mr,
                                     agl_m=hgt, depth_m=100, centered=True)

        data = pd.merge(
            data, bvf_dry, left_index=True, right_index=True, how='outer')
        data = pd.merge(
            data, bvf_moist, left_index=True, right_index=True, how='outer')
        data.bvf_dry.interpolate(method='linear', inplace=True)
        data.bvf_moist.interpolate(method='linear', inplace=True)

        ''' drop last incorrect decreasing (increasing) altitude (pressure) value '''
        data2 = data.ix[:xnew[-2]]

        ''' return dataframe '''
        return data2
    else:
        hgt = data['PRES_ALT']
        Tc = data['AIR_TEMP']
        Tk = Tc+273.15
        press = data['AIR_PRESS']
        dewp = data['DEW_POINT']
        Rh = tm.relative_humidity(C=Tc, Dewp=dewp)
        Sat_mixr = tm.sat_mix_ratio(C=Tc, hPa=press)
        Mr = Rh*Sat_mixr/100.
        theta = tm.theta2(K=Tk, hPa=press, mixing_ratio=Mr)
        thetaeq = tm.theta_equiv2(K=Tk, hPa=press, relh=Rh, mixing_ratio=Mr)
        data['theta'] = theta.values
        data['thetaeq'] = thetaeq.values
        data['bvf_dry'] = np.nan
        data['bvf_moist'] = np.nan

        return data
Пример #3
0
def parse_sounding(file_sound):

    col_names = get_var_names(file_sound)
    # col_units = get_var_units(file_sound)

    ''' read tabular file '''
    raw_sounding = pd.read_table(file_sound, skiprows=36, header=None)
    raw_sounding.drop(19, axis=1, inplace=True)
    raw_sounding.columns = col_names
    sounding = raw_sounding[
        ['Height', 'TE', 'TD', 'RH', 'u', 'v', 'P', 'MR', 'DD']]
    sounding.units = {'Height': 'm', 'TE': 'K', 'TD': 'K',
                      'RH': '%', 'u': 'm s-1', 'v': 'm s-1',
                      'P': 'hPa', 'MR': 'g kg-1'}

    ''' replace nan values '''
    nan_value = -32768.00
    sounding = sounding.applymap(lambda x: np.nan if x == nan_value else x)

    ''' QC soundings that include descening trayectories;
        criteria is 3 consecutive values descending
    '''
    sign = np.sign(np.diff(sounding['Height']))
    rep = find_repeats(sign.tolist(), -1, 3)
    try:
        lastgood = np.where(rep)[0][0]-1
        sounding = sounding.ix[0:lastgood]
    except IndexError:
        ''' all good'''
        pass

    ''' set index '''
    sounding = sounding.set_index('Height')

    ''' QC  '''
    sounding = sounding.groupby(sounding.index).first()
    sounding.dropna(how='all', inplace=True)
    sounding.RH = sounding.RH.apply(lambda x: 100 if x > 100 else x)
    u_nans = nan_fraction(sounding.u)
    v_nans = nan_fraction(sounding.v)
    if u_nans > 0. or v_nans > 0.:
        sounding.u.interpolate(method='linear', inplace=True)
        sounding.v.interpolate(method='linear', inplace=True)
    rh_nans = nan_fraction(sounding.RH)
    td_nans = nan_fraction(sounding.TD)
    mr_nans = nan_fraction(sounding.MR)
    if rh_nans < 5. and td_nans > 50. and mr_nans > 50.:
        sat_mixr = tm.sat_mix_ratio(K=sounding.TE, hPa=sounding.P)
        mixr = (sounding.RH/100)*sat_mixr*1000
        sounding.loc[:, 'MR'] = mixr  # [g kg-1]

    ''' add potential temperature '''
    theta = tm.theta2(
        K=sounding.TE, hPa=sounding.P, mixing_ratio=sounding.MR/1000)
    thetaeq = tm.theta_equiv2(K=sounding.TE, hPa=sounding.P,
                              relh=sounding.RH, mixing_ratio=sounding.MR/1000)
    sounding.loc[:, 'theta'] = pd.Series(theta, index=sounding.index)
    sounding.loc[:, 'thetaeq'] = pd.Series(thetaeq, index=sounding.index)

    ''' add Brunt-Vaisala frequency '''
    hgt = sounding.index.values
    bvf_dry = tm.bv_freq_dry(theta=sounding.theta, agl_m=hgt,
                             depth_m=100, centered=True)
    bvf_moist = tm.bv_freq_moist(K=sounding.TE, hPa=sounding.P,
                                 mixing_ratio=sounding.MR/1000,
                                 agl_m=hgt, depth_m=100, centered=True)

    sounding = pd.merge(
        sounding, bvf_dry, left_index=True, right_index=True, how='outer')
    sounding = pd.merge(
        sounding, bvf_moist, left_index=True, right_index=True, how='outer')

    ''' interpolate between layer-averaged values '''
    sounding.bvf_dry.interpolate(method='linear', inplace=True)
    sounding.bvf_moist.interpolate(method='linear', inplace=True)
    sounding.loc[sounding.MR.isnull(), 'bvf_dry'] = np.nan
    sounding.loc[sounding.MR.isnull(), 'bvf_moist'] = np.nan

    '''     NOTE: if sounding hgt jumps from 12 to 53m then 12m
        bvf values are NaN since there are no data between 12
        and 53m to calculate a layer-based value.
    '''

    return sounding
Пример #4
0
def parse_sounding2(file_sound):
    '''
    This version make a resample of vertical gates
    and uses make_layer2 in bvf calculations
    (Thermodyn module)
    '''

    col_names = get_var_names(file_sound)
    # col_units = get_var_units(file_sound)

    ''' read tabular file '''
    raw_sounding = pd.read_table(file_sound, skiprows=36, header=None)
    raw_sounding.drop(19, axis=1, inplace=True)
    raw_sounding.columns = col_names
    sounding = raw_sounding[
        ['Height', 'TE', 'TD', 'RH', 'u', 'v', 'P', 'MR', 'DD']]
    sounding.units = {'Height': 'm', 'TE': 'K', 'TD': 'K',
                      'RH': '%', 'u': 'm s-1', 'v': 'm s-1',
                      'P': 'hPa', 'MR': 'g kg-1'}

    ''' replace nan values '''
    nan_value = -32768.00
    sounding = sounding.applymap(lambda x: np.nan if x == nan_value else x)

    ''' QC soundings that include descening trayectories;
        criteria is 3 consecutive values descending
    '''
    sign = np.sign(np.diff(sounding['Height']))
    rep = find_repeats(sign.tolist(), -1, 3)
    try:
        lastgood = np.where(rep)[0][0]-1
        sounding = sounding.ix[0:lastgood]
    except IndexError:
        ''' all good'''
        pass
#    print sounding
    ''' resample to constant height values '''
    resamp = 2  # [m]
    sounding = sounding.set_index('Height')
    hgt = sounding.index.values[-1]
    resample = np.arange(10, hgt, resamp)
    soundres = sounding.loc[resample]
    soundres.iloc[0] = sounding.iloc[0]  # copy first value
    soundres.iloc[-1] = sounding.iloc[-1]  # copy last value
    soundres.interpolate(
        method='linear', inplace=True, limit=80, limit_direction='backward')
    soundres = soundres.reset_index().drop_duplicates(
        subset='Height', keep='first')
    soundres = soundres.set_index('Height')

    ''' QC  '''
    soundres.RH = soundres.RH.apply(lambda x: 100 if x > 100 else x)
    rh_nans = nan_fraction(soundres.RH)  # [%]
    td_nans = nan_fraction(soundres.TD)  # [%]
    mr_nans = nan_fraction(soundres.MR)  # [%]
    if rh_nans < 5. and td_nans > 50. and mr_nans > 50.:
        sat_mixr = tm.sat_mix_ratio(K=soundres.TE, hPa=soundres.P)
        mixr = (soundres.RH/100.)*sat_mixr*1000
        soundres.loc[:, 'MR'] = mixr  # [g kg-1]

    ''' add potential temperature '''
    theta = tm.theta2(K=soundres.TE, hPa=soundres.P, mixing_ratio=soundres.MR/1000)
    thetaeq = tm.theta_equiv2(K=soundres.TE, hPa=soundres.P,
                              relh=soundres.RH, mixing_ratio=soundres.MR/1000)
    soundres.loc[:, 'theta'] = pd.Series(theta, index=soundres.index)
    soundres.loc[:, 'thetaeq'] = pd.Series(thetaeq, index=soundres.index)

    ''' add Brunt-Vaisala frequency '''
    hgt = soundres.index.values
    depth = 100  # [m]
    bvf_dry = tm.bv_freq_dry(theta=soundres.theta, agl_m=hgt, depth_m=depth)
    bvf_moist = tm.bv_freq_moist(K=soundres.TE,
                                 hPa=soundres.P,
                                 mixing_ratio=soundres.MR/1000,
                                 agl_m=hgt, depth_m=depth)

    soundres = pd.merge(
        soundres, bvf_dry, left_index=True, right_index=True, how='outer')
    soundres = pd.merge(
        soundres, bvf_moist, left_index=True, right_index=True, how='outer')

    ''' interpolate between layer-averaged values '''
    soundres.bvf_dry.interpolate(method='cubic', inplace=True)
    soundres.bvf_moist.interpolate(method='cubic', inplace=True)

    return soundres
Пример #5
0
def plot_thermo(**kwargs):

    hgt = kwargs['hgt']  #[hPa]
    pres = kwargs['press']  #[hPa]
    TE = kwargs['temp']  # [C]
    TD = kwargs['dewp']  # [C]
    U = kwargs['u']  # [m s-1]
    V = kwargs['v']  # [m s-1]
    date = kwargs['date']
    loc = kwargs['loc']
    theta = kwargs['theta']
    thetaeq = kwargs['thetaeq']
    BVFd = kwargs['bvf_dry']
    BVFm = kwargs['bvf_moist']
    hgt_lim = kwargs['top']

    relh = thermo.relative_humidity(C=TE, Dewp=TD)
    sat_mixr = thermo.sat_mix_ratio(C=TD, hPa=pres)
    mixr = relh * sat_mixr / 100.

    fig, ax = plt.subplots(1, 5, sharey=True, figsize=(11, 8.5))

    n = 0
    ax[n].plot(TE, hgt, label='Temp')
    ax[n].plot(TD, hgt, label='Dewp')
    ax[n].legend()
    ax[n].set_xlim([-30, 20])
    ax[n].set_ylim([0, hgt_lim])
    add_minor_grid(ax[n])
    ax[n].set_xlabel('T [C]')
    ax[n].set_ylabel('Altitude [m]')

    n = 1
    ln1 = ax[n].plot(mixr * 1000., hgt, label='mixr')
    ax[n].set_xlim([0, 8])
    ax[n].set_ylim([0, hgt_lim])
    add_minor_grid(ax[n])
    for label in ax[n].xaxis.get_ticklabels()[::2]:
        label.set_visible(False)
    ax[n].set_xlabel('MR [g kg-1]')
    axt = ax[n].twiny()
    ln2 = axt.plot(relh, hgt, 'g', label='relh')
    axt.set_xlim([0, 100])
    axt.set_ylim([0, hgt_lim])
    axt.set_xlabel('RH [%]')
    axt.xaxis.set_label_coords(0.5, 1.04)
    axt.grid(False)
    lns = ln1 + ln2
    labs = [l.get_label() for l in lns]
    axt.legend(lns, labs, loc=0)

    n = 2
    ax[n].plot(theta, hgt, label='Theta')
    ax[n].plot(thetaeq, hgt, label='ThetaEq')
    ax[n].legend()
    ax[n].set_xlim([280, 320])
    ax[n].set_ylim([0, hgt_lim])
    add_minor_grid(ax[n])
    for label in ax[n].xaxis.get_ticklabels()[::2]:
        label.set_visible(False)
    ax[n].set_xlabel('Theta [K]')

    n = 3
    ax[n].plot(U, hgt, label='u')
    ax[n].plot(V, hgt, label='v')
    ax[n].axvline(x=0, linestyle=':', color='r')
    ax[n].legend()
    ax[n].set_xlim([-10, 40])
    ax[n].set_ylim([0, hgt_lim])
    add_minor_grid(ax[n])
    ax[n].set_xlabel('WS [ms-1]')

    n = 4
    ax[n].plot(BVFd * 10000., hgt, label='dry')
    ax[n].plot(BVFm * 10000., hgt, label='moist')
    ax[n].axvline(x=0, linestyle=':', color='r')
    ax[n].legend(loc=2)
    ax[n].set_xlim([-6, 6])
    ax[n].set_ylim([0, hgt_lim])
    add_minor_grid(ax[n])
    ax[n].set_xlabel('BVF (x10^-4) [s-1]')

    l1 = 'Sounding from NOAA P3'
    l2 = '\nIni: ' + date[0].strftime('%Y-%b-%d  %H:%M:%S UTC')
    l3 = '\nEnd: ' + date[1].strftime('%Y-%b-%d  %H:%M:%S UTC')
    l4 = '\nLat: ' + '{:.2f}'.format(loc[0]) + ' Lon: ' + '{:.2f}'.format(
        loc[1])

    plt.suptitle(l1 + l2 + l3 + l4, horizontalalignment='right', x=0.9)
    plt.subplots_adjust(bottom=0.06, top=0.89)

    plt.draw()
Пример #6
0
def parse_acft_sounding(flight_level_file, req_ini, req_end, return_interp):

    raw = pd.read_table(flight_level_file, engine='python', delimiter='\s*')

    ini_raw = raw['TIME'].iloc[0]
    end_raw = raw['TIME'].iloc[-1]
    timestamp = pd.date_range('2001-01-23 ' + ini_raw,
                              '2001-01-24 ' + end_raw,
                              freq='s')
    raw.index = timestamp
    raw.drop(['TIME'], axis=1, inplace=True)
    ''' req_ini and req_end are python datatime variables '''
    st = raw.index.searchsorted(req_ini)
    en = raw.index.searchsorted(req_end)
    data = raw[[
        'PRES_ALT', 'AIR_PRESS', 'AIR_TEMP', 'DEW_POINT', 'WIND_SPD',
        'WIND_DIR', 'LAT', 'LON'
    ]].ix[st:en]

    x = data['PRES_ALT'].values
    xnew = np.linspace(min(x), max(x), x.size)

    if x[0] > x[-1]:
        descening = True
        data = data.iloc[::-1]

    if return_interp:
        ''' flight sounding might include constant height levels
        or descening trayectories, so we interpolate data to a
        common vertical grid '''
        data2 = data.drop_duplicates(subset='PRES_ALT')
        x2 = data2['PRES_ALT'].values
        ''' interpolate each field '''
        for n in [
                'AIR_PRESS', 'AIR_TEMP', 'DEW_POINT', 'WIND_SPD', 'WIND_DIR'
        ]:
            y = data2[n].values
            # spl = UnivariateSpline(x2,y,k=4)
            # data[n]= spl(xnew)
            rbf = Rbf(x2, y, smooth=1.0)
            ynew = rbf(xnew)
            data[n] = ynew
        '''' update values '''
        data['PRES_ALT'] = xnew
        ''' set index '''
        data = data.set_index('PRES_ALT')
        ''' compute thermo '''
        hgt = data.index.values
        Tc = data['AIR_TEMP']
        Tk = Tc + 273.15
        press = data['AIR_PRESS']
        dewp = data['DEW_POINT']
        Rh = tm.relative_humidity(C=Tc, Dewp=dewp)
        Sat_mixr = tm.sat_mix_ratio(C=Tc, hPa=press)
        Mr = Rh * Sat_mixr / 100.
        theta = tm.theta2(K=Tk, hPa=press, mixing_ratio=Mr)
        thetaeq = tm.theta_equiv2(K=Tk, hPa=press, relh=Rh, mixing_ratio=Mr)
        data['theta'] = theta.values
        data['thetaeq'] = thetaeq.values
        bvf_dry = tm.bv_freq_dry(theta=theta,
                                 agl_m=hgt,
                                 depth_m=100,
                                 centered=True)
        bvf_moist = tm.bv_freq_moist(K=Tk,
                                     hPa=press,
                                     mixing_ratio=Mr,
                                     agl_m=hgt,
                                     depth_m=100,
                                     centered=True)

        data = pd.merge(data,
                        bvf_dry,
                        left_index=True,
                        right_index=True,
                        how='outer')
        data = pd.merge(data,
                        bvf_moist,
                        left_index=True,
                        right_index=True,
                        how='outer')
        data.bvf_dry.interpolate(method='linear', inplace=True)
        data.bvf_moist.interpolate(method='linear', inplace=True)
        ''' drop last incorrect decreasing (increasing) altitude (pressure) value '''
        data2 = data.ix[:xnew[-2]]
        ''' return dataframe '''
        return data2
    else:
        hgt = data['PRES_ALT']
        Tc = data['AIR_TEMP']
        Tk = Tc + 273.15
        press = data['AIR_PRESS']
        dewp = data['DEW_POINT']
        Rh = tm.relative_humidity(C=Tc, Dewp=dewp)
        Sat_mixr = tm.sat_mix_ratio(C=Tc, hPa=press)
        Mr = Rh * Sat_mixr / 100.
        theta = tm.theta2(K=Tk, hPa=press, mixing_ratio=Mr)
        thetaeq = tm.theta_equiv2(K=Tk, hPa=press, relh=Rh, mixing_ratio=Mr)
        data['theta'] = theta.values
        data['thetaeq'] = thetaeq.values
        data['bvf_dry'] = np.nan
        data['bvf_moist'] = np.nan

        return data
Пример #7
0
def parse_sounding(file_sound):

    col_names = get_var_names(file_sound)
    # col_units = get_var_units(file_sound)
    ''' read tabular file '''
    raw_sounding = pd.read_table(file_sound, skiprows=36, header=None)
    raw_sounding.drop(19, axis=1, inplace=True)
    raw_sounding.columns = col_names
    sounding = raw_sounding[[
        'Height', 'TE', 'TD', 'RH', 'u', 'v', 'P', 'MR', 'DD'
    ]]
    sounding.units = {
        'Height': 'm',
        'TE': 'K',
        'TD': 'K',
        'RH': '%',
        'u': 'm s-1',
        'v': 'm s-1',
        'P': 'hPa',
        'MR': 'g kg-1'
    }
    ''' replace nan values '''
    nan_value = -32768.00
    sounding = sounding.applymap(lambda x: np.nan if x == nan_value else x)
    ''' QC soundings that include descening trayectories;
        criteria is 3 consecutive values descending
    '''
    sign = np.sign(np.diff(sounding['Height']))
    rep = find_repeats(sign.tolist(), -1, 3)
    try:
        lastgood = np.where(rep)[0][0] - 1
        sounding = sounding.ix[0:lastgood]
    except IndexError:
        ''' all good'''
        pass
    ''' set index '''
    sounding = sounding.set_index('Height')
    ''' QC  '''
    sounding = sounding.groupby(sounding.index).first()
    sounding.dropna(how='all', inplace=True)
    sounding.RH = sounding.RH.apply(lambda x: 100 if x > 100 else x)
    u_nans = nan_fraction(sounding.u)
    v_nans = nan_fraction(sounding.v)
    if u_nans > 0. or v_nans > 0.:
        sounding.u.interpolate(method='linear', inplace=True)
        sounding.v.interpolate(method='linear', inplace=True)
    rh_nans = nan_fraction(sounding.RH)
    td_nans = nan_fraction(sounding.TD)
    mr_nans = nan_fraction(sounding.MR)
    if rh_nans < 5. and td_nans > 50. and mr_nans > 50.:
        sat_mixr = tm.sat_mix_ratio(K=sounding.TE, hPa=sounding.P)
        mixr = (sounding.RH / 100) * sat_mixr * 1000
        sounding.loc[:, 'MR'] = mixr  # [g kg-1]
    ''' add potential temperature '''
    theta = tm.theta2(K=sounding.TE,
                      hPa=sounding.P,
                      mixing_ratio=sounding.MR / 1000)
    thetaeq = tm.theta_equiv2(K=sounding.TE,
                              hPa=sounding.P,
                              relh=sounding.RH,
                              mixing_ratio=sounding.MR / 1000)
    sounding.loc[:, 'theta'] = pd.Series(theta, index=sounding.index)
    sounding.loc[:, 'thetaeq'] = pd.Series(thetaeq, index=sounding.index)
    ''' add Brunt-Vaisala frequency '''
    hgt = sounding.index.values
    bvf_dry = tm.bv_freq_dry(theta=sounding.theta,
                             agl_m=hgt,
                             depth_m=100,
                             centered=True)
    bvf_moist = tm.bv_freq_moist(K=sounding.TE,
                                 hPa=sounding.P,
                                 mixing_ratio=sounding.MR / 1000,
                                 agl_m=hgt,
                                 depth_m=100,
                                 centered=True)

    sounding = pd.merge(sounding,
                        bvf_dry,
                        left_index=True,
                        right_index=True,
                        how='outer')
    sounding = pd.merge(sounding,
                        bvf_moist,
                        left_index=True,
                        right_index=True,
                        how='outer')
    ''' interpolate between layer-averaged values '''
    sounding.bvf_dry.interpolate(method='linear', inplace=True)
    sounding.bvf_moist.interpolate(method='linear', inplace=True)
    sounding.loc[sounding.MR.isnull(), 'bvf_dry'] = np.nan
    sounding.loc[sounding.MR.isnull(), 'bvf_moist'] = np.nan
    '''     NOTE: if sounding hgt jumps from 12 to 53m then 12m
        bvf values are NaN since there are no data between 12
        and 53m to calculate a layer-based value.
    '''

    return sounding
Пример #8
0
def parse_sounding2(file_sound):
    '''
    This version make a resample of vertical gates
    and uses make_layer2 in bvf calculations
    (Thermodyn module)
    '''

    col_names = get_var_names(file_sound)
    # col_units = get_var_units(file_sound)
    ''' read tabular file '''
    raw_sounding = pd.read_table(file_sound, skiprows=36, header=None)
    raw_sounding.drop(19, axis=1, inplace=True)
    raw_sounding.columns = col_names
    sounding = raw_sounding[[
        'Height', 'TE', 'TD', 'RH', 'u', 'v', 'P', 'MR', 'DD'
    ]]
    sounding.units = {
        'Height': 'm',
        'TE': 'K',
        'TD': 'K',
        'RH': '%',
        'u': 'm s-1',
        'v': 'm s-1',
        'P': 'hPa',
        'MR': 'g kg-1'
    }
    ''' replace nan values '''
    nan_value = -32768.00
    sounding = sounding.applymap(lambda x: np.nan if x == nan_value else x)
    ''' QC soundings that include descening trayectories;
        criteria is 3 consecutive values descending
    '''
    sign = np.sign(np.diff(sounding['Height']))
    rep = find_repeats(sign.tolist(), -1, 3)
    try:
        lastgood = np.where(rep)[0][0] - 1
        sounding = sounding.ix[0:lastgood]
    except IndexError:
        ''' all good'''
        pass


#    print sounding
    ''' resample to constant height values '''
    resamp = 2  # [m]
    sounding = sounding.set_index('Height')
    hgt = sounding.index.values[-1]
    resample = np.arange(10, hgt, resamp)
    soundres = sounding.loc[resample]
    soundres.iloc[0] = sounding.iloc[0]  # copy first value
    soundres.iloc[-1] = sounding.iloc[-1]  # copy last value
    soundres.interpolate(method='linear',
                         inplace=True,
                         limit=80,
                         limit_direction='backward')
    soundres = soundres.reset_index().drop_duplicates(subset='Height',
                                                      keep='first')
    soundres = soundres.set_index('Height')
    ''' QC  '''
    soundres.RH = soundres.RH.apply(lambda x: 100 if x > 100 else x)
    rh_nans = nan_fraction(soundres.RH)  # [%]
    td_nans = nan_fraction(soundres.TD)  # [%]
    mr_nans = nan_fraction(soundres.MR)  # [%]
    if rh_nans < 5. and td_nans > 50. and mr_nans > 50.:
        sat_mixr = tm.sat_mix_ratio(K=soundres.TE, hPa=soundres.P)
        mixr = (soundres.RH / 100.) * sat_mixr * 1000
        soundres.loc[:, 'MR'] = mixr  # [g kg-1]
    ''' add potential temperature '''
    theta = tm.theta2(K=soundres.TE,
                      hPa=soundres.P,
                      mixing_ratio=soundres.MR / 1000)
    thetaeq = tm.theta_equiv2(K=soundres.TE,
                              hPa=soundres.P,
                              relh=soundres.RH,
                              mixing_ratio=soundres.MR / 1000)
    soundres.loc[:, 'theta'] = pd.Series(theta, index=soundres.index)
    soundres.loc[:, 'thetaeq'] = pd.Series(thetaeq, index=soundres.index)
    ''' add Brunt-Vaisala frequency '''
    hgt = soundres.index.values
    depth = 100  # [m]
    bvf_dry = tm.bv_freq_dry(theta=soundres.theta, agl_m=hgt, depth_m=depth)
    bvf_moist = tm.bv_freq_moist(K=soundres.TE,
                                 hPa=soundres.P,
                                 mixing_ratio=soundres.MR / 1000,
                                 agl_m=hgt,
                                 depth_m=depth)

    soundres = pd.merge(soundres,
                        bvf_dry,
                        left_index=True,
                        right_index=True,
                        how='outer')
    soundres = pd.merge(soundres,
                        bvf_moist,
                        left_index=True,
                        right_index=True,
                        how='outer')
    ''' interpolate between layer-averaged values '''
    soundres.bvf_dry.interpolate(method='cubic', inplace=True)
    soundres.bvf_moist.interpolate(method='cubic', inplace=True)

    return soundres
Пример #9
0
def plot_thermo(**kwargs):

	hgt=kwargs['hgt'] #[hPa]
	pres=kwargs['press'] #[hPa]
	TE=kwargs['temp'] # [C]
	TD=kwargs['dewp'] # [C]
	U=kwargs['u'] # [m s-1]
	V=kwargs['v'] # [m s-1]
	date=kwargs['date']
	loc=kwargs['loc']
	theta=kwargs['theta']
	thetaeq=kwargs['thetaeq']
	BVFd=kwargs['bvf_dry']
	BVFm=kwargs['bvf_moist']
	hgt_lim=kwargs['top']

	relh=thermo.relative_humidity(C=TE,Dewp=TD)
	sat_mixr= thermo.sat_mix_ratio(C=TD, hPa=pres)
	mixr = relh*sat_mixr/100.
	

	fig,ax = plt.subplots(1,5,sharey=True,figsize=(11,8.5))


	n=0
	ax[n].plot(TE,hgt,label='Temp')
	ax[n].plot(TD,hgt,label='Dewp')
	ax[n].legend()
	ax[n].set_xlim([-30,20])
	ax[n].set_ylim([0,hgt_lim])
	add_minor_grid(ax[n])
	ax[n].set_xlabel('T [C]')
	ax[n].set_ylabel('Altitude [m]')

	n=1
	ln1=ax[n].plot(mixr*1000.,hgt,label='mixr')
	ax[n].set_xlim([0,8])
	ax[n].set_ylim([0,hgt_lim])
	add_minor_grid(ax[n])
	for label in ax[n].xaxis.get_ticklabels()[::2]:
		label.set_visible(False)
	ax[n].set_xlabel('MR [g kg-1]')
	axt=ax[n].twiny()
	ln2=axt.plot(relh,hgt,'g',label='relh')
	axt.set_xlim([0,100])
	axt.set_ylim([0,hgt_lim])	
	axt.set_xlabel('RH [%]')
	axt.xaxis.set_label_coords(0.5, 1.04)
	axt.grid(False)
	lns = ln1+ln2
	labs = [l.get_label() for l in lns]
	axt.legend(lns, labs, loc=0)

	n=2
	ax[n].plot(theta,hgt,label='Theta')
	ax[n].plot(thetaeq,hgt,label='ThetaEq')	
	ax[n].legend()
	ax[n].set_xlim([280,320])
	ax[n].set_ylim([0,hgt_lim])
	add_minor_grid(ax[n])
	for label in ax[n].xaxis.get_ticklabels()[::2]:
		label.set_visible(False)
	ax[n].set_xlabel('Theta [K]')

	n=3
	ax[n].plot(U,hgt,label='u')
	ax[n].plot(V,hgt,label='v')
	ax[n].axvline(x=0,linestyle=':',color='r')
	ax[n].legend()
	ax[n].set_xlim([-10,40])
	ax[n].set_ylim([0,hgt_lim])
	add_minor_grid(ax[n])
	ax[n].set_xlabel('WS [ms-1]')

	n=4
	ax[n].plot(BVFd*10000.,hgt,label='dry')
	ax[n].plot(BVFm*10000.,hgt,label='moist')	
	ax[n].axvline(x=0,linestyle=':',color='r')
	ax[n].legend(loc=2)
	ax[n].set_xlim([-6,6])
	ax[n].set_ylim([0,hgt_lim])
	add_minor_grid(ax[n])
	ax[n].set_xlabel('BVF (x10^-4) [s-1]')

	l1='Sounding from NOAA P3'
	l2='\nIni: ' + date[0].strftime('%Y-%b-%d  %H:%M:%S UTC')
	l3='\nEnd: ' + date[1].strftime('%Y-%b-%d  %H:%M:%S UTC')
	l4='\nLat: '+'{:.2f}'.format(loc[0])+' Lon: '+'{:.2f}'.format(loc[1])

	plt.suptitle(l1+l2+l3+l4,horizontalalignment='right',x=0.9)
	plt.subplots_adjust(bottom=0.06,top=0.89)

	plt.draw()