def plot_sounding(P, T, Td, U, V, r_time, ID):
    ##need the metpy package
    ##from metpy.plots import SkewT
    ##from metpy.units import units
    ##import metpy.calc as mcalc
    fig = plt.figure(figsize=(7, 6))
    skew = SkewT(fig)
    skew.plot(P, T, 'r')
    skew.plot(P, Td, 'g')
    idx = mcalc.resample_nn_1d(
        P,
        np.array([1000, 975, 950, 925, 900, 850, 800, 750, 700, 650, 600,
                  500]))
    skew.plot_barbs(P[idx],
                    U[idx] * units('m/s'),
                    V[idx] * units('m/s'),
                    plot_units=units('m/s'))
    ##special lines
    skew.plot_dry_adiabats()
    skew.plot_moist_adiabats(color='blue')
    skew.plot_mixing_lines(p=np.linspace(1100, 300) * units.hPa)
    ##title etc.,
    plt.title(str(ID) + '_' + str(r_time) + 'LST')
    plt.xlim(-40, 40)
    plt.ylim(1100, 300)
    for i in range(-70, 40, 20):
        plt.fill_between(range(i, i + 11), 1100, 300, color='#C4FF8C')

    #plt.savefig('merged_data_plot/' + fname + '.png')
    plt.show()
示例#2
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)
def plot_sounding(sndg_data, yr, day, mo, hr, diablo_sounding):
    plt.rcParams['figure.figsize'] = (9, 9)
    skew_evening = SkewT()
    one_sounding = sndg_data.loc[sndg_data[' Hour'] == hr]
    T = convert_temperature(one_sounding[' Temp'].values, 'F', 'C')
    rh = one_sounding[' RH'].values
    one_sounding[' Dewpt'] = calc_dewpt(T, rh)
    one_sounding = one_sounding.dropna(subset=(' Temp', ' Dewpt'),
                                       how='all').reset_index(drop=True)

    T = convert_temperature(one_sounding[' Temp'].values, 'F',
                            'C') * units.degC
    p = one_sounding[' Pres'].values * units.hPa
    Td = one_sounding[' Dewpt'].values * units.degC
    wind_speed = one_sounding[' Spd'].values * units.knots
    wind_dir = one_sounding[' Dir '].values * units.degrees
    u, v = mpcalc.get_wind_components(wind_speed, wind_dir)
    skew_evening.plot(p, T, 'r')
    skew_evening.plot(p, Td, 'g')
    skew_evening.plot_barbs(p, u, v)
    skew_evening.plot_dry_adiabats()
    skew_evening.plot_moist_adiabats()
    skew_evening.plot_mixing_lines()
    skew_evening.ax.set_ylim(1000, 100)
    plt.title('OAK Sounding: ' + str(int(mo)) + '/' + str(int(day)) + '/' +
              str(int(yr)) + ': ' + str(int(hr)) + ' UTC')
    plt.savefig('../Images/20180703/' + diablo_sounding +
                '/OAK_sounding_eve_' + str(int(mo)) + '_' + str(int(day)) +
                '_' + str(int(yr)) + '_' + str(int(hr)) + 'UTC.png')
    plt.close()
    return one_sounding
示例#4
0
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, aspect='auto')

        # 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()

        # Call again to hit removal statements
        skew.plot_dry_adiabats()
        skew.plot_moist_adiabats()
        skew.plot_mixing_lines()

    return fig
示例#5
0
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')
示例#6
0
def test_skewt_barb_unit_conversion_exception(u, v):
    """Test that errors are raise if unit conversion is requested on un-united data."""
    p_wind = np.array([500]) * units.hPa

    fig = plt.figure(figsize=(9, 9))
    skew = SkewT(fig)
    with pytest.raises(ValueError):
        skew.plot_barbs(p_wind, u, v, plot_units='knots')
示例#7
0
def test_skewt_barb_unit_conversion_exception(u, v):
    """Test that errors are raise if unit conversion is requested on un-united data."""
    p_wind = np.array([500]) * units.hPa

    fig = plt.figure(figsize=(9, 9))
    skew = SkewT(fig, aspect='auto')
    with pytest.raises(ValueError):
        skew.plot_barbs(p_wind, u, v, plot_units='knots')
示例#8
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
示例#9
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
示例#10
0
def test_skewt_barb_color():
    """Test plotting colored wind barbs on the Skew-T."""
    fig = plt.figure(figsize=(9, 9))
    skew = SkewT(fig)

    p = np.linspace(1000, 100, 10)
    u = np.linspace(-10, 10, 10)
    skew.plot_barbs(p, u, u, c=u)

    return fig
示例#11
0
def test_skewt_barb_color():
    """Test plotting colored wind barbs on the Skew-T."""
    fig = plt.figure(figsize=(9, 9))
    skew = SkewT(fig)

    p = np.linspace(1000, 100, 10)
    u = np.linspace(-10, 10, 10)
    skew.plot_barbs(p, u, u, c=u)

    return fig
示例#12
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
示例#13
0
def make_skewt():
    # Get the data
    date = request.args.get('date')
    time = request.args.get('time')
    region = request.args.get('region')
    station = request.args.get('station')
    date = datetime.strptime(date, '%Y%m%d')
    date = datetime(date.year, date.month, date.day, int(time))
    df = get_sounding_data(date, region, station)
    p = df['pressure'].values * units(df.units['pressure'])
    T = df['temperature'].values * units(df.units['temperature'])
    Td = df['dewpoint'].values * units(df.units['dewpoint'])
    u = df['u_wind'].values * units(df.units['u_wind'])
    v = df['v_wind'].values * units(df.units['v_wind'])

    # Make the Skew-T
    fig = plt.figure(figsize=(9, 9))
    add_metpy_logo(fig, 115, 100)
    skew = SkewT(fig, rotation=45)

    # 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, 'tab:red')
    skew.plot(p, Td, 'tab:green')
    skew.plot_barbs(p, u, v)
    skew.ax.set_ylim(1000, 100)
    skew.ax.set_xlim(-40, 60)

    # Calculate LCL height and plot as black dot
    lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0])
    skew.plot(lcl_pressure, lcl_temperature, 'ko', markerfacecolor='black')

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

    # Shade areas of CAPE and CIN
    skew.shade_cin(p, T, prof)
    skew.shade_cape(p, T, prof)

    # An example of a slanted line at constant T -- in this case the 0
    # 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()

    canvas = FigureCanvas(fig)
    img = BytesIO()
    fig.savefig(img)
    img.seek(0)
    return send_file(img, mimetype='image/png')
示例#14
0
def test_skewt_barb_no_default_unit_conversion():
    """Test that barbs units are left alone by default (#737)."""
    u_wind = np.array([3.63767155210412]) * units('m/s')
    v_wind = np.array([3.63767155210412]) * units('m/s')
    p_wind = np.array([500]) * units.hPa

    fig = plt.figure(figsize=(9, 9))
    skew = SkewT(fig)
    skew.plot_barbs(p_wind, u_wind, v_wind)

    return fig
示例#15
0
def test_skewt_barb_unit_conversion():
    """Test that barbs units can be converted at plot time (#737)."""
    u_wind = np.array([3.63767155210412]) * units('m/s')
    v_wind = np.array([3.63767155210412]) * units('m/s')
    p_wind = np.array([500]) * units.hPa

    fig = plt.figure(figsize=(9, 9))
    skew = SkewT(fig)
    skew.plot_barbs(p_wind, u_wind, v_wind, plot_units='knots')

    return fig
    def plot_skewt(self, station_data):
        """
        :param adjusted_data: receives the post processed dataframe
        :param valid:
        :return:
        """

        # We will pull the data out of the example dataset into individual variables
        # and assign units.

        p = station_data['pressure'].values * units.hPa
        T = station_data['Temperature_isobaric'].values * units.degC
        Td = station_data['Dewpoint'].replace(np.nan,
                                              0.0000001).values * units.degC
        u = station_data['u-component_of_wind_isobaric'].values * \
            units('meters / second').to('knots')
        v = station_data['v-component_of_wind_isobaric'].values * \
            units('meters / second').to('knots')

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

        # 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)
        skew.ax.set_ylim(1020, 100)
        skew.ax.set_xlim(-40, 60)

        # Calculate LCL height and plot as black dot
        lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0])
        skew.plot(lcl_pressure, lcl_temperature, 'ko', markerfacecolor='black')

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

        # An example of a slanted line at constant T -- in this case the 0
        # 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()

        skew.shade_cape(p, T, prof)
        skew.shade_cin(p, T, prof)

        return skew
示例#17
0
def test_skewt_barb_no_default_unit_conversion():
    """Test that barbs units are left alone by default (#737)."""
    u_wind = np.array([3.63767155210412]) * units('m/s')
    v_wind = np.array([3.63767155210412]) * units('m/s')
    p_wind = np.array([500]) * units.hPa

    fig = plt.figure(figsize=(9, 9))
    skew = SkewT(fig)
    skew.ax.set_ylabel('')  # remove_text doesn't do this as of pytest 0.9
    skew.plot_barbs(p_wind, u_wind, v_wind)
    skew.ax.set_ylim(1000, 500)
    skew.ax.set_yticks([1000, 750, 500])

    return fig
示例#18
0
def test_skewt_barb_no_default_unit_conversion():
    """Test that barbs units are left alone by default (#737)."""
    u_wind = np.array([3.63767155210412]) * units('m/s')
    v_wind = np.array([3.63767155210412]) * units('m/s')
    p_wind = np.array([500]) * units.hPa

    fig = plt.figure(figsize=(9, 9))
    skew = SkewT(fig)
    skew.ax.set_ylabel('')  # remove_text doesn't do this as of pytest 0.9
    skew.plot_barbs(p_wind, u_wind, v_wind)
    skew.ax.set_ylim(1000, 500)
    skew.ax.set_yticks([1000, 750, 500])

    return fig
示例#19
0
def core(p, T, Td, u, v, **kwargs):

    # Calculate the LCL
    lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0])

    #print('LCL p, t:', int(lcl_pressure), int(lcl_temperature))

    # Calculate the parcel profile.
    parcel_prof = 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, rotation=45)

    # 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, 'k-')
    skew.plot(p, T, 'r.-', ms=5, lw=2, label='mean T')
    skew.plot(p, Td, 'g.-', ms=5, lw=2, label='mean Td')
    skew.plot_barbs(p, u, v)
    skew.ax.set_ylim(1000, 180)
    skew.ax.set_xlim(-20, 40)

    # Plot LCL temperature as black dot
    skew.plot(lcl_pressure, lcl_temperature, 'k.', markerfacecolor='black')

    # Plot the parcel profile as a black line
    skew.plot(p, parcel_prof, 'k', linewidth=2)

    # Shade areas of CAPE and CIN
    skew.shade_cin(p, T, parcel_prof)
    skew.shade_cape(p, T, parcel_prof)

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

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

    # Show the plot
    #plt.show()
    #skew.ax.set_title(time_str)
    plt.legend(loc='lower left')
    plt.title(kwargs.get('title'))
    fname = kwargs.get('saveto', 'profile.png')
    fig.savefig(fname)
    print(fname, 'saved.')
    plt.close()
示例#20
0
def test_skewt_barb_unit_conversion():
    """Test that barbs units can be converted at plot time (#737)."""
    u_wind = np.array([3.63767155210412]) * units('m/s')
    v_wind = np.array([3.63767155210412]) * units('m/s')
    p_wind = np.array([500]) * units.hPa

    fig = plt.figure(figsize=(9, 9))
    skew = SkewT(fig, aspect='auto')
    skew.ax.set_ylabel('')  # remove_text doesn't do this as of pytest 0.9
    skew.plot_barbs(p_wind, u_wind, v_wind, plot_units='knots')
    skew.ax.set_ylim(1000, 500)
    skew.ax.set_yticks([1000, 750, 500])
    skew.ax.set_xlim(-20, 20)

    return fig
示例#21
0
def plot_skewt(df):
    # We will pull the data out of the example dataset into individual variables
    # and assign units.
    hght = df['height'].values * units.hPa
    p = df['pressure'].values * units.hPa
    T = df['temperature'].values * units.degC
    Td = df['dewpoint'].values * units.degC
    wind_speed = df['speed'].values * units.knots
    wind_dir = df['direction'].values * units.degrees
    u, v = mpcalc.wind_components(wind_speed, wind_dir)

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

    # 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)
    skew.ax.set_ylim(1000, 100)
    skew.ax.set_xlim(-40, 60)

    # Calculate LCL height and plot as black dot
    lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0])
    skew.plot(lcl_pressure, lcl_temperature, 'ko', markerfacecolor='black')

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

    # An example of a slanted line at constant T -- in this case the 0
    # 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()

    # Create a hodograph
    ax_hod = inset_axes(skew.ax, '40%', '40%', loc=2)
    h = Hodograph(ax_hod, component_range=80.)
    h.add_grid(increment=20)
    h.plot_colormapped(u, v, hght)

    return skew
示例#22
0
def plot_skewt(p, t, td, puv=None, u=None, v=None, title=None, outfile=None):

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

    # 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', linewidth=2)
    skew.plot(p, td, 'g', linewidth=2)
    if u is not None and v is not None:
        skew.plot_barbs(puv, u, v)

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

    # Calculate the LCL
    lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], t[0], td[0])

    # Calculate the parcel profile.
    parcel_prof = mpcalc.parcel_profile(p, t[0], td[0]).to('degC')

    # Plot LCL temperature as black dot
    skew.plot(lcl_pressure, lcl_temperature, 'ko', markerfacecolor='black')

    # Plot the parcel profile as a black line
    skew.plot(p, parcel_prof, 'k--', linewidth=1)

    # Shade areas of CAPE and CIN
    skew.shade_cin(p, t, parcel_prof)
    skew.shade_cape(p, t, parcel_prof)

    # 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()

    if title is not None:
        plt.title(title)

    # Show the plot
    #plt.show()
    if outfile is None: outfile = 'skewt.png'
    fig.savefig(outfile, format='png')
示例#23
0
def skewt(p, T, Td, u, v):
    """

    Adapted from the Metpy advanced sounding example
    (https://unidata.github.io/MetPy/latest/examples/Advanced_Sounding.html#sphx-glr-examples-advanced-sounding-py)

    """
    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.
    skew.plot(p, T, 'r')
    skew.plot(p, Td, 'g')
    skew.plot_barbs(p, u, v)


    # Calculate LCL height and plot as black dot. Because `p`'s first value is
    # ~1000 mb and its last value is ~250 mb, the `0` index is selected for
    # `p`, `T`, and `Td` to lift the parcel from the surface. If `p` was inverted,
    # i.e. start from low value, 250 mb, to a high value, 1000 mb, the `-1` index
    # should be selected.
    #lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0])
    #skew.plot(lcl_pressure, lcl_temperature, 'ko', markerfacecolor='black')

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

    # Shade areas of CAPE and CIN
    #skew.shade_cin(p, T, prof, Td)
    #skew.shade_cape(p, T, prof)

    # An example of a slanted line at constant T -- in this case the 0
    # 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()

    skew.ax.set_ylim(1000, 600)
    skew.ax.set_xlim(0, 60)

    return
示例#24
0
def test_skewt_api_units():
    """#Test the SkewT API when units are provided."""
    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).to(units.Pa)
        t = (np.linspace(18, -20, 10) * units.degC).to(units.kelvin)
        u = np.linspace(-20, 20, 10) * units.knots

        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
示例#25
0
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
示例#26
0
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
示例#27
0
def test_skewt_api_units():
    """#Test the SkewT API when units are provided."""
    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).to(units.Pa)
        t = (np.linspace(18, -20, 10) * units.degC).to(units.kelvin)
        u = np.linspace(-20, 20, 10) * units.knots

        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()

        # This works around the fact that newer pint versions default to degrees_Celsius
        skew.ax.set_xlabel('degC')

    return fig
示例#28
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)
示例#29
0
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
示例#30
0
    T = df['temperature'].values * units.degC
    Td = df['dewpoint'].values * units.degC
    u = df['Uwind'].values * units.meter / (units.second)
    v = df['Vwind'].values * units.meter / (units.second)

    # lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0])
    # parcel_prof = mpcalc.parcel_profile(p, T[0], Td[0]).to('degC')

    fig = plt.figure(figsize=(11, 8.5))
    skew = SkewT(fig, rotation=45)

    # 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', linewidth=3)
    skew.plot(p, Td, 'g', linewidth=3)
    skew.plot_barbs(p[::100], u[::100], v[::100])
    skew.ax.set_ylim(1020, 300)
    skew.ax.set_xlim(-20, 40)
    skew.ax.tick_params(labelsize=24.)
    skew.ax.set_xlabel('temperature ($\degree C$)',
                       linespacing=7,
                       fontsize=24.)
    skew.ax.set_ylabel('pressure ($hPa$)', linespacing=4, fontsize=24.)
    skew.ax.set_title('Skew-T Log-P Diagram' + '\n' + '$_{station:}$ $_{' +
                      station + '}$'
                      '   $_{local}$ $_{time:}$ $_{' + file[i][29:33] + '/' +
                      file[i][33:35] + '/' + file[i][35:37] + '}$' + ' $_{' +
                      file[i][37:39] + ':00}$',
                      verticalalignment='bottom',
                      fontsize=30.)
    '''
示例#31
0
u, v = mpcalc.get_wind_components(wind_speed, wind_dir)

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

# Create a new figure. The dimensions here give a good aspect ratio
fig = plt.figure(figsize=(9, 9))
add_metpy_logo(fig, 115, 100)

# Grid for plots
skew = SkewT(fig, rotation=45)

# 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)
skew.ax.set_ylim(1000, 100)

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

# Good bounds for aspect ratio
skew.ax.set_xlim(-50, 60)

# Create a hodograph
ax_hod = inset_axes(skew.ax, '40%', '40%', loc=1)
h = Hodograph(ax_hod, component_range=80.)
h.add_grid(increment=20)
h.plot_colormapped(u, v, np.hypot(u, v))
示例#32
0
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)
示例#33
0
        bunkerL.set_data(srwind[2], srwind[3]) # Update Bunker's Storm motion left mover
    else:
        bunkerR.set_visible(False)
        bunkerL.set_visible(False)
        bunkerleg.set_visible(False)

    # 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()
示例#34
0
def plotUAVskewT(filenamecsv):
	'''
	Input filepath of post-processed uav data

	Outputs Skew-T log-p plot of UAV data, includes hodograph and some
	convective parameters
	'''
	copdata = csvread_copter(filenamecsv)
	lat = copdata[0]
	lon = copdata[1]
	alt = copdata[2]
	pressure = copdata[3]
	temperature = copdata[4]
	dewpoint = copdata[5]
	speed = copdata[9]
	speed_kts = speed * 1.94
	direction = copdata[10]
	site = findSite(lat[0], lon[0])
	sitename, sitelong = site.split('/')
	fname = filenamecsv.split('\\')[-1]
	timeTakeoff = datetime.strptime(fname[:15], '%Y%m%d_%H%M%S')
	copterNum = fname[-10]

	u,v = mcalc.get_wind_components(speed_kts*units.kts, direction * units.deg)
	u = u.to(units.kts)
	v = v.to(units.kts)
	# Wind shear
	bulkshear = speed_kts[-3] - speed_kts[0]
	print '0-%d m Bulk Shear: %.0f kts' % (alt[-3], bulkshear)
	if np.isnan(dewpoint).all():
		moist = 0
	else: 
		moist = 1


	print 'Plotting...'
	fignum = plt.figure(figsize=(12,9))
	gs = gridspec.GridSpec(4, 4)
	skew = SkewT(fignum, rotation=20, subplot=gs[:, :2])

	skew.plot(pressure, temperature, 'r', linewidth = 2)
	skew.plot(pressure, dewpoint, 'g', linewidth = 2)
	skew.plot_barbs(pressure[0::4], u[0::4], v[0::4], x_clip_radius = 0.12, \
	    y_clip_radius = 0.12)

	# Plot convective parameters
	if moist:
		plcl, Tlcl, isbelowlcl, profile = parcelUAV(temperature,
			dewpoint, pressure)
		SBCAPE = uavCAPE(temperature * units.degC, profile,
			pressure * units.hPa)
		skew.plot(plcl, Tlcl, 'ko', markerfacecolor='black')
		skew.plot(pressure, profile, 'k', linewidth=2)
	else:
		isbelowlcl = 0

	# set up plot limits and labels - use LCL as max if higher than profile
	# if moist:
	#     xmin = math.floor(np.nanmin(dewpoint)) + 2
	# else:
	#     xmin = math.floor(np.nanmin(temperature))
	# xmax = math.floor(np.nanmax(temperature)) + 20
	xmin = 0.
	xmax = 50.
	if isbelowlcl:
	    ymin = round((plcl / units.mbar), -1) - 10
	else:
	    ymin = round(np.nanmin(pressure),-1) - 10
	    
	ymax = round(np.nanmax(pressure),-1) + 10

	skew.ax.set_ylim(ymax, ymin)
	skew.ax.set_xlim(xmin, xmax)
	skew.ax.set_yticks(np.arange(ymin, ymax+10, 10))

	skew.ax.set_xlabel('Temperature ($^\circ$C)')
	skew.ax.set_ylabel('Pressure (hPa)')
	titleName = 'Coptersonde-%s %s UTC - %s' % (copterNum, 
	    timeTakeoff.strftime('%d-%b-%Y %H:%M:%S'), sitename)
	skew.ax.set_title(titleName)

	skew.plot_dry_adiabats(linewidth=0.75)
	skew.plot_moist_adiabats(linewidth=0.75)
	skew.plot_mixing_lines(linewidth=0.75)

	# Hodograph
	ax_hod = fignum.add_subplot(gs[:2,2:])
	#gs.tight_layout(fig5)
	if np.nanmax(speed_kts) > 18:
	    comprange = 35
	else:
	    comprange = 20

	h = Hodograph(ax_hod, component_range=comprange)
	h.add_grid(increment=5)
	h.plot_colormapped(u, v, pressure, cmap=cmocean.cm.deep_r)
	ax_hod.set_title('Hodograph (kts)')
	ax_hod.yaxis.set_ticklabels([])
	#ax_hod.set_xlabel('Wind Speed (kts)')

	# Map - Oklahoma
	llcrnrlat = 33.6
	urcrnrlat = 37.2
	llcrnrlon = -103.2
	urcrnrlon = -94.2
	ax_map = fignum.add_subplot(gs[2, 2:])

	m = Basemap(projection='merc', llcrnrlat=llcrnrlat, urcrnrlat=urcrnrlat, 
	    llcrnrlon=llcrnrlon,urcrnrlon=urcrnrlon, lat_ts=20, resolution='l',
	    ax=ax_map)

	print 'Basemap...'
	m.drawcounties()
	m.drawstates()
	x,y = m(lon[0], lat[0])
	plt.plot(x,y,'b.')
	plt.text(x+40000, y-5000, sitelong, 
		bbox=dict(facecolor='yellow', alpha=0.5))

	if moist:
	    # Convective parameter values
	    ax_data = fignum.add_subplot(gs[3, 2])
	    plt.axis('off')
	    datastr = 'LCL = %.0f hPa\nSBCAPE = %.0f J kg$^{-1}$\n0-%.0f m bulk shear\n\
	    = %.0f kts' % \
	        (plcl.magnitude, SBCAPE.magnitude, alt[-3], bulkshear)
	    boxprops = dict(boxstyle='round', facecolor='none')
	    ax_data.text(0.05, 0.95, datastr, transform=ax_data.transAxes, 
	    	fontsize=14, verticalalignment='top', bbox=boxprops)
	    # Logos
	    ax_png = fignum.add_subplot(gs[3, 3])
	    img = mpimg.imread(logoName)
	    plt.axis('off')
	    plt.imshow(img)
	else:
	    # Logos
	    ax_png = fignum.add_subplot(gs[3, 2:])
	    img = mpimg.imread(logoName)
	    plt.axis('off')
	    plt.imshow(img)

	plt.show(block=False)
	return
示例#35
0
dpdz = rho * 9.8
heights = np.zeros_like(p)
heights[0] = 10.0
for i in range(1,len(heights)):
    heights[i] = ((((p[i-1] - p[i])*100.)) / dpdz[i-1]) + heights[i-1]

p=p*units.hPa45
T=T*units.degC
Td=Td*units.degC

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

skew.plot(p, T, 'r',linewidth=2)
skew.plot(p, Td, 'g',linewidth=2)
skew.plot_barbs(p, u, v)
skew.ax.set_ylim(1000, 100)
skew.ax.set_xlim(-40,60)

cape, cin, prof = get_cape(filename,'ml')
print cape
prof = prof-273.15
skew.plot(p, prof, 'k')

skew.plot_dry_adiabats()
skew.plot_moist_adiabats()
skew.plot_mixing_lines()
#skew.ax.set_title('August 11')

plt.savefig('sounding1.png')
plt.close()
示例#36
0
文件: modules.py 项目: nebain/raspPy
    def skewt(self, ranges='Range', temp='Temperature', dewpoint=None, rel_hum='Relative Humidity',
              temp_units='K', wind=None, **kwargs):
        from metpy.plots import SkewT
        if not 'col' in kwargs.keys() and not 'row' in kwargs.keys():
            # get unused dimensions
            unused = list(self._obj[temp].dims)
            if ranges in unused:
                unused.remove(ranges)
            # convert range (m) to hectopascals
            hpascals = 1013.25 * np.exp(-self._obj.coords[ranges] / 7)
            # return hpascals
            #return hpascals
            # convert temperature from Kelvins to Celsius
            #tempC = self._obj[temp] - 273.15
            if temp_units == 'K':
                tempK = self._obj[temp].drop(unused)
                tempC = tempK - 273.15
            else:
                tempC = self._obj[temp].drop(unused)
                tempK = tempC + 273.15

            if dewpoint is None:
                # estimate dewpoint from relative humidity
                dewpoints = tempK - ((100 - self._obj[rel_hum].drop(unused)) / 5) - 273.15
            else:
                dewpoints = self._obj[dewpoint].drop(unused)

            skew = SkewT()
            #return tempC
            skew.plot(hpascals, tempC, 'r')
            skew.plot(hpascals, dewpoints, 'g')
            skew.plot_dry_adiabats()
            skew.plot_moist_adiabats()
            if not wind is None:
                u = self._obj[wind].sel(Component='x').drop(unused)
                v = self._obj[wind].sel(Component='y').drop(unused)
                skew.plot_barbs(hpascals, u, v, xloc=.9)
            # skew.plot_mixing_lines()
            # skew.ax.set_ylim(1100, 100)
        else:
            if not wind is None:
                skewtdat = xr.concat([self._obj['Temperature'], self._obj['Relative Humidity'],
                                      self._obj[wind].sel(Component='x').drop('Component'),
                                      self._obj[wind].sel(Component='y').drop('Component')],
                                     'measure')
                skewtdat.coords['measure'] = ['Temperature', 'Relative Humidity', 'windx', 'windy']
            else:
                skewtdat = xr.concat([self._obj['Temperature'], self._obj['Relative Humidity']], 'measure')
                skewtdat.coords['measure'] = ['Temperature', 'Relative Humidity']

            # skewtdat
            sk1 = xr.plot.FacetGrid(skewtdat, **kwargs)
            #return sk1
            # need to make the subplot tuples

            for ax in sk1.axes.flat:
                ax.axis('off')

            #return sk1.axes.flat
            #return len(sk1.axes.flat)
            splots = range(len(sk1.axes.flat))
            #return splots
            splot_dims = sk1.axes.shape
            splot_tuples = []
            for i in splots:
                splot_tuples.append((splot_dims[0], splot_dims[1], i + 1))

            if not wind is None:
                sk1.map(rasp.skewt, [0, 1, 2, 3], splots=splot_tuples, ranges=skewtdat.coords['Range'].values)
            else:
                sk1.map(rasp.skewt, [0, 1], splots=splot_tuples, ranges=skewtdat.coords['Range'].values)
示例#37
0
    dataset = get_upper_air_data(datetime(2013, 1, 20, 12), 'OUN')

p = dataset.variables['pressure'][:]
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')
示例#38
0
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)
示例#39
0
def plot_upper_air(station='11035', date=False):
    '''
    -----------------------------
    Default use of plot_upper_air:

    This will plot a SkewT sounding for station '11035' (Wien Hohe Warte)
    plot_upper_air(station='11035', date=False)
    '''
    # sns.set(rc={'axes.facecolor':'#343837', 'figure.facecolor':'#343837',
    #  'grid.linestyle':'','axes.labelcolor':'#04d8b2','text.color':'#04d8b2',
    #  'xtick.color':'#04d8b2','ytick.color':'#04d8b2'})
    # Get time in UTC
    station = str(station)
    if date is False:
        now = datetime.utcnow()
        # If morning then 0z sounding, otherwise 12z
        if now.hour < 12:
            hour = 0
        else:
            hour = 12
        date = datetime(now.year, now.month, now.day, hour)
        datestr = date.strftime('%Hz %Y-%m-%d')
        print('{}'.format(date))
    else:
        year = int(input('Please specify the year: '))
        month = int(input('Please specify the month: '))
        day = int(input('Please specify the day: '))
        hour = int(input('Please specify the hour: '))
        if hour < 12:
            hour = 0
        else:
            hour = 12
        date = datetime(year, month, day, hour)
        datestr = date.strftime('%Hz %Y-%m-%d')
        print('You entered {}'.format(date))

    # This requests the data 11035 is
    df = WyomingUpperAir.request_data(date, station)

    # Create single variables wih the right units
    p = df['pressure'].values * units.hPa
    T = df['temperature'].values * units.degC
    Td = df['dewpoint'].values * units.degC
    wind_speed = df['speed'].values * units.knots
    wind_dir = df['direction'].values * units.degrees

    wind_speed_6k = df['speed'][df.height <= 6000].values * units.knots
    wind_dir_6k = df['direction'][df.height <= 6000].values * units.degrees

    u, v = mpcalc.get_wind_components(wind_speed, wind_dir)
    u6, v6 = mpcalc.get_wind_components(wind_speed_6k, wind_dir_6k)

    # Calculate the LCL
    lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0])
    print(lcl_pressure, lcl_temperature)
    # Calculate the parcel profile.
    parcel_prof = mpcalc.parcel_profile(p, T[0], Td[0]).to('degC')
    cape, cin = mpcalc.cape_cin(p, T, Td, parcel_prof)

    #############################
    # Create a new figure. The dimensions here give a good aspect ratio
    fig = plt.figure(figsize=(9, 9))
    gs = gridspec.GridSpec(3, 3)
    skew = SkewT(fig, rotation=45, subplot=gs[:, :2])

    # 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)
    skew.ax.set_ylim(1000, 100)
    skew.ax.set_xlim(-45, 40)

    # Plot LCL as black dot
    skew.plot(lcl_pressure, lcl_temperature, 'ko', markerfacecolor='black')

    # Plot the parcel profile as a black line
    skew.plot(p, parcel_prof, 'k', linewidth=2)

    # Shade areas of CAPE and CIN
    skew.shade_cin(p, T, parcel_prof)
    skew.shade_cape(p, T, parcel_prof)

    # Plot a zero degree isotherm
    skew.ax.axvline(0, color='c', linestyle='--', linewidth=2)
    skew.ax.set_title('Station: ' + str(station) + '\n' + datestr)  # set title
    skew.ax.set_xlabel('Temperature (C)')
    skew.ax.set_ylabel('Pressure (hPa)')

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

    # Create a hodograph
    # Create an inset axes object that is 40% width and height of the
    # figure and put it in the upper right hand corner.
    # ax_hod = inset_axes(skew.ax, '40%', '40%', loc=1)
    ax = fig.add_subplot(gs[0, -1])
    h = Hodograph(ax, component_range=60.)
    h.add_grid(increment=20)
    # Plot a line colored by windspeed
    h.plot_colormapped(u6, v6, wind_speed_6k)

    # add another subplot for the text of the indices
    # ax_t = fig.add_subplot(gs[1:,2])
    skew2 = SkewT(fig, rotation=0, subplot=gs[1:, 2])
    skew2.plot(p, T, 'r')
    skew2.plot(p, Td, 'g')
    # skew2.plot_barbs(p, u, v)
    skew2.ax.set_ylim(1000, 700)
    skew2.ax.set_xlim(-30, 10)

    # Show the plot
    plt.show()

    return cape
示例#40
0
#    the independent variable, is first even though it is plotted on the y-axis).
#
# 4. Plot the pressure and dewpoint temperature.
#
# 5. Plot the wind barbs at the appropriate pressure using the u and v wind
#    components.

# Create a new figure. The dimensions here give a good aspect ratio
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
skew.plot(p, T, 'r', linewidth=2)
skew.plot(p, Td, 'g', linewidth=2)
skew.plot_barbs(p, u, v)

# Show the plot
plt.show()

##########################################################################
# Advanced Skew-T Plotting
# ------------------------
#
# Fiducial lines indicating dry adiabats, moist adiabats, and mixing ratio are
# useful when performing further analysis on the Skew-T diagram. Often the
# 0C isotherm is emphasized and areas of CAPE and CIN are shaded.

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