示例#1
0
def ex_wavelet(plot=True):
    """Demonstrates how to use wavelets with pyspedas."""
    # Delete any existing pytplot variables
    pytplot.del_data()

    # Create a pytplot variable.
    t = np.arange(4000.)
    y = np.sin(2 * np.pi * t / 32.)
    y2 = np.sin(2 * np.pi * t / 64.)
    y[1000:3000] = y2[1000:3000]
    var = 'sin_wav'
    time = time_float('2010-01-01') + 10 * t
    pytplot.store_data(var, data={'x': time, 'y': y})

    # Complex wavelet transformation.
    powervar = wavelet(var, wavename='cmorl0.5-1.0')
    # Also try the following and compare:
    # powervar = wavelet(var, wavename='gaus1')
    pvar = powervar[0]

    # Plot.
    pytplot.options(pvar, 'colormap', 'jet')
    pytplot.options(pvar, 'ylog', True)
    pytplot.options(pvar, 'ytitle', pvar)
    pytplot.ylim(pvar, 0.001, 1.0)

    if plot:
        pytplot.tplot([var, pvar])

    return 1
示例#2
0
def ex_avg(plot=True):
    """Load GMAG data and average over 5 min intervals."""
    # Delete any existing pytplot variables.
    pytplot.del_data()

    # Define a time rage as a list
    trange = ['2007-03-23', '2007-03-23']

    # Download gmag files and load data into pytplot variables.
    sites = ['ccnv']
    var = 'thg_mag_ccnv'
    pyspedas.themis.gmag(sites=sites, trange=trange, varnames=[var])
    pytplot.tplot_options('title', 'GMAG data, thg_mag_ccnv 2007-03-23')
    pyspedas.subtract_average(var, median=1)
    var += '-m'

    # Five minute average using time dt.
    avg_data(var, dt=5 * 60.)
    # Five minute average using width (number of measurements).
    # Each measurement is 0.5 sec.
    avg_data(var, width=5 * 60. * 2., new_names=var + '-avg2')

    # Plot.
    if plot:
        pytplot.tplot([var, var + '-avg', var + '-avg2'])

    # Return 1 as indication that the example finished without problems.
    return 1
示例#3
0
def ex_create():
    # Delete any existing pytplot variables
    pytplot.del_data()
    # Create a sin wave plot
    a = list(range(0, 101))
    b = [2.0 / 100.0 * numpy.pi * s for s in a]
    c = pyspedas.time_float('2017-01-01')
    x = list()
    y = list()
    for i in range(len(b)):
        x.append(c + 60.0 / (2 * numpy.pi) * 60.0 * b[i])
        y.append(1000.0 * numpy.sin(b[i]))

    # Store data
    pytplot.store_data('sinx', data={'x': x, 'y': y})
    # Apply tclip
    pyspedas.tclip('sinx', -800.0, 800.0)
    # Remove NaN values
    pyspedas.tdeflag('sinx-clip')
    # Interpolate
    pyspedas.tinterpol(['sinx-clip-deflag'], ['sinx'], 'quadratic')
    # Plot
    pytplot.ylim('sinx', -1100.0, 1100.0)
    pytplot.ylim('sinx-clip', -1100.0, 1100.0)
    pytplot.ylim('sinx-clip-deflag', -1100.0, 1100.0)
    pytplot.ylim('sinx-clip-deflag-itrp', -1100.0, 1100.0)
    pytplot.tplot_options('title', 'Interpolation example')
    pytplot.tplot(
        ['sinx', 'sinx-clip', 'sinx-clip-deflag', 'sinx-clip-deflag-itrp'])
示例#4
0
def ex_spectra(plot=True):
    """Download THEMIS data and create a plot."""
    # Delete any existing pytplot variables
    pytplot.del_data()

    # Download THEMIS data for 2015-12-31
    # pyspedas.load_data('themis', ['2015-12-31'], ['tha'], 'state', 'l1')
    # pyspedas.load_data('themis', ['2015-12-31'], ['tha'], 'sst', 'l2')
    time_range = ['2015-12-31 00:00:00', '2015-12-31 23:59:59']
    pyspedas.themis.state(probe='a', trange=time_range)
    pyspedas.themis.sst(probe='a', trange=time_range,
                        varnames=['tha_psif_en_eflux'])

    # Specify options
    pytplot.ylim('tha_pos', -23000.0, 81000.0)
    pytplot.ylim('tha_psif_en_eflux', 10000.0, 4000000.0)
    pytplot.options('tha_psif_en_eflux', 'colormap', 'jet')
    pytplot.tplot_options('title', 'tha 2015-12-31')

    # Plot line and spectrogram
    if plot:
        pytplot.tplot(['tha_pos', 'tha_psif_en_eflux'])

    # Return 1 as indication that the example finished without problems.
    return 1
示例#5
0
def ex_deriv(plot=True):
    """Find the derivative of a GMAG variable."""
    # Derivative of data
    pytplot.del_data()

    # Define a time rage as a list
    trange = ['2007-03-23', '2007-03-23']

    # Download gmag files and load data into pytplot variables
    sites = ['ccnv']
    var = 'thg_mag_ccnv'
    pyspedas.themis.gmag(sites=sites, trange=trange, varnames=[var])
    # pytplot.tplot_options('title', 'GMAG data, thg_mag_ccnv 2007-03-23')
    pyspedas.subtract_average(var, median=1)
    var += '-m'

    # Five minute average
    deriv_data(var)
    # pytplot.options(var, 'ytitle', var)
    # pytplot.options(var + '-der', 'ytitle', var + '-der')
    if plot:
        pytplot.tplot([var, var + '-der'])

    # Return 1 as indication that the example finished without problems.
    return 1
示例#6
0
def test_altitude_plot():

    pytplot.netcdf_to_tplot(current_directory +
                            "/testfiles/g15_xrs_2s_20170619_20170619.nc",
                            time='time_tag')
    pytplot.store_data(
        'altitude',
        data={
            'x':
            pytplot.data_quants['A_COUNT'].coords['time'].values,
            'y':
            np.arange(
                0,
                len(pytplot.data_quants['A_COUNT'].coords['time'].values),
                step=1)
        })
    pytplot.link('A_COUNT', 'altitude')
    pytplot.xlim('2017-06-19 02:00:00', '2017-06-19 04:00:00')
    pytplot.ylim("A_COUNT", 17000, 18000)
    pytplot.timebar('2017-06-19 03:00:00',
                    "A_COUNT",
                    color=(100, 255, 0),
                    thick=3)
    pytplot.timebar('2017-06-19 03:30:00', "A_COUNT", color='g')
    pytplot.options("A_COUNT", 'alt', 1)
    pytplot.tplot(2, testing=True)
    pytplot.tplot(2, testing=True, bokeh=True)
示例#7
0
def ex_cotrans():
    """Transform state data for THEMIS from GEI to GSE.

    Load position and velocity from THEMIS.
    Transform the coordinates to GSE and plot.

    Notes
    -----
    IDL SPEDAS contains a more extended example: thm_crib_contrans.pro
    """
    trange = ['2007-06-23/00:00:00', '2007-06-23/23:59:59']
    probe = 'a'
    pos_in = "tha_pos"
    pos_out = "tha_pos_gse"
    vel_in = "tha_vel"
    vel_out = "tha_vel_gse"
    pyspedas.themis.state(probe=probe, trange=trange, time_clip=True,
                          varnames=[pos_in, vel_in])

    # Coordinate transformation.
    cotrans(name_in=pos_in, name_out=pos_out, coord_in="gei", coord_out="gse")
    cotrans(name_in=vel_in, name_out=vel_out, coord_in="gei", coord_out="gse")

    # Plot.
    pytplot.tplot_options('title', 'Themis pos and vel in GEI and GSE')
    pytplot.options(pos_in, 'ytitle', pos_in)
    pytplot.options(pos_out, 'ytitle', pos_out)
    pytplot.options(vel_in, 'ytitle', vel_in)
    pytplot.options(vel_out, 'ytitle', vel_out)
    pytplot.tplot([pos_in, vel_in, pos_out, vel_out])

    # Return 1 as indication that the example finished without problems.
    return 1
示例#8
0
def ex_spikes(plot=True):
    """Load GMAG data and show how to remove spikes."""
    # Delete any existing pytplot variables.
    pytplot.del_data()

    # Define a time rage as a list
    trange = ['2007-03-23', '2007-03-23']

    # Download gmag files and load data into pytplot variables.
    sites = ['ccnv']
    var = 'thg_mag_ccnv'
    pyspedas.themis.gmag(sites=sites, trange=trange, varnames=[var])
    pytplot.tplot_options('title', 'GMAG data, thg_mag_ccnv 2007-03-23')

    # Add spikes to data.
    data = pytplot.data_quants[var].values
    dlen = len(data)
    for i in range(1, 16):
        s = (1 if random.random() < 0.5 else -1)
        p1 = int(i * dlen / 16)
        data[p1, 0] = s * i * 40000
        data[p1 + 2000, 1] = s * i * 30000
        data[p1 + 4000, 2] = s * i * 20000

    pytplot.data_quants[var].values = data

    # Clean spikes.
    clean_spikes(var, sub_avg=True)

    # Plot all variables.
    if plot:
        pytplot.tplot(pytplot.tplot_names())

    # Return 1 as indication that the example finished without problems.
    return 1
示例#9
0
def ex_gmag(plot=True):
    """Demonstrate how to use gmag functions."""
    # Delete any existing pytplot variables
    pytplot.del_data()

    # Define a time rage as a list
    trange = ['2015-12-31', '2015-12-31']

    # Get a list of EPO gmag stations
    sites = pyspedas.themis.ground.gmag.gmag_list('epo')

    # Download gmag files and load data into pytplot variables
    pyspedas.themis.gmag(sites=sites, trange=trange)

    # Get a list of loaded sites
    sites_loaded = pyspedas.tnames()

    # Subtract mean values
    pyspedas.subtract_average(sites_loaded, '')

    # Download AE index data
    # pyspedas.load_data('gmag', time_list, ['idx'], '', '')
    pyspedas.themis.gmag(sites='idx', trange=trange)

    # Plot
    sites_loaded = pytplot.tplot_names()
    pytplot.tplot_options('title', 'EPO GMAG 2015-12-31')

    if plot:
        pytplot.tplot(sites_loaded)

    # Return 1 as indication that the example finished without problems.
    return 1
示例#10
0
def ex_spectra():
    # Delete any existing pytplot variables
    pytplot.del_data()
    # Download THEMIS data for 2015-12-31
    pyspedas.load_data('themis', ['2015-12-31'], ['tha'], 'sst', 'l2')
    # Specify options
    pytplot.tplot_options('title', 'tha_psif_en_eflux 2015-12-31')
    pytplot.ylim('tha_psif_en_eflux', 10000.0, 10000000.0)
    pytplot.options('tha_psif_en_eflux', 'colormap', 'viridis')
    # Plot spectrogram
    pytplot.tplot(['tha_psif_en_eflux'])
示例#11
0
def ex_omni():
    # Print the installed version of pyspedas
    pyspedas.version()
    # Delete any existing pytplot variables
    pytplot.del_data()
    # Download OMNI data for 2015-12-31
    pyspedas.load_data('omni', ['2015-12-31 00:00:00', '2016-01-01 23:59:59'],
                       '', '', '1min')

    # Plot
    pytplot.tplot_options('title', 'OMNI flow_speed 2015-12-31 to 2016-01-01')
    pytplot.tplot(['flow_speed'])
示例#12
0
def ex_analysis():
    # Print the installed version of pyspedas
    pyspedas.version()
    # Delete any existing pytplot variables
    pytplot.del_data()
    # Download THEMIS state data for 2015-12-31
    pyspedas.load_data('themis', '2015-12-31', ['tha'], 'state', 'l1')
    # Use some analysis functions on tplot variables
    pyspedas.subtract_average('tha_pos')
    pyspedas.subtract_median('tha_pos')
    # Plot
    pytplot.tplot(["tha_pos", "tha_pos-d", "tha_pos-m"])
示例#13
0
def test_cdf_swe_read():
    pytplot.cdf_to_tplot(current_directory +
                         "/testfiles/mvn_swe_l2_svyspec_20170619_v04_r04.cdf")
    pytplot.options('diff_en_fluxes', 'colormap', 'magma')
    pytplot.options('diff_en_fluxes', 'ztitle', 'FLUX')
    pytplot.options('diff_en_fluxes', 'ytitle', 'Energy')
    pytplot.options("diff_en_fluxes", "spec", 1)
    pytplot.options("diff_en_fluxes", "crosshair_y", "banana")
    pytplot.options("diff_en_fluxes", "crosshair_z", "tomato")
    pytplot.options("diff_en_fluxes", 'panel_size', 1)
    pytplot.options('diff_en_fluxes', 'ylog', 1)
    pytplot.options('diff_en_fluxes', 'zlog', 1)
    pytplot.tplot(1, testing=True)
示例#14
0
def ex_omni():
    # Delete any existing pytplot variables
    pytplot.del_data()

    # Download OMNI data for 2015-12-31
    trange = ['2015-12-31 00:00:00', '2015-12-31 23:59:59']
    pyspedas.omni.load(trange=trange, datatype='1min')

    # Plot
    pytplot.tplot_options('title', 'OMNI flow_speed 2015-12-31')
    pytplot.tplot(['flow_speed'])

    # Return 1 as indication that the example finished without problems.
    return 1
示例#15
0
def test_goes_read():

    pytplot.netcdf_to_tplot(current_directory +
                            "/testfiles/g15_xrs_2s_20170619_20170619.nc",
                            time='time_tag')
    pytplot.xlim('2017-06-19 02:00:00', '2017-06-19 04:00:00')
    pytplot.ylim("B_COUNT", 17000, 18000)
    pytplot.timebar('2017-06-19 03:00:00',
                    "B_COUNT",
                    color=(100, 255, 0),
                    thick=3)
    pytplot.timebar('2017-06-19 03:30:00', "B_COUNT", color='g')
    pytplot.options("B_COUNT", 'ylog', 1)
    pytplot.store_data("BCOUNTFLUX", data=["B_COUNT", "B_FLUX"])
    pytplot.tplot([1, 2, 3, 4, 5, 7], var_label=6, testing=True)
示例#16
0
def ex_analysis():

    # Delete any existing pytplot variables
    pytplot.del_data()

    # Download THEMIS state data for 2015-12-31
    time_range = ['2015-12-31 00:00:00', '2015-12-31 23:59:59']
    pyspedas.themis.state(probe='a', trange=time_range)

    # Use some analysis functions on tplot variables
    pyspedas.subtract_average('tha_pos')
    pyspedas.subtract_median('tha_pos')

    # Plot
    pytplot.tplot(["tha_pos", "tha_pos-d", "tha_pos-m"])

    # Return 1 as indication that the example finished without problems.
    return 1
示例#17
0
def ex_basic():
    # Delete any existing pytplot variables
    pytplot.del_data()
    # Download THEMIS state data for 2015-12-31
    time_range = ['2015-12-31 00:00:00', '2016-01-01 12:00:00']
    pyspedas.load_data('themis', time_range, ['tha'], 'state', 'l1')
    # Get data into python variables
    alldata = pytplot.get_data("tha_pos")
    time = alldata[0]
    data = alldata[1]
    # Store a new pytplot variable
    pytplot.store_data("tha_position", data={'x': time, 'y': data})
    # Define the y-axis limits
    pytplot.ylim('tha_pos', -23000.0, 81000.0)
    pytplot.ylim('tha_position', -23000.0, 81000.0)
    pytplot.ylim('tha_vel', -8.0, 12.0)
    # Plot position and velocity using the pyqtgraph library (default)
    pytplot.tplot(["tha_pos", "tha_position", "tha_vel"])
示例#18
0
def ex_gmag():
    # Delete any existing pytplot variables
    pytplot.del_data()
    # Define list of dates
    time_list = ['2015-12-31']
    # Get a list of EPO gmag stations
    sites = pyspedas.gmag_list(group='epo')
    # Download gmag files and load data into pytplot variables
    pyspedas.load_data('gmag', time_list, sites, '', '')
    # Get a list of loaded sites
    sites_loaded = pyspedas.tplot_names()
    # Subtact mean values
    pyspedas.subtract_average(sites_loaded, '')
    # Download AE index data
    pyspedas.load_data('gmag', time_list, ['idx'], '', '')
    # Plot
    sites_loaded = pyspedas.tplot_names()
    pytplot.tplot_options('title', 'EPO GMAG 2015-12-31')
    pytplot.tplot(sites_loaded)
示例#19
0
def ex_test_smooth():

    t = [1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.]
    y = [3., 5., 8., 15., 20., 1., 2., 3., 4., 5., 6., 4.]

    pytplot.store_data('original', data={'x': t, 'y': y})
    tsmooth('original', width=5, new_names='smooth', preserve_nans=1)

    pytplot.tplot(['original', 'smooth'])

    d0 = pytplot.get_data('original')
    print('Original data: ', d0[1])
    d = pytplot.get_data('smooth')
    print('Smooth data: ', d[1])
    """
    Results:
    Original data:[ 3., 5., 8.,   15., 20., 1.,  2., 3., 4., 5.,  6.,  4.]
    Smooth data:  [ 3., 5., 10.2, 9.8, 9.2, 8.2  6., 3., 4., 4.4, 6.,  4.]
    """
    # Return 1 as indication that the example finished without problems.
    return 1
示例#20
0
def ex_create(plot=True):
    """Show how to create and plot pytplot variables."""
    # Delete any existing pytplot variables
    pytplot.del_data()

    # Create a sin wave plot
    a = list(range(0, 101))
    b = [2.0 / 100.0 * numpy.pi * s for s in a]
    c = time_float('2017-01-01')
    x = list()
    y = list()
    for i in range(len(b)):
        x.append(c + 60.0 / (2 * numpy.pi) * 60.0 * b[i])
        y.append(1000.0 * numpy.sin(b[i]))

    # Store data
    pytplot.store_data('sinx', data={'x': x, 'y': y})

    # Apply yclip
    pyspedas.yclip('sinx', -800.0, 800.0)

    # Remove NaN values
    pyspedas.tdeflag('sinx-clip')

    # Interpolate
    pyspedas.tinterpol(['sinx-clip-deflag'], 'sinx', 'quadratic')

    # Plot
    pytplot.ylim('sinx', -1100.0, 1100.0)
    pytplot.ylim('sinx-clip', -1100.0, 1100.0)
    pytplot.ylim('sinx-clip-deflag', -1100.0, 1100.0)
    pytplot.ylim('sinx-clip-deflag-itrp', -1100.0, 1100.0)
    pytplot.tplot_options('title', 'Interpolation example')

    if plot:
        pytplot.tplot(
            ['sinx', 'sinx-clip', 'sinx-clip-deflag', 'sinx-clip-deflag-itrp'])

    # Return 1 as indication that the example finished without problems.
    return 1
示例#21
0
def ex_avg(plot=False):
    """Load GMAG data and average over 5 min intervals."""
    # Delete any existing pytplot variables
    pytplot.del_data()

    # Define a time rage as a list
    trange = ['2007-03-23', '2007-03-23']

    # Download gmag files and load data into pytplot variables
    sites = ['ccnv']
    var = 'thg_mag_ccnv'
    pyspedas.themis.gmag(sites=sites, trange=trange, varnames=[var])
    pytplot.tplot_options('title', 'GMAG data, thg_mag_ccnv 2007-03-23')
    pyspedas.subtract_average(var, median=1)
    var += '-m'

    # Five minute average
    avg_data(var, width=5 * 60)
    if plot:
        pytplot.tplot([var, var + '-avg'])

    # Return 1 as indication that the example finished without problems.
    return 1
示例#22
0
def ex_deriv2():
    """Find the derivative of sinx."""
    # Delete any existing pytplot variables
    pytplot.del_data()

    # Create a sin wave plot
    a = list(range(0, 101))
    b = [2.0 / 100.0 * np.pi * s for s in a]
    c = pyspedas.time_float('2017-01-01')
    x = list()
    y = list()
    for i in range(len(b)):
        x.append(c + 60.0 / (2 * np.pi) * 60.0 * b[i])
        y.append(1000.0 * np.sin(b[i]))

    # Store data
    pytplot.store_data('sinx', data={'x': x, 'y': y})

    var = 'sinx'
    deriv_data(var)
    pytplot.tplot([var, var + '-der'])

    return 1
示例#23
0
def ex_basic(plot=True):
    """Download and plot THEMIS data."""
    # Delete any existing pytplot variables
    pytplot.del_data()

    # Download THEMIS state data for 2015-12-31
    time_range = ['2015-12-31 00:00:00', '2016-01-01 12:00:00']
    pyspedas.themis.state(probe='a', trange=time_range, time_clip=True)

    # Get data into python variables
    alldata = pytplot.get_data("tha_pos")
    time = alldata[0]
    data = alldata[1]
    # Here we could work on the data before saving a new tplot variable.

    # Store a new pytplot variable
    pytplot.store_data("tha_position", data={'x': time, 'y': data})

    # Define the y-axis limits
    pytplot.ylim('tha_pos', -23000.0, 81000.0)
    pytplot.ylim('tha_position', -23000.0, 81000.0)
    pytplot.ylim('tha_vel', -8.0, 12.0)

    # Give a title to the plot and labels for the y-axis panels.
    pytplot.tplot_options('title', 'tha position and velocity, 2015-12-31')
    pytplot.options('tha_pos', 'ytitle', 'Position')
    pytplot.options('tha_vel', 'ytitle', 'Velocity')

    # Plot position and velocity using the pyqtgraph library (default)
    if plot:
        pytplot.tplot(["tha_pos", "tha_position", "tha_vel"])

    # Plot position and velocity using the bokeh library
    # pytplot.tplot(["tha_pos", "tha_position", "tha_vel"], bokeh=True)

    # Return 1 as indication that the example finished without problems.
    return 1
示例#24
0
def ex_dsl2gse(plot=True):
    """Run dsl2gse."""
    time_range = ['2017-03-23 00:00:00', '2017-03-23 23:59:59']
    pyspedas.themis.state(probe='a',
                          trange=time_range,
                          get_support_data=True,
                          varnames=['tha_spinras', 'tha_spindec'])
    pyspedas.themis.fgm(probe='a', trange=time_range, varnames=['tha_fgl_dsl'])

    dsl2gse('tha_fgl_dsl', 'tha_spinras', 'tha_spindec', 'tha_fgl_gse')

    # Get the third component only
    d_in = pytplot.get_data('tha_fgl_dsl')
    pytplot.store_data('z_dsl', data={'x': d_in[0], 'y': d_in[1][:, 2]})
    d_out = pytplot.get_data('tha_fgl_gse')
    pytplot.store_data('z_gse', data={'x': d_out[0], 'y': d_out[1][:, 2]})

    # Plot
    pytplot.tplot_options('title', 'tha_fgl DSL and GSE, 2017-03-23')
    if plot:
        pytplot.tplot(['tha_fgl_dsl', 'tha_fgl_gse', 'z_dsl', 'z_gse'])

    # Return 1 as indication that the example finished without problems.
    return 1
示例#25
0
def corona(iuvs,
           sameplot=True,
           density=True,
           radiance=True,
           orbit_num=None,
           species=None,
           log=False,
           title='IUVS Corona Observations',
           qt=True):

    density_names_to_plot = []
    density_legend_names = []
    dplot = 0

    radiance_names_to_plot = []
    radiance_legend_names = []
    rplot = 0

    if not isinstance(species, builtins.list):
        species = [species]

    if not isinstance(orbit_num, builtins.list):
        orbit_num = [orbit_num]

    if orbit_num != [None]:
        restrict_orbit = True
    else:
        restrict_orbit = False

    if species != [None]:
        restrict_species = True
    else:
        restrict_species = False

    xmin = []
    xmax = []

    for orbit in iuvs:
        for obs in orbit:
            if obs.lower() == 'corona_lores_high':
                if restrict_orbit and int(
                        orbit[obs]['orbit_number']) not in orbit_num:
                    continue
                if density:
                    x = np.array(orbit[obs]['density']['ALTITUDE'])
                    for var in orbit[obs]['density']:
                        if var.lower() != "altitude":
                            if restrict_species and var not in species:
                                continue
                            if not np.isnan(orbit[obs]['density'][var]).all():
                                xmin.append(np.min(x))
                                xmax.append(np.max(x))
                                density_names_to_plot.append(
                                    obs + '_density_' + var + '_' +
                                    str(orbit[obs]['orbit_number']))
                                density_legend_names.append(
                                    'Orbit ' +
                                    str(orbit[obs]['orbit_number']) + ' ' +
                                    var + ' density')
                                data = np.array(orbit[obs]['density'][var])
                                alts = x[~np.isnan(data)]
                                data = data[~np.isnan(data)]
                                fake_times = np.arange(len(alts))
                                pytplot.store_data(
                                    density_names_to_plot[dplot],
                                    data={
                                        'x': fake_times,
                                        'y': data
                                    })
                                pytplot.store_data(
                                    density_names_to_plot[dplot] + "_alt",
                                    data={
                                        'x': fake_times,
                                        'y': alts
                                    })
                                pytplot.options(
                                    density_names_to_plot[dplot], "link", [
                                        'alt',
                                        density_names_to_plot[dplot] + "_alt"
                                    ])
                                pytplot.options(density_names_to_plot[dplot],
                                                'alt', 1)
                                pytplot.options(density_names_to_plot[dplot],
                                                'alt', 1)
                                dplot += 1
                if radiance:
                    x = np.array(orbit[obs]['radiance']['ALTITUDE'])
                    for var in orbit[obs]['radiance']:
                        if var.lower() != "altitude":
                            if restrict_species and var not in species:
                                continue
                            if not np.isnan(orbit[obs]['radiance'][var]).all():
                                xmin.append(np.min(x))
                                xmax.append(np.max(x))
                                radiance_names_to_plot.append(
                                    obs + '_radiance_' + var + '_' +
                                    str(orbit['corona_lores_high']
                                        ['orbit_number']))
                                radiance_legend_names.append(
                                    'Orbit ' +
                                    str(orbit[obs]['orbit_number']) + ' ' +
                                    var + ' radiance')
                                data = np.array(orbit[obs]['radiance'][var])
                                alts = x[~np.isnan(data)]
                                data = data[~np.isnan(data)]
                                fake_times = np.arange(len(alts))
                                pytplot.store_data(
                                    radiance_names_to_plot[rplot],
                                    data={
                                        'x': fake_times,
                                        'y': data
                                    })
                                pytplot.store_data(
                                    radiance_names_to_plot[rplot] + "_alt",
                                    data={
                                        'x': fake_times,
                                        'y': alts
                                    })
                                pytplot.options(
                                    radiance_names_to_plot[rplot], "link", [
                                        'alt',
                                        radiance_names_to_plot[rplot] + "_alt"
                                    ])
                                pytplot.options(radiance_names_to_plot[rplot],
                                                'alt', 1)
                                rplot += 1

    if radiance and rplot == 0:
        print("There is no corona radiance data in the given IUVS variable")
        radiance = False
    if density and dplot == 0:
        print("There is no corona density data in the given IUVS variable")
        density = False

    list_of_plots = []
    if sameplot:
        if density:
            pytplot.store_data('corona_lores_high_density',
                               data=density_names_to_plot)
            list_of_plots.append('corona_lores_high_density')
            pytplot.options('corona_lores_high_density', 'alt', 1)
            if log:
                pytplot.options('corona_lores_high_density', 'ylog', 1)
            pytplot.options('corona_lores_high_density', 'legend_names',
                            density_legend_names)

        if radiance:
            pytplot.store_data('corona_lores_high_radiance',
                               data=radiance_names_to_plot)
            list_of_plots.append('corona_lores_high_radiance')
            pytplot.options('corona_lores_high_radiance', 'alt', 1)
            if log:
                pytplot.options('corona_lores_high_radiance', 'ylog', 1)
            pytplot.options('corona_lores_high_radiance', 'legend_names',
                            radiance_legend_names)
    else:
        i = 0
        for d in density_names_to_plot:
            list_of_plots.append(d)
            pytplot.options(d, 'ytitle', density_legend_names[i])
            if log:
                pytplot.options(d, 'ylog', 1)
            i += 1
        i = 0
        for r in radiance_names_to_plot:
            list_of_plots.append(r)
            pytplot.options(r, 'ytitle', radiance_legend_names[i])
            if log:
                pytplot.options(r, 'ylog', 1)
            i += 1
    pytplot.tplot_options('alt_range', [np.min(xmin), np.max(xmax)])
    pytplot.tplot_options('title', title)
    pytplot.tplot_options('wsize', [1000, 400 * len(list_of_plots)])
    pytplot.tplot(list_of_plots, bokeh=not qt)
    pytplot.del_data(list_of_plots)

    return
示例#26
0
             trange=['2015-10-16/13:06', '2015-10-16/13:07'])
mms_load_feeps(get_support_data=True,
               probe=2,
               data_rate=['srvy', 'brst'],
               trange=['2015-10-16/13:06', '2015-10-16/13:07'])
mms_load_aspoc()
''' ==========================================================================

Plotting MMS Data in Python

========================================================================== '''

from pytplot import tplot

# like in IDL, pyTplot supports strings, lists of strings, as well as tplot variable #s
tplot('mms4_fgm_b_gsm_brst_l2')

tplot(['mms4_fgm_b_gsm_brst_l2', 'mms4_edp_dce_gse_brst_l2'])

# change the plot metadata
from pytplot import options
options('mms4_edp_dce_gse_brst_l2', 'color', ['b', 'g', 'r'])
options('mms4_edp_dce_gse_brst_l2', 'legend_names', ['Ex', 'Ey', 'Ez'])

tplot([
    'mms4_fgm_b_gsm_brst_l2', 'mms4_edp_dce_gse_brst_l2',
    'mms4_des_energyspectr_omni_brst', 'mms4_des_pitchangdist_miden_brst'
])

tplot('b_vector')
options('b_vector', 'ytitle', 'MMS4 FGM')
示例#27
0
pytplot.tplot_options('wsize', [800, 800])

# Adding a region of interest (ROI)
# pytplot will add a ROI (indicated by two vertical red lines, with grey shading in between)
# to all plot via specifying the 'roi' option
pytplot.tplot_options('roi', ['2016-06-20 11:12:24', '2016-06-20 14:12:00'])

# Another option available in tplot_options is to specify the number of seconds with consecutive nan
# values allowed before no interpolation should occur
pytplot.tplot_options('data_gap', 80)

##############################################################################
# Displaying data using tplot
# ---------------------------
# Single Panel Plot
pytplot.tplot('swia_vel')  # or, pytplot.tplot(6)

# Multiple Panel Plot
pytplot.tplot(['swia_counts', 'swia_vel', 'mag'])  # or, pytplot.tplot([4,6,7])

##############################################################################
# Interacting with Data Plots
# ---------------------------
# There are several ways to interact with the data plots. There is command line interaction
# that follows the same pattern of functions IDL utilizes. Pytplot additionally has interactivity
# built into the viewing window in the form of "tools".

# Moving forward and backward in time
# The Pan tool allows the user to click and drag the mouse on the plot to move along the x- or y-axis.

# Zooming in and out
示例#28
0
def altplot(kp,
            parameter=None,
            time=None,
            errors=None,
            sameplot=True,
            list=False,
            title='Altitude Plot',
            ylog=False,
            qt=True):
    '''
    Plot the provided data plotted against spacecraft altitude.
    If time is not provided plot entire data set.

    Parameters:
        kp : dict
            insitu kp data structure/dictionary read from file(s)
        parameter : list of str/int
            The parameter(s) to be plotted.  Can be provided as
            integers (by index) or strings (by name: inst.obs).  If a 
            single parameter is provided, it must be an int or str.  If
            several are provided it must be a list.  A list may contain
            a mixture of data types.
        time : list of str
            Two-element list of strings or integers indicating the
            range of Time to be plotted.  At present, there are no
            checks on whether provided Times are within provided data
        sameplot : bool
            if True, put all curves on same axes
            if False, generate new axes for each plot
        list : bool
            Lists all Key Parameters instead of plotting
        title : str
            The Title to give the plot
        ylog : bool
            Displays the log of the y axis
        qt : bool
            If true, plots with qt.  Else creates an HTML page with bokeh.

    Returns:
        None

    Examples:
        >>> # Plot LPW.ELECTRON_DENSITY against spacecraft altitude.
        >>> pydivide.altplot(insitu, parameter=['LPW.ELECTRON_DENSITY','MAG.MSO_Y'], qt=False, ylog=True)
    '''

    if list:
        x = param_list(kp)
        for param in x:
            print(param)
        return

    # Check for orbit num rather than time string
    if isinstance(time, builtins.list):
        if isinstance(time[0], int):
            time = orbit_time(time[0], time[1])
    elif isinstance(time, int):
        time = orbit_time(time)

    # Check existence of parameter
    if parameter is None:
        print("Must provide an index (or name) for param to be plotted.")
        return
    # Store instrument and observation of parameter(s) in lists
    inst = []
    obs = []
    if type(parameter) is int or type(parameter) is str:
        a, b = get_inst_obs_labels(kp, parameter)
        inst.append(a)
        obs.append(b)
    else:
        for param in parameter:
            a, b = get_inst_obs_labels(kp, param)
            inst.append(a)
            obs.append(b)
    inst_obs = builtins.list(zip(inst, obs))

    # Check the time variable
    if time is not None:
        kp = range_select(kp, time)

    # Generate the altitude array
    z = []
    index = 0
    for i in kp['TimeString']:
        z.append(kp['SPACECRAFT']['ALTITUDE'][index])
        index += 1

    pytplot.store_data('sc_alt', data={'x': kp['Time'], 'y': z})

    # Cycle through the parameters, plotting each according to
    #  the given keywords
    names_to_plot = []
    legend_names = []
    iplot = 0  # subplot indexes on 1
    for inst, obs in inst_obs:
        # First, generate the dependent array from data
        y = []
        index = 0
        for i in kp['TimeString']:
            y.append(kp[inst][obs][index])
            index += 1

        names_to_plot.append('%s.%s' % (inst, obs))
        legend_names.append(obs)

        pytplot.store_data(names_to_plot[iplot],
                           data={
                               'x': kp['Time'],
                               'y': y
                           })
        pytplot.options(names_to_plot[iplot], 'link', ['alt', 'sc_alt'])
        pytplot.options(names_to_plot[iplot], 'alt', 1)
        pytplot.options(names_to_plot[iplot], 'ylog', ylog)

        iplot += 1

    if sameplot:
        pytplot_name = ','.join(legend_names)
        pytplot.store_data(pytplot_name, data=names_to_plot)
        pytplot.options(pytplot_name, 'alt', 1)
        pytplot.options(pytplot_name, 'ylog', ylog)
        pytplot.options(pytplot_name, 'legend_names', legend_names)
        pytplot.tplot_options('title', title)
        pytplot.tplot_options('wsize', [1000, 300])
        pytplot.tplot(pytplot_name, bokeh=not qt)
        pytplot.del_data(pytplot_name)
    else:
        pytplot.tplot_options('title', title)
        pytplot.tplot_options('wsize', [1000, 300 * (iplot - 1)])
        pytplot.tplot(names_to_plot, bokeh=not qt)
        pytplot.del_data(names_to_plot)
    return
示例#29
0
'''

This crib sheet shows how to load MMS electric field data

'''

from pyspedas import mms_load_edp
from pytplot import tplot

# 'fast' mode electric field data for MMS1 are loaded by default
mms_load_edp(trange=['2015-10-16', '2015-10-17'])
tplot('mms1_edp_dce_gse_fast_l2')

# to load the burst mode data, set the data rate to 'brst'
mms_load_edp(data_rate='brst', trange=['2015-10-16/13:06', '2015-10-16/13:07'])
tplot('mms1_edp_dce_gse_brst_l2')

# to load the spacecraft potential data, set the datatype to 'scpot'
mms_load_edp(datatype='scpot', trange=['2015-10-16', '2015-10-17'])
tplot('mms1_edp_scpot_fast_l2')
示例#30
0
'''

This crib sheet shows how to load and plot Electron Drift Instrument (EDI) data

'''

from pyspedas import mms_load_edi
from pytplot import tplot

# load data from the Electron Drift Instrument
mms_load_edi(trange=['2015-12-23', '2015-12-24'],
             data_rate='srvy',
             datatype='efield')

# plot the ExB drift velocity and electric field
tplot(['mms1_edi_vdrift_gse_srvy_l2', 'mms1_edi_e_gse_srvy_l2'])