コード例 #1
0
ファイル: utils.py プロジェクト: nebain/raspPy
def skewt(data, splots, ranges, temp=None, rel_hum=None, **kwargs):
    from metpy.plots import SkewT
    if temp is None:
        temp = 'Temperature'
    if rel_hum is None:
        rel_hum = 'Relative Humidity'
    # convert range (m) to hectopascals
    #hpascals = 1013.25 * np.exp(-data.coords['Range'] / 7)
    hpascals = 1013.25 * np.exp(-ranges / 7)
    # convert temperature from Kelvins to Celsius
    tempC = data[0] - 273.15
    # estimate dewpoint from relative humidity
    dewpoints = data[0] - ((100 - data[1]) / 5) - 273.15

    # get info about the current figure
    # fshape = plt.gcf().axes.shape
    # skew = SkewT(fig=plt.gcf(), subplot=(fshape[0], fshape[1], splots[0]))
    skew = SkewT(fig=plt.gcf(), subplot=splots[0])
    #plt.gca().axis('off')
    splots.pop(0)
    skew.plot(hpascals, tempC, 'r')
    skew.plot(hpascals, dewpoints, 'g')
    skew.plot_dry_adiabats()
    skew.plot_moist_adiabats()
    if data.shape[0] == 4:
        u = data[2]
        v = data[3]
        skew.plot_barbs(hpascals, u, v, xloc=.9)
コード例 #2
0
    def create_skewt(self, rdat):
        """ Create the SkewT plot inside the figure instance """

        # Extract pressure from data
        P = rdat['PRES'].values * units.hPa

        # Extract temperature from data
        T = rdat['TEMP'].values * units.degC

        # Extract dewpt from data
        Td = rdat['DWPT'].values * units.degC

        skew = SkewT(self.fig, rotation=45)
        # Change to read in min/max from data arrays??
        skew.ax.set_ylim(1000, 100)
        skew.ax.set_xlim(-40, 80)
        skew.ax.set_title(self.title)
        skew.plot(P, T, 'r', linewidth=2)
        skew.plot(P, Td, 'g', linewidth=2)

        # Plot a zero degree isotherm
        skew.ax.axvline(0, color='c', linestyle='--', linewidth=2)

        # Add the relevant special lines
        skew.plot_dry_adiabats()
        skew.plot_moist_adiabats()
        skew.plot_mixing_lines()
コード例 #3
0
ファイル: plot_sonde_log.py プロジェクト: ZigiWalter/myAutoRX
def plot_metpy(data, title="", saveplot=None, showplot=True):

    # Convert data into a suitable format for metpy.
    _altitude = data[:,0] * units('m')
    p = mpcalc.height_to_pressure_std(_altitude)
    T = data[:,3] * units.degC
    Td = data[:,4] * units.degC
    wind_speed = data[:,1] * units('m/s')
    wind_direction = data[:,2] * units.degrees
    u, v = mpcalc.wind_components(wind_speed, wind_direction)


    fig = plt.figure(figsize=(6,8))
    skew = SkewT(fig=fig)
    skew.plot(p, T, 'r')
    skew.plot(p, Td, 'g')

    my_interval = np.arange(300, 1000, 50) * units('mbar')
    ix = mpcalc.resample_nn_1d(p, my_interval)
    skew.plot_barbs(p[ix], u[ix], v[ix])
    skew.ax.set_ylim(1000,300)
    skew.ax.set_xlim(-40, 30)
    skew.plot_dry_adiabats()

    heights = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) * units.km
    std_pressures = mpcalc.height_to_pressure_std(heights)
    for height_tick, p_tick in zip(heights, std_pressures):
        trans, _, _ = skew.ax.get_yaxis_text1_transform(0)
        skew.ax.text(0.02, p_tick, '---{:~d}'.format(height_tick), transform=trans)

    plt.title("Sounding: " + title)

    if saveplot != None:
        fig.savefig(saveplot, bbox_inches='tight')
コード例 #4
0
def plot_sounding(date, station):
    p, T, Td, u, v, windspeed = get_sounding_data(date, station)

    lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0])
    lfc_pressure, lfc_temperature = mpcalc.lfc(p, T, Td)
    parcel_path = mpcalc.parcel_profile(p, T[0], Td[0]).to('degC')

    # Create a new figure. The dimensions here give a good aspect ratio
    fig = plt.figure(figsize=(8, 8))
    skew = SkewT(fig)

    # Plot the data
    temperature_line, = skew.plot(p, T, color='tab:red')
    dewpoint_line, = skew.plot(p, Td, color='blue')
    cursor = mplcursors.cursor([temperature_line, dewpoint_line])

    # Plot thermodynamic parameters and parcel path
    skew.plot(p, parcel_path, color='black')

    if lcl_pressure:
        skew.ax.axhline(lcl_pressure, color='black')

    if lfc_pressure:
        skew.ax.axhline(lfc_pressure, color='0.7')

    # Add the relevant special lines
    skew.ax.axvline(0, color='c', linestyle='--', linewidth=2)
    skew.plot_dry_adiabats()
    skew.plot_moist_adiabats()
    skew.plot_mixing_lines()

    # Shade areas representing CAPE and CIN
    skew.shade_cin(p, T, parcel_path)
    skew.shade_cape(p, T, parcel_path)

    # Add wind barbs
    skew.plot_barbs(p, u, v)

    # Add an axes to the plot
    ax_hod = inset_axes(skew.ax, '30%', '30%', loc=1, borderpad=3)

    # Plot the hodograph
    h = Hodograph(ax_hod, component_range=100.)

    # Grid the hodograph
    h.add_grid(increment=20)

    # Plot the data on the hodograph
    mask = (p >= 100 * units.mbar)
    h.plot_colormapped(u[mask], v[mask], windspeed[mask])  # Plot a line colored by wind speed

    # Set some sensible axis limits
    skew.ax.set_ylim(1000, 100)
    skew.ax.set_xlim(-40, 60)

    return fig, skew
コード例 #5
0
def plot_skewt_icon(sounding, parcel=None, base=1000, top=100, skew=45):
    model_time = np.datetime_as_string(sounding.metadata.model_time, unit='m')
    valid_time = np.datetime_as_string(sounding.metadata.valid_time, unit='m')

    top_idx = find_closest_model_level(sounding.p * units.Pa, top * units("hPa"))

    fig = plt.figure(figsize=(11, 11), constrained_layout=True)
    skew = SkewT(fig, rotation=skew)

    skew.plot(sounding.p * units.Pa, sounding.T * units.K, 'r')
    skew.plot(sounding.p * units.Pa, sounding.Td, 'b')
    skew.plot_barbs(sounding.p[:top_idx] * units.Pa, sounding.U[:top_idx] * units.mps,
                    sounding.V[:top_idx] * units.mps, plot_units=units.knot, alpha=0.6, xloc=1.13, x_clip_radius=0.3)

    if parcel == "surface-based":
        prof = mpcalc.parcel_profile(sounding.p * units.Pa, sounding.T[0] * units.K, sounding.Td[0]).to('degC')
        skew.plot(sounding.p * units.Pa, prof, 'y', linewidth=2)

    # Add the relevant special lines
    skew.plot_dry_adiabats()
    skew.plot_moist_adiabats()
    skew.plot_mixing_lines()
    skew.plot(sounding.p * units.Pa, np.zeros(len(sounding.p)) * units.degC, "#03d3fc", linewidth=1)
    skew.ax.set_ylim(base, top)

    plt.title(f"Model run: {model_time}Z", loc='left')
    plt.title(f"Valid time: {valid_time}Z", fontweight='bold', loc='right')
    plt.xlabel("Temperature [°C]")
    plt.ylabel("Pressure [hPa]")

    fig.suptitle(f"ICON-EU Model for {sounding.latitude_pretty}, {sounding.longitude_pretty}", fontsize=14)

    ax1 = plt.gca()
    ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis

    color = '#333333'
    ax2.set_ylabel('Geometric Altitude [kft]', color=color)  # we already handled the x-label with ax1
    ax2_data = (sounding.p * units.Pa).to('hPa')
    ax2.plot(np.zeros(len(ax2_data)), ax2_data, color=color, alpha=0.0)
    ax2.tick_params(axis='y', labelcolor=color)
    ax2.set_yscale('log')
    ax2.set_ylim((base, top))
    ticks = np.linspace(base, top, num=10)

    ideal_ticks = np.geomspace(base, top, 20)
    real_tick_idxs = [find_closest_model_level(sounding.p * units.Pa, p_level * units("hPa")) for p_level in
                      ideal_ticks]
    ticks = (sounding.p * units.Pa).to("hPa")[real_tick_idxs]
    full_levels = [full_level_height(sounding.HHL, idx) for idx in real_tick_idxs]
    tick_labels = np.around((full_levels * units.m).m_as("kft"), decimals=1)
    ax2.set_yticks(ticks)
    ax2.set_yticklabels(tick_labels)
    ax2.minorticks_off()

    return fig
コード例 #6
0
ファイル: test_skewt.py プロジェクト: ahill818/MetPy
def test_skewt_api():
    """Test the SkewT API."""
    fig = plt.figure(figsize=(9, 9))
    skew = SkewT(fig)

    # Plot the data using normal plotting functions, in this case using
    # log scaling in Y, as dictated by the typical meteorological plot
    p = np.linspace(1000, 100, 10)
    t = np.linspace(20, -20, 10)
    u = np.linspace(-10, 10, 10)
    skew.plot(p, t, 'r')
    skew.plot_barbs(p, u, u)

    # Add the relevant special lines
    skew.plot_dry_adiabats()
    skew.plot_moist_adiabats()
    skew.plot_mixing_lines()

    return fig
コード例 #7
0
ファイル: test_skewt.py プロジェクト: jibbals/MetPy
def test_skewt_adiabat_units():
    """Test adiabats and mixing lines can handle different units."""
    with matplotlib.rc_context({'axes.autolimit_mode': 'data'}):
        fig = plt.figure(figsize=(9, 9))
        skew = SkewT(fig)
        p = np.linspace(950, 100, 10) * units.hPa
        t = np.linspace(18, -20, 10) * units.degC

        skew.plot(p, t, 'r')

        # Add lines with units different to the xaxis
        t0 = (np.linspace(-20, 20, 5) * units.degC).to(units.degK)
        skew.plot_dry_adiabats(t0=t0)
        # add lines with no units
        t0 = np.linspace(-20, 20, 5)
        skew.plot_moist_adiabats(t0=t0)
        skew.plot_mixing_lines()

    return fig
コード例 #8
0
ファイル: test_skewt.py プロジェクト: jibbals/MetPy
def test_skewt_adiabat_kelvin_base():
    """Test adiabats and mixing lines can handle different units."""
    with matplotlib.rc_context({'axes.autolimit_mode': 'data'}):
        fig = plt.figure(figsize=(9, 9))
        skew = SkewT(fig, rotation=45)
        p = np.linspace(950, 100, 10) * units.hPa
        t = (np.linspace(18, -30, 10) * units.degC).to(units.degK)

        skew.plot(p, t, 'r')

        # At this point the xaxis is actually degC
        # Add lines using kelvin base
        t0 = (np.linspace(-20, 40, 5) * units.degC).to(units.degK)
        skew.plot_dry_adiabats(t0=t0)
        # add lines with no units (but using kelvin)
        t0 = np.linspace(253.15, 313.15, 5)
        skew.plot_moist_adiabats(t0=t0)
        skew.plot_mixing_lines()

    return fig
コード例 #9
0
    def plot(self, savename=None):
        # p in hPa, T and Td in K, qv in kg/kg.
        # u and v (optional) in m/s.
        # All inputs are 1-D arrays.

        from matplotlib import pyplot as plt
        from metpy.units import units
        from metpy.plots import SkewT
        import numpy as np

        plt.rcParams['figure.figsize'] = (6, 8)

        # Set lower limit for plotting on p-axis.
        maxp = np.max(self.p)

        skew = SkewT()

        # Plot data.
        skew.plot(self.p * units.hPa, self.T * units.K, 'r')
        skew.plot(self.p * units.hPa, self.Td * units.K, 'g')
        if self.u is not None and self.v is not None:
            skew.plot_barbs((self.p * units.hPa)[::100],
                            (self.u * units.meters / units.seconds)[::100],
                            (self.v * units.meters / units.seconds)[::100])

        # Add some lines and labels.
        skew.plot_dry_adiabats()
        skew.plot_moist_adiabats()
        skew.plot_mixing_lines()
        skew.ax.set_ylabel('Pressure (hPa)')
        skew.ax.set_xlabel(
            r'Temperature ($^{\circ}$C), Mixing Ratio (g kg$^{-1}$)')
        # Set lower limit for plotting on p-axis.
        skew.ax.set_ylim(max(maxp, 1000), 100)

        # Save plot to a file based on input name.
        if savename is not None:
            fig = plt.gcf()
            fig.savefig(savename)
コード例 #10
0
ファイル: test_skewt.py プロジェクト: akrherz/MetPy
def test_skewt_api():
    """Test the SkewT API."""
    with matplotlib.rc_context({'axes.autolimit_mode': 'data'}):
        fig = plt.figure(figsize=(9, 9))
        skew = SkewT(fig)

        # Plot the data using normal plotting functions, in this case using
        # log scaling in Y, as dictated by the typical meteorological plot
        p = np.linspace(1000, 100, 10)
        t = np.linspace(20, -20, 10)
        u = np.linspace(-10, 10, 10)
        skew.plot(p, t, 'r')
        skew.plot_barbs(p, u, u)

        skew.ax.set_xlim(-20, 30)
        skew.ax.set_ylim(1000, 100)

        # Add the relevant special lines
        skew.plot_dry_adiabats()
        skew.plot_moist_adiabats()
        skew.plot_mixing_lines()

    return fig
コード例 #11
0
ファイル: Simple_Sounding.py プロジェクト: ahill818/MetPy
T = dataset.variables['temperature'][:]
Td = dataset.variables['dewpoint'][:]
u = dataset.variables['u_wind'][:]
v = dataset.variables['v_wind'][:]

###########################################
skew = SkewT()

# Plot the data using normal plotting functions, in this case using
# log scaling in Y, as dictated by the typical meteorological plot
skew.plot(p, T, 'r')
skew.plot(p, Td, 'g')
skew.plot_barbs(p, u, v)

# Add the relevant special lines
skew.plot_dry_adiabats()
skew.plot_moist_adiabats()
skew.plot_mixing_lines()
skew.ax.set_ylim(1000, 100)

###########################################

# Example of defining your own vertical barb spacing
skew = SkewT()

# Plot the data using normal plotting functions, in this case using
# log scaling in Y, as dictated by the typical meteorological plot
skew.plot(p, T, 'r')
skew.plot(p, Td, 'g')

# Set spacing interval--Every 50 mb from 1000 to 100 mb
コード例 #12
0
ファイル: draw_soundings_from_csv.py プロジェクト: guziy/RPN
def main():
    img_dir = Path("hail_plots/soundings/")

    if not img_dir.exists():
        img_dir.mkdir(parents=True)


    data_dir = Path("/HOME/huziy/skynet3_rech1/hail/soundings_from_erai/")

    # dates = [datetime(1991, 9, 7), datetime(1991, 9, 7, 6), datetime(1991, 9, 7, 12), datetime(1991, 9, 7, 18),
    #          datetime(1991, 9, 8, 0), datetime(1991, 9, 8, 18)]
    #
    # dates.extend([datetime(1991, 9, 6, 0), datetime(1991, 9, 6, 6), datetime(1991, 9, 6, 12), datetime(1991, 9, 6, 18)])
    #
    # dates = [datetime(1990, 7, 7), datetime(2010, 7, 12), datetime(1991, 9, 8, 0)]



    dates_s = """
- 07/09/1991 12:00
- 07/09/1991 18:00
- 08/09/1991 00:00
- 08/09/1991 06:00
- 08/09/1991 12:00
- 13/09/1991 12:00
- 13/09/1991 18:00
- 14/09/1991 00:00
- 14/09/1991 06:00
- 14/09/1991 12:00
    """

    dates = [datetime.strptime(line.strip()[1:].strip(), "%d/%m/%Y %H:%M") for line in dates_s.split("\n") if line.strip() != ""]




    def __date_parser(s):
        return pd.datetime.strptime(s, '%Y-%m-%d %H:%M:%S')


    tt = pd.read_csv(data_dir.joinpath("TT.csv"), index_col=0, parse_dates=['Time'])
    uu = pd.read_csv(data_dir.joinpath("UU.csv"), index_col=0, parse_dates=['Time'])
    vv = pd.read_csv(data_dir.joinpath("VV.csv"), index_col=0, parse_dates=['Time'])
    hu = pd.read_csv(data_dir.joinpath("HU.csv"), index_col=0, parse_dates=['Time'])


    print(tt.head())
    print([c for c in tt])
    print(list(tt.columns.values))




    temp_perturbation_degc = 0

    for the_date in dates:

        p = np.array([float(c) for c in tt])

        fig = plt.figure(figsize=(9, 9))
        skew = SkewT(fig)

        skew.ax.set_ylim(1000, 100)
        skew.ax.set_xlim(-40, 60)


        tsel = tt.select(lambda d: d == the_date)
        usel = uu.select(lambda d: d == the_date)
        vsel = vv.select(lambda d: d == the_date)
        husel = hu.select(lambda d: d == the_date)


        tvals = tsel.values.mean(axis=0)
        uvals = usel.values.mean(axis=0) * mul_mpers_per_knot
        vvals = vsel.values.mean(axis=0) * mul_mpers_per_knot
        huvals = husel.values.mean(axis=0) * units("g/kg")


        # ignore the lowest level
        all_vars = [p, tvals, uvals, vvals, huvals]

        for i in range(len(all_vars)):
            all_vars[i] = all_vars[i][:-5]

        p, tvals, uvals, vvals, huvals = all_vars


        assert len(p) == len(huvals)

        tdvals = calc.dewpoint(calc.vapor_pressure(p * units.mbar, huvals).to(units.mbar))


        print(tvals, tdvals)
        # Calculate full parcel profile and add to plot as black line
        parcel_profile = calc.parcel_profile(p[::-1] * units.mbar, (tvals[-1] + temp_perturbation_degc) * units.degC, tdvals[-1]).to('degC')
        parcel_profile = parcel_profile[::-1]
        skew.plot(p, parcel_profile, 'k', linewidth=2)



        # Example of coloring area between profiles
        greater = tvals * units.degC >= parcel_profile
        skew.ax.fill_betweenx(p, tvals, parcel_profile, where=greater, facecolor='blue', alpha=0.4)
        skew.ax.fill_betweenx(p, tvals, parcel_profile, where=~greater, facecolor='red', alpha=0.4)



        skew.plot(p, tvals, "r")
        skew.plot(p, tdvals, "g")

        skew.plot_barbs(p, uvals, vvals)

        # Plot a zero degree isotherm
        l = skew.ax.axvline(0, color='c', linestyle='--', linewidth=2)


        # Add the relevant special lines
        skew.plot_dry_adiabats()
        skew.plot_moist_adiabats()
        skew.plot_mixing_lines()

        plt.title("{} (dT={})".format(the_date, temp_perturbation_degc))

        img_path = "{}_dT={}.png".format(the_date.strftime("%Y%m%d_%H%M%S"), temp_perturbation_degc)
        img_path = img_dir.joinpath(img_path)
        fig.savefig(str(img_path), bbox_inches="tight")

        plt.close(fig)
コード例 #13
0
ファイル: cape.py プロジェクト: JLGarciaFranco/PyDropsondes
def cape(filelist,storm,track,show):
    #Sort filelist.
    filelist=np.sort(filelist)

    # Get sampling periods (this will be a dictionary). See the toolbox
    print('Retrieving sampling periods')
    sampleperiods=getsamplingperiods(filelist,3.)

    # Iterate over all sampling periods.
    for sampindex,periodskey in enumerate(sampleperiods):

        #Allocate starting (stdt) and ending date (endt). Remeber dt is the convetional short-name for date.
        stdt=periodskey
        endt=sampleperiods[periodskey]

        # Define sampling period string
        period=str(stdt.hour)+'_'+str(stdt.day)+'-'+str(endt.hour)+'_'+str(endt.day)

        # Create new-empty lists.
        lats=[]
        lons=[]
        xs=[]
        ys=[]
        capes=[]
        cins=[]
	
        distfig = plt.figure(figsize=(13, 9))
        ax=distfig.add_subplot(111)
        print('start filelist loop')
        # Iterate over all files.
        for filename in filelist:



            # Select end-name of file by inspecting filename string. Notice how filename can change how file is read.
            if 'radazm' in filename.split('/')[-1] or 'eol' in filename.split('/')[-1]:
                end='radazm'
            else:
                end='avp'
            # Obtain properties of file, i.e., launch time and location into a dictionary (dicc).
            dicc=findproperties(filename,end)

            # Condition to see if current file is in sampling period.
            # Notice how if structure is constructed, condition finds times outside of sampling period and
            # if found outside the sampling period, continue to next file.
            if dicc['Launch Time']<stdt or dicc['Launch Time'] > endt:
                continue

            nump=np.genfromtxt(filename,skip_header=16,skip_footer=0)
            temperature=clean1(nump[:,5])
            pressure=clean1(nump[:,4])
            Height=clean1(nump[:,13])
            if np.nanmax(Height)<3500:
                continue
            #Clean for cape
            RelH=clean1(nump[:,7])
            lon=clean1(nump[:,14])
            lat=clean1(nump[:,15])
            lon=clean1(lon)
            lat=clean1(lat)
            mlon=np.nanmean(lon)
            mlat=np.nanmean(lat)
            RH=RelH/100
            T,P,rh,dz=cleanforcape(temperature,pressure,RH,Height)

            #Metpy set-up
            T=np.flip(T,0)
            rh=np.flip(rh,0)
            p=np.flip(P,0)
            dz=np.flip(dz,0)
            p=p*units.hPa
            T=T*units.celsius


            mixing=rh*mpcalc.saturation_mixing_ratio(p,T)
            epsilon=0.6219800858985514
            Tv=mpcalc.virtual_temperature(T, mixing,
                                      molecular_weight_ratio=epsilon)
            dwpoint=mpcalc.dewpoint_rh(T, rh)

            blh_indx=np.where(dz<500)
            try:
                parcelprofile=mpcalc.parcel_profile(p,np.nanmean(T[blh_indx])*units.celsius,mpcalc.dewpoint_rh(np.nanmean(T[blh_indx])*units.celsius, np.nanmean(rh[blh_indx]))).to('degC')
                Tv_parcelprofile=mpcalc.virtual_temperature(parcelprofile, mixing,
                                          molecular_weight_ratio=epsilon)
                cape,cin=cape_cin(p,Tv,dwpoint,Tv_parcelprofile,dz,T)
            except:
                continue

            plotskewT=True
            if plotskewT==True:

                os.system('mkdir figs/skewt')
                fig = plt.figure(figsize=(9, 9))
                skew = SkewT(fig, rotation=45)
                skew.ax.set_ylim(1000, 100)
                skew.ax.set_xlim(-40, 60)

                skew.plot(p, dwpoint, 'g',label=r'$T_{dp}$')
                skew.plot(p, Tv, 'r',label=r'$T_v$')
                plt.text(-120,120,str(np.around(cape,2)),fontsize=14,fontweight='bold')

                # Plot the data using normal plotting functions, in this case using
                # log scaling in Y, as dictated by the typical meteorological plot
                skew.plot(p,Tv_parcelprofile,'k',label=r'$T_{v env}$')
                skew.shade_cin(p, T, parcelprofile,label='CIN')
                skew.shade_cape(p, Tv, Tv_parcelprofile,label='CAPE')
                skew.plot_dry_adiabats()
                skew.plot_moist_adiabats()

                plt.legend()
                plt.title(storm + ' on' + period,fontsize=14)
                plt.savefig('figs/skewt/'+storm+str(dicc['Launch Time'].time())+'.png')
                #plt.show()
                plt.close()

            r,theta=cart_to_cylindr(mlon,mlat,track,dicc['Launch Time'])
            if not(np.isnan(r)) and not(np.isnan(theta)) and not(np.isnan(cape.magnitude)):
                xs.append(r*np.cos(theta))
                ys.append(r*np.sin(theta))
                capes.append(cape.magnitude)
                cins.append(cin)


            cs=ax.scatter(xs,ys,c=np.asarray(capes),cmap='jet')
            for i,xi in enumerate(xs):
                ax.text(xi,ys[i]+10,str(np.around(capes[i],1)))
        plt.colorbar(cs)
        ax.scatter(0,0,marker='v',s=100,color='black')
        ax.grid()
        ax.set_xlabel('X distance [km]')
        ax.set_ylabel('Y distance [km]')
        ax.set_title('CAPE distribution for '+storm+' on '+period,fontsize=14)
        distfig.savefig('figs/cape'+storm+period+'.png')
        if show:
            plt.show()
コード例 #14
0
ファイル: SHARPpy_skewts.py プロジェクト: ahijevyc/work
    # Recreate stack of wind barbs
    s = []
    bot=2000.
    # Space out wind barbs evenly on log axis.
    for ind, i in enumerate(prof.pres):
        if i < 100: break
        if np.log(bot/i) > 0.04:
            s.append(ind)
            bot = i
    b = skew.plot_barbs(prof.pres[s], prof.u[s], prof.v[s], linewidth=0.4, length=6)
    # 'knots' label under wind barb stack
    kts = ax.text(1.0, 0, 'knots', clip_on=False, ha='center',va='bottom',size=7,zorder=2)

    # Tried drawing adiabats and mixing lines right after creating SkewT object but got errors. 
    draw_adiabats  = skew.plot_dry_adiabats(color='r', alpha=0.2, linestyle="solid")
    moist_adiabats = skew.plot_moist_adiabats(linewidth=0.5, color='black', alpha=0.2)
    mixing_lines   = skew.plot_mixing_lines(color='g', alpha=0.35, linestyle="dotted")


    string = "created "+str(datetime.datetime.now(tz=None)).split('.')[0]
    plt.annotate(s=string, xy=(10,2), xycoords='figure pixels', fontsize=5)
        
    res = plt.savefig(ofile,dpi=125)
    skew.ax.clear()
    ax.clear()
    if verbose:
        print 'created', os.path.realpath(ofile)
    mapax.clear()
    hodo_ax.clear()
コード例 #15
0
ファイル: mainwindow.py プロジェクト: Unidata/Wave
class Window(QtGui.QMainWindow):
    r""" A mainwindow object for the GUI display. Inherits from QMainWindow."""

    def __init__(self):
        super(Window, self).__init__()
        self.interface()

    def interface(self):
        r""" Contains the main window interface generation functionality. Commented where needed."""

        # Get the screen width and height and set the main window to that size
        screen = QtGui.QDesktopWidget().screenGeometry()
        self.setGeometry(0, 0, 800, screen.height())
        self.setMaximumSize(QtCore.QSize(800, 2000))

        # Set the window title and icon
        self.setWindowTitle("WAVE: Weather Analysis and Visualization Environment")
        self.setWindowIcon(QtGui.QIcon('./img/wave_64px.png'))

        # Import the stylesheet for this window and set it to the window
        stylesheet = "css/MainWindow.css"
        with open(stylesheet, "r") as ssh:
            self.setStyleSheet(ssh.read())
        self.setAutoFillBackground(True)
        self.setBackgroundRole(QtGui.QPalette.Highlight)

        # Create actions for menus and toolbar
        exit_action = QtGui.QAction(QtGui.QIcon('./img/exit_64px.png'), 'Exit', self)
        exit_action.setShortcut('Ctrl+Q')
        exit_action.setStatusTip('Exit application')
        exit_action.triggered.connect(self.close)
        clear_action = QtGui.QAction(QtGui.QIcon('./img/clear_64px.png'), 'Clear the display', self)
        clear_action.setShortcut('Ctrl+C')
        clear_action.setStatusTip('Clear the display')
        clear_action.triggered.connect(self.clear_canvas)
        skewt_action = QtGui.QAction(QtGui.QIcon('./img/skewt_64px.png'), 'Open the skew-T dialog', self)
        skewt_action.setShortcut('Ctrl+S')
        skewt_action.setStatusTip('Open the skew-T dialog')
        skewt_action.triggered.connect(self.skewt_dialog)
        radar_action = QtGui.QAction(QtGui.QIcon('./img/radar_64px.png'), 'Radar', self)
        radar_action.setShortcut('Ctrl+R')
        radar_action.setStatusTip('Open Radar Dialog Box')
        radar_action.triggered.connect(self.radar_dialog)

        # Create the top menubar, setting native to false (for OS) and add actions to the menus
        menubar = self.menuBar()
        menubar.setNativeMenuBar(False)
        filemenu = menubar.addMenu('&File')
        editmenu = menubar.addMenu('&Edit')
        helpmenu = menubar.addMenu('&Help')
        filemenu.addAction(exit_action)

        # Create the toolbar, place it on the left of the GUI and add actions to toolbar
        left_tb = QtGui.QToolBar()
        self.addToolBar(QtCore.Qt.LeftToolBarArea, left_tb)
        left_tb.setMovable(False)
        left_tb.addAction(clear_action)
        left_tb.addAction(skewt_action)
        left_tb.addAction(radar_action)
        self.setIconSize(QtCore.QSize(30, 30))

        # Create the toolbar, place it on the left of the GUI and add actions to toolbar
        right_tb = QtGui.QToolBar()
        self.addToolBar(QtCore.Qt.RightToolBarArea, right_tb)
        right_tb.setMovable(False)
        right_tb.addAction(clear_action)
        right_tb.addAction(skewt_action)
        right_tb.addAction(radar_action)

        # Create the status bar with a default display
        self.statusBar().showMessage('Ready')

        # Figure and canvas widgets that display the figure in the GUI
        self.figure = plt.figure(facecolor='#2B2B2B')
        self.canvas = FigureCanvas(self.figure)

        # Add subclassed matplotlib navbar to GUI
        # spacer widgets for left and right of buttons
        left_spacer = QtGui.QWidget()
        left_spacer.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        right_spacer = QtGui.QWidget()
        right_spacer.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        self.mpltb = QtGui.QToolBar()
        self.mpltb.addWidget(left_spacer)
        self.mpltb.addWidget(MplToolbar(self.canvas, self))
        self.mpltb.addWidget(right_spacer)
        self.mpltb.setMovable(False)
        self.addToolBar(QtCore.Qt.TopToolBarArea, self.mpltb)

        # Set the figure as the central widget and show the GUI
        self.setCentralWidget(self.canvas)
        self.show()

    def skewt_dialog(self):
        r""" When the toolbar icon for the Skew-T dialog is clicked, this function is executed. Creates an instance of
        the SkewTDialog object which is the dialog box. If the submit button on the dialog is clicked, get the user
        inputted values and pass them into the sounding retrieval call (DataAccessor.get_sounding) to fetch the data.
        Finally, plot the returned data via self.plot.

        Args:
            None.
        Returns:
            None.
        Raises:
            None.

        """

        dialog = SkewTDialog()
        if dialog.exec_():
            source, lat, long = dialog.get_values()
            t, td, p, u, v, lat, long, time = DataAccessor.get_sounding(source, lat, long)
            self.plot(t, td, p, u, v, lat, long, time)

    def plot(self, t, td, p, u, v, lat, long, time):
        r"""Displays the Skew-T data on a matplotlib figure.

        Args:
            t (array-like): A list of temperature values.
            td (array-like): A list of dewpoint values.
            p (array-like): A list of pressure values.
            u (array-like): A list of u-wind component values.
            v (array-like): A list of v-wind component values.
            lat (string): A string containing the requested latitude value.
            long (string): A string containing the requested longitude value.
            time (string): A string containing the UTC time requested with seconds truncated.
        Returns:
            None.
        Raises:
            None.

        """

        # Create a new figure. The dimensions here give a good aspect ratio
        self.skew = SkewT(self.figure, rotation=40)

        # Plot the data using normal plotting functions, in this case using
        # log scaling in Y, as dictated by the typical meteorological plot
        self.skew.plot(p, t, 'r')
        self.skew.plot(p, td, 'g')
        self.skew.plot_barbs(p, u, v, barbcolor='#FF0000', flagcolor='#FF0000')
        self.skew.ax.set_ylim(1000, 100)
        self.skew.ax.set_xlim(-40, 60)

        # Axis colors
        self.skew.ax.tick_params(axis='x', colors='#A3A3A4')
        self.skew.ax.tick_params(axis='y', colors='#A3A3A4')

        # Calculate LCL height and plot as black dot
        l = lcl(p[0], t[0], td[0])
        lcl_temp = dry_lapse(concatenate((p[0], l)), t[0])[-1].to('degC')
        self.skew.plot(l, lcl_temp, 'ko', markerfacecolor='black')

        # Calculate full parcel profile and add to plot as black line
        prof = parcel_profile(p, t[0], td[0]).to('degC')
        self.skew.plot(p, prof, 'k', linewidth=2)

        # Color shade areas between profiles
        self.skew.ax.fill_betweenx(p, t, prof, where=t >= prof, facecolor='#5D8C53', alpha=0.7)
        self.skew.ax.fill_betweenx(p, t, prof, where=t < prof, facecolor='#CD6659', alpha=0.7)

        # Add the relevant special lines
        self.skew.plot_dry_adiabats()
        self.skew.plot_moist_adiabats()
        self.skew.plot_mixing_lines()

        # Set title
        deg = u'\N{DEGREE SIGN}'
        self.skew.ax.set_title('Sounding for ' + lat + deg + ', ' + long + deg + ' at ' + time + 'z', y=1.02,
                               color='#A3A3A4')

        # Discards old graph, works poorly though
        # skew.ax.hold(False)
        # Figure and canvas widgets that display the figure in the GUI

        # set canvas size to display Skew-T appropriately
        self.canvas.setMaximumSize(QtCore.QSize(800, 2000))
        # refresh canvas
        self.canvas.draw()

    def radar_dialog(self):
        r""" When the toolbar icon for the Skew-T dialog is clicked, this function is executed. Creates an instance of
        the SkewTDialog object which is the dialog box. If the submit button on the dialog is clicked, get the user
        inputted values and pass them into the sounding retrieval call (DataAccessor.get_sounding) to fetch the data.
        Finally, plot the returned data via self.plot.

        Args:
            None.
        Returns:
            None.
        Raises:
            None.

        """

        radar_dialog = RadarDialog()

        if radar_dialog.exec_():
            station, product = radar_dialog.get_radarvals()
            x, y, ref = DataAccessor.get_radar(station, product)
            self.plot_radar(x, y, ref)

    def plot_radar(self, x, y, ref):
        r"""Displays the Skew-T data on a matplotlib figure.

        Args:
            t (array-like): A list of temperature values.
            td (array-like): A list of dewpoint values.
            p (array-like): A list of pressure values.
            u (array-like): A list of u-wind component values.
            v (array-like): A list of v-wind component values.
            lat (string): A string containing the requested latitude value.
            long (string): A string containing the requested longitude value.
            time (string): A string containing the UTC time requested with seconds truncated.
        Returns:
            None.
        Raises:
            None.

        """

        self.ax = self.figure.add_subplot(111)
        self.ax.pcolormesh(x, y, ref)
        self.ax.set_aspect('equal', 'datalim')
        self.ax.set_xlim(-460, 460)
        self.ax.set_ylim(-460, 460)
        self.ax.tick_params(axis='x', colors='#A3A3A4')
        self.ax.tick_params(axis='y', colors='#A3A3A4')

        # set canvas size to display Skew-T appropriately
        self.canvas.setMaximumSize(QtCore.QSize(800, 2000))
        # refresh canvas
        self.canvas.draw()

    def clear_canvas(self):
        self.canvas.close()
        self.figure = plt.figure(facecolor='#2B2B2B')
        self.canvas = FigureCanvas(self.figure)
        self.setCentralWidget(self.canvas)