def get_pc1_spectra(rbsp_path, time_start, time_end, probe, pc1_res=25.0,
                    overlap=0.99, high_pass_mHz=None):
    '''
    Helper function to load magnetic field and calculate dynamic spectrum for
    overlaying on plots
    '''
    import rbsp_fields_loader as rfl
    import fast_scripts       as fscr
    
    print('Generating magnetic dynamic spectra...')
    
    times, mags, dt, gyfreqs = \
        rfl.load_magnetic_field(rbsp_path, time_start, time_end, probe,
                                pad=3600, LP_B0=1.0, get_gyfreqs=False,
                                return_raw=False, wave_HP=None, wave_LP=None)
    
    if high_pass_mHz is not None:
        mags = ascr.clw_high_pass(mags, high_pass_mHz, dt, filt_order=4)
    
    pc1_xpower, pc1_xtimes, pc1_xfreq = fscr.autopower_spectra(times, mags[:, 0], time_start, 
                                                     time_end, dt, overlap=overlap, df=pc1_res)
    
    pc1_ypower, pc1_ytimes, pc1_yfreq = fscr.autopower_spectra(times, mags[:, 1], time_start, 
                                                     time_end, dt, overlap=overlap, df=pc1_res)
    
    pc1_perp_power = np.log10(pc1_xpower[:, :] + pc1_ypower[:, :])
    
    return pc1_xtimes, pc1_xfreq, pc1_perp_power
Esempio n. 2
0
def stackplot_with_parameters(param_dict, max_k, max_g, output='show'):
    plt.ioff()
    fig, ax = plt.subplots(10, 1, figsize=(8.27, 11.69))

    mag_times, B_mag, dt = rfl.load_magnetic_field('G://DATA//RBSP//',
                                                   time_start,
                                                   time_end,
                                                   probe=probe,
                                                   wave_HP=250,
                                                   wave_LP=700,
                                                   get_gyfreqs=False)
    trans_mag = np.sqrt(B_mag[:, 0]**2 + B_mag[:, 1]**2 + B_mag[:, 2]**2)

    ax[0].plot(param_dict['times'], param_dict['field'])
    ax[0].set_ylabel('$|B|$\n(nT)', rotation=0, labelpad=25)
    ax[0].legend(bbox_to_anchor=(1.0, 0), loc=3, borderaxespad=0.)

    ax0b = ax[0].twinx()
    ax0b.plot(mag_times, trans_mag)
    ax0b.set_ylabel('$B_{EMIC}$\n(nT)', rotation=0, labelpad=25)

    for jj in range(3):
        ax[1].plot(param_dict['times'],
                   param_dict['ndensc'][jj, :],
                   label=band_labels[jj],
                   color=species_colors[jj])
        ax[1].set_ylabel('$n_c$\n$(cm^{-3})$', rotation=0, labelpad=25)
        ax[1].legend(bbox_to_anchor=(1.0, 0), loc=3, borderaxespad=0.)

        ax[2].plot(param_dict['times'],
                   param_dict['ndensw'][jj, :],
                   label=band_labels[jj],
                   color=species_colors[jj])
        ax[2].set_ylabel('$n_{h1}$\n$(cm^{-3})$', rotation=0, labelpad=25)

        ax[3].plot(param_dict['times'],
                   param_dict['temp_perp'][jj, :] * 1e-3,
                   label=band_labels[jj],
                   color=species_colors[jj])
        ax[3].set_ylabel('$T_{\perp1}$\n(keV)', rotation=0, labelpad=25)

        ax[4].plot(param_dict['times'],
                   param_dict['A'][jj, :],
                   label=band_labels[jj],
                   color=species_colors[jj])
        ax[4].set_ylabel('$A_{h1}$', rotation=0, labelpad=25)

        ax[5].plot(param_dict['times'],
                   param_dict['ndensw2'][jj, :],
                   label=band_labels[jj],
                   color=species_colors[jj])
        ax[5].set_ylabel('$n_{h2}$\n$(cm^{-3})$', rotation=0, labelpad=25)

        ax[6].plot(param_dict['times'],
                   param_dict['temp_perp2'][jj, :] * 1e-3,
                   label=band_labels[jj],
                   color=species_colors[jj])
        ax[6].set_ylabel('$T_{\perp2}$\n(keV)', rotation=0, labelpad=25)

        ax[7].plot(param_dict['times'],
                   param_dict['A2'][jj, :],
                   label=band_labels[jj],
                   color=species_colors[jj])
        ax[7].set_ylabel('$A_{h2}$', rotation=0, labelpad=25)

        ax[8].plot(param_dict['times'],
                   max_k[:, jj],
                   label=band_labels[jj],
                   color=species_colors[jj])
        ax[8].set_ylabel('$k_m$', rotation=0, labelpad=25)

        ax[9].plot(param_dict['times'],
                   max_g[:, jj],
                   label=band_labels[jj],
                   color=species_colors[jj])
        ax[9].set_ylabel('$\gamma_m$', rotation=0, labelpad=25)

    for _ax in ax:
        if False:
            _ax.set_xlim(time_start, time_end)
            ax0b.set_xlim(time_start, time_end)
            figsave_path = save_dir + '_LT_stackplot_CC_{:03}_{:03}_{:03}_{}.png'.format(
                cmp[0], cmp[1], cmp[2], save_string)
        else:
            figsave_path = save_dir + '_LT_stackplot_CC_{:03}_{:03}_{:03}_{}_shortest2.png'.format(
                cmp[0], cmp[1], cmp[2], save_string)
            _ax.set_xlim(np.datetime64('2013-07-25T21:32:00'),
                         np.datetime64('2013-07-25T21:40:00'))
            ax0b.set_xlim(np.datetime64('2013-07-25T21:32:00'),
                          np.datetime64('2013-07-25T21:40:00'))

        if _ax is not ax[-1]:
            _ax.set_xticklabels([])

    ax[0].set_title('LINEAR THEORY INPUT STACKPLOT: RBSP-{} {}'.format(
        probe.upper(), date_string))

    fig.tight_layout()

    ax[-1].xaxis.set_major_locator(mdates.MinuteLocator(interval=2))
    ax[-1].xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))

    fig.subplots_adjust(hspace=0)
    fig.align_ylabels()
    fig.autofmt_xdate()

    if output.lower() == 'save':
        print('Saving {}'.format(figsave_path))
        fig.savefig(figsave_path)
        plt.close('all')
    elif output.lower() == 'show':
        plt.show()
    else:
        return
Esempio n. 3
0
def load_and_interpolate_plasma_params(time_start,
                                       time_end,
                                       probe,
                                       nsec=None,
                                       rbsp_path='G://DATA//RBSP//',
                                       HM_filter_mhz=None,
                                       time_array=None,
                                       check_interp=False):
    '''
    Same copy+paste as other versions, without the SPICE stuff
    '''
    print('Loading and interpolating satellite data')
    # Ephemeris data
    # Load ephemeris data
    eph_params = ['L', 'CD_MLAT', 'CD_MLT']
    eph_times, eph_dict = rfr.retrieve_RBSP_ephemeris_data(rbsp_path,
                                                           probe,
                                                           time_start,
                                                           time_end,
                                                           eph_params,
                                                           padding=[60, 60])

    # Cold (total?) electron plasma density
    den_times, edens, dens_err = rfr.retrieve_RBSP_electron_density_data(
        rbsp_path, time_start, time_end, probe, pad=30)

    # Magnetic magnitude
    mag_times, raw_mags = rfl.load_magnetic_field(rbsp_path,
                                                  time_start,
                                                  time_end,
                                                  probe,
                                                  return_raw=True,
                                                  pad=3600)

    # Filter out EMIC waves (background plus HM)
    if HM_filter_mhz is not None:
        filt_mags = np.zeros(raw_mags.shape)
        for ii in range(3):
            filt_mags[:, ii] = ascr.clw_low_pass(raw_mags[:, ii],
                                                 HM_filter_mhz,
                                                 1. / 64.,
                                                 filt_order=4)
    else:
        filt_mags = raw_mags

    # HOPE data
    itime, etime, pdict, perr = rfr.retrieve_RBSP_hope_moment_data(rbsp_path,
                                                                   time_start,
                                                                   time_end,
                                                                   padding=30,
                                                                   probe=probe)
    hope_dens = np.array(
        [pdict['Dens_p_30'], pdict['Dens_he_30'], pdict['Dens_o_30']])
    hope_tperp = np.array(
        [pdict['Tperp_p_30'], pdict['Tperp_he_30'], pdict['Tperp_o_30']])
    hope_tpar = np.array(
        [pdict['Tpar_p_30'], pdict['Tpar_he_30'], pdict['Tpar_o_30']])
    hope_anis = np.array([
        pdict['Tperp_Tpar_p_30'], pdict['Tperp_Tpar_he_30'],
        pdict['Tperp_Tpar_o_30']
    ]) - 1.

    # Interpolation step
    if nsec is None:
        # This should let me set my own timebase by feeding in an array
        if time_array is None:
            time_array = den_times.copy()
            iedens = edens.copy()
        else:
            iedens = interpolate_ne(time_array, den_times, edens)
    else:
        time_array = np.arange(time_start,
                               time_end,
                               np.timedelta64(nsec, 's'),
                               dtype='datetime64[us]')
        iedens = interpolate_ne(time_array, den_times, edens)

    ihope_dens, ihope_tpar, ihope_anis = HOPE_interpolate_to_time(
        time_array, itime, hope_dens, hope_tpar, hope_anis)
    ihope_dens, ihope_tperp, ihope_anis = HOPE_interpolate_to_time(
        time_array, itime, hope_dens, hope_tperp, hope_anis)

    Bi = interpolate_B(time_array, mag_times, filt_mags, nsec, LP_filter=False)

    iL = interpolate_ne(time_array, eph_times, eph_dict['L'])
    if check_interp:
        plt.ioff()

        # Cold dens + Magnetic field
        fig1, axes1 = plt.subplots(2)

        axes1[0].plot(den_times, edens, c='b')
        axes1[0].plot(time_array, iedens, c='r', lw=0.75)
        axes1[0].set_ylabel('$n_e$')

        B_total = np.sqrt(raw_mags[:, 0]**2 + raw_mags[:, 1]**2 +
                          raw_mags[:, 2]**2)
        axes1[1].plot(mag_times, B_total, c='b')
        axes1[1].plot(time_array, Bi, c='r', lw=0.75)
        axes1[1].set_ylabel('B')

        for ax in axes1:
            ax.set_xlim(time_start, time_end)

        # HOPE parameters (dens, temp, anis)
        fig2, axes2 = plt.subplots(3)

        for xx, clr in zip(range(3), ['r', 'g', 'b']):
            axes2[0].plot(itime, hope_dens[xx], c=clr, ls='-')
            axes2[0].plot(time_array, ihope_dens[xx], c=clr, ls='--')
            axes2[0].set_ylabel('$n_i (cc)$')

            axes2[1].plot(itime, hope_tpar[xx], c=clr, ls='-')
            axes2[1].plot(time_array, ihope_tpar[xx], c=clr, ls='--')
            axes2[1].set_ylabel('$T_{\perp, i} (keV)$')

            axes2[2].plot(itime, hope_anis[xx], c=clr, ls='-')
            axes2[2].plot(time_array, ihope_anis[xx], c=clr, ls='--')
            axes2[2].set_ylabel('$A_i$')

        for ax in axes2:
            ax.set_xlim(time_start, time_end)

        plt.show()

    # Subtract energetic components from total electron density (assuming each is singly charged)
    cold_dens = iedens - ihope_dens.sum(axis=0)

    # Original DTs just for reference
    den_dt = (den_times[1] - den_times[0]) / np.timedelta64(1, 's')
    mag_dt = (mag_times[1] - mag_times[0]) / np.timedelta64(1, 's')
    hope_dt = (itime[1] - itime[0]) / np.timedelta64(1, 's')
    new_dt = (time_array[1] - time_array[0]) / np.timedelta64(1, 's')
    print('Original sample periods:')
    print(f'Cold Plasma Density:   {den_dt} s')
    print(f'Magnetic field:        {mag_dt} s ')
    print(f'HOPE Particle data:    {hope_dt} s')
    print('')
    print(f'New sample period: {new_dt} s')
    return time_array, Bi * 1e-9, iedens * 1e6, cold_dens * 1e6, ihope_dens * 1e6, ihope_tpar, ihope_tperp, ihope_anis, iL
def load_and_interpolate_plasma_params(time_start,
                                       time_end,
                                       probe,
                                       pad,
                                       rbsp_path='G://DATA//RBSP//',
                                       cold_composition=np.array([70, 20,
                                                                  10])):
    # Cold (total?) electron plasma density
    den_times, edens, dens_err = rfr.retrieve_RBSP_electron_density_data(
        rbsp_path, time_start, time_end, probe, pad=pad)

    # Magnetic magnitude
    mag_times, B_mag = rfl.load_magnetic_field(rbsp_path,
                                               time_start,
                                               time_end,
                                               probe,
                                               return_raw=True)

    # HOPE data
    itime, etime, pdict, perr = rfr.retrieve_RBSP_hope_moment_data(rbsp_path,
                                                                   time_start,
                                                                   time_end,
                                                                   padding=pad,
                                                                   probe=probe)
    hope_dens = np.array(
        [pdict['Dens_p_30'], pdict['Dens_he_30'], pdict['Dens_o_30']])
    hope_temp = np.array(
        [pdict['Tperp_p_30'], pdict['Tperp_he_30'], pdict['Tperp_o_30']])
    hope_anis = np.array([
        pdict['Tperp_Tpar_p_30'], pdict['Tperp_Tpar_he_30'],
        pdict['Tperp_Tpar_o_30']
    ]) - 1

    # SPICE data
    spice_dens = []
    spice_temp = []
    spice_anis = []
    for product, spec in zip(['TOFxEH', 'TOFxEHe', 'TOFxEO'],
                             ['P', 'He', 'O']):
        spice_time, spice_dict = rfr.retrieve_RBSPICE_data(rbsp_path,
                                                           time_start,
                                                           time_end,
                                                           product,
                                                           padding=pad,
                                                           probe=probe)

        this_dens = spice_dict['F{}DU_Density'.format(spec)]
        this_anis = spice_dict['F{}DU_PerpPressure'.format(spec)] / spice_dict[
            'F{}DU_ParaPressure'.format(spec)] - 1

        # Perp Temperature - Calculate as T = P/nk
        kB = 1.381e-23
        q = 1.602e-19
        t_perp_kelvin = 1e-9 * spice_dict['F{}DU_PerpPressure'.format(
            spec)] / (kB * 1e6 * spice_dict['F{}DU_Density'.format(spec)])
        this_temp = kB * t_perp_kelvin / q  # Convert to eV

        spice_dens.append(this_dens)
        spice_temp.append(this_temp)
        spice_anis.append(this_anis)

    ihope_dens, ihope_temp, ihope_anis = interpolate_to_edens(
        den_times, itime, hope_dens, hope_temp, hope_anis)
    ispice_dens, ispice_temp, ispice_anis = interpolate_to_edens(
        den_times, spice_time, np.array(spice_dens), np.array(spice_temp),
        np.array(spice_anis))

    Bi = interpolate_B(den_times, mag_times, B_mag)

    # Subtract energetic components from total electron density (assuming each is singly charged)
    cold_dens = edens - ihope_dens.sum(axis=0) - ispice_dens.sum(axis=0)

    # Calculate cold ion composition. Assumes static percentage composition, but this could be changed.
    cold_comp = np.array([
        cold_composition[0] * cold_dens * 0.01,
        cold_composition[1] * cold_dens * 0.01,
        cold_composition[2] * cold_dens * 0.01
    ])

    param_dict = {}
    param_dict['times'] = den_times
    param_dict['field'] = Bi
    param_dict['ndensc'] = cold_comp
    param_dict['ndensw'] = ihope_dens
    param_dict['temp_perp'] = ihope_temp
    param_dict['A'] = ihope_anis
    param_dict['ndensw2'] = ispice_dens
    param_dict['temp_perp2'] = ispice_temp
    param_dict['A2'] = ispice_anis
    return param_dict
Esempio n. 5
0
def load_and_interpolate_plasma_params(time_start,
                                       time_end,
                                       probe,
                                       pad,
                                       nsec=None,
                                       rbsp_path='G://DATA//RBSP//',
                                       HM_filter_mhz=None):
    '''
    Outputs as SI units: B0 in T, densities in /m3, temperatures in eV (pseudo SI)
    
    nsec is cadence of interpolated array in seconds. If None, defaults to using den_times
    as interpolant.
    
    If HOPE or RBSPICE data does not exist, file retrieval returns NoneType - have to deal 
    with that.
    '''
    print('Loading and interpolating satellite data')

    # Cold (total?) electron plasma density
    den_times, edens, dens_err = rfr.retrieve_RBSP_electron_density_data(
        rbsp_path, time_start, time_end, probe, pad=pad)

    # Magnetic magnitude
    mag_times, raw_mags = rfl.load_magnetic_field(rbsp_path,
                                                  time_start,
                                                  time_end,
                                                  probe,
                                                  return_raw=True,
                                                  pad=3600)

    # Filter out EMIC waves (background plus HM)
    if HM_filter_mhz is not None:
        filt_mags = np.zeros(raw_mags.shape)
        for ii in range(3):
            filt_mags[:, ii] = ascr.clw_low_pass(raw_mags[:, ii],
                                                 HM_filter_mhz,
                                                 1. / 64.,
                                                 filt_order=4)
    else:
        filt_mags = raw_mags

    # HOPE data
    itime, etime, pdict, perr = rfr.retrieve_RBSP_hope_moment_data(rbsp_path,
                                                                   time_start,
                                                                   time_end,
                                                                   padding=pad,
                                                                   probe=probe)
    hope_dens = np.array(
        [pdict['Dens_p_30'], pdict['Dens_he_30'], pdict['Dens_o_30']])
    hope_temp = np.array(
        [pdict['Tperp_p_30'], pdict['Tperp_he_30'], pdict['Tperp_o_30']])
    hope_anis = np.array([
        pdict['Tperp_Tpar_p_30'], pdict['Tperp_Tpar_he_30'],
        pdict['Tperp_Tpar_o_30']
    ]) - 1

    # SPICE data
    spice_dens = []
    spice_temp = []
    spice_anis = []
    spice_times = []
    for product, spec in zip(['TOFxEH', 'TOFxEHe', 'TOFxEO'],
                             ['P', 'He', 'O']):
        spice_epoch, spice_dict = rfr.retrieve_RBSPICE_data(rbsp_path,
                                                            time_start,
                                                            time_end,
                                                            product,
                                                            padding=pad,
                                                            probe=probe)

        # Collect all times (don't assume every file is good)
        spice_times.append(spice_epoch)

        if spice_dict is not None:
            this_dens = spice_dict['F{}DU_Density'.format(spec)]
            this_anis = spice_dict['F{}DU_PerpPressure'.format(
                spec)] / spice_dict['F{}DU_ParaPressure'.format(spec)] - 1

            # Perp Temperature - Calculate as T = P/nk
            kB = 1.381e-23
            q = 1.602e-19
            t_perp_kelvin = 1e-9 * spice_dict['F{}DU_PerpPressure'.format(
                spec)] / (kB * 1e6 * spice_dict['F{}DU_Density'.format(spec)])
            this_temp = kB * t_perp_kelvin / q  # Convert from K to eV

            spice_dens.append(this_dens)
            spice_temp.append(this_temp)
            spice_anis.append(this_anis)
        else:
            spice_dens.append(None)
            spice_temp.append(None)
            spice_anis.append(None)

    # Interpolation step
    if nsec is None:
        time_array = den_times.copy()
        iedens = edens.copy()
    else:
        time_array = np.arange(time_start,
                               time_end,
                               np.timedelta64(nsec, 's'),
                               dtype='datetime64[us]')
        iedens = interpolate_ne(time_array, den_times, edens)

    ihope_dens, ihope_temp, ihope_anis = HOPE_interpolate_to_time(
        time_array, itime, hope_dens, hope_temp, hope_anis)

    ispice_dens, ispice_temp, ispice_anis = SPICE_interpolate_to_time(
        time_array, spice_times, np.array(spice_dens), np.array(spice_temp),
        np.array(spice_anis))

    Bi = interpolate_B(time_array, mag_times, filt_mags, nsec, LP_filter=False)

    # Subtract energetic components from total electron density (assuming each is singly charged)
    cold_dens = iedens - ihope_dens.sum(axis=0) - ispice_dens.sum(axis=0)
    return time_array, Bi * 1e-9, cold_dens * 1e6, ihope_dens * 1e6, ihope_temp, ihope_anis, ispice_dens * 1e6, ispice_temp, ispice_anis
Esempio n. 6
0
    _time_end = np.datetime64('2013-07-25T22:00:00')
    _probe = 'a'
    _pad = 0

    convert_data_to_hybrid_plasmafile(_time_start, _time_end, _probe, _pad)

    if False:
        _times, _B0, _cold_dens, _hope_dens, _hope_temp, _hope_anis, _spice_dens, _spice_temp, _spice_anis =\
            load_and_interpolate_plasma_params(_time_start, _time_end, _probe, _pad, HM_filter_mhz=50, nsec=None)

        ### LOAD RAW VALUES ###
        den_times, edens, dens_err = rfr.retrieve_RBSP_electron_density_data(
            _rbsp_path, _time_start, _time_end, _probe, pad=_pad)
        mag_times, raw_mags = rfl.load_magnetic_field(_rbsp_path,
                                                      _time_start,
                                                      _time_end,
                                                      _probe,
                                                      return_raw=True,
                                                      pad=3600)

        itime, etime, pdict, perr = rfr.retrieve_RBSP_hope_moment_data(
            _rbsp_path, _time_start, _time_end, padding=_pad, probe=_probe)
        hope_dens = np.array(
            [pdict['Dens_p_30'], pdict['Dens_he_30'], pdict['Dens_o_30']])
        hope_temp = np.array(
            [pdict['Tperp_p_30'], pdict['Tperp_he_30'], pdict['Tperp_o_30']])
        hope_anis = np.array([
            pdict['Tperp_Tpar_p_30'], pdict['Tperp_Tpar_he_30'],
            pdict['Tperp_Tpar_o_30']
        ]) - 1

        spice_dens = []