Exemple #1
0
 def get_sounding(self, sounding):
     """
     Ingests the sounding (either a skewt - i.e., UWYO - formatted file
     or a properly formatted dict).
     """
     if sounding is None:
         print('No sounding provided')
         self.T_flag = False
     else:
         if isinstance(sounding, str):
             # Removing exception handling so if SkewT is messing up
             # the end user will understand better how to fix it.
             if True:
                 snd = SkewT.Sounding(sounding)
                 # Test for new version of skewt package
                 if hasattr(snd, 'soundingdata'):
                     self.snd_T = snd.soundingdata['temp']
                     self.snd_z = snd.soundingdata['hght']
                 else:
                     self.snd_T = snd.data['temp']
                     self.snd_z = snd.data['hght']
             else:
                 print('Sounding read fail')
                 self.T_flag = False
         else:
             try:
                 self.snd_T = sounding['T']
                 self.snd_z = sounding['z']
             except:
                 print('Sounding in wrong data format')
                 self.T_flag = False
     self.interpolate_sounding_to_radar()
def plot_sounding(sounding_dict, line_colour=DEFAULT_LINE_COLOUR,
                  line_width=DEFAULT_LINE_WIDTH):
    """Plots atmospheric sounding.

    :param sounding_dict: See documentation for output of
        sounding_table_to_skewt.
    :param axes_object: Instance of `matplotlib.axes._subplots.AxesSubplot`.
    :param line_colour: Colour for dewpoint and temperature traces (in any
        format accepted by `matplotlib.colors`).
    :param line_width: Line width for dewpoint and temperature traces (real
        positive number).
    """

    sounding_object = SkewT.Sounding(data=sounding_dict)
    sounding_object.plot_skewt(color=line_colour, lw=line_width, title='')
def plot_skew2(**kwargs):

    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']
    hgt = kwargs['hgt']

    TD[TD > TE] = TE[TD > TE]

    mydata = dict(zip(('hght', 'pres', 'temp', 'dwpt'), (hgt, pres, TE, TD)))
    S = sk.Sounding(soundingdata=mydata)
    S.plot_skewt()
    plt.draw()
Exemple #4
0
from skewt import SkewT

import os, sys
Dir, filename = os.path.split(os.path.abspath(sys.argv[0]))
Dir = Dir + '\\'

S = SkewT.Sounding("./58457.txt")
S.plot_skewt(imagename='58457', color='b')
Exemple #5
0
10.5 24540 
11.5 20984
'''

std_atm = StringIO(data_std_atm)
height = np.loadtxt(std_atm, usecols=range(0, 1), unpack=True)
print(len(height))
height_m = height * 1000
print(len(height_m))
pressure_pa = pressure
temperature_c = temperature - 273.15
dewpoint_c = dewpoint - 273.15

mydata=dict(zip(('hght','pres','temp','dwpt'),(height_m,pressure_pa,temperature_c,dewpoint_c)))
print(mydata)
S=SkewT.Sounding(soundingdata=mydata)
S.make_skewt_axes(tmin=-40.,tmax=40.,pmin=100.,pmax=1050.)
S.add_profile()
parcel=S.get_parcel(method='sb')
S.lift_parcel(*parcel)
print(parcel)
P_lcl,P_lfc,P_el,CAPE,CIN=S.get_cape(*parcel)
print("CAPE = ",CAPE)
fig.suptitle('NPP MIRS 0751 UTC 27 August 2020')
plt.suptitle('NPP MIRS 0751 UTC 27 August 2020',size=12)
plt.savefig("skewt_0827_sb.png",dpi=250,bbox_inches='tight')
print("Figure saved")
plt.show()

#Compute the Microburst Windspeed Potential Index (MWPI)
Z_UP = 5.5
Exemple #6
0
    Dist[i] = np.array(dfs['dist_clu'][i])

#*****************************************************************************\
case = 0
temperature_c = T[case, :]
dewpoint_c = DP[case, :]
wsp = WSP[case, :] * 1.943844
wdir = DIR[case, :]
date = dfs.index[case]

mydataG1 = dict(
    zip(('hght', 'pres', 'temp', 'dwpt', 'drct', 'sknt', 'StationNumber',
         'SoundingDate'), (height_m, pressure_pa, temperature_c, dewpoint_c,
                           wdir, wsp, 'C3 - ', date)))

S1 = SkewT.Sounding(soundingdata=mydataG1)
S1.plot_skewt(color='r')
plt.savefig(path_data_save + 'C3/C3_' + date.strftime('%Y%m%d') + '_' +
            str(date.hour) + '.png',
            format='png',
            dpi=600)
#*****************************************************************************\
case = 1
temperature_c = T[case, :]
dewpoint_c = DP[case, :]
wsp = WSP[case, :] * 1.943844
wdir = DIR[case, :]
date = dfs.index[case]

mydataG1 = dict(
    zip(('hght', 'pres', 'temp', 'dwpt', 'drct', 'sknt', 'StationNumber',
    cb.ax.set_ylabel('')
    cb.ax.tick_params(length=0)
    return cb


# ----------------------------------------------------------------------
# test of fuzzy logic hydrometeor classification
# ----------------------------------------------------------------------

# Read in the data
filepath = '/data/pyart_examples/'
sndfile = 'snd_Darwin.txt'
radarfile = 'cfrad.20060119_170029.000_to_20060121_020810.000_CPOL_v1_PPI.nc'
radar = pyart.io.read(filepath + radarfile)
print(radar.fields.keys())
sounding = SkewT.Sounding(filepath + sndfile)

# Extract relevant radar fields
dz = radar.fields['ZC']['data']
dr = radar.fields['ZD']['data']
kd = radar.fields['KD']['data']
rh = radar.fields['RH']['data']

# interpolate the sounding to radar grid
radar_T, radar_z = interpolate_sounding_to_radar(sounding, radar)

# run the classification
scores = csu_fhc.csu_fhc_summer(dz=dz,
                                zdr=dr,
                                rho=rh,
                                kdp=kd,
Exemple #8
0
    zip(('hght', 'pres', 'temp', 'dwpt', 'drct', 'sknt', 'StationNumber',
         'SoundingDate'), (height_m, pressure_pa, temperature_c, dewpoint_c,
                           wdir, wsp, 'Cold Fronts 4K', 'C1')))
#DCF
temperature_c = temp_CL4_G1_DCF
dewpoint_c = dewp_CL4_G1_DCF
wsp = wsp_CL4_G1_DCF * 1.943844
wdir = wdir_CL4_G1_DCF

mydataG1_DCF = dict(
    zip(('hght', 'pres', 'temp', 'dwpt', 'drct', 'sknt', 'StationNumber',
         'SoundingDate'), (height_m, pressure_pa, temperature_c, dewpoint_c,
                           wdir, wsp, 'Cold Fronts 4K', 'C1')))

# #Individuals
S = SkewT.Sounding(soundingdata=mydataG1_CF)
S2 = SkewT.Sounding(soundingdata=mydataG1_DCF)
S.make_skewt_axes()
S.add_profile(color='r', bloc=0)
S.soundingdata = S2.soundingdata
S.add_profile(color='b', bloc=1)
plt.savefig(path_data_save + '4K_C1_CF_Dif.png', format='png', dpi=1200)

#*****************************************************************************\
# Cluster 2
#*****************************************************************************\

df_CL4_G2 = df_myclucfro[df_myclucfro['CL_4'] == 2]
df_CL4_G2_DCF = df_CL4_G2[np.isfinite(df_CL4_G2['Dist CFront'])]
df_CL4_G2_CF = df_CL4_G2[np.isnan(df_CL4_G2['Dist CFront'])]
print len(df_CL4_G2), len(df_CL4_G2_CF), len(df_CL4_G2_DCF)
    WSPei=np.sqrt(Uei**2 + Uei**2)
    DIRei=np.arctan2(Uei, Vei)*(180/np.pi)+180
    DIRei[(Uei == 0) & (Vei == 0)]=0
    DP[0]=np.nan

    #*****************************************************************************\
    height=H
    pressure=pres_ei
    temperature=T
    dewpoint=DP
    wsp=WSP*1.943844
    wdir=DIR

    mydataM1=dict(zip(('hght','pres','temp','dwpt','drct','sknt','StationNumber','SoundingDate'),(height,pressure,temperature,dewpoint,wdir,wsp,' ','Case '+str(i+1) +' - 5KC1 ('+str(date)+')')))

    S=SkewT.Sounding(soundingdata=mydataM1)

    #*****************************************************************************\
    height=Hei
    pressure=pres_ei
    temperature=Tei
    dewpoint=DPei
    wsp=WSPei*1.943844
    wdir=DIRei

    mydataE1=dict(zip(('hght','pres','temp','dwpt','drct','sknt','StationNumber','SoundingDate'),(height,pressure,temperature,dewpoint,wdir,wsp,' ','Case '+str(i+1) +' - 5KC1 ('+str(date)+')')))

    S2=SkewT.Sounding(soundingdata=mydataE1)


    S.make_skewt_axes()
for ic in range(cape.shape[0]):

    c = ic  # cell array position to check

    if np.mod(c, 50) == 0: print '%2.2f%%' % (100.0 * float(c) / cape.shape[0])

    snd_dict = {
        'pres': pres[::-1] / 100.0,
        'temp': temp[:, c][::-1],
        'dwpt': dew[:, c][::-1],
        'sknt': spd[:, c][::-1],
        'drct': drct[:, c][::-1]
    }

    s = SkewT.Sounding(data=snd_dict)
    s.plot_skewt(lw=2, title='test', mixdepth=md,
                 pres_s=surf_parc_pres)  #, imagename = 'testsnd.png')
    s_surf = s.surface_parcel(mixdepth=md, pres_s=surf_parc_pres)
    p, tdry, tiso, pwet, twet = s.lift_parcel(s_surf[0], s_surf[1], s_surf[2])

    p_lcl = pwet[0]

    atm = pres / 100. <= surf_parc_pres  # finding pres elements that are above the surface
    p_atm = pres[atm]

    dry = np.where(p_atm / 100.0 >= p_lcl)
    moist = np.where(p_atm / 100.0 < p_lcl)

    for d in dry[0]:
        p_diff = p - p_atm[d] / 100.
Exemple #11
0
    vert_x_array_km = vertgrid.x['data'] / 1000
    vert_y_array_km = vertgrid.y['data'] / 1000
    vert_z_array_km = vertgrid.z['data'] / 1000

    #assign grid lat/lon data to a variable
    vertlat = vertgrid.point_latitude['data']
    vertlon = vertgrid.point_longitude['data']

    #==============================================================================
    #Sounding data
    #==============================================================================
    #read in sounding data
    #    sndfile = '/Users/kurtispinkney/Desktop/MastersThesis/sounding_data/2015/20150619.txt'
    #    sndfile = '/Users/kurtispinkney/Desktop/MastersThesis/sounding_data/2015/'+snd_date+'.txt'
    sndfile = '/Users/kurtispinkney/Desktop/MastersThesis/sounding_data/2016/' + snd_date + '_snd.txt'
    sounding = SkewT.Sounding(sndfile)

    #assign temp and height data to variables
    stemp = sounding.soundingdata['temp']
    stemp = ma.getdata(stemp)
    shght = sounding.soundingdata['hght']
    shght = ma.getdata(shght)

    #find values below 15 km (size of grid in vertical)
    below15hght = shght[np.where(shght < 15000)]
    below15temp = stemp[np.where(shght < 15000)]

    #find important isotherms
    #0°C
    freezelayeridx = np.abs(0 - below15temp).argmin()
    freezelayerhght = below15hght[freezelayeridx] / 1000  #km
Exemple #12
0
def main(argv):
    inputfile = ''
    outputfile = ''
    try:
        opts, args = getopt.getopt(argv, "hi:o:", ["ifile=", "ofile="])
    except getopt.GetoptError:
        print 'test.py -i <inputfile> -o <outputfile>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'test.py -i <inputfile> -o <outputfile>'
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg
    print 'Input file is "', inputfile
    #    print 'Output file is "', outputfile

    #    path = 'L:\Radar2016\sample_data\pky1.vol'
    path = inputfile
    files = sorted(glob.glob(path))

    tstart = dt.datetime.now()
    for filename in files:
        print 'Creating folder ' + filename + '.dir ...'

        #filename = 'n:\\rason1\F2017111606S6008157.csv'

        #StaNo = filename[-20:-15]
        StaNo = '96253'

        rason_datetime = filename[-14:-4]
        #rason_datetime = filename[-22:-12]
        YY = str(rason_datetime[0:4])
        MM = str(rason_datetime[4:6])
        DD = str(rason_datetime[6:8])
        HH = str(rason_datetime[8:10])
        dt_rason = dt.datetime.strptime(YY + '-' + MM + '-' + DD + '_' + HH,
                                        '%Y-%m-%d_%H')
        #dt_rason = dt_rason - dt.timedelta(hours=6) # 6 hours time difference
        strdt_rason = dt_rason.strftime('%Y-%m-%d_%H')

        df = pd.read_csv(filename, nrows=0)
        rason_type = df.columns[0]
        rason_release_date_local = df.columns[4]
        rason_release_time_local = df.columns[5]
        rason_sounding_length = df.columns[7]
        rason_lat = str(round(float(df.columns[9]), 2))
        rason_lon = str(round(float(df.columns[10]), 2))
        rason_observer = df.columns[13]

        newdir = filename + '.dir'
        try:
            os.mkdir(newdir, 0755)
        except:
            print newdir + ' already exists'

        df = pd.read_csv(filename, skiprows=6)

        obstime = df[df.columns[0]].map(
            lambda x: dt.datetime.strptime(str(x), '%H:%M:%S'))  #ObsTime
        height = pad(df[df.columns[11]].replace('-----',
                                                np.nan).astype(float))  #Height
        lat = pad(df[df.columns[17]].replace('-----',
                                             np.nan).astype(float))  #GeodetLat
        lon = pad(df[df.columns[18]].replace('-----',
                                             np.nan).astype(float))  #GeodetLon
        wd = pad(df[df.columns[9]].replace(
            '-----', np.nan).astype(float))  #Wind Direction
        ws = pad(df[df.columns[10]].replace(
            '-----', np.nan).astype(float))  # Wind Speed
        press = df[df.columns[20]].replace('-----', np.nan)  #Pressure
        press = pad(press.replace('------', np.nan).astype(float))
        temp = pad(df[df.columns[21]].replace(
            '-----', np.nan).astype(float))  #Temperature
        rh = pad(df[df.columns[22]].replace(
            '-----', np.nan).astype(float))  #Relative Humidity
        dewtemp = temp - ((100 - rh) / 5.)  # Dewpoint temperature

        #_AllowedKeys=['pres','hght','temp','dwpt','relh','mixr','drct','sknt','thta','thte','thtv']

        mydata=dict(zip(('StationNumber','SoundingDate','hght','pres','temp','dwpt','relh','drct','sknt'),\
        ('Bengkulu ('+StaNo+')', strdt_rason +'UTC', height, press,temp,dewtemp,rh,wd,ws)))
        S = SkewT.Sounding(soundingdata=mydata)

        #S.do_thermodynamics()

        #S.plot_skewt(tmin=-40.,tmax=40.,pmin=100.,pmax=1050.,parcel_type='sb')

        try:
            #S.plot_skewt(tmin=-40.,tmax=40.,pmin=100.,pmax=1050.,parcel_type='mu')
            ##S.plot_skewt(parcel_type='sb',imagename='f:/rason/test.png')

            #S.fig.savefig(newdir+'\\'+StaNo+'_skewt-mu_'+strdt_rason+'.png', format='png', dpi=500)

            #S.plot_skewt(tmin=-40.,tmax=40.,pmin=100.,pmax=1050.,parcel_type='ml')
            ##S.plot_skewt(parcel_type='sb',imagename='f:/rason/test.png')

            #S.fig.savefig(newdir+'\\'+StaNo+'_skewt-ml_'+strdt_rason+'.png', format='png', dpi=500)

            S.plot_skewt(tmin=-40.,
                         tmax=40.,
                         pmin=100.,
                         pmax=1050.,
                         parcel_type='sb')
            #S.plot_skewt(parcel_type='sb',imagename='f:/rason/test.png')

            S.fig.savefig(newdir + '\\' + StaNo + '_skewt-sb_' + strdt_rason +
                          '.png',
                          format='png',
                          dpi=500)
        except:
            #S.make_skewt_axes()
            S.make_skewt_axes(tmin=-40., tmax=40., pmin=100., pmax=1050.)
            #S.make_skewt_axes(tmin=-50,tmax=40,pmin=100)
            S.add_profile(lw=1)
            #pc=S.most_unstable_parcel()
            #sounding.lift_parcel(*pc,totalcape=True)

        #S.fig.savefig('f:/rason/test.png', format='png', dpi=500)
        #S.fig.savefig(newdir+'\\'+strdt_rason+'UTC-bengkulu-skewt.png', format='png', dpi=500)

        #parcel=S.get_parcel()
        #S.lift_parcel(*parcel)
        #S.get_cape(*parcel)

        # Create a Figure Manager
        #mySkewT_Figure = figure()

        # Add an Skew-T axes to the Figure
        #mySkewT_Axes = mySkewT_Figure.add_subplot(111, projection='skewx')

        # Add a profile to the Skew-T diagram
        #mySkewT_Axes.addProfile(press.astype(float),temp.astype(float), dewtemp.astype(float) ,
        #                hPa=True, celsius=True, method=1, diagnostics=True, useVirtual=0)

        # Show the figure
        #mySkewT_Figure.show()

        print 'Plotting figures in ' + filename + '.dir ...'

        # draw figure
        fig = pl.figure(figsize=(10, 8))

        pl.plot(temp.astype(float), height.astype(float) / 1000, 'b')
        pl.plot(dewtemp.astype(float), height.astype(float) / 1000, 'r')
        #pl.xlabel('Temperature (C)')
        pl.ylabel('Height (km)', fontsize=12)
        pl.ylim(0, 30)
        pl.xlim(-120, 40)
        pl.text(-100, -3, 'Temperature (C)', color='b', fontsize=12)
        pl.text(-50, -3, 'Dew Point Temperature (C)', color='r', fontsize=12)
        pl.title('Temperature ' + HH + 'UTC ' + DD + '-' + MM + '-' + YY +
                 ' LON=' + rason_lon + ',LAT=' + rason_lat,
                 fontsize=12)
        #cbar = pl.colorbar(pm, shrink=0.75)
        fig.savefig(newdir + '\\' + StaNo + '_t_' + strdt_rason + '.png',
                    format='png',
                    dpi=500)

        fig = pl.figure(figsize=(10, 8))

        pl.plot(rh.astype(float), height.astype(float) / 1000, 'b')
        #pl.plot(dewtemp.astype(float),height.astype(float)/1000,'r')
        #pl.xlabel('Relative Humidity (%)')
        pl.ylabel('Height (km)', fontsize=12)
        pl.ylim(0, 30)
        pl.xlim(0, 100)
        pl.text(10, -3, 'Relative Humidity (%)', color='b', fontsize=12)
        #pl.text(-100,4000,'Dew point temperature',color='r')
        pl.title('Humidity ' + HH + 'UTC ' + DD + '-' + MM + '-' + YY +
                 ' LON=' + rason_lon + ',LAT=' + rason_lat,
                 fontsize=12)
        #cbar = pl.colorbar(pm, shrink=0.75)
        fig.savefig(newdir + '\\' + StaNo + '_rh_' + strdt_rason + '.png',
                    format='png',
                    dpi=500)

        fig = pl.figure(figsize=(10, 8))
        ax1 = fig.add_subplot(111)
        ax2 = ax1.twiny()

        ax1.plot(wd.astype(float), height.astype(float) / 1000, 'y')
        ax1.set_xlim(0, 360)
        ax1.set_xticks(np.arange(0, 361, 45))
        ax1.set_ylim(0, 30)

        ax2.plot(ws.astype(float), height.astype(float) / 1000, 'g')
        ax2.set_xlim(0, 50)
        ax2.set_ylim(0, 30)
        #pl.xlabel('Temperature (C)')
        ax1.set_ylabel('Height (km)', fontsize=12)
        ax1.text(45, -3, 'Wind Direction (deg)', color='y', fontsize=12)
        ax2.text(5, 32, 'Wind Speed (m/s)', color='g', fontsize=12)
        ax2.text(23,
                 32,
                 'Wind ' + HH + 'UTC ' + DD + '-' + MM + '-' + YY + ' LON=' +
                 rason_lon + ',LAT=' + rason_lat,
                 fontsize=12)
        #pl.title('Wind',fontsize=12)
        #cbar = pl.colorbar(pm, shrink=0.75)

        fig.savefig(newdir + '\\' + StaNo + '_wind_' + strdt_rason + '.png',
                    format='png',
                    dpi=500)
Exemple #13
0
def process_thermal_wx(thermal):

    print 'Calculating WX for {}'.format(thermal)

    lon = thermal.longitude
    lat = thermal.latitude

    terrain = retrieve_band(lat, lon)

    if terrain == -1:
        return

    df = pd.read_csv(thermal_file.format(thermal.thermal_id))

    if len(df.index) < 185:
        df.to_csv(home + "/RAP/CSV/{}.error".format(thermal.thermal_id))
        return

    df['paramId'] = pd.to_numeric(df.paramId, errors='coerce')
    df['value'] = pd.to_numeric(df.value, errors='coerce')
    df['level'] = pd.to_numeric(df.level, errors='coerce')

    # Geopotential Height
    df_hgt = df.loc[df['paramId'] == 156][0:37]
    df_hgt = df_hgt.rename(columns={'value': 'HGT'}).drop('paramId', 1)

    # Temperature
    df_tmp = df.loc[df['paramId'] == 130][0:37]
    df_tmp = df_tmp.rename(columns={'value': 'TMP_K'}).drop('paramId', 1)

    # Relative Humidity
    df_rh = df.loc[df['paramId'] == 157][0:37]
    df_rh = df_rh.rename(columns={'value': 'RH'}).drop('paramId', 1)

    # U component of wind
    df_uw = df.loc[df['paramId'] == 131][0:37]
    df_uw = df_uw.rename(columns={'value': 'W_U'}).drop('paramId', 1)

    # V component of windcd R
    df_vw = df.loc[df['paramId'] == 132][0:37]
    df_vw = df_vw.rename(columns={'value': 'W_V'}).drop('paramId', 1)

    # Ground Temperature
    # df_gtmp = df.loc[df['paramId'] == 167]

    dfs = [df_hgt, df_tmp, df_rh, df_uw, df_vw]

    df_snd = reduce(lambda left, right: pd.merge(left, right, on='level'), dfs)

    # Wind Speed
    df_snd['W_SPD_MS'] = (df_snd.W_U**2 + df_snd.W_V**2)**(0.5)
    df_snd['W_SPD_KTS'] = df_snd.W_SPD_MS * 1.94384

    # Wind Direction
    df_snd['W_DIR'] = np.arctan2(df_snd.W_U, df_snd.W_V) * (180. / np.pi)

    # Temperature in Celcius
    df_snd['TMP_C'] = df_snd.TMP_K - 273.15

    # Dewpoint Temperature
    dew_point(df_snd)

    # Get the lift parcel for the terrain altitude
    parcel = get_parcel_at_hgt(terrain, df_snd)
    df_snd = strip_to_terrain(df_snd, parcel)

    # Retrieve surface temperature
    print parcel
    base_tmp = parcel[1]
    base_hgt = parcel[4]

    thermal['ground_temp_c'] = base_tmp
    thermal['ground_elev'] = base_hgt
    thermal['ground_w_dir'] = parcel[5]
    thermal['ground_w_spd_kts'] = parcel[6]

    # Add the DALR

    df_snd['DALR'] = base_tmp - ((df_snd.HGT - base_hgt) / 1000) * 9.8

    # Virtual Temperature
    df_snd['VIRTT'] = (df_snd.TMP_K) / (1 - 0.379 * (6.11 * np.power(
        ((7.5 * df_snd.DEWP_C) /
         (237.7 + df_snd.DEWP_C)), 10)) / df_snd.level) - 273.15

    # Thermal Index
    df_snd['TI'] = df_snd.TMP_C - df_snd.DALR
    df_snd['TI_ROUND'] = df_snd['TI'].round()

    # Top of lift
    lift_top = np.NAN
    df_lift = df_snd.loc[df_snd['TI_ROUND'] <= 0]
    if len(df_lift.index > 0):
        lift_top = df_lift.iloc[-1]['HGT']

    thermal['lift_top'] = lift_top

    hght = df_snd[['HGT']].as_matrix().flatten()
    pres = df_snd[['level']].as_matrix().flatten()
    temp = df_snd[['TMP_C']].as_matrix().flatten()
    dwpt = df_snd[['DEWP_C']].as_matrix().flatten()
    sknt = df_snd[['W_DIR']].as_matrix().flatten()
    drct = df_snd[['W_SPD_KTS']].as_matrix().flatten()

    mydata = dict(
        zip(('hght', 'pres', 'temp', 'dwpt', 'sknt', 'drct'),
            (hght, pres, temp, dwpt, sknt, drct)))
    S = SkewT.Sounding(soundingdata=mydata)
    S.make_skewt_axes()
    S.add_profile()
    S.lift_parcel(*parcel[0:4])
    Plcl, Plfc, P_el, CAPE, CIN = S.get_cape(*parcel[0:4])
    # S.plot_skewt(title=thermal.time)
    plt.title('Test')
    plt.savefig(home + "/RAP/PNG/{}.png".format(thermal.thermal_id))
    Hlcl = calc_hgt(df_snd, Plcl)
    thermal['H_lcl'] = Hlcl

    Hlfc = Plfc
    if not (math.isnan(Plfc)):
        Hlfc = calc_hgt(df_snd, Plfc)
    thermal['H_lfc'] = Hlfc

    H_el = P_el
    if not (math.isnan(P_el)):
        H_el = calc_hgt(df_snd, P_el)
    thermal['H_el'] = H_el

    thermal['CAPE'] = CAPE
    thermal['CIN'] = CIN

    return thermal
Exemple #14
0
url = 'http://weather.uwyo.edu/cgi-bin/sounding?region=naconf&TYPE=TEXT%3ALIST&YEAR=' + year + '&MONTH=' + month + '&FROM=' + day + hour + '&TO=' + day + hour + '&STNM=' + stn
content = urllib2.urlopen(url).read()

# 2)
# Remove the html tags
soup = BeautifulSoup(content)
data_text = soup.get_text()

# 3)
# Split the content by new line.
splitted = data_text.split("\n", data_text.count("\n"))

#4)
# Must save the processed data as a .txt file to be read in by the skewt module.
# Write this splitted text to a .txt document. Save in current directory.
Sounding_dir = './'
Sounding_filename = str(stn) + '.' + str(year) + str(month) + str(day) + str(
    hour) + '.txt'
f = open(Sounding_dir + Sounding_filename, 'w')
for line in splitted[4:]:
    f.write(line + '\n')
f.close()

#5)
# Add skewt data to plot
S = SkewT.Sounding(filename=Sounding_dir + Sounding_filename)
S.make_skewt_axes(tmin=-40., tmax=50., pmin=100., pmax=1050.)
S.add_profile(bloc=0)
parcel = S.get_parcel()
S.lift_parcel(*parcel)
Exemple #15
0
def plotSkewT(URL, stid):
    date, year, month, day = getDateTime()
    SoundingFile = urllib2.urlopen(URL).read()  #reads sounding file
    filename = str(stid) + 'SoundingFile.html'

    with open(filename, 'w') as fid:
        fid.write(SoundingFile)
        fid.close()

    file = open(filename, "r")

    # Skip the appropriate number of header lines
    for i in range(12):
        line = file.readline()
        if i == 4:
            #stid = line[4:9]
            dtime = line[40:]
            stname = line[10:13]

# Read remaining lines from file into a list of text lines
    lines = file.readlines()

    file.close()
    pres = []
    temp = []
    dwpt = []
    Zsnd = []  #height
    mixingRatio = []
    wsp = []
    wdir = []

    for line in lines:
        words = line.split()
        if len(
                words
        ) != 11:  #this happens when the pressure level doesn't have a measurement for each variable
            break
        pres.append(float(words[0]))
        temp.append(float(words[2]))
        dwpt.append(float(words[3]))
        Zsnd.append(float(words[1]))
        mixingRatio.append(float(words[5]))
        wsp.append(float(words[7]))
        wdir.append(float(words[6]))
    dict = {
        'pres': pres,
        'temp': temp,
        'dwpt': dwpt,
        'drct': wdir,
        'sknt': wsp,
        'hght': Zsnd
    }  #in format for skewT plot

    #Plot Data
    fig = plt.figure()
    plt.rcParams['xtick.labelsize'] = 16
    plt.rcParams['ytick.labelsize'] = 16
    ax = fig.add_subplot(111)
    sounding = SkewT.Sounding(soundingdata=dict)  #plots skew T
    if stname == 'GRB':  #the following if statements are for the title of each graph
        station = 'Green Bay, WI'
    if stname == 'MPX':
        station = 'Chanhassen, MN'
    if stname == 'DVN':
        station = 'Davenport, IA'
    if stname == 'ILX':
        station = 'Lincoln, IL'

    sounding.plot_skewt(title=station + ': ' + str(month) + '/' + str(day) +
                        '/' + str(year) + ' 12Z',
                        lw=3)

    text = """
Data from UWYO Department of Atmospheric Science (http://weather.uwyo.edu/upperair/sounding.html)
Learn how to interpret soundings here: http://www.wunderground.com/blog/24hourprof/introduction-
    to-skewt-logp-diagrams
"""
    plt.text(-0.15,
             0.08,
             text,
             verticalalignment='top',
             horizontalalignment='left',
             fontsize='13',
             transform=ax.transAxes)
    plt.savefig(stname + "SkewT.png")

    plt.close()

    return stname + "SkewT.png"
Exemple #16
0
        mydata_fix = mydata

## !!! Brian Blaylock: The problem here is that it's trying to plot all
##                     the data in the dictionary on the same plot.
#S=SkewT.Sounding(soundingdata=mydata)
## !!! Instead, Need to create a new dictionary for each hour.
## Note: use the fixed data
    hourdata = {
        'drct': mydata_fix['drct'][i],
        'dwpt': mydata_fix['dwpt'][i],
        'hght': mydata_fix['hght'][i],
        'pres': mydata_fix['pres'][i],
        'sknt': mydata_fix['sknt'][i],
        'temp': mydata_fix['temp'][i]
    }
    S = SkewT.Sounding(soundingdata=hourdata)

    #
    #     Info for header and filename
    #
    if fhr[i] <= 9:
        cfhr = '00' + str(fhr[i])
    elif fhr[i] <= 99:
        cfhr = '0' + str(fhr[i])
    else:
        cfhr = str(fhr[i])
    ccccddyy = '%.i' % starttime.year + '%02d' % starttime.month + '%02d' % starttime.day
    hh = '%02d' % starttime.hour
    if 'nam4' in model:
        subdir = 'namhires'
        modid = 'NAM'
Exemple #17
0
                           wdir, wsp, ' ', 'Cluster 4')))

#C5
height_m = hght_CL4_G5
temperature_c = temp_CL4_G5
dewpoint_c = dewp_CL4_G5
wsp = wsp_CL4_G5 * 1.943844
wdir = wdir_CL4_G5

mydataG5 = dict(
    zip(('hght', 'pres', 'temp', 'dwpt', 'drct', 'sknt', 'StationNumber',
         'SoundingDate'), (height_m, pressure_pa, temperature_c, dewpoint_c,
                           wdir, wsp, ' ', 'Cluster 5')))

#Individuals
S1 = SkewT.Sounding(soundingdata=mydataG1)
S1.plot_skewt(color='r')
plt.savefig(path_data_save + '5K_C1.png', format='png', dpi=1200)
S2 = SkewT.Sounding(soundingdata=mydataG2)
S2.plot_skewt(color='r')
plt.savefig(path_data_save + '5K_C2.png', format='png', dpi=1200)
S3 = SkewT.Sounding(soundingdata=mydataG3)
S3.plot_skewt(color='r')
plt.savefig(path_data_save + '5K_C3.png', format='png', dpi=1200)
S4 = SkewT.Sounding(soundingdata=mydataG4)
S4.plot_skewt(color='r')
plt.savefig(path_data_save + '5K_C4.png', format='png', dpi=1200)
S5 = SkewT.Sounding(soundingdata=mydataG5)
S5.plot_skewt(color='r')
plt.savefig(path_data_save + '5K_C5.png', format='png', dpi=1200)
Exemple #18
0
mydataG2 = dict(
    zip(('hght', 'pres', 'temp', 'dwpt', 'drct', 'sknt', 'StationNumber',
         'SoundingDate'), (height_m, pressure_pa, temperature_c, dewpoint_c,
                           wdir, wsp, '4K', 'CL1')))

temperature_c = T[2, :]
dewpoint_c = DP[2, :]
wsp = WSP[2, :] * 1.943844
wdir = DIR[2, :]

mydataG3 = dict(
    zip(('hght', 'pres', 'temp', 'dwpt', 'drct', 'sknt', 'StationNumber',
         'SoundingDate'), (height_m, pressure_pa, temperature_c, dewpoint_c,
                           wdir, wsp, '4K', 'CL1')))

S1 = SkewT.Sounding(soundingdata=mydataG1)
#S1.plot_skewt(color='r')
S2 = SkewT.Sounding(soundingdata=mydataG2)
#S2.plot_skewt(color='r')
S3 = SkewT.Sounding(soundingdata=mydataG3)
#S3.plot_skewt(color='r')

S = SkewT.Sounding(soundingdata=mydataG1)
S.make_skewt_axes()
S.add_profile(color='r', bloc=0)
S.soundingdata = S2.soundingdata
S.add_profile(color='b', bloc=1)
S.soundingdata = S3.soundingdata
S.add_profile(color='g', bloc=2)
plt.savefig(path_data_save + '4K_C1_3C.png', format='png', dpi=1200)
Exemple #19
0
 def calc_cape(self, fnamelist, u, v, precip99, xy, idx, latlons):
     r'''Description:
         Variable required to calculate Convective Available Potential
         Energy: $\int_{zf}^{zn} g
         \left( \frac{T_{v, parcel} - T_{v,env}}{T_{v,env}}\right)
         \mathrm{d}z$
         If > 0 storms possible if enough moisture
         Notes:
             Blindly follows Rory's meathod
         Args:
             fnamelist (:obj:`list` of :obj:`str`): list of filenames:
                 [qf, q15f, Tf, t15f]
             u (iris.cube): x_wind
             v (iris.cube): y_wind
             precip99 (float): 99th percentile precp
             xy (iris.Constraint): slice from genslice
             idx (int): index
             latlons (:obj:`list` of :obj:`int`): list of lat-lons:
                 [llon, llat, ulat, ulon]
             idx: row index
         Returns:
         CAPE(dataframe): dataframe containing Vars for cape calculations
         TEPHI(dataframe): dataframe containg vars for tephigrams
     '''
     qf, q15f, Tf, t15f = fnamelist
     # ? 975 is a max value ?
     T = iris.load_cube(Tf)
     q = iris.load_cube(qf)
     # Find mslp but keep it greater that 975
     mslp = self.allvars['eve_mslp_mean'].loc[idx]/100
     if mslp > 975:
         mslp = 975
     # Special slice
     xy850 = genslice(latlons, n1=mslp, n2=100)
     T = iris.load_cube(Tf)
     Q = iris.load_cube(qf)
     T850 = T[3, :, :].extract(xy850)
     q850 = Q[3, :, :].extract(xy850)
     Tp = T850.data
     Qp = q850.data
     Tp[Tp < 100] = np.nan
     Qp[Qp < 100] = np.nan
     Tcol = np.nanmean(Tp, axis=(1, 2))
     Qcol = np.nanmean(Qp, axis=(1, 2))
     pressures = T850.coord('pressure').points
     P = np.append(pressures, mslp)
     pval = T850.data.shape[0] + 1
     Temp = Tcol
     T15 = cubemean(iris.load_cube(t15f)[11, :, :].extract(xy)).data
     T = np.append(Temp, T15)
     Tkel = T - 273.16
     humcol = Qcol
     Q15 = cubemean(iris.load_cube(q15f)[11, :, :].extract(xy)).data
     hum = np.append(humcol, Q15)
     dwpt = np.zeros_like(P)
     if pval == 18:
         humidity = ((0.263 * hum * P*100) / 2.714**((17.67*(Tkel))/(T - 29.65)))
         RH_650 = (0.263 * hum * P) / 2.714**((17.67*(Tkel)) / (T - 29.65))
         height = T*((mslp/P)**(1./5.257) - 1)/0.0065
         height[-1] = 1.5
         dwpt[:] = self.mcdp(Tkel, humidity)  # vectorized dew_point calc
     else:
         height, dwpt, humidity, RH_650 = np.zeros((4, pval))
     RH_650 = RH_650[np.where((P > 690) & (P <= 710))[0]]
     xwind = cubemean(u[3, :, :])
     ywind = cubemean(v[3, :, :])
     self.allvars['Tephi_pressure'].loc[idx] = np.average(pressures, axis=0)
     self.allvars['Tephi_T'].loc[idx] = np.average(T, axis=0)
     self.allvars['Tephi_dewpT'].loc[idx] = np.average(dwpt, axis=0)
     self.allvars['Tephi_height'].loc[idx] = np.average(height, axis=0)
     self.allvars['Tephi_Q'].loc[idx] = np.average(humidity, axis=0)
     self.allvars['Tephi_p99'].loc[idx] = precip99*3600.
     self.allvars['Tephi_xwind'].loc[idx] = xwind.data
     self.allvars['Tephi_ywind'].loc[idx] = ywind.data
     self.allvars['Tephi_RH650'].loc[idx] = np.average(RH_650, axis=0)
     mydata = dict(zip(('hght', 'pres', 'temp', 'dwpt'),
                       (height[::-1], P[::-1], Tkel[::-1],
                        dwpt[:: -1])))
     try:
         S = sk.Sounding(soundingdata=mydata)
         parcel = S.get_parcel('mu')
         P_lcl, P_lfc, P_el, CAPE, CIN = S.get_cape(*parcel)
     except AssertionError:
         print('dew_point = ', dwpt[:: -1])
         print('height = ', height[:: -1])
         print('pressures = ', P[:: -1])
         print('Temp = ', Tkel[:: -1])
         print('AssertionError: Use a monotonically increasing abscissa')
         print('Setting to np.nan')
         P_lcl, P_lfc, P_el, CAPE, CIN = [np.nan, np.nan, np.nan, np.nan, np.nan]
     self.allvars['CAPE_P_lcl'].loc[idx] = P_lcl
     self.allvars['CAPE_P_lfc'].loc[idx] = P_lfc
     self.allvars['CAPE_P_el'].loc[idx] = P_el
     self.allvars['CAPE_CAPE'].loc[idx] = CAPE
     self.allvars['CAPE_CIN'].loc[idx] = CIN
    zip(('hght', 'pres', 'temp', 'dwpt', 'drct', 'sknt', 'StationNumber',
         'SoundingDate'), (height_m, pressure_pa, temperature_c, dewpoint_c,
                           wdir, wsp, 'Post Front', '')))

#Pre
temperature_c = temp_pref
dewpoint_c = dewp_pref
wsp = wsp_pref * 1.943844
wdir = wdir_pref

mydatapref = dict(
    zip(('hght', 'pres', 'temp', 'dwpt', 'drct', 'sknt', 'StationNumber',
         'SoundingDate'), (height_m, pressure_pa, temperature_c, dewpoint_c,
                           wdir, wsp, 'Pre Front', '')))

S1 = SkewT.Sounding(soundingdata=mydataposf)
S1.plot_skewt(color='r')
plt.savefig(path_data_save + 'sounding_postcoldfront.png',
            format='png',
            dpi=1200)
S2 = SkewT.Sounding(soundingdata=mydatapref)
S2.plot_skewt(color='r')
plt.savefig(path_data_save + 'sounding_precoldfront.png',
            format='png',
            dpi=1200)

S = SkewT.Sounding(soundingdata=mydataposf)
S.make_skewt_axes()
S.add_profile(color='r', bloc=0)
S.soundingdata = S2.soundingdata
S.add_profile(color='b', bloc=1)