예제 #1
0
            # Cold plasma params, SI units
            B0      = mag[ii]
            name    = np.array(['H'   , 'He'   , 'O'        ])
            mass    = np.array([1.0   , 4.0    , 16.0       ]) * PMASS
            charge  = np.array([1.0   , 1.0    , 1.0        ]) * PCHARGE
            density = np.array([h_frac, he_frac, o_frac[ii] ]) * edens[ii] 
            ani     = np.array([0.0   , 0.0    , 0.0        ])
            tpar    = np.array([0.0   , 0.0    , 0.0        ])
            tper    = (ani + 1) * tpar

            Species, PP = create_species_array(B0, name, mass, charge, density, tper, ani)
            
            # Velocities and Energies
            k_vals = nls.get_k_cold(w_vals, Species)
            all_VG[ii], all_VP[ii], all_VR[ii] = nls.get_velocities(w_vals, Species, PP)
            all_LR[ii], all_CR[ii] = nls.get_energies(w_vals, k_vals, PP['pcyc_rad'], PMASS)
            
            fidx = np.where(abs(f_vals - max_freqs[ii]) == np.min(abs(f_vals - max_freqs[ii])))[0][0] 
            freq = f_vals[fidx]
        
            # Get values at the frequency of max power
            line_LR[ii] = all_LR[ii, fidx]
            line_CR[ii] = all_CR[ii, fidx]
            
            line_VP[ii] = all_VP[ii, fidx]
            line_VG[ii] = all_VG[ii, fidx]
            line_VR[ii] = all_VR[ii, fidx]

        # Line plots for each he_frac
        axes[1, 0].plot(time, line_CR*1e-3, c=clr, lw=0.75, label=f'{he_frac*100.:.0f}% $He^+$')
        axes[2, 0].plot(time, line_VG*1e-3, c=clr, lw=0.75)
예제 #2
0
def plot_velocities_and_energies_single(time_start, time_end, probe='a'):
    # Import cutoff-derived composition information
    cutoff_dict = epd.read_cutoff_file(cutoff_filename)
        
    # Load particle and field information
    time, mag, edens = load_CRRES_data(time_start, time_end, nsec=None,
                                        crres_path='E://DATA//CRRES//')

    mag_time, pc1_mags, HM_mags, imf_time, IA, IF, IP, stime, sfreq, spower = \
            load_EMIC_IMFs_and_dynspec(time_start, time_end)
    spower = spower.sum(axis=0)

    cutoff  = np.interp(time.astype(np.int64),
                        cutoff_dict['CUTOFF_TIME'].astype(np.int64),
                        cutoff_dict['CUTOFF_NORM'])
    o_fracs = epd.calculate_o_from_he_and_cutoff(cutoff, he_frac)        
    
    # Get velocity/energy data for time
    plt.ioff()
    for ii in range(time.shape[0]):
        
        # Define time, time index
        this_time   = time[ii]
        maxpwr_tidx = np.where(abs(stime - this_time) == np.min(abs(stime - this_time)))[0][0]
        
        # Find max freq and index
        fst, fen     = ascr.boundary_idx64(sfreq, _band_start, _band_end)
        maxpwr_fidx  = spower[maxpwr_tidx, fst:fen].argmax()
        maxpwr_fidx += fst
        maxpwr_freq  = sfreq[maxpwr_fidx]
        
        #date_string = this_time.astype(object).strftime('%Y%m%d')
        save_string = this_time.astype(object).strftime('%Y%m%d_%H%M%S')
    
        #clr = mapper.to_rgba(time[ii].astype(np.int64))
        print('Doing time:', this_time)
        
        fig, axes = plt.subplots(nrows=4, ncols=2, figsize=(8.0, 0.5*11.00),
                                 gridspec_kw={'width_ratios':[1, 0.01],
                                              'height_ratios':[1, 2, 2, 2]
                                              })
        
        # Spectra/IP
        im0 = axes[0, 0].pcolormesh(stime, sfreq, spower.T, cmap='jet',
                             norm=colors.LogNorm(vmin=1e-4, vmax=1e1))
        axes[0, 0].set_ylim(0, _band_end)
        axes[0, 0].set_ylabel('$f$ [Hz]', rotation=90)
        fig.colorbar(im0, cax=axes[0, 1], extend='both').set_label(
                    r'$\frac{nT^2}{Hz}$', fontsize=16, rotation=0, labelpad=15)
        
        axes[0, 0].axvline(this_time, color='white', ls='-' , alpha=0.7)
        axes[0, 0].set_xlim(time_start, time_end)
        axes[0, 0].set_xticklabels([])
        
        axes[0, 0].axvline(this_time,   color='white', ls='-', alpha=0.75)
        axes[0, 0].axhline(maxpwr_freq, color='white', ls='-', alpha=0.75)
        axes[0, 0].set_title(f'Velocities and Energies :: {this_time}')

        h_frac = 1. - he_frac - o_fracs[ii]
        
        # Cold plasma params, SI units
        B0      = mag[ii]
        name    = np.array(['H'   , 'He'   , 'O'    ])
        mass    = np.array([1.0   , 4.0    , 16.0   ]) * PMASS
        charge  = np.array([1.0   , 1.0    , 1.0    ]) * PCHARGE
        density = np.array([h_frac, he_frac, o_fracs[ii] ]) * edens[ii]
        ani     = np.array([0.0   , 0.0    , 0.0    ])
        tpar    = np.array([0.0   , 0.0    , 0.0    ])
        tper    = (ani + 1) * tpar
        Species, PP = create_species_array(B0, name, mass, charge, density, tper, ani)
        
        # Frequencies to evaluate, calculate wavenumber (cold approximation)
        f_min  = _band_start
        f_max  = _band_end
        Nf     = 10000
        f_vals = np.linspace(f_min, f_max, Nf)
        w_vals = 2*np.pi*f_vals
        k_vals = nls.get_k_cold(w_vals, Species)
        wv_len = 1e-3 * 2*np.pi / k_vals
        
        fidx = np.where(abs(f_vals - maxpwr_freq) == np.min(abs(f_vals - maxpwr_freq)))[0][0] 
        freq = f_vals[fidx]
        
        axes[1, 0].plot(f_vals, wv_len, c='k')
        axes[1, 0].set_ylabel('$\lambda_{EMIC}$ [km]')
        axes[1, 0].set_ylim(0, 2000)
        
        # Velocities
        Vg, Vp, Vr = nls.get_velocities(w_vals, Species, PP)
    
        axes[2, 0].semilogy(f_vals, Vg*1e-3, c='k', label='$V_g$') 
        axes[2, 0].semilogy(f_vals, Vp*1e-3, c='r', label='$V_p$')
        axes[2, 0].semilogy(f_vals,-Vr*1e-3, c='b', label='$-V_R$')
        axes[2, 0].set_ylim(10, 4500)
        axes[2, 0].set_ylabel('Velocities [km/s]')
        axes[2, 0].legend(bbox_to_anchor=(1.0, 0), loc=3, borderaxespad=0.)
        
        # Energies
        ELAND, ECYCL = nls.get_energies(w_vals, k_vals, PP['pcyc_rad'], PMASS)
        axes[3, 0].semilogy(f_vals, ELAND*1e-3, c='r', label='$E_0$')
        axes[3, 0].semilogy(f_vals, ECYCL*1e-3, c='b', label='$E_1$')
        axes[3, 0].set_ylim(1e-1, 1e3)
        axes[3, 0].set_ylabel('$E_R$ [keV]')
        axes[3, 0].set_xlabel('Freq [Hz]', rotation=0)
        axes[3, 0].legend(bbox_to_anchor=(1.0, 0), loc=3, borderaxespad=0.)
        
        # Work out what the energy is at maxpwr_freq
        num_landau    = ELAND[fidx]*1e-3
        num_cyclotron = ECYCL[fidx]*1e-3
        
        axes[3, 0].text(0.8, 0.9, f'$E_0(f) =$ {num_landau:.1f} keV', horizontalalignment='left',
                        verticalalignment='center', transform=axes[3, 0].transAxes)
        axes[3, 0].text(0.8, 0.8, f'$E_1(f) =$ {num_cyclotron:.1f} keV', horizontalalignment='left',
                        verticalalignment='center', transform=axes[3, 0].transAxes)
        
        axes[0, 0].set_xticklabels([])
        axes[1, 0].set_yticks(np.array([0, 500, 1000, 1500]))
        for ax in axes[1:, 0]:
            ax.set_xlim(_band_start, _band_end)
            ax.axvline(freq, color='k', alpha=0.5, ls='--')
            if ax != axes[-1, 0]:
                ax.set_xticklabels([])
        
        axes[1, 1].set_visible(False)
        axes[2, 1].set_visible(False)
        axes[3, 1].set_visible(False)
        
        #fig.tight_layout(rect=[0, 0, 0.95, 1])
        fig.tight_layout()
        fig.subplots_adjust(wspace=0.05, hspace=0)
        fig.align_ylabels()
        
        if save_plot == True:
            print('Saving plot...')
            fig.savefig(_plot_path + 'VELENG_FROMDATA_' + save_string + '.png', dpi=dpi)
            plt.close('all')
        else:
            plt.show()
    return
def plot_HM_and_energy(time_start, time_end, probe):
    '''
    For a specific frequency, calculate what the first order cyclotron resonance
    energy is and plot this as a timeseries. Secondary plots for the Pc1 spectra
    and HM/|B| spectra
    
    Do for all frequencies and select specific frequency at end (or option to
    show as a pcolormesh)
    '''
    # Import cutoff-derived composition information
    cutoff_filename = 'D://Google Drive//Uni//PhD 2017//Josh PhD Share Folder//Thesis//Data_Plots//20130725_RBSP-A//pearl_times.txt'
    cutoff_dict = epd.read_cutoff_file(cutoff_filename)

    time, mag, edens, cold_dens, hope_dens, hope_tpar, hope_tperp, hope_anis, L_vals =\
                                       load_and_interpolate_plasma_params(
                                       time_start, time_end, probe, nsec=None,
                                       rbsp_path='E://DATA//RBSP//', HM_filter_mhz=50.0,
                                       time_array=None, check_interp=False)

    mag_time, pc1_mags, HM_mags, imf_time, IA, IF, IP, stime, sfreq, spower = \
            load_EMIC_IMFs_and_dynspec(time_start, time_end)

    # Frequencies to evaluate, calculate wavenumber (cold approximation)
    f_min = _band_start
    f_max = _band_end
    Nf = 10000
    f_vals = np.linspace(f_min, f_max, Nf)
    w_vals = 2 * np.pi * f_vals

    all_CR = np.zeros((time.shape[0], Nf), dtype=np.float64)
    all_LR = np.zeros((time.shape[0], Nf), dtype=np.float64)
    all_VP = np.zeros((time.shape[0], Nf), dtype=np.float64)
    all_VG = np.zeros((time.shape[0], Nf), dtype=np.float64)
    all_VR = np.zeros((time.shape[0], Nf), dtype=np.float64)

    # Collect info for each time
    for ii in range(time.shape[0]):
        this_time = time[ii]
        print('Doing time:', this_time)

        # Get oxygen concentration from cutoffs
        cutoff = np.interp(this_time.astype(np.int64),
                           cutoff_dict['CUTOFF_TIME'].astype(np.int64),
                           cutoff_dict['CUTOFF_NORM'])
        o_frac = epd.calculate_o_from_he_and_cutoff(cutoff, he_frac)
        h_frac = 1. - he_frac - o_frac

        # Cold plasma params, SI units
        B0 = mag[ii]
        name = np.array(['H', 'He', 'O'])
        mass = np.array([1.0, 4.0, 16.0]) * PMASS
        charge = np.array([1.0, 1.0, 1.0]) * PCHARGE
        density = np.array([h_frac, he_frac, o_frac]) * edens[ii]
        ani = np.array([0.0, 0.0, 0.0])
        tpar = np.array([0.0, 0.0, 0.0])
        tper = (ani + 1) * tpar
        Species, PP = create_species_array(B0, name, mass, charge, density,
                                           tper, ani)

        # Velocities and Energies
        k_vals = nls.get_k_cold(w_vals, Species)
        all_VG[ii], all_VP[ii], all_VR[ii] = nls.get_velocities(
            w_vals, Species, PP)
        all_LR[ii], all_CR[ii] = nls.get_energies(w_vals, k_vals,
                                                  PP['pcyc_rad'], PMASS)

    fig, axes = plt.subplots(nrows=5,
                             ncols=2,
                             figsize=(8.0, 1.0 * 11.00),
                             gridspec_kw={'width_ratios': [1, 0.01]})

    # To plot: Spectra, velocities (Vg, Vr) and energies (cyclotron, landau resonances)
    # HM/|B| overlay
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        axes[0, 0].set_title(f'Velocities and Energies :: {this_time}')

        # Spectra
        im0 = axes[0, 0].pcolormesh(stime,
                                    sfreq,
                                    spower.sum(axis=0).T,
                                    cmap='jet',
                                    norm=colors.LogNorm(vmin=1e-4, vmax=1e1))
        axes[0, 0].set_ylim(0, fmax)
        axes[0, 0].set_ylabel('$f$ [Hz]', rotation=90)
        fig.colorbar(im0, cax=axes[0, 1],
                     extend='both').set_label(r'$\frac{nT^2}{Hz}$',
                                              fontsize=14,
                                              rotation=0,
                                              labelpad=15)

        # E_RES_CYCLOTRON
        im1 = axes[1, 0].pcolormesh(time,
                                    f_vals,
                                    all_CR.T * 1e-3,
                                    cmap='jet',
                                    norm=colors.Normalize())
        axes[1, 0].set_ylabel('$f$ [Hz]', rotation=90)
        fig.colorbar(im1, cax=axes[1, 1],
                     extend='both').set_label('$E_R$ Cyclotron\n[keV]',
                                              fontsize=14,
                                              rotation=0,
                                              labelpad=15)

        # E_RES_LANDAU
        im2 = axes[2, 0].pcolormesh(time,
                                    f_vals,
                                    all_LR.T * 1e-3,
                                    cmap='jet',
                                    norm=colors.Normalize())
        axes[2, 0].set_ylabel('$f$ [Hz]', rotation=90)
        fig.colorbar(im2, cax=axes[2, 1],
                     extend='both').set_label('$E_R$ Landau\n[keV]',
                                              fontsize=14,
                                              rotation=0,
                                              labelpad=15)

        # VR
        im3 = axes[3, 0].pcolormesh(time,
                                    f_vals,
                                    all_VR.T * 1e-3,
                                    cmap='jet',
                                    norm=colors.Normalize())
        axes[3, 0].set_ylabel('$f$ [Hz]', rotation=90)
        fig.colorbar(im3, cax=axes[3, 1],
                     extend='both').set_label('$V_R$\n[$km/s$]',
                                              fontsize=14,
                                              rotation=0,
                                              labelpad=15)

        # VG
        im4 = axes[4, 0].pcolormesh(time,
                                    f_vals,
                                    all_VG.T * 1e-3,
                                    cmap='jet',
                                    norm=colors.Normalize())
        axes[4, 0].set_ylabel('$f$ [Hz]', rotation=90)
        fig.colorbar(im4, cax=axes[4, 1],
                     extend='both').set_label('$V_G$\n[$km/s$]',
                                              fontsize=14,
                                              rotation=0,
                                              labelpad=15)

        for ax in axes[:, 0]:
            ax.set_xlim(time_start, time_end)
            ax.set_ylim(_band_start, _band_end)

            ax2 = ax.twinx()
            ax2.plot(mag_time, HM_mags[:, 2], c='k', lw=0.75)

    fig.tight_layout()
    fig.subplots_adjust(wspace=0.05, hspace=0)
    fig.align_ylabels()

    if save_plot == True:
        save_string = time_start.astype(object).strftime('%Y%m%d_%H%M')

        print('Saving plot...')
        fig.savefig(_plot_path + 'VELENG_FROMDATA_PCOLOR_' + save_string +
                    '.png')
        plt.close('all')
    else:
        plt.show()
    return