Esempio n. 1
0
def calc_vsingle(run_dir, mime):
    """Calculate single fluid velocity
    """
    fname = run_dir + 'data/ne.gda'
    ne = np.fromfile(fname, dtype=np.float32)
    fname = run_dir + 'data/ni.gda'
    ni = np.fromfile(fname, dtype=np.float32)
    inrho = 1.0 / (ne + ni * mime)

    fdir = run_dir + 'data1/'
    mkdir_p(fdir)

    fname = run_dir + 'data/vex.gda'
    ve = np.fromfile(fname, dtype=np.float32)
    fname = run_dir + 'data/vix.gda'
    vi = np.fromfile(fname, dtype=np.float32)
    vs = (ve * ne + vi * ni * mime) * inrho
    vs.tofile(fdir + 'vx.gda')

    fname = run_dir + 'data/vey.gda'
    ve = np.fromfile(fname, dtype=np.float32)
    fname = run_dir + 'data/viy.gda'
    vi = np.fromfile(fname, dtype=np.float32)
    vs = (ve * ne + vi * ni * mime) * inrho
    vs.tofile(fdir + 'vy.gda')

    fname = run_dir + 'data/vez.gda'
    ve = np.fromfile(fname, dtype=np.float32)
    fname = run_dir + 'data/viz.gda'
    vi = np.fromfile(fname, dtype=np.float32)
    vs = (ve * ne + vi * ni * mime) * inrho
    vs.tofile(fdir + 'vz.gda')
def calc_force_charge_efield_single(job_id, drange):
    print job_id
    ct = job_id
    data_dir = '../data/force/'
    mkdir_p(data_dir)
    force_single = np.zeros(3)
    kwargs = {"current_time": ct, "xl": 0, "xr": 200, "zb": -50, "zt": 50}
    fname1 = root_dir + 'data/ne.gda'
    x, z, ne_all = read_2d_fields(pic_info, fname1, **kwargs)
    fname2 = root_dir + 'data/ni.gda'
    x, z, ni_all = read_2d_fields(pic_info, fname2, **kwargs)
    fname = root_dir + 'data/ex.gda'
    x, z, ex_all = read_2d_fields(pic_info, fname, **kwargs)
    fname = root_dir + 'data/ey.gda'
    x, z, ey_all = read_2d_fields(pic_info, fname, **kwargs)
    fname = root_dir + 'data/ez.gda'
    x, z, ez_all = read_2d_fields(pic_info, fname, **kwargs)
    nx, = x.shape
    nz, = z.shape
    xs = int(drange[0] * nx)
    xe = int(drange[1] * nx)
    zs = int(drange[2] * nz)
    ze = int(drange[3] * nz)
    ne = ne_all[zs:ze, xs:xe]
    ni = ni_all[zs:ze, xs:xe]
    ex = ex_all[zs:ze, xs:xe]
    ey = ey_all[zs:ze, xs:xe]
    ez = ez_all[zs:ze, xs:xe]
    ntot = ni - ne
    force_single[0] = np.sum(ntot * ex)
    force_single[1] = np.sum(ntot * ey)
    force_single[2] = np.sum(ntot * ez)
    fname = data_dir + 'force_' + str(ct) + '.dat'
    force_single.tofile(fname)
def calc_force_charge_efield_single(job_id, drange):
    print job_id
    ct = job_id
    data_dir = '../data/force/'
    mkdir_p(data_dir)
    force_single = np.zeros(3)
    kwargs = {"current_time": ct, "xl": 0, "xr": 200, "zb": -50, "zt": 50}
    fname1 = root_dir + 'data/ne.gda'
    x, z, ne_all = read_2d_fields(pic_info, fname1, **kwargs)
    fname2 = root_dir + 'data/ni.gda'
    x, z, ni_all = read_2d_fields(pic_info, fname2, **kwargs)
    fname = root_dir + 'data/ex.gda'
    x, z, ex_all = read_2d_fields(pic_info, fname, **kwargs)
    fname = root_dir + 'data/ey.gda'
    x, z, ey_all = read_2d_fields(pic_info, fname, **kwargs)
    fname = root_dir + 'data/ez.gda'
    x, z, ez_all = read_2d_fields(pic_info, fname, **kwargs)
    nx, = x.shape
    nz, = z.shape
    xs = int(drange[0] * nx)
    xe = int(drange[1] * nx)
    zs = int(drange[2] * nz)
    ze = int(drange[3] * nz)
    ne = ne_all[zs:ze, xs:xe]
    ni = ni_all[zs:ze, xs:xe]
    ex = ex_all[zs:ze, xs:xe]
    ey = ey_all[zs:ze, xs:xe]
    ez = ez_all[zs:ze, xs:xe]
    ntot = ni - ne
    force_single[0] = np.sum(ntot * ex)
    force_single[1] = np.sum(ntot * ey)
    force_single[2] = np.sum(ntot * ez)
    fname = data_dir + 'force_' + str(ct) + '.dat'
    force_single.tofile(fname)
def energy_spectrum_multi(bg, spect_info, species='e'):
    """Plot energy spectra for runs with different guide field
    """
    if species == 'h':
        species = 'H'
    bg_str = str(int(bg * 10)).zfill(2)
    mimes = np.asarray([25, 100, 400])
    tmaxs = np.asarray([114, 114, 102])
    fig = plt.figure(figsize=[7, 5])
    ax = fig.add_axes([0.15, 0.15, 0.8, 0.8])
    COLORS = palettable.tableau.Tableau_10.mpl_colors
    ax.set_prop_cycle('color', COLORS)
    for mime, tmax in zip(mimes, tmaxs):
        run_name = "mime" + str(mime) + "_beta002_bg" + bg_str
        picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
        pic_info = read_data_from_json(picinfo_fname)
        if species == 'e':
            vth = pic_info.vthe
        else:
            vth = pic_info.vthi
        gama = 1.0 / math.sqrt(1.0 - 3 * vth**2)
        eth = gama - 1.0

        fdir = '../data/spectra/' + run_name + '/'
        fname = fdir + 'spectrum-' + species.lower() + '.' + str(tmax)
        flog = np.fromfile(fname)

        emin_log = math.log10(spect_info["emin"])
        emax_log = math.log10(spect_info["emax"])
        elog = 10**(np.linspace(emin_log, emax_log, spect_info["nbins"]))
        flog *= np.gradient(elog)
        elog /= eth
        flog /= np.gradient(elog)
        nptot = pic_info.nx * pic_info.ny * pic_info.nz * pic_info.nppc

        flog /= nptot
        ltext = r"$m_i/m_e=" + str(mime) + "$"
        ax.loglog(elog, flog, linewidth=3, label=ltext)

    ax.legend(loc=3, prop={'size': 16}, ncol=1,
              shadow=False, fancybox=False, frameon=False)
    if species == 'e':
        ax.set_xlim([3E-1, 5E2])
    else:
        ax.set_xlim([3E-1, 1E3])
    ax.set_ylim([1E-11, 1E0])
    ax.set_yticks(np.logspace(-10, 0, num=6))
    ax.set_xlabel(r'$\varepsilon/\varepsilon_\text{th}$',
                  fontdict=FONT, fontsize=20)
    ax.set_ylabel(r'$f(\varepsilon)$', fontdict=FONT, fontsize=20)
    ax.tick_params(labelsize=16)
    fpath = "../img/img_high_mime/spectra/"
    mkdir_p(fpath)
    fname = fpath + "spect_bg" + bg_str + "_" + species + ".pdf"
    fig.savefig(fname)
    plt.show()
Esempio n. 5
0
def transfer_to_csv(plot_config):
    """Transfer current HDF5 file to CSV

    Each CSV file contains one trajectory

    """
    run_dir = plot_config["run_dir"]
    tindex = plot_config["tframe"] * plot_config["tinterval"]
    ptl_vel = plot_config["ptl_vel"]
    fname = (run_dir + 'data_' + str(tindex) + '_' + str(ptl_vel) +
             'c/particle_diagnostics.h5')
    file = h5py.File(fname, 'r')
    group = file['/particles_fields']
    dset_ptl = group['particles']
    dset_emf = group['fields']
    sz, = dset_ptl.shape
    tinterval_traj = get_traj_tinterval(run_dir)
    nsteps_tot = get_num_steps(run_dir)
    if nsteps_tot > 1E6:
        nsteps_tot = int(1E6)
    ntraj = nsteps_tot // tinterval_traj + 1
    nptl = sz / ntraj
    fdir = run_dir + 'data_' + str(tindex) + '_' + str(ptl_vel) + 'c/'
    fdir += 'traj_csv/'
    mkdir_p(fdir)
    pdata = np.zeros([14, ntraj])
    # for iptl in range(nptl):
    for iptl in range(2):
        print(iptl)
        ps, pt = ntraj * iptl, ntraj * (iptl + 1)
        pdata[0] = np.array(dset_ptl['x'][ps:pt])
        pdata[1] = np.array(dset_ptl['y'][ps:pt])
        pdata[2] = np.array(dset_ptl['z'][ps:pt])
        pdata[3] = np.array(dset_ptl['ux'][ps:pt])
        pdata[4] = np.array(dset_ptl['uy'][ps:pt])
        pdata[5] = np.array(dset_ptl['uz'][ps:pt])
        pdata[6] = np.sqrt(1.0 + np.sum(pdata[3:6]**2, axis=0))
        pdata[7] = np.array(dset_ptl['t'][ps:pt])
        pdata[8] = np.array(dset_emf['Ex'][ps:pt])
        pdata[9] = np.array(dset_emf['Ey'][ps:pt])
        pdata[10] = np.array(dset_emf['Ez'][ps:pt])
        pdata[11] = np.array(dset_emf['Bx'][ps:pt])
        pdata[12] = np.array(dset_emf['By'][ps:pt])
        pdata[13] = np.array(dset_emf['Bz'][ps:pt])
        fname = fdir + 'traj_' + str(iptl) + '.csv'
        # np.savetxt(fname, pdata.T, delimiter=",",
        #            header="x,y,z,ux,uy,uz,gamma,t,Ex,Ey,Ez,Bx,By,Bz")
        df = pd.DataFrame(pdata.T)
        df.to_csv(fname,
                  mode='w',
                  index=True,
                  header=[
                      "x", "y", "z", "ux", "uy", "uz", "gamma", "t", "Ex",
                      "Ey", "Ez", "Bx", "By", "Bz"
                  ])
def plot_beta_dist(plot_config, show_plot=True):
    """
    Plot plasma beta distribution
    """
    pic_run = plot_config["pic_run"]
    pic_run_dir = plot_config["pic_run_dir"]
    species = plot_config["species"]
    tframe = plot_config["tframe"]
    picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    tinit = pic_info.vthe**2
    beta_init = tinit * 2 / pic_info.b0**2

    fdir = '../data/temperature_anisotropy/' + pic_run + '/'
    fname = fdir + 'fbpara_' + species + '_' + str(tframe) + '.gda'
    fdata = np.fromfile(fname, dtype=np.float32)
    nbins_beta = int(fdata[0])
    beta_bins_edge = fdata[1:nbins_beta+2]
    beta_bins_mid = 0.5 * (beta_bins_edge[1:] + beta_bins_edge[:-1])
    beta_bins_mid /= beta_init
    dtemp = np.diff(beta_bins_edge)
    fbpara = fdata[nbins_beta+2:] / dtemp

    fname = fdir + 'fbperp_' + species + '_' + str(tframe) + '.gda'
    fdata = np.fromfile(fname, dtype=np.float32)
    fbperp = fdata[nbins_beta+2:] / dtemp

    fig = plt.figure(figsize=[3.25, 2.5])
    rect = [0.16, 0.16, 0.79, 0.8]
    ax = fig.add_axes(rect)
    ax.set_prop_cycle('color', COLORS)
    ax.tick_params(bottom=True, top=True, left=True, right=True)
    ax.tick_params(axis='x', which='minor', direction='in', bottom=True, top=True)
    ax.tick_params(axis='x', which='major', direction='in', bottom=True, top=True)
    ax.tick_params(axis='y', which='minor', direction='in')
    ax.tick_params(axis='y', which='major', direction='in')

    ax.loglog(beta_bins_mid, fbpara, linewidth=1, label=r'$\beta_\parallel$')
    ax.loglog(beta_bins_mid, fbperp, linewidth=1, label=r'$\beta_\perp$')
    ax.legend(loc=1, prop={'size': 10}, ncol=1,
              shadow=False, fancybox=False, frameon=False)
    ax.set_xlim([1E-1, 1E5])
    ax.tick_params(labelsize=8)
    ax.set_xlabel(r'$\beta/\beta_0$', fontsize=10)
    ax.set_ylabel(r'$f(\beta)$', fontsize=10)
    fdir = '../img/beta_dist/' + pic_run + '/'
    mkdir_p(fdir)
    fname = fdir + 'beta_dist_' + species + '_' + str(tframe) + '.pdf'
    fig.savefig(fname)

    if show_plot:
        plt.show()
    else:
        plt.close()
Esempio n. 7
0
def plot_tratio_dist(plot_config, show_plot=True):
    """
    Plot the distribution of the ratio between Tperp and Tpara
    """
    pic_run = plot_config["pic_run"]
    pic_run_dir = plot_config["pic_run_dir"]
    species = plot_config["species"]
    tframe = plot_config["tframe"]
    picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json'
    pic_info = read_data_from_json(picinfo_fname)

    fdir = '../data/temperature_anisotropy/' + pic_run + '/'
    fname = fdir + 'ftratio_' + species + '_' + str(tframe) + '.gda'
    fdata = np.fromfile(fname, dtype=np.float32)
    nbins_tratio = int(fdata[0])
    tratio_bins_edge = fdata[1:nbins_tratio + 2]
    tratio_bins_mid = 0.5 * (tratio_bins_edge[1:] + tratio_bins_edge[:-1])
    dtemp = np.diff(tratio_bins_edge)
    ftratio = fdata[nbins_tratio + 2:] / dtemp

    fig = plt.figure(figsize=[3.25, 2.5])
    rect = [0.16, 0.16, 0.79, 0.8]
    ax = fig.add_axes(rect)
    ax.set_prop_cycle('color', COLORS)
    ax.tick_params(bottom=True, top=True, left=True, right=True)
    ax.tick_params(axis='x',
                   which='minor',
                   direction='in',
                   bottom=True,
                   top=True)
    ax.tick_params(axis='x',
                   which='major',
                   direction='in',
                   bottom=True,
                   top=True)
    ax.tick_params(axis='y', which='minor', direction='in')
    ax.tick_params(axis='y', which='major', direction='in')

    ax.loglog(tratio_bins_mid, ftratio, linewidth=1)
    ax.set_xlim([5E-2, 2E1])
    ax.tick_params(labelsize=8)
    ax.set_xlabel(r'$T_\perp/T_\parallel$', fontsize=10)
    ax.set_ylabel(r'$f(T_\perp/T_\parallel)$', fontsize=10)
    fdir = '../img/tratio_dist/' + pic_run + '/'
    mkdir_p(fdir)
    fname = fdir + 'tratio_dist_' + species + '_' + str(tframe) + '.pdf'
    fig.savefig(fname)

    if show_plot:
        plt.show()
    else:
        plt.close()
Esempio n. 8
0
def plot_dxx(plot_config):
    """
    """
    run_dir = plot_config["run_dir"]
    run_name = plot_config["run_name"]
    tindex = plot_config["tframe"] * plot_config["tinterval"]
    ptl_vel = plot_config["ptl_vel"]
    vels = np.linspace(0.3, 0.9, 7)
    vels = np.append(vels, 0.95)
    vels = vels[::-1]
    gammas = 1.0 / np.sqrt(1 - vels**2)
    moms = vels * gammas
    vthe = 0.1 * math.sqrt(2)
    gamma0 = 1.0 / math.sqrt(1 - vthe**2)
    p0 = gamma0 * vthe
    moms /= p0
    tframes = np.linspace(10, 20, 11, dtype=int)
    tindices = tframes * plot_config["tinterval"]

    fdir = '../data/' + run_name + '/'
    fname = fdir + 'dxxs.dat'
    dxxs = np.fromfile(fname)
    dxxs = dxxs.reshape((len(tframes), len(vels)))

    dxx_mean = np.mean(dxxs, axis=0)
    dxx_std = np.std(dxxs, axis=0)

    dxx_min = np.min(dxxs, axis=0)
    dxx_max = np.max(dxxs, axis=0)

    fig = plt.figure(figsize=[3.25, 2.5])
    rect = [0.16, 0.18, 0.8, 0.77]
    ax1 = fig.add_axes(rect)

    p1, = ax1.plot(moms, dxx_mean)
    ax1.fill_between(moms, dxx_min, dxx_max, color=p1.get_color(), alpha=0.5)
    ax1.tick_params(labelsize=10)
    ax1.tick_params(axis='x', which='minor', direction='in', top='on')
    ax1.tick_params(axis='x', which='major', direction='in', top='on')
    ax1.tick_params(axis='y', which='minor', direction='in', left='on')
    ax1.tick_params(axis='y', which='major', direction='in')
    ax1.set_xlabel(r'$p/p_0$', fontdict=FONT, fontsize=12)
    # ax1.set_ylabel(r'$d_e^2\omega_{pe}$', fontdict=FONT, fontsize=12)
    ax1.set_ylabel(r'$D_{xx}/(v_Ad_i)$', fontdict=FONT, fontsize=12)

    fdir = '../img/' + run_name + '/'
    mkdir_p(fdir)
    fname = fdir + 'dxxs.pdf'
    fig.savefig(fname)

    plt.show()
def plot_particle_phase_distribution(pic_info, ct, base_dir, run_name, species,
                                     shock_pos):
    """
    """
    particle_interval = pic_info.particle_interval
    tratio = particle_interval / pic_info.fields_interval
    ptl_tindex = ct * particle_interval / tratio
    xmin, xmax = 0, pic_info.lx_di
    xmin, xmax = 0, 105
    zmin, zmax = -0.5 * pic_info.lz_di, 0.5 * pic_info.lz_di
    kwargs = {
        "current_time": ct,
        "xl": xmin,
        "xr": xmax,
        "zb": zmin,
        "zt": zmax
    }
    fname = base_dir + 'data1/vex.gda'
    x, z, vel = read_2d_fields(pic_info, fname, **kwargs)
    # nx, = x.shape
    # nz, = z.shape
    # data_cum = np.sum(vel, axis=0) / nz
    # data_grad = np.abs(np.gradient(data_cum))
    # xs = 5
    # max_index = np.argmax(data_grad[xs:])
    # xm = x[max_index]
    xm = x[shock_pos]
    max_index = shock_pos

    pos = [xm / 2, 0.0, 0.0]
    nxc = max_index
    csizes = [max_index, pic_info.ny, pic_info.nz]
    # csizes = [max_index/4, pic_info.ny, pic_info.nz/4]
    corners, mpi_ranks = set_mpi_ranks(pic_info, pos, sizes=csizes)

    fig1, fig2 = get_phase_distribution(base_dir, pic_info, species,
                                        ptl_tindex, corners, mpi_ranks)

    fig_dir = '../img/img_phase_distribution/' + run_name + '/'
    mkdir_p(fig_dir)
    fname = fig_dir + '/vdist_para_perp_' + species + '_' + str(ct).zfill(
        3) + '.jpg'
    fig1.savefig(fname, dpi=300)

    fname = fig_dir + '/vdist_para_perp_1d_' + species + '_' + str(ct).zfill(
        3) + '.jpg'
    fig2.savefig(fname, dpi=300)

    # plt.show()
    plt.close("all")
Esempio n. 10
0
def plot_number_density(run_name, root_dir, pic_info, species, ct):
    """Plot particle number density
    """
    kwargs = {"current_time": ct, "xl": 0, "xr": 1000, "zb": -250, "zt": 250}
    fname = root_dir + 'data/n' + species + '.gda'
    # fname = root_dir + 'data/jy.gda'
    x, z, nrho = read_2d_fields(pic_info, fname, **kwargs)
    fname = root_dir + 'data/Ay.gda'
    # x, z, Ay = read_2d_fields(pic_info, fname, **kwargs)
    nx, = x.shape
    nz, = z.shape
    xs, ys = 0.1, 0.15
    w1, h1 = 0.85, 0.8
    fig = plt.figure(figsize=[10, 5])

    ax1 = fig.add_axes([xs, ys, w1, h1])
    kwargs_plot = {"xstep": 2, "zstep": 2, "vmin": 0.0, "vmax": 10}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p1 = plot_2d_contour(x, z, nrho, ax1, fig, is_cbar=0, **kwargs_plot)
    p1.set_cmap(plt.cm.get_cmap('jet'))
    # ax1.contour(x[0:nx:xstep], z[0:nz:zstep], Ay[0:nz:zstep, 0:nx:xstep],
    #         colors='black', linewidths=0.5)
    ax1.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=20)
    ax1.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=20)
    ax1.tick_params(labelsize=16)
    t_wci = ct * pic_info.dt_fields
    title = r'$t = ' + "{:10.1f}".format(t_wci) + '/\Omega_{ci}$'
    ax1.text(0.02,
             0.9,
             title,
             color='white',
             fontsize=20,
             bbox=dict(facecolor='none', alpha=1.0, edgecolor='none',
                       pad=10.0),
             horizontalalignment='left',
             verticalalignment='center',
             transform=ax1.transAxes)

    nrho = 'n' + species
    fdir = '../img/' + nrho + '/'
    mkdir_p(fdir)
    fname = fdir + nrho + '_' + str(ct) + '.jpg'
    fig.savefig(fname, dpi=200)

    plt.show()
def calc_force_charge_efield(root_dir, pic_info, drange=[0.0, 1.0, 0.0, 1.0]):
    """Calculate force using charge density and electric field
    """
    ntf = pic_info.ntf
    dx = pic_info.dx_di
    dz = pic_info.dz_di
    cts = range(ntf)
    ncores = multiprocessing.cpu_count()
    Parallel(n_jobs=ncores)(
        delayed(calc_force_charge_efield_single)(ct, drange) for ct in cts)
    force = np.zeros((3, ntf))
    data_dir = '../data/force/'
    for ct in cts:
        fname = data_dir + 'force_' + str(ct) + '.dat'
        force[:, ct] = np.fromfile(fname)

    mkdir_p('../data/')
    force.tofile('../data/force_partial.dat')
def plot_tratio_dist(plot_config, show_plot=True):
    """
    Plot the distribution of the ratio between Tperp and Tpara
    """
    pic_run = plot_config["pic_run"]
    pic_run_dir = plot_config["pic_run_dir"]
    species = plot_config["species"]
    tframe = plot_config["tframe"]
    picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json'
    pic_info = read_data_from_json(picinfo_fname)

    fdir = '../data/temperature_anisotropy/' + pic_run + '/'
    fname = fdir + 'ftratio_' + species + '_' + str(tframe) + '.gda'
    fdata = np.fromfile(fname, dtype=np.float32)
    nbins_tratio = int(fdata[0])
    tratio_bins_edge = fdata[1:nbins_tratio+2]
    tratio_bins_mid = 0.5 * (tratio_bins_edge[1:] + tratio_bins_edge[:-1])
    dtemp = np.diff(tratio_bins_edge)
    ftratio = fdata[nbins_tratio+2:] / dtemp

    fig = plt.figure(figsize=[3.25, 2.5])
    rect = [0.16, 0.16, 0.79, 0.8]
    ax = fig.add_axes(rect)
    ax.set_prop_cycle('color', COLORS)
    ax.tick_params(bottom=True, top=True, left=True, right=True)
    ax.tick_params(axis='x', which='minor', direction='in', bottom=True, top=True)
    ax.tick_params(axis='x', which='major', direction='in', bottom=True, top=True)
    ax.tick_params(axis='y', which='minor', direction='in')
    ax.tick_params(axis='y', which='major', direction='in')

    ax.loglog(tratio_bins_mid, ftratio, linewidth=1)
    ax.set_xlim([5E-2, 2E1])
    ax.tick_params(labelsize=8)
    ax.set_xlabel(r'$T_\perp/T_\parallel$', fontsize=10)
    ax.set_ylabel(r'$f(T_\perp/T_\parallel)$', fontsize=10)
    fdir = '../img/tratio_dist/' + pic_run + '/'
    mkdir_p(fdir)
    fname = fdir + 'tratio_dist_' + species + '_' + str(tframe) + '.pdf'
    fig.savefig(fname)

    if show_plot:
        plt.show()
    else:
        plt.close()
def combine_energy_spectrum(run_dir, run_name, tframe, species='e'):
    """Combine particle energy spectrum from different mpi_rank

    Args:
        run_dir: PIC simulation directory
        run_name: PIC simulation run name
        tframe: time frame
        species: 'e' for electrons, 'H' for ions
    """
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    interval = pic_info.fields_interval
    mpi_size = pic_info.topology_x * pic_info.topology_y * pic_info.topology_z
    rank = 0
    ndata = (NBINS + 3) if INCLUDE_BFIELDS else NBINS
    tindex = tframe * interval
    fname_pre = run_dir + 'hydro/T.' + str(tindex)
    if species == 'h':
        species = 'H'
    fname_pre += '/spectrum-' + species + 'hydro.' + str(tindex)
    fname = fname_pre + '.' + str(rank)
    fdata = np.fromfile(fname, dtype=np.float32)
    dsz, = fdata.shape
    nzone = dsz // ndata
    for rank in range(1, mpi_size):
        fname = fname_pre + '.' + str(rank)
        fdata += np.fromfile(fname, dtype=np.float32)
    print("number of zones: %d" % nzone)
    flog_tot = np.zeros(NBINS)
    for i in range(nzone):
        if INCLUDE_BFIELDS:
            flog = fdata[i*ndata+3:(i+1)*ndata]
        else:
            flog = fdata[i*ndata:(i+1)*ndata]
        flog_tot += flog
    emin_log = math.log10(EMIN)
    emax_log = math.log10(EMAX)
    elog = 10**(np.linspace(emin_log, emax_log, NBINS))
    delog = np.gradient(elog)
    flog_tot /= delog
    fdir = '../data/spectra/' + run_name + '/'
    mkdir_p(fdir)
    fname = fdir + 'spectrum-' + species.lower() + '.' + str(tframe)
    flog_tot.tofile(fname)
Esempio n. 14
0
def combine_energy_spectrum(run_dir, run_name, tframe, species='e'):
    """Combine particle energy spectrum from different mpi_rank

    Args:
        run_dir: PIC simulation directory
        run_name: PIC simulation run name
        tframe: time frame
        species: 'e' for electrons, 'H' for ions
    """
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    interval = pic_info.fields_interval
    mpi_size = pic_info.topology_x * pic_info.topology_y * pic_info.topology_z
    rank = 0
    ndata = (NBINS + 3) if INCLUDE_BFIELDS else NBINS
    tindex = tframe * interval
    fname_pre = run_dir + 'hydro/T.' + str(tindex)
    if species == 'h':
        species = 'H'
    fname_pre += '/spectrum-' + species + 'hydro.' + str(tindex)
    fname = fname_pre + '.' + str(rank)
    fdata = np.fromfile(fname, dtype=np.float32)
    dsz, = fdata.shape
    nzone = dsz // ndata
    for rank in range(1, mpi_size):
        fname = fname_pre + '.' + str(rank)
        fdata += np.fromfile(fname, dtype=np.float32)
    print("number of zones: %d" % nzone)
    flog_tot = np.zeros(NBINS)
    for i in range(nzone):
        if INCLUDE_BFIELDS:
            flog = fdata[i * ndata + 3:(i + 1) * ndata]
        else:
            flog = fdata[i * ndata:(i + 1) * ndata]
        flog_tot += flog
    emin_log = math.log10(EMIN)
    emax_log = math.log10(EMAX)
    elog = 10**(np.linspace(emin_log, emax_log, NBINS))
    delog = np.gradient(elog)
    flog_tot /= delog
    fdir = '../data/spectra/' + run_name + '/'
    mkdir_p(fdir)
    fname = fdir + 'spectrum-' + species.lower() + '.' + str(tframe)
    flog_tot.tofile(fname)
def save_particle_number():
    """Save PIC information and particle number information
    """
    root_dir = '/net/scratch3/xiaocanli/herts/tether_potential_tests/'
    # run_names = ['v50', 'v100', 'v150', 'v200']
    run_names = ['v200_b0_wce']
    mkdir_p('../data/pic_info/')
    mkdir_p('../data/particle_number/')
    for run_name in run_names:
        fdir = root_dir + run_name + '/'
        pic_info = pic_information.get_pic_info(fdir)
        pic_info_json = data_to_json(pic_info)
        fname = '../data/pic_info/pic_info_' + run_name + '.json'
        with open(fname, 'w') as f:
            json.dump(pic_info_json, f)
        t, ntot = read_particle_number(fdir, pic_info)
        fname = '../data/particle_number/nptl_' + run_name + '.dat'
        data = np.column_stack((t, ntot))
        np.savetxt(fname, data)
def calc_force_charge_efield(root_dir, pic_info, drange=[0.0, 1.0, 0.0, 1.0]):
    """Calculate force using charge density and electric field
    """
    ntf = pic_info.ntf
    dx = pic_info.dx_di
    dz = pic_info.dz_di
    cts = range(ntf)
    ncores = multiprocessing.cpu_count()
    Parallel(n_jobs=ncores)(delayed(calc_force_charge_efield_single)(ct,
                                                                     drange)
                            for ct in cts)
    force = np.zeros((3, ntf))
    data_dir = '../data/force/'
    for ct in cts:
        fname = data_dir + 'force_' + str(ct) + '.dat'
        force[:, ct] = np.fromfile(fname)

    mkdir_p('../data/')
    force.tofile('../data/force_partial.dat')
def save_particle_number():
    """Save PIC information and particle number information
    """
    root_dir = '/net/scratch3/xiaocanli/herts/tether_potential_tests/'
    # run_names = ['v50', 'v100', 'v150', 'v200']
    run_names = ['v200_b0_wce']
    mkdir_p('../data/pic_info/')
    mkdir_p('../data/particle_number/')
    for run_name in run_names:
        fdir = root_dir + run_name + '/'
        pic_info = pic_information.get_pic_info(fdir)
        pic_info_json = data_to_json(pic_info)
        fname = '../data/pic_info/pic_info_' + run_name + '.json'
        with open(fname, 'w') as f:
            json.dump(pic_info_json, f)
        t, ntot = read_particle_number(fdir, pic_info)
        fname = '../data/particle_number/nptl_' + run_name + '.dat'
        data = np.column_stack((t, ntot))
        np.savetxt(fname, data)
Esempio n. 18
0
def plot_spectrum(plot_config, show_plot=True):
    """Plot power spectrum

    Args:
        plot_config: plot configuration
    """
    pic_run = plot_config["pic_run"]
    pic_run_dir = plot_config["pic_run_dir"]
    tframe = plot_config["tframe"]
    var_name = plot_config["var_name"]
    picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    tratio = pic_info.particle_interval / pic_info.fields_interval
    tindex = tframe * pic_info.fields_interval
    fname = pic_run_dir + "vkappa_spectrum/" + var_name + str(tindex) + ".kx"
    fx = np.fromfile(fname, dtype=np.float32)
    fname = pic_run_dir + "vkappa_spectrum/" + var_name + str(tindex) + ".ky"
    fy = np.fromfile(fname, dtype=np.float32)
    fname = pic_run_dir + "vkappa_spectrum/" + var_name + str(tindex) + ".kz"
    fz = np.fromfile(fname, dtype=np.float32)
    fx = fx.reshape((2, -1))
    fy = fy.reshape((2, -1))
    fz = fz.reshape((2, -1))
    fig = plt.figure(figsize=[7, 5])
    ax = fig.add_axes([0.17, 0.15, 0.75, 0.8])
    ax.loglog(fx[0, :], fx[1, :], linewidth=2, label=r'$x$')
    ax.loglog(fy[0, :], fy[1, :], linewidth=2, label=r'$y$')
    ax.loglog(fz[0, :], fz[1, :], linewidth=2, label=r'$z$')
    ax.legend(loc=1, prop={'size': 16}, ncol=1,
              shadow=False, fancybox=False, frameon=False)
    ax.tick_params(labelsize=16)
    ax.set_xlabel(r'$k_x, k_y, k_z (d_e^{-1})$', fontsize=20)
    ax.set_ylabel(r'$f(k_x), f(k_y), f(k_z)$', fontsize=20)
    fdir = '../img/power_spectrum_vkappa/' + pic_run + '/'
    mkdir_p(fdir)
    fname = fdir + var_name + "_" + str(tindex).zfill(5) + ".pdf"
    fig.savefig(fname)
    if show_plot:
        plt.show()
    else:
        plt.close()
def combine_spectrum(plot_config):
    """Combine the spectrum in the whole box

    Here we assume that PIC only splits z into different zones
    """
    pic_run_dir = plot_config["pic_run_dir"]
    spect_dir = plot_config["spect_dir"]
    species = plot_config["species"]
    mpi_size = plot_config["mpi_size"]
    mpi_sizex = plot_config["mpi_sizex"]
    mpi_sizey = plot_config["mpi_sizey"]
    mpi_sizez = plot_config["mpi_sizez"]
    num_fold = plot_config["num_fold"]
    nbins = plot_config["nbins"]
    tindex = plot_config["tframe"] * plot_config["tinterval"]
    fdir = pic_run_dir + spect_dir + '/0/T.' + str(tindex) + '/'
    fname = fdir + 'spectrum-' + species + 'hydro.' + str(tindex) + '.0'
    fdata = np.fromfile(fname, dtype=np.float32)
    nzones = fdata.shape[0] // nbins
    fspect = np.zeros((nzones * mpi_sizez, mpi_sizey, mpi_sizex, nbins))
    nxy = mpi_sizex * mpi_sizey
    for mpi_rank in range(mpi_size):
        print("MPI rank: %d" % mpi_rank)
        iz = mpi_rank // nxy
        iy = (mpi_rank % nxy) // mpi_sizex
        ix = mpi_rank % mpi_sizex
        findex = mpi_rank // num_fold
        fdir = (pic_run_dir + spect_dir + '/' + str(findex) +
                '/T.' + str(tindex) + '/')
        fname = (fdir + 'spectrum-' + species + 'hydro.' +
                 str(tindex) + '.' + str(mpi_rank))
        fdata = np.fromfile(fname, dtype=np.float32)
        # fdata = fdata.reshape((nzones, nbins))
        # fspect[iz*nzones:(iz+1)*nzones, iy, ix, :] = fdata

    fdir = ('/net/scratch3/xiaocanli/reconnection/NERSC_ADAM/' +
            plot_config['pic_run'] + '/spectrum/')
    mkdir_p(fdir)
    fname = fdir + species + 'spectrum.gda'
    fspect.tofile(fname)
def plot_number_density(run_name, root_dir, pic_info, species, ct):
    """Plot particle number density
    """
    kwargs = {"current_time": ct, "xl": 0, "xr": 1000, "zb": -250, "zt": 250}
    fname = root_dir + 'data/n' + species + '.gda'
    # fname = root_dir + 'data/jy.gda'
    x, z, nrho = read_2d_fields(pic_info, fname, **kwargs)
    fname = root_dir + 'data/Ay.gda'
    # x, z, Ay = read_2d_fields(pic_info, fname, **kwargs)
    nx, = x.shape
    nz, = z.shape
    xs, ys = 0.1, 0.15
    w1, h1 = 0.85, 0.8
    fig = plt.figure(figsize=[10, 5])

    ax1 = fig.add_axes([xs, ys, w1, h1])
    kwargs_plot = {"xstep": 2, "zstep": 2, "vmin": 0.0, "vmax": 10}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p1 = plot_2d_contour(x, z, nrho, ax1, fig, is_cbar=0, **kwargs_plot)
    p1.set_cmap(plt.cm.get_cmap('jet'))
    # ax1.contour(x[0:nx:xstep], z[0:nz:zstep], Ay[0:nz:zstep, 0:nx:xstep],
    #         colors='black', linewidths=0.5)
    ax1.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=20)
    ax1.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=20)
    ax1.tick_params(labelsize=16)
    t_wci = ct * pic_info.dt_fields
    title = r'$t = ' + "{:10.1f}".format(t_wci) + '/\Omega_{ci}$'
    ax1.text(0.02, 0.9, title, color='white', fontsize=20,
        bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
        horizontalalignment='left', verticalalignment='center',
        transform=ax1.transAxes)

    nrho = 'n' + species
    fdir = '../img/' + nrho + '/'
    mkdir_p(fdir)
    fname = fdir + nrho + '_' + str(ct) + '.jpg'
    fig.savefig(fname, dpi=200)

    plt.show()
def calc_avg_bfield(pic_info, ct, run_name, xm, base_dir='../../'):
    """Calculate the average magnetic field in the shock downstream

    Args:
        pic_info: namedtuple for the PIC simulation information.
        ct: current time frame.
        run_name: the simulation run name
        xm: the shock position in di
        base_dir: the root directory of the run
    """
    xmin, xmax = 0, pic_info.lx_di
    xmin, xmax = 0, 105
    zmin, zmax = -0.5 * pic_info.lz_di, 0.5 * pic_info.lz_di
    kwargs = {
        "current_time": ct,
        "xl": xmin,
        "xr": xmax,
        "zb": zmin,
        "zt": zmax
    }
    xmin, xmax = 0, xm
    fname = base_dir + 'data1/bx.gda'
    x, z, bx = read_2d_fields(pic_info, fname, **kwargs)
    fname = base_dir + 'data1/by.gda'
    x, z, by = read_2d_fields(pic_info, fname, **kwargs)
    fname = base_dir + 'data1/bz.gda'
    x, z, bz = read_2d_fields(pic_info, fname, **kwargs)

    bx_avg = np.average(bx)
    by_avg = np.average(by)
    bz_avg = np.average(bz)

    bavg = np.asarray([bx_avg, by_avg, bz_avg])

    data_dir = '../data/b_average/'
    mkdir_p(data_dir)
    fname = data_dir + 'bavg_' + str(ct) + '.txt'
    bavg.tofile(fname)
def calc_avg_bfield(pic_info, ct, run_name, xm, base_dir='../../'):
    """Calculate the average magnetic field in the shock downstream

    Args:
        pic_info: namedtuple for the PIC simulation information.
        ct: current time frame.
        run_name: the simulation run name
        xm: the shock position in di
        base_dir: the root directory of the run
    """
    xmin, xmax = 0, pic_info.lx_di
    xmin, xmax = 0, 105
    zmin, zmax = -0.5 * pic_info.lz_di, 0.5 * pic_info.lz_di
    kwargs = {
        "current_time": ct,
        "xl": xmin,
        "xr": xmax,
        "zb": zmin,
        "zt": zmax
    }
    xmin, xmax = 0, xm
    fname = base_dir + 'data1/bx.gda'
    x, z, bx = read_2d_fields(pic_info, fname, **kwargs)
    fname = base_dir + 'data1/by.gda'
    x, z, by = read_2d_fields(pic_info, fname, **kwargs)
    fname = base_dir + 'data1/bz.gda'
    x, z, bz = read_2d_fields(pic_info, fname, **kwargs)

    bx_avg = np.average(bx)
    by_avg = np.average(by)
    bz_avg = np.average(bz)

    bavg = np.asarray([bx_avg, by_avg, bz_avg])

    data_dir = '../data/b_average/'
    mkdir_p(data_dir)
    fname = data_dir + 'bavg_' + str(ct) + '.txt'
    bavg.tofile(fname)
def plot_energy_spectrum(run_name, spect_info, species='e', show_plot=True):
    """Plot particle energy spectrum

    Args:
        run_name: PIC simulation run name
        species: 'e' for electrons, 'H' for ions
        spect_info: dictionary for spectra information
    """
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    if species == 'h':
        species = 'H'
    # ntf = spect_info["tmax"]
    ntf = pic_info.ntf
    if species == 'e':
        vth = pic_info.vthe
    else:
        vth = pic_info.vthi
    gama = 1.0 / math.sqrt(1.0 - 3 * vth**2)
    eth = gama - 1.0
    emin_log = math.log10(spect_info["emin"])
    emax_log = math.log10(spect_info["emax"])
    nbins = spect_info["nbins"]
    elog = 10**(np.linspace(emin_log, emax_log, nbins))
    elog /= eth
    nptot = pic_info.nx * pic_info.ny * pic_info.nz * pic_info.nppc

    tframes = range(0, ntf - 1)
    nframes = len(tframes)
    flogs = np.zeros((nframes, nbins))

    fig = plt.figure(figsize=[7, 5])
    rect = [0.14, 0.16, 0.82, 0.8]
    ax = fig.add_axes(rect)
    for iframe, tframe in enumerate(tframes):
        print("Time frame: %d" % tframe)
        fdir = '../data/spectra/' + run_name + '/'
        fname = fdir + 'spectrum-' + species.lower() + '.' + str(tframe)
        flog = np.fromfile(fname)
        flog /= nptot
        color = plt.cm.jet(tframe/float(ntf), 1)
        flogs[iframe, :] = flog
        # ax.loglog(elog, flog, linewidth=2, color=color)

    # fmin = np.min(flogs[np.nonzero(flogs)])
    fmin = 1E-9
    flogs += fmin

    fdata = np.diff(np.log10(flogs[:, 400:600]), axis=0).T
    ng = 3
    kernel = np.ones((ng,ng)) / float(ng*ng)
    fdata = signal.convolve2d(fdata, kernel, mode='same')
    ax.imshow(fdata, vmin=-1E-1, vmax=1E-1, cmap=plt.cm.seismic,
              origin='lower', interpolation='bicubic')
    # if species == 'e':
    #     ax.set_xlim([1E0, 5E2])
    #     ax.set_ylim([1E-9, 1E2])
    # else:
    #     ax.set_xlim([1E0, 2E3])
    #     ax.set_ylim([1E-7, 1E4])
    ax.tick_params(bottom=True, top=True, left=True, right=False)
    ax.tick_params(axis='x', which='minor', direction='in')
    ax.tick_params(axis='x', which='major', direction='in')
    ax.tick_params(axis='y', which='minor', direction='in')
    ax.tick_params(axis='y', which='major', direction='in')
    ax.set_xlabel(r'$\varepsilon/\varepsilon_\text{th}$',
                  fontdict=FONT, fontsize=20)
    ax.set_ylabel(r'$f(\varepsilon)$', fontdict=FONT, fontsize=20)
    ax.tick_params(labelsize=16)
    ename = 'electron' if species == 'e' else 'ion'
    fpath = "../img/img_high_mime/spectra/" + ename + "/"
    mkdir_p(fpath)
    fname = fpath + "spect_time_" + run_name + "_" + species + ".pdf"
    fig.savefig(fname)
    if show_plot:
        plt.show()
    else:
        plt.close()
Esempio n. 24
0
def plot_spectrum(plot_config):
    """Plot spectrum for all time frames for a single run

    Args:
        plot_config: plotting configuration
    """
    species = plot_config["species"]
    tstart = plot_config["tstart"]
    tend = plot_config["tend"]
    pic_run = plot_config["pic_run"]
    root_dir = "/net/scratch3/xiaocanli/reconnection/Cori_runs/"
    pic_run_dir = root_dir + pic_run + "/"
    species = plot_config["species"]
    picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    if species == 'e':
        vth = pic_info.vthe
        sname = 'e'
    else:
        vth = pic_info.vthi
        sname = 'i'
    ebins = np.logspace(-4, 6, 1000)
    if species in ['i', 'ion', 'proton']:
        ebins *= pic_info.mime
    dt_particles = pic_info.dt_particles  # in 1/wci
    nframes = tend - tstart + 1
    dtf = math.ceil(pic_info.dt_particles / 0.1) * 0.1

    fig = plt.figure(figsize=[7, 5])
    rect = [0.13, 0.16, 0.7, 0.8]
    ax = fig.add_axes(rect)
    for tframe in range(tstart, tend + 1):
        print("Time frame: %d" % tframe)
        tindex = pic_info.eparticle_interval * tframe
        fname = (pic_run_dir + "spectrum_combined/spectrum_" + species + "_" +
                 str(tindex) + ".dat")
        spect = np.fromfile(fname, dtype=np.float32)
        ndata, = spect.shape
        spect[3:] /= np.gradient(ebins)
        spect[spect == 0] = np.nan
        ax.loglog(ebins,
                  spect[3:],
                  linewidth=1,
                  color=plt.cm.Spectral_r((tframe - tstart) / float(nframes),
                                          1))
    if species == 'e':
        pindex = -2.5
        power_index = "{%0.1f}" % pindex
        pname = r'$\propto (\gamma - 1)^{' + power_index + '}$'
        fpower = 1E13 * ebins**pindex
        ax.loglog(ebins, fpower, linewidth=1, color='k', linestyle='--')
    else:
        pindex = -3.5
        power_index = "{%0.1f}" % pindex
        pname = r'$\propto (\gamma - 1)^{' + power_index + '}$'
        fpower = 1E15 * ebins**pindex
        ax.loglog(ebins, fpower, linewidth=1, color='k', linestyle='--')
    ax.text(0.94,
            0.85,
            pname,
            color='k',
            fontsize=20,
            bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)
    ax.tick_params(bottom=True, top=True, left=True, right=True)
    ax.tick_params(axis='x', which='minor', direction='in', top=True)
    ax.tick_params(axis='x', which='major', direction='in')
    ax.tick_params(axis='y', which='minor', direction='in', left=True)
    ax.tick_params(axis='y', which='major', direction='in')
    if species in ['e', 'electron']:
        ax.set_xlim([1E-1, 1E3])
    else:
        ax.set_xlim([1E-1, 1E3])
    if '3D' in pic_run:
        ax.set_ylim([1E0, 1E12])
        ax.set_yticks(np.logspace(0, 10, num=6))
    else:
        ax.set_ylim([1E-1, 1E9])
        ax.set_yticks(np.logspace(-1, 9, num=6))
    text1 = r'$(\gamma - 1)m_' + species + r'c^2$'
    ax.set_xlabel(text1, fontsize=20)
    ax.set_ylabel(r'$f(\gamma - 1)$', fontsize=20)
    ax.tick_params(labelsize=16)
    rect_cbar = np.copy(rect)
    rect_cbar[0] += rect[2] + 0.02
    rect_cbar[2] = 0.03
    cax = fig.add_axes(rect_cbar)
    colormap = plt.cm.get_cmap('jet', tend - tstart + 1)
    sm = plt.cm.ScalarMappable(cmap=plt.cm.Spectral_r,
                               norm=plt.Normalize(vmin=tstart * dtf,
                                                  vmax=tend * dtf))
    cax.tick_params(axis='x', which='major', direction='in')
    # fake up the array of the scalar mappable. Urgh...
    sm._A = []
    cbar = fig.colorbar(sm, cax=cax)
    cbar.set_label(r'$t\Omega_{ci}$', fontsize=16)
    cbar.ax.tick_params(labelsize=12)
    fdir = '../img/cori_3d/spectrum/' + pic_run + '/'
    mkdir_p(fdir)
    fname = fdir + 'spectrum_' + species + '_2.pdf'
    fig.savefig(fname)
    plt.show()
Esempio n. 25
0
def plot_spectrum_both(plot_config, show_plot=True):
    """Plot spectrum both species

    Args:
        plot_config: plotting configuration
    """
    species = plot_config["species"]
    tstart = plot_config["tstart"]
    tend = plot_config["tend"]
    tframe = plot_config["tframe"]
    pic_run = plot_config["pic_run"]
    pic_run_dir = plot_config["pic_run_dir"]
    species = plot_config["species"]
    picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    vthe = pic_info.vthe
    gama = 1.0 / math.sqrt(1.0 - 3 * vthe**2)
    ethe = gama - 1.0
    vthi = pic_info.vthi
    gama = 1.0 / math.sqrt(1.0 - 3 * vthi**2)
    ethi = gama - 1.0
    ebins = np.logspace(-6, 4, 1000)
    ebins_e = ebins / ethe
    ebins_i = ebins / ethi
    dt_particles = pic_info.dt_particles  # in 1/wci
    nframes = tend - tstart + 1
    dtf = math.ceil(pic_info.dt_particles / 0.1) * 0.1

    fig = plt.figure(figsize=[3.5, 2.5])
    rect = [0.16, 0.16, 0.8, 0.8]
    ax = fig.add_axes(rect)
    ax.set_prop_cycle('color', COLORS)
    # for tframe in range(tstart_plot, tend_plot + 1):
    print("Time frame: %d" % tframe)
    tindex = pic_info.particle_interval * tframe
    fname = (pic_run_dir + "spectrum_combined/spectrum_e_" + str(tindex) +
             ".dat")
    spect_e = np.fromfile(fname, dtype=np.float32)
    fname = (pic_run_dir + "spectrum_combined/spectrum_i_" + str(tindex) +
             ".dat")
    spect_i = np.fromfile(fname, dtype=np.float32)
    spect_e[3:] /= np.gradient(ebins_e)
    spect_i[3:] /= np.gradient(ebins_i)

    # initial thermal distribution
    fname = (pic_run_dir + "spectrum_combined/spectrum_e_0.dat")
    spect_init = np.fromfile(fname, dtype=np.float32)
    ndata, = spect_init.shape
    spect_init[3:] /= np.gradient(ebins_e)

    ax.loglog(ebins_e,
              spect_init[3:],
              linewidth=1,
              color='k',
              linestyle='--',
              label='initial')
    ax.loglog(ebins_e, spect_e[3:], linewidth=1, label='electron')
    ax.loglog(ebins_i, spect_i[3:], linewidth=1, label='ion')
    ax.legend(loc=3,
              prop={'size': 10},
              ncol=1,
              shadow=False,
              fancybox=False,
              frameon=False)
    ax.tick_params(bottom=True, top=True, left=True, right=True)
    ax.tick_params(axis='x', which='minor', direction='in', top='on')
    ax.tick_params(axis='x', which='major', direction='in')
    ax.tick_params(axis='y', which='minor', direction='in', left='on')
    ax.tick_params(axis='y', which='major', direction='in')
    ax.set_xlim([1E-1, 2E3])
    ax.set_ylim([1E-1, 2E12])
    ax.set_yticks(np.logspace(-1, 11, num=7))
    ax.set_xlabel(r'$\varepsilon/\varepsilon_\text{th}$', fontsize=10)
    ax.set_ylabel(r'$f(\varepsilon)$', fontsize=10)
    ax.tick_params(labelsize=8)
    fdir = '../img/cori_3d/spectrum/' + pic_run + '/both_species/'
    mkdir_p(fdir)
    fname = fdir + 'spectrum_both_' + str(tframe) + '.pdf'
    fig.savefig(fname)
    if show_plot:
        plt.show()
    else:
        plt.close()
def calc_power_spectrum_mag(pic_info,
                            ct,
                            run_name,
                            shock_pos,
                            base_dir='../../'):
    """calculate power spectrum using magnetic fields

    Args:
        pic_info: namedtuple for the PIC simulation information.
        ct: current time frame.
    """
    xmin, xmax = 0, pic_info.lx_di
    xmin, xmax = 0, 105
    zmin, zmax = -0.5 * pic_info.lz_di, 0.5 * pic_info.lz_di
    kwargs = {
        "current_time": ct,
        "xl": xmin,
        "xr": xmax,
        "zb": zmin,
        "zt": zmax
    }
    fname = base_dir + 'data1/vex.gda'
    x, z, vel = read_2d_fields(pic_info, fname, **kwargs)
    nx, = x.shape
    nz, = z.shape
    # data_cum = np.sum(vel, axis=0) / nz
    # data_grad = np.abs(np.gradient(data_cum))
    # xs = 5
    # max_index = np.argmax(data_grad[xs:])
    # xm = x[max_index]
    xm = x[shock_pos]

    xmin, xmax = 0, xm
    fname = base_dir + 'data1/bx.gda'
    x, z, bx = read_2d_fields(pic_info, fname, **kwargs)
    fname = base_dir + 'data1/by.gda'
    x, z, by = read_2d_fields(pic_info, fname, **kwargs)
    fname = base_dir + 'data1/bz.gda'
    x, z, bz = read_2d_fields(pic_info, fname, **kwargs)
    smime = math.sqrt(pic_info.mime)
    lx = np.max(x) - np.min(x)
    lz = np.max(z) - np.min(z)

    bx_k = np.fft.rfft2(bx)
    by_k = np.fft.rfft2(by)
    bz_k = np.fft.rfft2(bz)
    b2_k = np.absolute(bx_k)**2 + np.absolute(by_k)**2 + np.absolute(bz_k)**2
    xstep = lx / nx
    kx = np.fft.fftfreq(nx, xstep)
    idx = np.argsort(kx)
    zstep = lz / nz
    kz = np.fft.fftfreq(nz, zstep)
    idz = np.argsort(kz)
    print np.min(kx), np.max(kx), np.min(kz), np.max(kz)

    kxs, kzs = np.meshgrid(kx[:nx // 2 + 1], kz)
    ks = np.sqrt(kxs * kxs + kzs * kzs)
    # kmin, kmax = np.min(ks), np.max(ks)
    # kbins = np.linspace(kmin, kmax, nx//2+1, endpoint=True)
    kmin = 1E-2
    kmax = np.max(ks)
    kmin_log, kmax_log = math.log10(kmin), math.log10(kmax)
    kbins = 10**np.linspace(kmin_log, kmax_log, 64, endpoint=True)
    ps, kbins_edges = np.histogram(
        ks, bins=kbins, weights=b2_k * ks, density=True)
    w1, h1 = 0.8, 0.8
    xs, ys = 0.15, 0.95 - h1
    fig = plt.figure(figsize=[7, 5])
    ax1 = fig.add_axes([xs, ys, w1, h1])
    for index, k in np.ndenumerate(kbins):
        pass
        # print index, k
    psm = 25
    # pindex = -5.0/3.0
    pindex = -2.0
    power_k = kbins[psm:]**pindex
    shift = 22
    ax1.loglog(kbins_edges[:-1], ps, linewidth=2)
    ax1.loglog(
        kbins[psm:psm + shift],
        power_k[:shift] * 2 / power_k[0],
        linestyle='--',
        linewidth=2,
        color='k')
    # power_index = "{%0.2f}" % pindex
    power_index = '-2.0'
    tname = r'$\sim k^{' + power_index + '}$'
    ax1.text(
        0.45,
        0.7,
        tname,
        color='black',
        fontsize=24,
        horizontalalignment='left',
        verticalalignment='center',
        transform=ax1.transAxes)
    ax1.tick_params(labelsize=16)
    ax1.set_xlabel(r'$kd_i$', fontdict=font, fontsize=20)
    ax1.set_ylabel(r'$E_B(k)$', fontdict=font, fontsize=20)
    ax1.set_xlim([1E-2, 3E1])
    ax1.set_ylim([1E-3, 3E1])

    fig_dir = '../img/img_power_spectrum/' + run_name + '/'
    mkdir_p(fig_dir)
    fname = fig_dir + '/ps_mag_' + str(ct).zfill(3) + '.jpg'
    fig.savefig(fname, dpi=300)

    # plt.show()
    plt.close()
def transfer_pic_to_mhd(run_dir, run_name, tframe):
    """Transfer the required fields

    Args:
        run_dir: simulation directory
        run_name: name of the simulation run
        tframe: time frame
        boundary_x: boundary condition along x-direction
                    0 for periodic; 1 for others
        boundary_z: boundary condition along z-direction
    """
    print("Time frame: %d" % tframe)
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    lx_di = pic_info.lx_di
    lz_di = pic_info.lz_di
    kwargs = {"current_time": tframe, "xl": 0, "xr": lx_di,
              "zb": -0.5 * lz_di, "zt": 0.5 * lz_di}
    fname = run_dir + "data/bx.gda"
    x, z, bx = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data/by.gda"
    x, z, by = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data/bz.gda"
    x, z, bz = read_2d_fields(pic_info, fname, **kwargs)
    nx, = x.shape
    nz, = z.shape
    mhd_data = np.zeros((nz+4, nx+4, 8), dtype=np.float32)

    # We need to switch y and z directions
    absB = np.sqrt(bx**2 + by**2 + bz**2)
    mhd_data[2:nz+2, 2:nx+2, 4] = bx
    mhd_data[2:nz+2, 2:nx+2, 5] = bz
    mhd_data[2:nz+2, 2:nx+2, 6] = -by
    mhd_data[2:nz+2, 2:nx+2, 7] = absB

    del bx, by, bz, absB

    mime = pic_info.mime

    # Electron
    fname = run_dir + "data/ne.gda"
    x, z, ne = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data/vex.gda"
    x, z, vex = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data/vey.gda"
    x, z, vey = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data/vez.gda"
    x, z, vez = read_2d_fields(pic_info, fname, **kwargs)

    vx = ne * vex
    vy = ne * vey
    vz = ne * vez

    del vex, vey, vez

    # Ion
    fname = run_dir + "data/ni.gda"
    x, z, ni = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data/vix.gda"
    x, z, vix = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data/viy.gda"
    x, z, viy = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data/viz.gda"
    x, z, viz = read_2d_fields(pic_info, fname, **kwargs)

    imass = 1.0 / (ne + ni * mime)
    vx = (vx + ni * mime * vix) * imass
    vy = (vy + ni * mime * viy) * imass
    vz = (vz + ni * mime * viz) * imass

    del vix, viy, viz, ne, ni, imass

    absV = np.sqrt(vx**2 + vy**2 + vz**2)
    mhd_data[2:nz+2, 2:nx+2, 0] = vx
    mhd_data[2:nz+2, 2:nx+2, 1] = vz
    mhd_data[2:nz+2, 2:nx+2, 2] = -vy
    mhd_data[2:nz+2, 2:nx+2, 3] = absV

    del vx, vy, vz, absV

    # Assuming periodic boundary along x for fields and particles
    # Assuming conducting boundary along z for fields and reflective for particles
    mhd_data[:, 0:2, :] = mhd_data[:, nx-1:nx+1, :]
    mhd_data[:, nx+2:, :] = mhd_data[:, 3:5, :]
    mhd_data[0:2, :, :] = mhd_data[3:1:-1, :, :]
    mhd_data[nz+2:, :, :] = mhd_data[nz+1:nz-1:-1, :, :]

    fpath = run_dir + 'bin_data/'
    mkdir_p(fpath)
    fname = fpath + 'mhd_data_' + str(tframe).zfill(4)
    print(mhd_data.shape)
    print(np.isfortran(mhd_data))
    mhd_data.tofile(fname)
Esempio n. 28
0
def plot_diffusion_coefficients(plot_config):
    """
    """
    run_dir = plot_config["run_dir"]
    run_name = plot_config["run_name"]
    tindex = plot_config["tframe"] * plot_config["tinterval"]
    ptl_vel = plot_config["ptl_vel"]
    fname = (run_dir + 'data_' + str(tindex) + '_' + str(ptl_vel) +
             'c/diff_coeffs.dat')
    fdata = np.genfromtxt(fname, skip_header=1)
    xs, ys = 0.15, 0.15
    w1, h1 = 0.8, 0.8
    fdir = '../img/' + run_name + '/'
    mkdir_p(fdir)

    def plot_one_diff(index, label1, img_name):
        fig = plt.figure(figsize=[7, 5])
        ax1 = fig.add_axes([xs, ys, w1, h1])
        nptl = fdata[:, -1]
        kappa = fdata[:, index] / nptl
        nframes, = kappa.shape
        tfs = np.arange(nframes)
        tstart1, tend1 = nframes // 4, 6 * nframes // 10
        coeff = np.polyfit(tfs[tstart1:tend1], kappa[tstart1:tend1], 1)
        p = np.poly1d(coeff)
        kappa_fit1 = p(tfs)
        tstart2 = tend1
        coeff = np.polyfit(tfs[tstart2:], kappa[tstart2:], 1)
        p = np.poly1d(coeff)
        kappa_fit2 = p(tfs)
        kappa_fit1 -= kappa_fit1[0]
        kappa_fit2 -= kappa_fit2[0]
        kappa_fit2 += kappa_fit1[tstart2] - kappa_fit2[tstart2]
        kappa_adjust = np.copy(kappa)
        kappa_adjust[:tend1] -= kappa_fit1[:tend1]
        kappa_adjust[tstart2:] -= kappa_fit2[tstart2:]
        # ax1.plot(tfs, kappa, linewidth=2, label=label1, color='k')
        # ax1.plot(tfs, kappa_adjust, linewidth=2, label=label1, color='k')
        # coeff = np.polyfit(tfs[tstart1:], kappa[tstart1:], 3)
        # p = np.poly1d(coeff)
        # kappa_fit1 = p(tfs)
        coeff = np.polyfit(tfs[tstart1:], np.log(kappa[tstart1:]), 1)
        p = np.poly1d(coeff)
        kappa_fit1 = np.exp(p(tfs))
        ax1.plot(tfs, np.log(kappa), linewidth=2, label=label1, color='k')
        # ax1.plot(tfs, kappa_fit1, linewidth=2, label=label1, color='k')
        # ax1.plot(tfs, kappa_fit1 - kappa_fit1[0], linewidth=2,
        #          label=label1, color='k')
        # ax1.plot(tfs, kappa-kappa_fit1, linewidth=2, label=label1, color='k')
        # grad_kappa = np.gradient(kappa)
        # # grad_kappa = gaussian_filter(grad_kappa, 9)
        # grad_grad_kappa = np.gradient(grad_kappa)
        # # grad_grad_kappa = gaussian_filter(grad_grad_kappa, 7)
        # ax1.plot(grad_grad_kappa[2000:], linewidth=2,
        #          label=label1, color='k')
        ax1.tick_params(labelsize=16)
        ax1.tick_params(axis='x', which='minor', direction='in', top='on')
        ax1.tick_params(axis='x', which='major', direction='in', top='on')
        ax1.tick_params(axis='y', which='minor', direction='in', left='on')
        ax1.tick_params(axis='y', which='major', direction='in')
        leg = ax1.legend(loc=2,
                         prop={'size': 20},
                         ncol=1,
                         shadow=False,
                         fancybox=False,
                         frameon=False)
        fname = fdir + img_name + '.eps'
        fig.savefig(fname)

    # plot_one_diff(0, r'$D_{rr}$', 'drr')
    plot_one_diff(1, r'$D_{xx}$', 'dxx')
    # plot_one_diff(2, r'$D_{yy}$', 'dyy')
    # plot_one_diff(3, r'$D_{zz}$', 'dzz')
    # plot_one_diff(4, r'$D_{pp}$', 'dpp')
    # plot_one_diff(5, r'$D_{\mu\mu}$', 'duu')
    # plot_one_diff(6, r'$D_{aa}$', 'daa')
    # plot_one_diff(7, r'$D_{ee}$', 'dee')
    plt.show()
Esempio n. 29
0
def diffusion_coefficients_multi(plot_config):
    """
    """
    run_dir = plot_config["run_dir"]
    run_name = plot_config["run_name"]
    tindex = plot_config["tframe"] * plot_config["tinterval"]
    ptl_vel = plot_config["ptl_vel"]
    vels = np.linspace(0.3, 0.9, 7)
    vels = np.append(vels, 0.95)
    gammas = 1.0 / np.sqrt(1 - vels**2)
    moms = vels * gammas
    tframes = np.linspace(10, 20, 11, dtype=int)
    tindices = tframes * plot_config["tinterval"]
    dxxs = np.zeros((len(tframes), len(vels)))

    fdir = '../img/' + run_name + '/'
    mkdir_p(fdir)
    for itindex, tindex in enumerate(tindices):
        fig = plt.figure(figsize=[7, 2.5])
        rect = [0.08, 0.18, 0.38, 0.76]
        xlen = fig.get_figwidth()
        ylen = fig.get_figheight()
        ax1 = fig.add_axes(rect)
        rect[0] += rect[2] + 0.1
        ax2 = fig.add_axes(rect)
        for ivel, vel in enumerate(vels[::-1]):
            fname = (run_dir + 'data_' + str(tindex) + '_' + str(vel) +
                     'c/diff_coeffs.dat')
            fdata = np.genfromtxt(fname, skip_header=1)
            nptl = fdata[:, -1]
            kappa = fdata[:, 1] / nptl
            nframes, = kappa.shape
            tfs = np.arange(nframes)
            tstart = nframes // 4
            # coeff = np.polyfit(tfs[tstart:], kappa[tstart:], 4)
            # p = np.poly1d(coeff)
            # kappa_fit = p(tfs)
            # kappa_fit -= kappa_fit[0]
            coeff = np.polyfit(tfs[tstart:], np.log(kappa[tstart:]), 3)
            p = np.poly1d(coeff)
            kappa_fit = np.exp(p(tfs))
            kappa_fit -= kappa_fit[0]
            kappa_adjust = kappa - kappa_fit
            label1 = r'$' + str(vel) + 'c$'
            if ivel == 4:
                p1, = ax1.plot(tfs,
                               kappa,
                               linewidth=1,
                               linestyle='--',
                               color='k')
                p2, = ax1.plot(tfs,
                               kappa_adjust,
                               linewidth=1,
                               linestyle='-',
                               color=p1.get_color())
                p3, = ax1.plot(tfs,
                               kappa_fit,
                               linewidth=1,
                               linestyle='-.',
                               color=p1.get_color())
                vel_str = r'$' + str(vel) + 'c$'
                ax1.text(0.02,
                         0.95,
                         vel_str,
                         color='k',
                         fontsize=10,
                         bbox=dict(facecolor='none',
                                   alpha=1.0,
                                   edgecolor='none',
                                   pad=10.0),
                         horizontalalignment='left',
                         verticalalignment='top',
                         transform=ax1.transAxes)
                xlim = ax1.get_xlim()
                ylim = ax1.get_ylim()
                lx = xlim[1] - xlim[0]
                ly = ylim[1] - ylim[0]
                t0 = 7000
                xextent = 2000 / lx
                yextent = (kappa[t0 + 1000] - kappa[t0 - 1000]) / ly
                angle = math.atan((yextent * ylen) / (xextent * xlen))
                angle *= 180 / math.pi
                angle += 10
                yoffset = (kappa[t0] - ylim[0]) / (ylim[1] - ylim[0]) - 0.03
                ax1.text(0.6,
                         yoffset,
                         'all particles',
                         color='k',
                         fontsize=10,
                         rotation=angle,
                         bbox=dict(facecolor='none',
                                   alpha=1.0,
                                   edgecolor='none',
                                   pad=10.0),
                         horizontalalignment='left',
                         verticalalignment='bottom',
                         transform=ax1.transAxes)
                yoffset = (kappa_fit[t0] - ylim[0]) / (ylim[1] -
                                                       ylim[0]) - 0.03
                ax1.text(0.6,
                         yoffset,
                         'streaming particles',
                         color='k',
                         fontsize=10,
                         rotation=angle,
                         bbox=dict(facecolor='none',
                                   alpha=1.0,
                                   edgecolor='none',
                                   pad=10.0),
                         horizontalalignment='left',
                         verticalalignment='bottom',
                         transform=ax1.transAxes)
                yoffset = (kappa_adjust[t0] - ylim[0]) / (ylim[1] -
                                                          ylim[0]) + 0.01
                ax1.text(0.8,
                         yoffset,
                         'rest',
                         color='k',
                         fontsize=10,
                         bbox=dict(facecolor='none',
                                   alpha=1.0,
                                   edgecolor='none',
                                   pad=10.0),
                         horizontalalignment='left',
                         verticalalignment='top',
                         transform=ax1.transAxes)
            p2, = ax2.plot(tfs,
                           kappa_adjust,
                           linewidth=1,
                           label=label1,
                           linestyle='-',
                           color='k')
            kappa_mean = np.mean(kappa_adjust[nframes // 5:])
            dxxs[itindex, ivel] = kappa_mean
            ylim = ax2.get_ylim()
            k0 = (kappa_adjust[-1] - ylim[0]) / (ylim[1] - ylim[0])
            vel_str = r'$' + str(vel) + 'c$'
            ax2.text(1.01,
                     k0,
                     vel_str,
                     color='k',
                     fontsize=10,
                     bbox=dict(facecolor='none',
                               alpha=1.0,
                               edgecolor='none',
                               pad=10.0),
                     horizontalalignment='left',
                     verticalalignment='center',
                     transform=ax2.transAxes)
        ax1.set_xlim([tfs.min(), tfs.max()])
        ax1.tick_params(labelsize=10)
        ax1.tick_params(axis='x', which='minor', direction='in', top='on')
        ax1.tick_params(axis='x', which='major', direction='in', top='on')
        ax1.tick_params(axis='y', which='minor', direction='in', left='on')
        ax1.tick_params(axis='y', which='major', direction='in')
        ax1.set_xlabel(r'$t\omega_{pe}$', fontdict=FONT, fontsize=12)
        # ax1.set_ylabel(r'$d_e^2\omega_{pe}$', fontdict=FONT, fontsize=12)
        ax1.set_ylabel(r'$D_{xx}/(v_Ad_i)$', fontdict=FONT, fontsize=12)

        ax2.set_xlim([tfs.min(), tfs.max()])
        ax2.tick_params(labelsize=10)
        ax2.tick_params(axis='x', which='minor', direction='in', top='on')
        ax2.tick_params(axis='x', which='major', direction='in', top='on')
        ax2.tick_params(axis='y', which='minor', direction='in', left='on')
        ax2.tick_params(axis='y', which='major', direction='in')
        ax2.set_xlabel(r'$t\omega_{pe}$', fontdict=FONT, fontsize=12)
        # ax2.set_ylabel(r'$d_e^2\omega_{pe}$', fontdict=FONT, fontsize=12)
        ax2.set_ylabel(r'$D_{xx}/(v_Ad_i)$', fontdict=FONT, fontsize=12)

        fname = fdir + "dxx_" + str(tindex) + ".pdf"
        fig.savefig(fname)
        plt.close()
        # plt.show()

    fdir = '../data/' + run_name + '/'
    mkdir_p(fdir)
    fname = fdir + 'dxxs.dat'
    dxxs.tofile(fname)
Esempio n. 30
0
def piecewise_trajectory(plot_config):
    """Save piecewise trajectory
    """
    iptl = plot_config['iptl']
    tint = plot_config['tint']
    run_dir = plot_config["run_dir"]
    tindex = plot_config["tframe"] * plot_config["tinterval"]
    ptl_vel = plot_config["ptl_vel"]
    fname = (run_dir + 'data_' + str(tindex) + '_' + str(ptl_vel) +
             'c/particle_diagnostics.h5')
    file = h5py.File(fname, 'r')
    group = file['/particles_fields']
    dset_ptl = group['particles']
    sz, = dset_ptl.shape
    tinterval_traj = get_traj_tinterval(run_dir)
    nsteps_tot = get_num_steps(run_dir)
    if nsteps_tot > 1E6:
        nsteps_tot = int(1E6)
    nframes = nsteps_tot // tinterval_traj + 1
    nptl = sz / nframes
    lx, ly, lz = get_domain_sizes(run_dir)
    pdata = np.zeros([6, nframes])
    ps, pt = nframes * iptl, nframes * (iptl + 1)
    pdata[0] = np.array(dset_ptl['x'][ps:pt])
    pdata[1] = np.array(dset_ptl['y'][ps:pt])
    pdata[2] = np.array(dset_ptl['z'][ps:pt])
    pdata[3] = np.array(dset_ptl['ux'][ps:pt])
    pdata[4] = np.array(dset_ptl['uy'][ps:pt])
    pdata[5] = np.array(dset_ptl['uz'][ps:pt])
    fdir = run_dir + 'data_' + str(tindex) + '_' + str(ptl_vel) + 'c/'
    fdir += 'piecewise_trajectory/ptl_' + str(iptl) + '/'
    mkdir_p(fdir)
    nc_x, cross_x, offsets_x = get_crossings(pdata[0], lx)
    nc_y, cross_y, offsets_y = get_crossings(pdata[1], ly)
    nc_z, cross_z, offsets_z = get_crossings(pdata[2], lz)
    crossings = np.unique(np.sort(np.hstack((cross_x, cross_y, cross_z))))
    ncross, = crossings.shape
    icross1 = 0
    icross2 = 0
    for tframe in range(nframes):
        if tframe > crossings[icross2]:
            icross1 = icross2
            if icross2 < ncross - 1:
                icross2 += 1
            else:
                icross2 = ncross - 1
        neighbors = [
            0, crossings[icross1], tframe - tint, tframe, tframe + tint,
            crossings[icross2], nframes
        ]
        neighbors = sorted(list(set(neighbors)))
        tindex = neighbors.index(tframe)
        if tframe == 0:
            ts = 0
            te = int(neighbors[tindex + 1])
        elif tframe == crossings[icross2]:
            ts = int(neighbors[tindex - 1])
            te = tframe + 1
        else:
            ts = int(neighbors[tindex - 1])
            te = int(neighbors[tindex + 1])
        fname = fdir + "tframe_" + str(tframe)
        pointsToVTK(fname,
                    pdata[0, ts + 1:te],
                    pdata[1, ts + 1:te],
                    pdata[2, ts + 1:te],
                    data={
                        "ux": pdata[3, ts + 1:te],
                        "uy": pdata[4, ts + 1:te],
                        "uz": pdata[5, ts + 1:te]
                    })
Esempio n. 31
0
def plot_energy_spectrum(run_name, spect_info, species='e', show_plot=True):
    """Plot particle energy spectrum

    Args:
        run_name: PIC simulation run name
        species: 'e' for electrons, 'H' for ions
        spect_info: dictionary for spectra information
    """
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    if species == 'h':
        species = 'H'
    # ntf = spect_info["tmax"]
    ntf = pic_info.ntf
    if species == 'e':
        vth = pic_info.vthe
    else:
        vth = pic_info.vthi
    gama = 1.0 / math.sqrt(1.0 - 3 * vth**2)
    eth = gama - 1.0
    emin_log = math.log10(spect_info["emin"])
    emax_log = math.log10(spect_info["emax"])
    nbins = spect_info["nbins"]
    elog = 10**(np.linspace(emin_log, emax_log, nbins))
    elog /= eth
    nptot = pic_info.nx * pic_info.ny * pic_info.nz * pic_info.nppc

    tframes = range(0, ntf - 1)
    nframes = len(tframes)
    flogs = np.zeros((nframes, nbins))

    fig = plt.figure(figsize=[7, 5])
    rect = [0.14, 0.16, 0.82, 0.8]
    ax = fig.add_axes(rect)
    for iframe, tframe in enumerate(tframes):
        print("Time frame: %d" % tframe)
        fdir = '../data/spectra/' + run_name + '/'
        fname = fdir + 'spectrum-' + species.lower() + '.' + str(tframe)
        flog = np.fromfile(fname)
        flog /= nptot
        color = plt.cm.jet(tframe / float(ntf), 1)
        flogs[iframe, :] = flog
        # ax.loglog(elog, flog, linewidth=2, color=color)

    # fmin = np.min(flogs[np.nonzero(flogs)])
    fmin = 1E-9
    flogs += fmin

    fdata = np.diff(np.log10(flogs[:, 400:600]), axis=0).T
    ng = 3
    kernel = np.ones((ng, ng)) / float(ng * ng)
    fdata = signal.convolve2d(fdata, kernel, mode='same')
    ax.imshow(fdata,
              vmin=-1E-1,
              vmax=1E-1,
              cmap=plt.cm.seismic,
              origin='lower',
              interpolation='bicubic')
    # if species == 'e':
    #     ax.set_xlim([1E0, 5E2])
    #     ax.set_ylim([1E-9, 1E2])
    # else:
    #     ax.set_xlim([1E0, 2E3])
    #     ax.set_ylim([1E-7, 1E4])
    ax.tick_params(bottom=True, top=True, left=True, right=False)
    ax.tick_params(axis='x', which='minor', direction='in')
    ax.tick_params(axis='x', which='major', direction='in')
    ax.tick_params(axis='y', which='minor', direction='in')
    ax.tick_params(axis='y', which='major', direction='in')
    ax.set_xlabel(r'$\varepsilon/\varepsilon_\text{th}$',
                  fontdict=FONT,
                  fontsize=20)
    ax.set_ylabel(r'$f(\varepsilon)$', fontdict=FONT, fontsize=20)
    ax.tick_params(labelsize=16)
    ename = 'electron' if species == 'e' else 'ion'
    fpath = "../img/img_high_mime/spectra/" + ename + "/"
    mkdir_p(fpath)
    fname = fpath + "spect_time_" + run_name + "_" + species + ".pdf"
    fig.savefig(fname)
    if show_plot:
        plt.show()
    else:
        plt.close()
Esempio n. 32
0
def plot_particle_trajectory(plot_config):
    """
    """
    run_dir = plot_config["run_dir"]
    run_name = plot_config["run_name"]
    tindex = plot_config["tframe"] * plot_config["tinterval"]
    ptl_vel = plot_config["ptl_vel"]
    tinterval_traj = get_traj_tinterval(run_dir)
    nsteps_tot = get_num_steps(run_dir)
    if nsteps_tot > 1E6:
        nsteps_tot = int(1E6)
    ntraj = nsteps_tot // tinterval_traj + 1

    fname = (run_dir + 'data_' + str(tindex) + '_' + str(ptl_vel) +
             'c/particle_diagnostics.h5')
    with h5py.File(fname, 'r') as fh:
        group = fh['/particles_fields']
        dset_ptl = group['particles']
        dset_emf = group['fields']
        sz, = dset_ptl.shape
        nptl = sz // ntraj
        x = np.array(dset_ptl['x']).reshape((nptl, -1))
        y = np.array(dset_ptl['y']).reshape((nptl, -1))
        z = np.array(dset_ptl['z']).reshape((nptl, -1))
        ux = np.array(dset_ptl['ux']).reshape((nptl, -1))
        uy = np.array(dset_ptl['uy']).reshape((nptl, -1))
        uz = np.array(dset_ptl['uz']).reshape((nptl, -1))
        t = np.array(dset_ptl['t']).reshape((nptl, -1))
        Ex = np.array(dset_emf['Ex']).reshape((nptl, -1))
        Ey = np.array(dset_emf['Ey']).reshape((nptl, -1))
        Ez = np.array(dset_emf['Ez']).reshape((nptl, -1))
        Bx = np.array(dset_emf['Bx']).reshape((nptl, -1))
        By = np.array(dset_emf['By']).reshape((nptl, -1))
        Bz = np.array(dset_emf['Bz']).reshape((nptl, -1))
    lx, ly, lz = 750, 375, 312.5
    dxx = np.zeros(ntraj)
    nptl_select = 0
    for iptl in range(nptl):
        px = x[iptl, :]
        px = adjust_pos(px, 750)
        sign_switch = np.where((np.diff(np.sign(np.gradient(px))) != 0) *
                               1 == 1)
        sign_switch = np.squeeze(sign_switch)
        sign_switch = np.insert(sign_switch, 0, 0)
        sign_switch = np.append(sign_switch, ntraj - 1)
        interval = np.diff(sign_switch)
        sz, = interval.shape
        if sz > 0:
            max_interval = np.max(interval)
        else:
            max_interval = ntraj
        # if (np.max(px) - np.min(px)) < 500:
        if max_interval < ntraj // 4:
            nptl_select += 1
            dxx += (px - px[0])**2
    print("Number of selected particles: %d" % nptl_select)
    dxx /= np.linspace(1, 10000, ntraj) * nptl_select * 2
    plt.plot(dxx)
    plt.show()
    fdir1 = '../img/' + run_name + '/trajectory/'
    fdir2 = '../img/' + run_name + '/trajectory_scattering/'
    fdir3 = '../img/' + run_name + '/trajectory_streaming/'
    mkdir_p(fdir1)
    mkdir_p(fdir2)
    mkdir_p(fdir3)
Esempio n. 33
0
def magnetic_power_spectrum(plot_config, show_plot=True):
    """Plot power spectrum of magnetic field
    Args:
        plot_config: plot configuration
    """
    tframe = plot_config["tframe"]
    bg = plot_config["bg"]
    pic_runs = ["2D-Lx150-bg" + str(bg) + "-150ppc-16KNL"]
    pic_runs.append("3D-Lx150-bg" + str(bg) + "-150ppc-2048KNL")
    pic_run = pic_runs[1]
    root_dir = "/net/scratch3/xiaocanli/reconnection/Cori_runs/"
    pic_run_dir = root_dir + pic_run + "/"
    picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    k1, k2 = 0.03, 1.0
    nkbins = 100
    pindex = -2.7
    kpower = np.logspace(math.log10(k1), math.log10(k2), 100)
    fpower3 = kpower**pindex / 1E4

    fig = plt.figure(figsize=[3.5, 2.5])
    rect = [0.17, 0.16, 0.78, 0.8]
    ax = fig.add_axes(rect)
    COLORS = palettable.tableau.Tableau_10.mpl_colors
    ax.set_prop_cycle('color', COLORS)
    tframes = range(10, 36, 5)

    for tframe in tframes:
        tindex = tframe * pic_info.fields_interval
        for ivar, var in enumerate(["bx", "by", "bz"]):
            fdir = ('../data/power_spectrum/' + pic_run + '/power_spectrum_' +
                    var + '/')
            fname = fdir + var + str(tindex) + '.para'
            kpara, fdata = read_power_spectrum(fname)
            if ivar > 0:
                fkpara += fdata
            else:
                fkpara = fdata
            fname = fdir + var + str(tindex) + '.perp'
            kperp, fdata = read_power_spectrum(fname)
            if ivar > 0:
                fkperp += fdata
            else:
                fkperp = fdata
        ax.loglog(kperp, fkperp, linewidth=1, label=r'$k_\perp$')

    label1 = r'$\propto k_\perp^{' + str(pindex) + '}$'
    ax.loglog(kpower,
              fpower3,
              linewidth=0.5,
              color='k',
              linestyle='--',
              label=label1)
    ax.tick_params(bottom=True, top=True, left=True, right=True)
    ax.tick_params(axis='x', which='minor', direction='in', top=False)
    ax.tick_params(axis='x', which='major', direction='in')
    ax.tick_params(axis='y', which='minor', direction='in', left=False)
    ax.tick_params(axis='y', which='major', direction='in')
    twci = math.ceil((tframe * pic_info.dt_fields) / 0.1) * 0.1
    # text1 = r'$t\Omega_{ci}=' + ("{%0.0f}" % twci) + '$'
    ax.text(0.7,
            0.47,
            label1,
            color='k',
            fontsize=10,
            bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
            horizontalalignment='left',
            verticalalignment='center',
            transform=ax.transAxes)
    ax.set_xlim([1E-2, 5E0])
    # ax.set_ylim([1E-7, 2E-1])
    ax.set_yticks((np.logspace(-7, -1, 4)))
    ax.set_xlabel(r'$k_\perp d_e$', fontsize=10)
    ax.set_ylabel(r'$E_B(k_\perp)$', fontsize=10)
    ax.tick_params(labelsize=8)

    # Embedded plot for energy evolution
    rect1 = [0.29, 0.29, 0.30, 0.28]
    ax1 = fig.add_axes(rect1)
    ax1.tick_params(bottom=True, top=True, left=True, right=True)
    ax1.tick_params(axis='x', which='minor', direction='in', top=False)
    ax1.tick_params(axis='x', which='major', direction='in')
    ax1.tick_params(axis='y', which='minor', direction='in')
    ax1.tick_params(axis='y', which='major', direction='in')

    for irun, pic_run in enumerate(pic_runs):
        picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json'
        pic_info = read_data_from_json(picinfo_fname)
        enorm = pic_info.ene_magnetic[0]
        ene_bx = pic_info.ene_bx
        ene_by = pic_info.ene_by
        ene_bz = pic_info.ene_bz
        ene_magnetic = pic_info.ene_magnetic
        ene_electric = pic_info.ene_electric
        kene_e = pic_info.kene_e
        kene_i = pic_info.kene_i
        ene_bx /= enorm
        ene_by /= enorm
        ene_bz /= enorm
        ene_magnetic /= enorm
        kene_e /= enorm
        kene_i /= enorm
        tenergy = pic_info.tenergy

        lstyle = '-' if '3D' in pic_run else '--'
        ax1.plot(tenergy,
                 ene_magnetic,
                 linewidth=1,
                 linestyle=lstyle,
                 color='k')
    ax1.set_ylim([0.66, 1.02])
    # for iframe, tframe in enumerate(tframes):
    #     twci = tframe * pic_info.dt_fields
    #     ax1.plot([twci, twci], ax1.get_ylim(), linewidth=0.5,
    #              linestyle=':', color=COLORS[iframe])
    tframes = np.asarray(tframes) * pic_info.dt_fields
    nframe, = tframes.shape
    ax1.scatter(tframes, [0.7] * nframe,
                c=COLORS[:nframe],
                marker='x',
                s=10,
                linewidth=0.5)
    ax1.text(0.6,
             0.28,
             "2D",
             color='k',
             fontsize=6,
             bbox=dict(facecolor='none', alpha=1.0, edgecolor='none',
                       pad=10.0),
             horizontalalignment='center',
             verticalalignment='center',
             transform=ax1.transAxes)
    ax1.text(0.6,
             0.52,
             "3D",
             color='k',
             fontsize=6,
             bbox=dict(facecolor='none', alpha=1.0, edgecolor='none',
                       pad=10.0),
             horizontalalignment='center',
             verticalalignment='center',
             transform=ax1.transAxes)
    ax1.tick_params(labelsize=6)
    ax1.set_xlabel(r'$t\Omega_{ci}$', fontsize=6)
    ax1.set_ylabel(r'$\varepsilon_B/\varepsilon_{B0}$', fontsize=6)
    ax1.set_xlim([0, 400])

    fdir = '../img/cori_3d/power_spectrum_pub/' + pic_run + '/'
    mkdir_p(fdir)
    fname = fdir + 'mag_perp.pdf'
    fig.savefig(fname)

    if show_plot:
        plt.show()
    else:
        plt.close('all')
def save_mhd_config(run_name):
    """Save MHD configuration

    Need to switch y and z directions

    Args:
        run_name: simulation run name
    """
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)

    double_data = np.zeros(13)
    int_data = np.zeros(14, dtype=np.int32)
    smime = math.sqrt(pic_info.mime)
    lx = pic_info.lx_di * smime
    ly = pic_info.lz_di * smime
    lz = 0.0
    nx = pic_info.nx
    ny = pic_info.nz
    nz = pic_info.ny
    if nx > 1:
        double_data[0] = lx / nx
    else:
        double_data[0] = 0.0
    if ny > 1:
        double_data[1] = ly / ny
    else:
        double_data[1] = 0.0
    if nz > 1:
        double_data[2] = lz / nz
    else:
        double_data[2] = 0.0
    double_data[3] = 0.0
    double_data[4] = -0.5 * ly
    double_data[5] = 0.0 
    double_data[6] = lx
    double_data[7] = 0.5 * ly
    double_data[8] = 0.0
    double_data[9]  = lx
    double_data[10] = ly
    double_data[11] = lz
    double_data[12] = pic_info.dtwpe * pic_info.fields_interval
    int_data[0] = pic_info.nx
    int_data[1] = pic_info.nz
    int_data[2] = pic_info.ny
    int_data[3] = pic_info.nx / pic_info.topology_x
    int_data[4] = pic_info.nz / pic_info.topology_z
    int_data[5] = pic_info.ny / pic_info.topology_y
    int_data[6] = pic_info.topology_x
    int_data[7] = pic_info.topology_z
    int_data[8] = pic_info.topology_y
    int_data[9] = 9
    int_data[10] = 0 # Periodic boundary condition as default
    int_data[11] = 0
    int_data[12] = 0

    int_data[13] = 0

    fpath = run_dir + 'bin_data/'
    mkdir_p(fpath)
    fname = fpath + 'mhd_config.dat'
    double_data.tofile(fname)
    f = open(fname, 'a')
    int_data.tofile(f)
    f.close()
Esempio n. 35
0
def pspect_mag_vel(plot_config, show_plot=True):
    """Plot power spectrum for magnetic field and velocity field
    Args:
        plot_config: plot configuration
    """
    pic_run = plot_config["pic_run"]
    pic_run_dir = plot_config["pic_run_dir"]
    tframe = plot_config["tframe"]
    component = plot_config["component"]
    picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    tindex = tframe * pic_info.fields_interval
    var_name = 'vi' + component
    fdir = '../data/power_spectrum/' + pic_run + '/power_spectrum_' + var_name + '/'
    fname = fdir + var_name + str(tindex) + '.para'
    kpara, fkpara_v = read_power_spectrum(fname)
    fname = fdir + var_name + str(tindex) + '.perp'
    kperp, fkperp_v = read_power_spectrum(fname)
    # fkpara_v *= pic_info.mime * 0.5
    # fkperp_v *= pic_info.mime * 0.5

    var_name = 'b' + component
    fdir = '../data/power_spectrum/' + pic_run + '/power_spectrum_' + var_name + '/'
    fname = fdir + var_name + str(tindex) + '.para'
    kpara, fkpara_b = read_power_spectrum(fname)
    fname = fdir + var_name + str(tindex) + '.perp'
    kperp, fkperp_b = read_power_spectrum(fname)

    k1, k2 = 0.05, 0.5
    nkbins = 100

    id_para = (np.abs(kpara - k1)).argmin()
    id_perp = (np.abs(kperp - k1)).argmin()
    fnorm1 = max(fkpara_b[id_para], fkperp_b[id_perp]) * 2
    fnorm2 = max(fkpara_v[id_para], fkperp_v[id_perp]) * 4

    kpower = np.logspace(math.log10(k1), math.log10(k2), 100)
    fpower1 = kpower**(-5 / 3)
    fpower1 /= fpower1[0]
    fpower2 = kpower**-1.5
    fpower2 *= fpower1[0] / fpower2[0]
    fpower3 = kpower**-2
    fpower3 *= fpower1[0] / fpower3[0]

    fig = plt.figure(figsize=[7, 5])
    rect = [0.15, 0.16, 0.8, 0.8]
    ax = fig.add_axes(rect)
    ax.set_prop_cycle('color', COLORS)
    p1, = ax.loglog(kpara, fkpara_b, linewidth=2, label=r'$E_B(k_\parallel)$')
    p2, = ax.loglog(kperp, fkperp_b, linewidth=2, label=r'$E_B(k_\perp)$')
    p3, = ax.loglog(kpara,
                    fkpara_v,
                    linewidth=2,
                    linestyle='--',
                    color=p1.get_color(),
                    label=r'$E_V(k_\parallel)$')
    p4, = ax.loglog(kperp,
                    fkperp_v,
                    linewidth=2,
                    linestyle='--',
                    color=p2.get_color(),
                    label=r'$E_V(k_\perp)$')
    ax.loglog(kpower,
              fpower1 * fnorm1,
              linewidth=1,
              color='k',
              linestyle='--',
              label=r'$\sim k^{-5/3}$')
    ax.loglog(kpower,
              fpower2 * fnorm1,
              linewidth=1,
              color='k',
              linestyle='-.',
              label=r'$\sim k^{-3/2}$')
    ax.loglog(kpower,
              fpower3 * fnorm1,
              linewidth=1,
              color='k',
              linestyle=':',
              label=r'$\sim k^{-2}$')
    ax.loglog(kpower, fpower1 * fnorm2, linewidth=1, color='k', linestyle='--')
    ax.loglog(kpower, fpower2 * fnorm2, linewidth=1, color='k', linestyle='-.')
    ax.loglog(kpower, fpower3 * fnorm2, linewidth=1, color='k', linestyle=':')
    ax.legend(loc=1,
              prop={'size': 16},
              ncol=1,
              shadow=False,
              fancybox=False,
              frameon=False)
    ax.tick_params(bottom=True, top=True, left=True, right=True)
    ax.tick_params(axis='x', which='minor', direction='in', top='on')
    ax.tick_params(axis='x', which='major', direction='in')
    ax.tick_params(axis='y', which='minor', direction='in', left='on')
    ax.tick_params(axis='y', which='major', direction='in')
    ax.set_xlim([1E-2, 1E1])
    ax.set_ylim([5E-9, 2E-1])
    ax.set_xlabel(r'$kd_e$', fontsize=20)
    ax.set_ylabel(r'$E(k)$', fontsize=20)
    ax.tick_params(labelsize=16)
    fdir = '../img/power_spectrum/' + pic_run + '/mag_vel/'
    mkdir_p(fdir)
    fname = fdir + 'bvel_' + component + '_para_perp_' + str(tframe) + '.pdf'
    fig.savefig(fname)

    if show_plot:
        plt.show()
    else:
        plt.close('all')
def calc_power_spectrum_vel(pic_info,
                            ct,
                            species,
                            run_name,
                            shock_pos,
                            base_dir='../../'):
    """Calculate power spectrum using velocities

    Args:
        pic_info: namedtuple for the PIC simulation information.
        ct: current time frame.
        species: particle species
        run_name: the simulation run name
        shock_pos: the shock position in cell index
        base_dir: the root directory of the run
    """
    xmin, xmax = 0, pic_info.lx_di
    xmin, xmax = 0, 105
    zmin, zmax = -0.5 * pic_info.lz_di, 0.5 * pic_info.lz_di
    kwargs = {
        "current_time": ct,
        "xl": xmin,
        "xr": xmax,
        "zb": zmin,
        "zt": zmax
    }
    fname = base_dir + 'data1/vex.gda'
    x, z, vel = read_2d_fields(pic_info, fname, **kwargs)
    nx, = x.shape
    nz, = z.shape
    xm = x[shock_pos]

    xmin, xmax = 0, xm
    fname = base_dir + 'data1/v' + species + 'x.gda'
    x, z, vx = read_2d_fields(pic_info, fname, **kwargs)
    fname = base_dir + 'data1/v' + species + 'y.gda'
    x, z, vy = read_2d_fields(pic_info, fname, **kwargs)
    fname = base_dir + 'data1/v' + species + 'z.gda'
    x, z, vz = read_2d_fields(pic_info, fname, **kwargs)
    smime = math.sqrt(pic_info.mime)
    lx = np.max(x) - np.min(x)
    lz = np.max(z) - np.min(z)

    vx_k = np.fft.rfft2(vx)
    vy_k = np.fft.rfft2(vy)
    vz_k = np.fft.rfft2(vz)
    v2_k = np.absolute(vx_k)**2 + np.absolute(vy_k)**2 + np.absolute(vz_k)**2
    xstep = lx / nx
    kx = np.fft.fftfreq(nx, xstep)
    idx = np.argsort(kx)
    zstep = lz / nz
    kz = np.fft.fftfreq(nz, zstep)
    idz = np.argsort(kz)
    print np.min(kx), np.max(kx), np.min(kz), np.max(kz)

    kxs, kzs = np.meshgrid(kx[:nx // 2 + 1], kz)
    ks = np.sqrt(kxs * kxs + kzs * kzs)
    kmin, kmax = np.min(ks), np.max(ks)
    kbins = np.linspace(kmin, kmax, nx // 2 + 1, endpoint=True)
    ps, kbins_edges = np.histogram(
        ks, bins=kbins, weights=v2_k * ks, normed=True)
    w1, h1 = 0.8, 0.8
    xs, ys = 0.15, 0.95 - h1
    fig = plt.figure(figsize=[7, 5])
    ax1 = fig.add_axes([xs, ys, w1, h1])
    ax1.loglog(kbins_edges[:-1], ps, linewidth=2)
    # psm = np.argmax(ps)
    psm = 4
    pindex = -5.0 / 3
    power_k = kbins[psm:]**pindex
    shift = 400
    if species is 'electron':
        ax1.loglog(
            kbins[psm:psm + shift],
            power_k[:shift] * 0.5 / power_k[0],
            linestyle='--',
            linewidth=2,
            color='k')
    else:
        ax1.loglog(
            kbins[psm:psm + shift],
            power_k[:shift] * 10 / power_k[0],
            linestyle='--',
            linewidth=2,
            color='k')
    power_index = "{%0.1f}" % pindex
    # tname = r'$\sim k^{' + power_index + '}$'
    tname = r'$\sim k^{-5/3}$'
    ax1.text(
        0.4,
        0.8,
        tname,
        color='black',
        fontsize=24,
        horizontalalignment='left',
        verticalalignment='center',
        transform=ax1.transAxes)
    ax1.tick_params(labelsize=16)
    ax1.set_xlabel(r'$kd_i$', fontdict=font, fontsize=20)
    ax1.set_ylabel(r'$E_V(k)$', fontdict=font, fontsize=20)
    ax1.set_xlim([1E-2, 3E1])
    if species is 'electron':
        ax1.set_ylim([1E-2, 0.5])
    else:
        ax1.set_ylim([1E-2, 5])

    fig_dir = '../img/img_power_spectrum/' + run_name + '/'
    mkdir_p(fig_dir)
    # fname = fig_dir + '/ps_vel_' + species + str(ct).zfill(3) + '.jpg'
    # fig.savefig(fname, dpi=300)

    plt.show()
Esempio n. 37
0
def plot_power_spectrum(plot_config, show_plot=True):
    """Plot power spectrum for one variable at one time frame
    Args:
        plot_config: plot configuration
    """
    pic_run = plot_config["pic_run"]
    pic_run_dir = plot_config["pic_run_dir"]
    tframe = plot_config["tframe"]
    var_name = plot_config["var_name"]
    picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    tindex = tframe * pic_info.fields_interval
    fdir = '../data/power_spectrum/' + pic_run + '/power_spectrum_' + var_name + '/'
    labels = var_labels()
    var_label = labels[var_name]
    fname = fdir + var_name + str(tindex) + '.kx'
    kx, fkx = read_power_spectrum(fname)
    fname = fdir + var_name + str(tindex) + '.ky'
    ky, fky = read_power_spectrum(fname)
    fname = fdir + var_name + str(tindex) + '.kz'
    kz, fkz = read_power_spectrum(fname)
    fname = fdir + var_name + str(tindex) + '.para'
    kpara, fkpara = read_power_spectrum(fname)
    fname = fdir + var_name + str(tindex) + '.perp'
    kperp, fkperp = read_power_spectrum(fname)

    smime = math.sqrt(pic_info.mime)
    dx_de = pic_info.dx_di * smime
    dy_de = pic_info.dy_di * smime
    dz_de = pic_info.dz_di * smime
    k1, k2 = 0.02, 0.5
    nkbins = 100

    idx = (np.abs(kx - k1)).argmin()
    idy = (np.abs(ky - k1)).argmin()
    idz = (np.abs(kz - k1)).argmin()
    fnorm = max(fkx[idx], fky[idy], fkz[idz]) * 2

    kpower = np.logspace(math.log10(k1), math.log10(k2), 100)
    fpower1 = kpower**(-5 / 3)
    fpower1 *= fnorm / fpower1[0]
    fpower2 = kpower**-1.5
    fpower2 *= fpower1[0] / fpower2[0]
    fpower3 = kpower**-2
    fpower3 *= fpower1[0] / fpower3[0]

    fig = plt.figure(figsize=[7, 5])
    rect = [0.15, 0.16, 0.8, 0.8]
    ax = fig.add_axes(rect)
    ax.set_prop_cycle('color', COLORS)
    ax.loglog(kx, fkx, linewidth=2, label=r'$k_x$')
    ax.loglog(ky, fky, linewidth=2, label=r'$k_y$')
    ax.loglog(kz, fkz, linewidth=2, label=r'$k_z$')
    ax.loglog(kpower,
              fpower1,
              linewidth=1,
              color='k',
              linestyle='--',
              label=r'$\sim k^{-5/3}$')
    ax.loglog(kpower,
              fpower2,
              linewidth=1,
              color='k',
              linestyle='-.',
              label=r'$\sim k^{-3/2}$')
    ax.loglog(kpower,
              fpower3,
              linewidth=1,
              color='k',
              linestyle=':',
              label=r'$\sim k^{-2}$')
    ax.legend(loc=1,
              prop={'size': 16},
              ncol=1,
              shadow=False,
              fancybox=False,
              frameon=False)
    ax.tick_params(bottom=True, top=True, left=True, right=True)
    ax.tick_params(axis='x', which='minor', direction='in', top=True)
    ax.tick_params(axis='x', which='major', direction='in')
    ax.tick_params(axis='y', which='minor', direction='in', left=True)
    ax.tick_params(axis='y', which='major', direction='in')
    text1 = r'$' + var_label + '$'
    ax.text(0.02,
            0.05,
            text1,
            color='k',
            fontsize=20,
            bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
            horizontalalignment='left',
            verticalalignment='center',
            transform=ax.transAxes)
    ax.set_xlim([1E-2, 1E1])
    # ax.set_ylim([1E-7, 2E-1])
    ax.set_xlabel(r'$kd_e$', fontsize=20)
    ax.set_ylabel(r'$E_{' + var_label + '}(k)$', fontsize=20)
    ax.tick_params(labelsize=16)

    fdir = '../img/power_spectrum/' + pic_run + '/' + var_name + '/'
    mkdir_p(fdir)
    fname = fdir + var_name + '_xyz_' + str(tframe) + '.pdf'
    fig.savefig(fname)

    fig = plt.figure(figsize=[7, 5])
    rect = [0.15, 0.16, 0.8, 0.8]
    ax = fig.add_axes(rect)
    ax.set_prop_cycle('color', COLORS)
    ax.loglog(kpara, fkpara, linewidth=2, label=r'$k_\parallel$')
    ax.loglog(kperp, fkperp, linewidth=2, label=r'$k_\perp$')
    ax.loglog(kpower,
              fpower1,
              linewidth=1,
              color='k',
              linestyle='--',
              label=r'$\sim k^{-5/3}$')
    ax.loglog(kpower,
              fpower2,
              linewidth=1,
              color='k',
              linestyle='-.',
              label=r'$\sim k^{-3/2}$')
    ax.loglog(kpower,
              fpower3,
              linewidth=1,
              color='k',
              linestyle=':',
              label=r'$\sim k^{-2}$')
    ax.legend(loc=1,
              prop={'size': 16},
              ncol=1,
              shadow=False,
              fancybox=False,
              frameon=False)
    ax.tick_params(bottom=True, top=True, left=True, right=True)
    ax.tick_params(axis='x', which='minor', direction='in', top=True)
    ax.tick_params(axis='x', which='major', direction='in')
    ax.tick_params(axis='y', which='minor', direction='in', left=True)
    ax.tick_params(axis='y', which='major', direction='in')
    text1 = r'$' + var_label + '$'
    ax.text(0.02,
            0.05,
            text1,
            color='k',
            fontsize=20,
            bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
            horizontalalignment='left',
            verticalalignment='center',
            transform=ax.transAxes)
    ax.set_xlim([1E-2, 1E1])
    # ax.set_ylim([1E-7, 2E-1])
    ax.set_xlabel(r'$kd_e$', fontsize=20)
    ax.set_ylabel(r'$E_{' + var_label + '}(k)$', fontsize=20)
    ax.tick_params(labelsize=16)
    fname = fdir + var_name + '_para_perp_' + str(tframe) + '.pdf'
    fig.savefig(fname)

    if show_plot:
        plt.show()
    else:
        plt.close('all')
def calc_power_spectrum_vel_comp(pic_info,
                                 ct,
                                 species,
                                 run_name,
                                 xshock,
                                 base_dir='../../',
                                 single_file=True):
    """Calculate power spectrum of compressible mode and incompressible mode

    Args:
        pic_info: namedtuple for the PIC simulation information.
        ct: current time frame.
        species: particle species
        run_name: the simulation run name
        xshock: the shock position along the x-direction in di
        base_dir: the root directory of the run
    """
    xmin, xmax = 0, pic_info.lx_di
    xmin, xmax = 0, 105
    zmin, zmax = -0.5 * pic_info.lz_di, 0.5 * pic_info.lz_di

    xmin, xmax = 0, xshock
    if single_file:
        kwargs = {
            "current_time": ct,
            "xl": xmin,
            "xr": xmax,
            "zb": zmin,
            "zt": zmax
        }
        fname = base_dir + 'data1/v' + species + 'x.gda'
        x, z, vx = read_2d_fields(pic_info, fname, **kwargs)
        fname = base_dir + 'data1/v' + species + 'y.gda'
        x, z, vy = read_2d_fields(pic_info, fname, **kwargs)
        fname = base_dir + 'data1/v' + species + 'z.gda'
        x, z, vz = read_2d_fields(pic_info, fname, **kwargs)
    else:
        kwargs = {
            "current_time": 0,
            "xl": xmin,
            "xr": xmax,
            "zb": zmin,
            "zt": zmax
        }
        fields_interval = pic_info.fields_interval
        tframe = str(fields_interval * ct)
        fname = base_dir + 'data/v' + species + 'x_' + tframe + '.gda'
        x, z, vx = read_2d_fields(pic_info, fname, **kwargs)
        fname = base_dir + 'data/v' + species + 'y_' + tframe + '.gda'
        x, z, vy = read_2d_fields(pic_info, fname, **kwargs)
        fname = base_dir + 'data/v' + species + 'z_' + tframe + '.gda'
        x, z, vz = read_2d_fields(pic_info, fname, **kwargs)
    nx, = x.shape
    nz, = z.shape
    smime = math.sqrt(pic_info.mime)
    lx = np.max(x) - np.min(x)
    lz = np.max(z) - np.min(z)

    vx_k = np.fft.rfft2(vx)
    vy_k = np.fft.rfft2(vy)
    vz_k = np.fft.rfft2(vz)
    xstep = lx / nx
    kx = np.fft.fftfreq(nx, xstep)
    idx = np.argsort(kx)
    zstep = lz / nz
    kz = np.fft.fftfreq(nz, zstep)
    idz = np.argsort(kz)
    print np.min(kx), np.max(kx), np.min(kz), np.max(kz)

    kxs, kzs = np.meshgrid(kx[:nx // 2 + 1], kz)
    k = np.sqrt(kxs * kxs + kzs * kzs)

    vkpara = div0(vx_k * kxs + vz_k * kzs, k)
    vkperp_x = div0(-vy_k * kzs, k)
    vkperp_y = div0(vx_k * kzs - vz_k * kxs, k)
    vkperp_z = div0(vy_k * kxs, k)

    v2_k = np.absolute(vx_k)**2 + np.absolute(vy_k)**2 + np.absolute(vz_k)**2
    v2_kpara = np.absolute(vkpara)**2
    v2_kperp = np.absolute(vkperp_x)**2 + np.absolute(vkperp_y)**2 + \
               np.absolute(vkperp_z)**2

    kxs, kzs = np.meshgrid(kx[:nx // 2 + 1], kz)
    ks = np.sqrt(kxs * kxs + kzs * kzs)
    kmin, kmax = np.min(ks), np.max(ks)
    kmin = 1E-2
    kmin_log = math.log10(kmin)
    kmax_log = math.log10(kmax)
    # kbins = np.linspace(kmin, kmax, 256, endpoint=True)
    kbins = 10**np.linspace(kmin_log, kmax_log, 64, endpoint=True)
    ps, kbins_edges = np.histogram(ks, bins=kbins, weights=v2_k * ks)
    ps_para, kbins_edges = np.histogram(ks, bins=kbins, weights=v2_kpara * ks)
    ps_perp, kbins_edges = np.histogram(ks, bins=kbins, weights=v2_kperp * ks)
    power1 = ps / np.diff(kbins_edges)
    power2 = ps_para / np.diff(kbins_edges)
    power3 = ps_perp / np.diff(kbins_edges)
    # print power1
    # print (power1 + 1E-5) / (power2 + power3 + 1E-5)
    # print (np.sum(ps)) / (np.sum(ps_para) + np.sum(ps_perp))
    # print (np.sum(ps*np.diff(kbins_edges)))
    # print (np.sum(ps_para*np.diff(kbins_edges)))
    # print (np.sum(ps_perp*np.diff(kbins_edges)))
    w1, h1 = 0.8, 0.8
    xs, ys = 0.15, 0.95 - h1
    fig = plt.figure(figsize=[7, 5])
    ax1 = fig.add_axes([xs, ys, w1, h1])
    ax1.loglog(kbins_edges[:-1], power1, linewidth=2, label='Total')
    ax1.loglog(kbins_edges[:-1], power2, linewidth=2, label='Compressible')
    ax1.loglog(kbins_edges[:-1], power3, linewidth=2, label='Incompressible')
    # psm = np.argmax(ps)
    psm = 5
    pindex = -5.0 / 3
    power_k = kbins[psm:]**pindex
    shift = 20
    if species is 'electron':
        ax1.loglog(
            kbins[psm:psm + shift],
            power_k[:shift] * 0.5 / power_k[0],
            linestyle='--',
            linewidth=2,
            color='k')
    else:
        index_s = 20
        index_ps = index_s - psm
        ax1.loglog(
            kbins[index_s:index_s + shift],
            power_k[index_ps:shift + index_ps] * 1E12 / power_k[index_ps],
            linestyle='--',
            linewidth=2,
            color='k')
    power_index = "{%0.1f}" % pindex
    # tname = r'$\sim k^{' + power_index + '}$'
    tname = r'$\sim k^{-5/3}$'
    ax1.text(
        0.72,
        0.6,
        tname,
        color='black',
        fontsize=24,
        horizontalalignment='left',
        verticalalignment='center',
        transform=ax1.transAxes)
    ax1.tick_params(labelsize=16)
    ax1.set_xlabel(r'$kd_i$', fontdict=font, fontsize=20)
    ax1.set_ylabel(r'$E_V(k)$', fontdict=font, fontsize=20)
    ax1.set_xlim([1E-2, 3E1])
    if species is 'electron':
        ax1.set_ylim([1E-2, 0.5])
    else:
        ax1.set_xlim([1E-2, 1E0])
        ax1.set_ylim([5E9, 5E12])
    leg = ax1.legend(
        loc=1,
        prop={'size': 16},
        ncol=1,
        shadow=False,
        fancybox=False,
        frameon=False)

    fig_dir = '../img/img_power_spectrum/' + run_name + '/'
    mkdir_p(fig_dir)
    fname = fig_dir + '/ps_comp_' + species + str(ct).zfill(3) + '.jpg'
    fig.savefig(fname, dpi=200)

    plt.close()
def plot_ne_jdote(pic_info, root_dir, run_name, current_time):
    """
    Plot electron number density and jdote

    Args:
        pic_info: namedtuple for the PIC simulation information.
        root_dir: simulation root directory
        current_time: current time frame.
    """
    print("Time frame: %d" % current_time)
    smime = math.sqrt(pic_info.mime)
    dx = pic_info.dx_di * smime
    dz = pic_info.dz_di * smime
    lx_de = pic_info.lx_di * smime
    lz_de = pic_info.lz_di * smime
    kwargs = {"current_time": current_time, "xl": 0, "xr": lx_de,
              "zb": -0.5 * lx_de, "zt": 0.5 * lx_de}
    fname = root_dir + "data/ne.gda"
    x, z, ne = read_2d_fields(pic_info, fname, **kwargs)
    fname = root_dir + "data/Ay.gda"
    x, z, Ay = read_2d_fields(pic_info, fname, **kwargs)

    fname = root_dir + "data/ex.gda"
    x, z, ex = read_2d_fields(pic_info, fname, **kwargs)
    fname = root_dir + "data/ey.gda"
    x, z, ey = read_2d_fields(pic_info, fname, **kwargs)
    fname = root_dir + "data/ez.gda"
    x, z, ez = read_2d_fields(pic_info, fname, **kwargs)

    fname = root_dir + "data/vex.gda"
    x, z, vex = read_2d_fields(pic_info, fname, **kwargs)
    fname = root_dir + "data/vey.gda"
    x, z, vey = read_2d_fields(pic_info, fname, **kwargs)
    fname = root_dir + "data/vez.gda"
    x, z, vez = read_2d_fields(pic_info, fname, **kwargs)

    wpe_wce = pic_info.dtwce / pic_info.dtwpe
    va = wpe_wce / math.sqrt(pic_info.mime)
    vex /= va
    vey /= va
    vez /= va

    jdote = -ne * (ex * vex + ey * vey + ez * vez)
    ng = 3
    kernel = np.ones((ng, ng)) / float(ng * ng)
    jdote = signal.convolve2d(jdote, kernel)

    jdote /= pic_info.b0 * va
    
    xmin, xmax = np.min(x), np.max(x)
    zmin, zmax = np.min(z), np.max(z)

    # w0, h0 = 0.41, 0.11
    w0, h0 = 0.4, 0.42
    xs0, ys0 = 0.06, 0.98 - h0
    vgap, hgap = 0.03, 0.1

    def plot_one_field(fdata, ax, text, text_color, label_bottom='on',
                       label_left='on', ylabel=False, vmin=0, vmax=10,
                       colormap=plt.cm.seismic, xs=xs0, ys=ys0, ay_color='k',
                       color_bar=False):
        plt.tick_params(labelsize=16)
        p1 = ax.imshow(fdata, vmin=vmin, vmax=vmax, cmap=colormap,
                       extent=[xmin, xmax, zmin, zmax], aspect='auto',
                       origin='lower', interpolation='bicubic')
        ax.tick_params(axis='x', labelbottom=label_bottom)
        ax.tick_params(axis='y', labelleft=label_left)
        if ylabel:
            ax.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=20)
        ax.contour(x, z, Ay, colors=ay_color, linewidths=0.5)
        ax.text(0.02, 0.85, text, color=text_color, fontsize=20,
                bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
                horizontalalignment='left', verticalalignment='center',
                transform=ax.transAxes)
        if color_bar:
            xs1 = xs + w0 * 1.02
            w1 = w0 * 0.04
            cax = fig.add_axes([xs1, ys, w1, h0])
            cbar = fig.colorbar(p1, cax=cax)
            cbar.ax.tick_params(labelsize=16)
            return (p1, cbar)
        else:
            return p1

    fig = plt.figure(figsize=[16, 8])
    xs, ys = xs0, ys0
    ax1 = fig.add_axes([xs, ys, w0, h0])
    text1 = r'$n_e$'
    print("min and max of electron density: %f %f" % (np.min(ne), np.max(ne)))
    nmin, nmax = 1.0, 4.0
    ax1.tick_params(axis='x', which='minor', direction='in')
    ax1.tick_params(axis='x', which='major', direction='in')
    ax1.tick_params(axis='y', which='minor', direction='in')
    ax1.tick_params(axis='y', which='major', direction='in')
    p1, cbar1 = plot_one_field(ne, ax1, text1, 'w', label_bottom='off',
                               label_left='on', ylabel=True, vmin=nmin,
                               vmax=nmax, colormap=plt.cm.viridis, xs=xs, ys=ys,
                               ay_color='w', color_bar=True)
    cbar1.set_ticks(np.arange(nmin, nmax + 0.5, 0.5))

    ys -= h0 + vgap
    ax2 = fig.add_axes([xs, ys, w0, h0])
    vmin, vmax = -0.1, 0.1
    text2 = r'$\boldsymbol{j}_e\cdot\boldsymbol{E}$'
    ax2.tick_params(axis='x', which='minor', direction='in')
    ax2.tick_params(axis='x', which='major', direction='in')
    ax2.tick_params(axis='y', which='minor', direction='in')
    ax2.tick_params(axis='y', which='major', direction='in')
    print("min and max of jdote: %f %f" % (np.min(jdote), np.max(jdote)))
    p2 = plot_one_field(jdote, ax2, text2, 'k', label_bottom='on',
                        label_left='on', ylabel=True, vmin=vmin, vmax=vmax,
                        colormap=plt.cm.seismic, xs=xs, ys=ys)
    ax2.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=20)
    xs1 = xs + w0 * 1.02
    w1 = w0 * 0.04
    cax2 = fig.add_axes([xs1, ys, w1, h0])
    cbar2 = fig.colorbar(p2, cax=cax2)
    cbar2.ax.tick_params(labelsize=16)

    xs = xs1 + w1 + hgap
    h1 = h0 * 2 + vgap
    w1 = 0.3
    ax3 = fig.add_axes([xs, ys, w0, h1])
    ax3.tick_params(axis='x', which='minor', direction='in')
    ax3.tick_params(axis='x', which='major', direction='in')
    ax3.tick_params(axis='y', which='minor', direction='in')
    ax3.tick_params(axis='y', which='major', direction='in')
    vth = pic_info.vthe
    gama = 1.0 / math.sqrt(1.0 - 3 * vth**2)
    eth = gama - 1.0

    fdir = '../data/spectra/' + run_name + '/'
    n0 = pic_info.nx * pic_info.ny * pic_info.nz * pic_info.nppc
    tratio = pic_info.particle_interval // pic_info.fields_interval
    nt = current_time // tratio
    
    fname = fdir + 'spectrum-e.1'
    elin, flin, elog, flog_e = spect_fit.get_energy_distribution(fname, n0)
    elog_norm_e = spect_fit.get_normalized_energy('e', elog, pic_info)
    f_intial = fitting_funcs.func_maxwellian(elog, n0, 1.5 / eth)
    nacc, eacc = spect_fit.accumulated_particle_info(elog, f_intial)
    f_intial /= nacc[-1]
    ax3.loglog(elog_norm_e, f_intial, linewidth=1, color='k',
               linestyle='--', label='initial')

    for ct in range(1, nt + 1):
        fname = fdir + 'spectrum-e.' + str(ct)
        elin, flin, elog, flog_e = spect_fit.get_energy_distribution(fname, n0)
        nacc, eacc = spect_fit.accumulated_particle_info(elog, flog_e)
        flog_e /= nacc[-1]

        if (ct != nt):
            ax3.loglog(elog_norm_e, flog_e, linewidth=1, color='k')
        else:
            ax3.loglog(elog_norm_e, flog_e, linewidth=3, color='r')

    ax3.set_xlim([5E-2, 5E2])
    ax3.set_ylim([1E-8, 2E2])
    ax3.set_xlabel(r'$\varepsilon/\varepsilon_\text{th}$',
                   fontdict=font, fontsize=20)
    ax3.set_ylabel(r'$f(\varepsilon)$', fontdict=font, fontsize=20)
    ax3.tick_params(labelsize=16)
    t_wci = current_time * pic_info.dt_fields
    title = r'$t\Omega_{ci} = ' + "{:10.1f}".format(t_wci) + '$'
    ax3.text(0.02, 0.05, title, color='k', fontsize=20,
             bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
             horizontalalignment='left', verticalalignment='center',
             transform=ax3.transAxes)

    fdir = '../img/img_apjl/ne_jdote/' + run_name + '/'
    mkdir_p(fdir)
    fname = fdir + 'ne_jdote_' + str(current_time) + '.jpg'
    fig.savefig(fname, dpi=200)
    plt.close()
def plot_power_spectrum_vel_comp_du(pic_info,
                                    ct,
                                    species,
                                    run_name,
                                    xs,
                                    base_dir='../../',
                                    single_file=True):
    """
    Plot the power spectrum of the compressible and incompressible modes of
    both the upstream field and downstream field

    Args:
        pic_info: namedtuple for the PIC simulation information.
        ct: current time frame.
        species: particle species
        run_name: the simulation run name
        xs: the shock position in ion inertial length
        base_dir: the root directory of the run
    """
    s1 = 1.0
    s2 = 5.0
    xmin, xmax = xs - s2, xs - s1
    kbins, pt_d, pc_d, pi_d = calc_power_spectrum(
        pic_info, ct, species, run_name, xmin, xmax, base_dir, single_file)
    xmin, xmax = xs + s1, xs + s2
    kbins, pt_u, pc_u, pi_u = calc_power_spectrum(
        pic_info, ct, species, run_name, xmin, xmax, base_dir, single_file)
    categories = ['Upstream', 'Downstream']
    w1, h1 = 0.8, 0.7
    xs, ys = 0.15, 0.8 - h1
    fig = plt.figure(figsize=[7, 6])
    ax1 = fig.add_axes([xs, ys, w1, h1])
    p1, = ax1.loglog(
        kbins[:-1], pt_d, linewidth=2, color='k', label='Down: total')
    p2, = ax1.loglog(
        kbins[:-1],
        pc_d,
        linewidth=2,
        color=colors[0],
        label='Down: compressible')
    p3, = ax1.loglog(
        kbins[:-1],
        pi_d,
        linewidth=2,
        color=colors[1],
        label='Down: incompressible')
    p4, = ax1.loglog(
        kbins[:-1],
        pt_u,
        linewidth=2,
        color='k',
        linestyle='--',
        label='Up: total')
    p5, = ax1.loglog(
        kbins[:-1],
        pc_u,
        linewidth=2,
        linestyle='--',
        color=colors[0],
        label='Up: compressible')
    p6, = ax1.loglog(
        kbins[:-1],
        pi_u,
        linewidth=2,
        linestyle='--',
        color=colors[1],
        label='Up: incompressible')
    # psm = np.argmax(ps)
    psm = 5
    pindex = -5.0 / 3
    power_k = kbins[psm:]**pindex
    shift = 12
    if species is 'electron':
        ax1.loglog(
            kbins[psm:psm + shift],
            power_k[:shift] * 0.5 / power_k[0],
            linestyle='--',
            linewidth=2,
            color='k')
    else:
        index_s = 20
        index_ps = index_s - psm
        print kbins[index_s], kbins[index_s + shift]
        ax1.loglog(
            kbins[index_s:index_s + shift],
            power_k[index_ps:shift + index_ps] * 4E8 / power_k[index_ps],
            linestyle='-.',
            linewidth=1,
            color='k')
    power_index = "{%0.1f}" % pindex
    # tname = r'$\sim k^{' + power_index + '}$'
    tname = r'$\sim k^{-5/3}$'
    ax1.text(
        0.5,
        0.8,
        tname,
        color='black',
        fontsize=24,
        horizontalalignment='left',
        verticalalignment='center',
        transform=ax1.transAxes)
    ax1.tick_params(labelsize=16)
    ax1.set_xlabel(r'$kd_i$', fontdict=font, fontsize=20)
    ax1.set_ylabel(r'$E_V(k)$', fontdict=font, fontsize=20)
    ax1.set_xlim([1E-1, 1E1])
    if species is 'electron':
        ax1.set_ylim([1E-2, 0.5])
    else:
        ax1.set_ylim([1E6, 1E9])
    leg = ax1.legend(
        bbox_to_anchor=(0., 1.02, 1., .102),
        loc=3,
        prop={'size': 16},
        ncol=2,
        mode="expand",
        borderaxespad=0.)

    fig_dir = '../img/img_power_spectrum_du/' + run_name + '/'
    mkdir_p(fig_dir)
    fname = fig_dir + '/ps_comp_' + species + str(ct).zfill(3) + '.jpg'
    fig.savefig(fname, dpi=200)

    plt.close()
Esempio n. 41
0
def energy_conversion(plot_config):
    """Plot energy conversion

    Args:
        plot_config: plotting configuration
    """
    pic_run = plot_config["pic_run"]
    root_dir = "/net/scratch3/xiaocanli/reconnection/Cori_runs/"
    pic_run_dir = root_dir + pic_run + '/'
    picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    fig = plt.figure(figsize=[3.25, 2.5])
    w1, h1 = 0.78, 0.78
    xs, ys = 0.96 - w1, 0.96 - h1
    ax = fig.add_axes([xs, ys, w1, h1])
    COLORS = palettable.tableau.Tableau_10.mpl_colors
    ax.set_prop_cycle('color', COLORS)

    tenergy = pic_info.tenergy
    enorm = pic_info.ene_magnetic[0]

    ene_bx = pic_info.ene_bx
    ene_by = pic_info.ene_by
    ene_bz = pic_info.ene_bz
    ene_magnetic = pic_info.ene_magnetic
    ene_electric = pic_info.ene_electric
    kene_e = pic_info.kene_e
    kene_i = pic_info.kene_i

    etot = ene_magnetic + ene_electric + kene_e + kene_i
    dene_mag = ene_magnetic[-1] - ene_magnetic[0]
    dene_ele = ene_electric[-1] - ene_electric[0]
    print("Energy conservation: %e" % ((etot[-1] - etot[0]) / etot[0]))
    print("Energy conversion: %e" % (dene_mag / ene_magnetic[0]))
    print("Electron gain: %e" % ((kene_e[-1] - kene_e[0]) / abs(dene_mag)))
    print("Ion gain: %e" % ((kene_i[-1] - kene_i[0]) / abs(dene_mag)))
    print("Electric: %e" % (dene_ele / abs(dene_mag)))

    ene_bx /= enorm
    ene_by /= enorm
    ene_bz /= enorm
    ene_magnetic /= enorm
    kene_e /= enorm
    kene_i /= enorm

    ax.plot(tenergy, ene_magnetic, linewidth=1, linestyle='-')
    ax.plot(tenergy, kene_e, linewidth=1, linestyle='-')
    ax.plot(tenergy, kene_i, linewidth=1, linestyle='-')

    ax.text(0.03,
            0.6,
            "magnetic",
            color=COLORS[0],
            fontsize=12,
            bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
            horizontalalignment='left',
            verticalalignment='center',
            transform=ax.transAxes)
    ax.text(0.03,
            0.5,
            "electron",
            color=COLORS[1],
            fontsize=12,
            bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
            horizontalalignment='left',
            verticalalignment='center',
            transform=ax.transAxes)
    ax.text(0.03,
            0.4,
            "ion",
            color=COLORS[2],
            fontsize=12,
            bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
            horizontalalignment='left',
            verticalalignment='center',
            transform=ax.transAxes)
    ax.tick_params(bottom=True, top=True, left=True, right=True)
    ax.tick_params(axis='x', which='minor', direction='in', top=False)
    ax.tick_params(axis='x', which='major', direction='in')
    ax.tick_params(axis='y', which='minor', direction='in', left=False)
    ax.tick_params(axis='y', which='major', direction='in')
    ax.set_xlim([0, 260])
    ax.set_ylim([0, 1.05])
    ax.set_xlabel(r'$t\Omega_{ci}$', fontsize=12)
    ax.set_ylabel(r'$\text{Energy}/\varepsilon_{B0}$', fontsize=12)
    ax.tick_params(labelsize=10)

    fdir = '../img/cori_3d/' + pic_run + '/'
    mkdir_p(fdir)
    fname = fdir + 'econv.pdf'
    fig.savefig(fname)
    plt.show()
Esempio n. 42
0
def compare_spectrum(plot_config):
    """Compare 2D and 3D spectra

    Args:
        plot_config: plotting configuration
    """
    species = plot_config["species"]
    bg = plot_config["bg"]
    root_dir = "/net/scratch3/xiaocanli/reconnection/Cori_runs/"
    pic_runs = ["2D-sigmae100-Lx125-bg0.0-100ppc-15gr"]
    pic_runs.append("3D-sigmae100-Lx125-bg0.0-100ppc-1024KNL")
    tframes = np.asarray([0, 20, 40, 52])
    fig = plt.figure(figsize=[7, 5])
    rect = [0.14, 0.14, 0.8, 0.8]
    ax = fig.add_axes(rect)
    # colors = np.copy(COLORS)
    # colors[5] = colors[6]
    colors = palettable.tableau.Tableau_10.mpl_colors
    for irun, pic_run in enumerate(pic_runs):
        pic_run_dir = root_dir + pic_run + "/"
        picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json'
        pic_info = read_data_from_json(picinfo_fname)
        if species == 'e':
            vth = pic_info.vthe
        else:
            vth = pic_info.vthi
        ebins = np.logspace(-4, 6, 1000)
        if species in ['i', 'ion', 'proton']:
            ebins *= pic_info.mime

        if irun == 0:
            fnorm = 1
            lstyle = '--'
        else:
            fnorm = pic_info.ny
            lstyle = '-'

        tinterval = pic_info.eparticle_interval
        dtf = math.ceil(pic_info.dt_fields / 0.1) * 0.1
        pdim = "2D" if "2D" in pic_run else "3D"
        for iframe, tframe in enumerate(tframes):
            tindex = tinterval * tframe
            fname = (pic_run_dir + "spectrum_combined/spectrum_" + species +
                     "_" + str(tindex) + ".dat")
            spect = np.fromfile(fname, dtype=np.float32)
            ndata, = spect.shape
            spect[3:] /= np.gradient(ebins) * fnorm
            if iframe == len(tframes) - 1:
                eindex_20, ene = find_nearest(ebins, 20)
            spect[spect == 0] = np.nan
            if iframe > 0:
                ax.loglog(ebins,
                          spect[3:],
                          linewidth=1,
                          linestyle=lstyle,
                          color=colors[iframe - 1])
            else:
                if irun == 1:
                    ax.loglog(ebins,
                              spect[3:],
                              linewidth=1,
                              linestyle='--',
                              color='k')

    if species == 'e':
        fpower = 1E10 * ebins**-2.5
        power_index = "{%0.1f}" % -2.5
        pname = r'$\sim \varepsilon^{' + power_index + '}$'
        ax.loglog(ebins[548:648], fpower[548:648], linewidth=1, color='k')
    else:
        fpower = 2E12 * ebins**-3.5
        power_index = "{%0.1f}" % -3.5
        pname = r'$\sim \varepsilon^{' + power_index + '}$'
        ax.loglog(ebins[368:468], fpower[368:468], linewidth=1, color='k')
    ax.text(0.95,
            0.7,
            pname,
            color='k',
            fontsize=20,
            bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)

    ax.plot([0, 10], [0, 0],
            linestyle="--",
            color='k',
            linewidth=1,
            label='2D')
    ax.plot([0, 10], [0, 0], linestyle="-", color='k', linewidth=1, label='3D')
    ax.legend(loc=3,
              prop={'size': 20},
              ncol=1,
              shadow=False,
              fancybox=False,
              frameon=False)
    ax.tick_params(bottom=True, top=True, left=True, right=True)
    ax.tick_params(axis='x', which='minor', direction='in', top=True)
    ax.tick_params(axis='x', which='major', direction='in')
    ax.tick_params(axis='y', which='minor', direction='in')
    ax.tick_params(axis='y', which='major', direction='in')
    if species in ['e', 'electron']:
        ax.set_xlim([1E-1, 2E3])
    else:
        ax.set_xlim([1E-1, 2E3])
    ax.set_ylim([1E-5, 1E9])
    text1 = r'$(\gamma - 1)m_' + species + r'c^2$'
    ax.set_xlabel(text1, fontsize=20)
    ax.set_ylabel(r'$f(\gamma - 1)$', fontsize=20)
    ax.tick_params(labelsize=16)

    if species == 'e':
        xpos = [0.4, 0.7, 0.87, 0.94]
    else:
        xpos = [0.4, 0.67, 0.86, 0.93]
    text1 = r'$t\Omega_{ci}=0$'
    ax.text(xpos[0],
            0.10,
            text1,
            color='k',
            fontsize=16,
            bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
            horizontalalignment='center',
            verticalalignment='bottom',
            transform=ax.transAxes)
    text2 = r'$' + str(int(tframes[1] * 10)) + '$'
    ax.text(xpos[1],
            0.10,
            text2,
            color=colors[0],
            fontsize=16,
            bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
            horizontalalignment='center',
            verticalalignment='bottom',
            transform=ax.transAxes)
    text3 = r'$' + str(int(tframes[2] * 10)) + '$'
    ax.text(xpos[2],
            0.10,
            text3,
            color=colors[1],
            fontsize=16,
            bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
            horizontalalignment='center',
            verticalalignment='bottom',
            transform=ax.transAxes)
    text4 = r'$' + str(int(tframes[3] * 10)) + '$'
    ax.text(xpos[3],
            0.10,
            text4,
            color=colors[2],
            fontsize=16,
            bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
            horizontalalignment='left',
            verticalalignment='bottom',
            transform=ax.transAxes)

    fdir = '../img/cori_sigma/spectrum/'
    mkdir_p(fdir)
    fname = fdir + species + 'spect_32.pdf'
    fig.savefig(fname)

    plt.show()
def plot_nrho(run_name,
              root_dir,
              pic_info,
              ct,
              plasma_type='solar_wind',
              drange=[0.0, 1.0, 0.0, 1.0]):
    """Plot particle number densities

    Args:
        run_name: the name of this run.
        root_dir: the root directory of this run.
        pic_info: PIC simulation information in a namedtuple.
        ct: current time frame
        plasma_type: default is solar wind plasma
        drange: the relative range of the data to plot
    """
    params = calc_plasma_parameters(plasma_type)
    if plasma_type is 'lab':
        n0 = 1.0
    if plasma_type is 'lab_updated':
        n0 = 1.0
    else:
        n0 = params['ne']
    kwargs = {"current_time": ct, "xl": 0, "xr": 200, "zb": -50, "zt": 50}
    fname1 = root_dir + 'data/ne.gda'
    x, z, ne_all = read_2d_fields(pic_info, fname1, **kwargs)
    fname2 = root_dir + 'data/ni.gda'
    x, z, ni_all = read_2d_fields(pic_info, fname2, **kwargs)
    nx, = x.shape
    nz, = z.shape
    xs = int(drange[0] * nx)
    xe = int(drange[1] * nx)
    zs = int(drange[2] * nz)
    ze = int(drange[3] * nz)
    ne = ne_all[zs:ze, xs:xe] * n0
    ni = ni_all[zs:ze, xs:xe] * n0
    if plasma_type is 'lab':
        vmin, vmax = 0, 6
    if plasma_type is 'lab_updated':
        vmin, vmax = 0, 6
    else:
        vmin, vmax = 0, 15
    xmax = np.max(x)
    di = math.sqrt(pic_info.mime)  # de is 1.0 in VPIC simulation
    if plasma_type is 'lab':
        # solar_wind plasma: m
        norm = params['di'] / 100  # di in params is in cm
        label_unit = 'm'
    if plasma_type is 'lab_updated':
        # solar_wind plasma: m
        norm = params['di'] / 100  # di in params is in cm
        label_unit = 'm'
    else:
        # solar_wind plasma: km
        norm = params['di'] / 1E5  # di in params is in cm
        label_unit = 'km'
    x = x[xs:xe] * norm
    z = z[zs:ze] * norm
    xmin = np.min(x)
    xmax = np.max(x)
    zmin = np.min(z)
    zmax = np.max(z)
    print xmax, zmax * 2
    print pic_info.dtwpe / params['wpe']
    fig = plt.figure(figsize=[10, 10])
    xs, ys = 0.12, 0.56
    w1, h1 = 0.8, 0.415
    ax = fig.add_axes([xs, ys, w1, h1])
    print 'Maximum and minimum electron density', np.max(ne), np.min(ne)
    p1 = ax.imshow(
        ne,
        cmap=plt.cm.rainbow,
        extent=[xmin, xmax, zmin, zmax],
        aspect='auto',
        origin='lower',
        # norm=LogNorm(vmin=0.1, vmax=30),
        vmin=vmin,
        vmax=vmax,
        interpolation='bicubic')
    ax.tick_params(labelsize=16)
    ax.tick_params(axis='x', labelleft='off')
    fname = r'$y$ / ' + label_unit
    ax.set_ylabel(fname, fontdict=font, fontsize=20)
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="3%", pad=0.05)
    cbar = fig.colorbar(p1, cax=cax)
    cbar.ax.tick_params(labelsize=16)
    if plasma_type is 'lab' or 'lab_updated':
        cbar.ax.set_ylabel(r'$n/n_0$', fontdict=font, fontsize=20)
    else:
        cbar.ax.set_ylabel('cm$^{-3}$', fontdict=font, fontsize=20)

    ys -= h1 + 0.05
    ax1 = fig.add_axes([xs, ys, w1, h1])
    print 'Maximum and minimum ion density', np.max(ni), np.min(ni)
    p2 = ax1.imshow(
        ni,
        cmap=plt.cm.rainbow,
        extent=[xmin, xmax, zmin, zmax],
        aspect='auto',
        origin='lower',
        vmin=vmin,
        vmax=vmax,
        interpolation='bicubic')
    ax1.tick_params(labelsize=16)
    fname = r'$x$ / ' + label_unit
    ax1.set_xlabel(fname, fontdict=font, fontsize=20)
    fname = r'$y$ / ' + label_unit
    ax1.set_ylabel(fname, fontdict=font, fontsize=20)

    divider = make_axes_locatable(ax1)
    cax = divider.append_axes("right", size="3%", pad=0.05)
    cbar = fig.colorbar(p2, cax=cax)
    cbar.ax.tick_params(labelsize=16)
    if plasma_type is 'lab' or 'lab_updated':
        cbar.ax.set_ylabel(r'$n/n_0$', fontdict=font, fontsize=20)
    else:
        cbar.ax.set_ylabel('cm$^{-3}$', fontdict=font, fontsize=20)

    ax.text(
        0.1,
        0.9,
        r'$n_e$',
        color='k',
        fontsize=24,
        bbox=dict(
            facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
        horizontalalignment='center',
        verticalalignment='center',
        transform=ax.transAxes)
    ax1.text(
        0.1,
        0.9,
        r'$n_i$',
        color='k',
        fontsize=24,
        bbox=dict(
            facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
        horizontalalignment='center',
        verticalalignment='center',
        transform=ax1.transAxes)

    fdir = '../img/density/'
    mkdir_p(fdir)
    # fig.savefig('../img/ne_ni.jpg', dpi=300)
    fname = fdir + 'nei_' + str(ct) + '.jpg'
    fig.savefig(fname, dpi=200)

    # plt.close()
    plt.show()
def plot_ne_jdote(pic_info, root_dir, run_name, current_time):
    """
    Plot electron number density and jdote

    Args:
        pic_info: namedtuple for the PIC simulation information.
        root_dir: simulation root directory
        current_time: current time frame.
    """
    print("Time frame: %d" % current_time)
    smime = math.sqrt(pic_info.mime)
    dx = pic_info.dx_di * smime
    dz = pic_info.dz_di * smime
    lx_de = pic_info.lx_di * smime
    lz_de = pic_info.lz_di * smime
    kwargs = {
        "current_time": current_time,
        "xl": 0,
        "xr": lx_de,
        "zb": -0.5 * lx_de,
        "zt": 0.5 * lx_de
    }
    fname = root_dir + "data/ne.gda"
    x, z, ne = read_2d_fields(pic_info, fname, **kwargs)
    fname = root_dir + "data/Ay.gda"
    x, z, Ay = read_2d_fields(pic_info, fname, **kwargs)

    fname = root_dir + "data/ex.gda"
    x, z, ex = read_2d_fields(pic_info, fname, **kwargs)
    fname = root_dir + "data/ey.gda"
    x, z, ey = read_2d_fields(pic_info, fname, **kwargs)
    fname = root_dir + "data/ez.gda"
    x, z, ez = read_2d_fields(pic_info, fname, **kwargs)

    fname = root_dir + "data/vex.gda"
    x, z, vex = read_2d_fields(pic_info, fname, **kwargs)
    fname = root_dir + "data/vey.gda"
    x, z, vey = read_2d_fields(pic_info, fname, **kwargs)
    fname = root_dir + "data/vez.gda"
    x, z, vez = read_2d_fields(pic_info, fname, **kwargs)

    wpe_wce = pic_info.dtwce / pic_info.dtwpe
    va = wpe_wce / math.sqrt(pic_info.mime)
    vex /= va
    vey /= va
    vez /= va

    jdote = -ne * (ex * vex + ey * vey + ez * vez)
    ng = 3
    kernel = np.ones((ng, ng)) / float(ng * ng)
    jdote = signal.convolve2d(jdote, kernel)

    jdote /= pic_info.b0 * va

    xmin, xmax = np.min(x), np.max(x)
    zmin, zmax = np.min(z), np.max(z)

    # w0, h0 = 0.41, 0.11
    w0, h0 = 0.4, 0.42
    xs0, ys0 = 0.06, 0.98 - h0
    vgap, hgap = 0.03, 0.1

    def plot_one_field(fdata,
                       ax,
                       text,
                       text_color,
                       label_bottom='on',
                       label_left='on',
                       ylabel=False,
                       vmin=0,
                       vmax=10,
                       colormap=plt.cm.seismic,
                       xs=xs0,
                       ys=ys0,
                       ay_color='k',
                       color_bar=False):
        plt.tick_params(labelsize=16)
        p1 = ax.imshow(fdata,
                       vmin=vmin,
                       vmax=vmax,
                       cmap=colormap,
                       extent=[xmin, xmax, zmin, zmax],
                       aspect='auto',
                       origin='lower',
                       interpolation='bicubic')
        ax.tick_params(axis='x', labelbottom=label_bottom)
        ax.tick_params(axis='y', labelleft=label_left)
        if ylabel:
            ax.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=20)
        ax.contour(x, z, Ay, colors=ay_color, linewidths=0.5)
        ax.text(0.02,
                0.85,
                text,
                color=text_color,
                fontsize=20,
                bbox=dict(facecolor='none',
                          alpha=1.0,
                          edgecolor='none',
                          pad=10.0),
                horizontalalignment='left',
                verticalalignment='center',
                transform=ax.transAxes)
        if color_bar:
            xs1 = xs + w0 * 1.02
            w1 = w0 * 0.04
            cax = fig.add_axes([xs1, ys, w1, h0])
            cbar = fig.colorbar(p1, cax=cax)
            cbar.ax.tick_params(labelsize=16)
            return (p1, cbar)
        else:
            return p1

    fig = plt.figure(figsize=[16, 8])
    xs, ys = xs0, ys0
    ax1 = fig.add_axes([xs, ys, w0, h0])
    text1 = r'$n_e$'
    print("min and max of electron density: %f %f" % (np.min(ne), np.max(ne)))
    nmin, nmax = 1.0, 4.0
    ax1.tick_params(axis='x', which='minor', direction='in')
    ax1.tick_params(axis='x', which='major', direction='in')
    ax1.tick_params(axis='y', which='minor', direction='in')
    ax1.tick_params(axis='y', which='major', direction='in')
    p1, cbar1 = plot_one_field(ne,
                               ax1,
                               text1,
                               'w',
                               label_bottom='off',
                               label_left='on',
                               ylabel=True,
                               vmin=nmin,
                               vmax=nmax,
                               colormap=plt.cm.viridis,
                               xs=xs,
                               ys=ys,
                               ay_color='w',
                               color_bar=True)
    cbar1.set_ticks(np.arange(nmin, nmax + 0.5, 0.5))

    ys -= h0 + vgap
    ax2 = fig.add_axes([xs, ys, w0, h0])
    vmin, vmax = -0.1, 0.1
    text2 = r'$\boldsymbol{j}_e\cdot\boldsymbol{E}$'
    ax2.tick_params(axis='x', which='minor', direction='in')
    ax2.tick_params(axis='x', which='major', direction='in')
    ax2.tick_params(axis='y', which='minor', direction='in')
    ax2.tick_params(axis='y', which='major', direction='in')
    print("min and max of jdote: %f %f" % (np.min(jdote), np.max(jdote)))
    p2 = plot_one_field(jdote,
                        ax2,
                        text2,
                        'k',
                        label_bottom='on',
                        label_left='on',
                        ylabel=True,
                        vmin=vmin,
                        vmax=vmax,
                        colormap=plt.cm.seismic,
                        xs=xs,
                        ys=ys)
    ax2.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=20)
    xs1 = xs + w0 * 1.02
    w1 = w0 * 0.04
    cax2 = fig.add_axes([xs1, ys, w1, h0])
    cbar2 = fig.colorbar(p2, cax=cax2)
    cbar2.ax.tick_params(labelsize=16)

    xs = xs1 + w1 + hgap
    h1 = h0 * 2 + vgap
    w1 = 0.3
    ax3 = fig.add_axes([xs, ys, w0, h1])
    ax3.tick_params(axis='x', which='minor', direction='in')
    ax3.tick_params(axis='x', which='major', direction='in')
    ax3.tick_params(axis='y', which='minor', direction='in')
    ax3.tick_params(axis='y', which='major', direction='in')
    vth = pic_info.vthe
    gama = 1.0 / math.sqrt(1.0 - 3 * vth**2)
    eth = gama - 1.0

    fdir = '../data/spectra/' + run_name + '/'
    n0 = pic_info.nx * pic_info.ny * pic_info.nz * pic_info.nppc
    tratio = pic_info.particle_interval // pic_info.fields_interval
    nt = current_time // tratio

    fname = fdir + 'spectrum-e.1'
    elin, flin, elog, flog_e = spect_fit.get_energy_distribution(fname, n0)
    elog_norm_e = spect_fit.get_normalized_energy('e', elog, pic_info)
    f_intial = fitting_funcs.func_maxwellian(elog, n0, 1.5 / eth)
    nacc, eacc = spect_fit.accumulated_particle_info(elog, f_intial)
    f_intial /= nacc[-1]
    ax3.loglog(elog_norm_e,
               f_intial,
               linewidth=1,
               color='k',
               linestyle='--',
               label='initial')

    for ct in range(1, nt + 1):
        fname = fdir + 'spectrum-e.' + str(ct)
        elin, flin, elog, flog_e = spect_fit.get_energy_distribution(fname, n0)
        nacc, eacc = spect_fit.accumulated_particle_info(elog, flog_e)
        flog_e /= nacc[-1]

        if (ct != nt):
            ax3.loglog(elog_norm_e, flog_e, linewidth=1, color='k')
        else:
            ax3.loglog(elog_norm_e, flog_e, linewidth=3, color='r')

    ax3.set_xlim([5E-2, 5E2])
    ax3.set_ylim([1E-8, 2E2])
    ax3.set_xlabel(r'$\varepsilon/\varepsilon_\text{th}$',
                   fontdict=font,
                   fontsize=20)
    ax3.set_ylabel(r'$f(\varepsilon)$', fontdict=font, fontsize=20)
    ax3.tick_params(labelsize=16)
    t_wci = current_time * pic_info.dt_fields
    title = r'$t\Omega_{ci} = ' + "{:10.1f}".format(t_wci) + '$'
    ax3.text(0.02,
             0.05,
             title,
             color='k',
             fontsize=20,
             bbox=dict(facecolor='none', alpha=1.0, edgecolor='none',
                       pad=10.0),
             horizontalalignment='left',
             verticalalignment='center',
             transform=ax3.transAxes)

    fdir = '../img/img_apjl/ne_jdote/' + run_name + '/'
    mkdir_p(fdir)
    fname = fdir + 'ne_jdote_' + str(current_time) + '.jpg'
    fig.savefig(fname, dpi=200)
    plt.close()
Esempio n. 45
0
def plot_spectrum(plot_config):
    """Plot spectrum for all time frames for a single run

    Args:
        plot_config: plotting configuration
    """
    species = plot_config["species"]
    tstart = plot_config["tstart"]
    tend = plot_config["tend"]
    pic_run = plot_config["pic_run"]
    root_dir = "/net/scratch3/xiaocanli/reconnection/Cori_runs/"
    pic_run_dir = root_dir + pic_run + "/"
    species = plot_config["species"]
    picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    if species == 'e':
        vth = pic_info.vthe
        sname = 'e'
    else:
        vth = pic_info.vthi
        sname = 'i'
    ebins = np.logspace(-6, 4, 1000)
    gama = 1.0 / math.sqrt(1.0 - 3 * vth**2)
    eth = gama - 1.0
    emin, emax = 1E-6, 1E4
    nband = 1000
    dloge = (math.log10(emax) - math.log10(emin)) / (nband - 1)
    emin0 = 10**(math.log10(emin) - dloge)
    ebins = np.logspace(math.log10(emin0), math.log10(emax), nband + 1)
    pbins = np.sqrt((ebins + 1)**2 - 1)
    pbins /= np.sqrt((eth + 1)**2 - 1)
    pbins_mid = (pbins[:-1] + pbins[1:]) * 0.5
    dpbins = np.diff(pbins)
    ebins /= eth
    ebins_mid = (ebins[:-1] + ebins[1:]) * 0.5
    debins = np.diff(ebins)
    dt_particles = pic_info.dt_particles  # in 1/wci
    nframes = tend - tstart + 1
    dtf = pic_info.fields_interval * pic_info.dtwci

    fig = plt.figure(figsize=[7, 5])
    rect = [0.13, 0.16, 0.7, 0.8]
    ax = fig.add_axes(rect)
    for tframe in range(tstart, tend + 1):
        print("Time frame: %d" % tframe)
        tindex = pic_info.fields_interval * tframe
        fname = (pic_run_dir + "spectrum_combined/spectrum_" + species + "_" +
                 str(tindex) + ".dat")
        spect = np.fromfile(fname, dtype=np.float32)
        ndata, = spect.shape
        spect[3:] /= np.diff(ebins)
        spect[spect == 0] = np.nan
        ax.loglog(ebins_mid,
                  spect[3:],
                  linewidth=1,
                  color=plt.cm.Spectral_r((tframe - tstart) / float(nframes),
                                          1))
    if species == 'e':
        pindex = -5.5
        power_index = "{%0.1f}" % pindex
        pname = r'$\sim \varepsilon^{' + power_index + '}$'
        fpower = 1E18 * ebins_mid**pindex
        ax.loglog(ebins_mid, fpower, linewidth=1, color='k', linestyle='--')
    else:
        pindex = -3.5
        power_index = "{%0.1f}" % pindex
        pname = r'$\sim \varepsilon^{' + power_index + '}$'
        fpower = 1E15 * ebins_mid**pindex
        ax.loglog(ebins_mid, fpower, linewidth=1, color='k', linestyle='--')
    ax.text(0.94,
            0.85,
            pname,
            color='k',
            fontsize=20,
            bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)
    ax.tick_params(bottom=True, top=True, left=True, right=True)
    ax.tick_params(axis='x', which='minor', direction='in', top=True)
    ax.tick_params(axis='x', which='major', direction='in')
    ax.tick_params(axis='y', which='minor', direction='in', left=True)
    ax.tick_params(axis='y', which='major', direction='in')
    if species in ['e', 'electron']:
        ax.set_xlim([1E-1, 1E3])
    else:
        ax.set_xlim([1E-1, 5E3])
    if '3D' in pic_run:
        ax.set_ylim([1E0, 1E12])
        ax.set_yticks(np.logspace(0, 10, num=6))
    else:
        ax.set_ylim([1E-1, 1E12])
        ax.set_yticks(np.logspace(-1, 9, num=6))
    ax.set_xlabel(r'$\varepsilon/\varepsilon_\text{th}$', fontsize=20)
    ax.set_ylabel(r'$f(\varepsilon)$', fontsize=20)
    ax.tick_params(labelsize=16)
    rect_cbar = np.copy(rect)
    rect_cbar[0] += rect[2] + 0.02
    rect_cbar[2] = 0.03
    cax = fig.add_axes(rect_cbar)
    colormap = plt.cm.get_cmap('jet', tend - tstart + 1)
    sm = plt.cm.ScalarMappable(cmap=plt.cm.Spectral_r,
                               norm=plt.Normalize(vmin=tstart * dtf,
                                                  vmax=tend * dtf))
    cax.tick_params(axis='x', which='major', direction='in')
    # fake up the array of the scalar mappable. Urgh...
    sm._A = []
    cbar = fig.colorbar(sm, cax=cax)
    cbar.set_label(r'$t\Omega_{ci}$', fontsize=16)
    cbar.ax.tick_params(labelsize=12)
    fdir = '../img/cori_3d/spectrum/' + pic_run + '/'
    mkdir_p(fdir)
    fname = fdir + 'spectrum_' + species + '_2.pdf'
    fig.savefig(fname)
    plt.show()
Esempio n. 46
0
def rho_bands_2d(plot_config, show_plot=True):
    """Plot densities for energetic particles in the 2D simulation
    """
    pic_run = plot_config["pic_run"]
    species = plot_config["species"]
    tframe = plot_config["tframe"]
    picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    pic_run_dir = pic_info.run_dir
    if species == 'e':
        vth = pic_info.vthe
    else:
        vth = pic_info.vthi
    nbins = 1000
    ndata = nbins + 3  # including magnetic field
    tindex = pic_info.particle_interval * tframe
    gama = 1.0 / math.sqrt(1.0 - 3 * vth**2)
    eth = gama - 1.0
    ebins = np.logspace(-6, 4, nbins)
    ebins /= eth
    xmin, xmax = 0, pic_info.lx_di
    zmin, zmax = -pic_info.lz_di * 0.5, pic_info.lz_di * 0.5
    nx, nz = pic_info.nx, pic_info.nz
    smime = math.sqrt(pic_info.mime)
    dx_de = pic_info.dx_di * smime
    dy_de = pic_info.dy_di * smime
    dz_de = pic_info.dz_di * smime
    kwargs = {
        "current_time": tframe,
        "xl": 0,
        "xr": pic_info.lx_di,
        "zb": -pic_info.lz_di,
        "zt": pic_info.lz_di
    }
    # fname = pic_run_dir + "data/Ay.gda"
    # x, z, Ay = read_2d_fields(pic_info, fname, **kwargs)
    fname = pic_run_dir + "data/bx.gda"
    x, z, bx = read_2d_fields(pic_info, fname, **kwargs)
    fname = pic_run_dir + "data/by.gda"
    x, z, by = read_2d_fields(pic_info, fname, **kwargs)
    fname = pic_run_dir + "data/bz.gda"
    x, z, bz = read_2d_fields(pic_info, fname, **kwargs)
    ib = 1.0 / np.sqrt(bx**2 + by**2 + bz**2)
    bx = bx * ib
    by = by * ib
    bz = bz * ib
    kappax = (bx * np.gradient(bx, axis=1) / dx_de +
              bz * np.gradient(bx, axis=0) / dz_de)
    kappay = (bx * np.gradient(by, axis=1) / dx_de +
              bz * np.gradient(by, axis=0) / dz_de)
    kappaz = (bx * np.gradient(bz, axis=1) / dx_de +
              bz * np.gradient(bz, axis=0) / dz_de)

    fname = pic_run_dir + "data/vex.gda"
    x, z, vex = read_2d_fields(pic_info, fname, **kwargs)
    fname = pic_run_dir + "data/vey.gda"
    x, z, vey = read_2d_fields(pic_info, fname, **kwargs)
    fname = pic_run_dir + "data/vez.gda"
    x, z, vez = read_2d_fields(pic_info, fname, **kwargs)
    fname = pic_run_dir + "data/vix.gda"
    x, z, vix = read_2d_fields(pic_info, fname, **kwargs)
    fname = pic_run_dir + "data/viy.gda"
    x, z, viy = read_2d_fields(pic_info, fname, **kwargs)
    fname = pic_run_dir + "data/viz.gda"
    x, z, viz = read_2d_fields(pic_info, fname, **kwargs)
    fname = pic_run_dir + "data/ne.gda"
    x, z, ne = read_2d_fields(pic_info, fname, **kwargs)
    fname = pic_run_dir + "data/ni.gda"
    x, z, ni = read_2d_fields(pic_info, fname, **kwargs)
    inrho = 1.0 / (ne + ni * pic_info.mime)
    vx = (ne * vex + ni * vix * pic_info.mime) * inrho
    vy = (ne * vey + ni * viy * pic_info.mime) * inrho
    vz = (ne * vez + ni * viz * pic_info.mime) * inrho
    vdot_kappa = vx * kappax + vy * kappay + vz * kappaz

    nbands = 7
    nreduce = 16
    nxr = pic_info.nx // nreduce
    nzr = pic_info.nz // nreduce
    ntot = np.zeros((nzr, nxr))
    nhigh = np.zeros((nzr, nxr))
    fig = plt.figure(figsize=[14, 7])
    rect0 = [0.055, 0.75, 0.4, 0.20]
    hgap, vgap = 0.09, 0.025
    if species == 'e':
        nmins = [1E-1, 1E-2, 5E-3, 1E-3, 6E-5, 2E-5, 6E-6]
        nmaxs = [5E0, 1E0, 5E-1, 1E-1, 6E-3, 2E-3, 6E-4]
    else:
        nmins = [1E-1, 2E-2, 1E-2, 5E-3, 5E-4, 5E-5, 1.2E-5]
        nmaxs = [5E0, 2E0, 1E0, 5E-1, 5E-2, 5E-3, 1.2E-3]
    nmins = np.asarray(nmins) / 10
    nmaxs = np.asarray(nmaxs) / 10
    axs = []
    rects = []
    nrows = (nbands + 1) // 2
    for iband in range(nbands + 1):
        row = iband % nrows
        col = iband // nrows
        if row == 0:
            rect = np.copy(rect0)
            rect[0] += (rect[2] + hgap) * col
        ax = fig.add_axes(rect)
        ax.set_ylim([-20, 20])
        ax.tick_params(bottom=True, top=True, left=True, right=True)
        ax.tick_params(axis='x', which='minor', direction='in')
        ax.tick_params(axis='x', which='major', direction='in')
        ax.tick_params(axis='y', which='minor', direction='in')
        ax.tick_params(axis='y', which='major', direction='in')
        if row < nrows - 1:
            ax.tick_params(axis='x', labelbottom=False)
        else:
            ax.set_xlabel(r'$x/d_i$', fontsize=16)
        if col == 0:
            ax.set_ylabel(r'$z/d_i$', fontsize=16)
        ax.tick_params(labelsize=12)
        axs.append(ax)
        rects.append(np.copy(rect))
        rect[1] -= rect[3] + vgap

    band_break = 4
    for iband in range(nbands):
        print("Energy band: %d" % iband)
        if iband < band_break:
            ax = axs[iband]
            rect = rects[iband]
        else:
            ax = axs[iband + 1]
            rect = rects[iband + 1]
        fname = (pic_run_dir + "data-smooth2/n" + species + "_" + str(iband) +
                 "_" + str(tindex) + ".gda")
        nrho = np.fromfile(fname, dtype=np.float32)
        nrho = nrho.reshape((nzr, nxr))
        if iband >= 5:
            nhigh += nrho
        ntot += nrho
        nmin, nmax = nmins[iband], nmaxs[iband]
        p1 = ax.imshow(nrho + 1E-10,
                       extent=[xmin, xmax, zmin, zmax],
                       norm=LogNorm(vmin=nmin, vmax=nmax),
                       cmap=plt.cm.inferno,
                       aspect='auto',
                       origin='lower',
                       interpolation='bicubic')
        # ax.contour(x, z, Ay, colors='w', linewidths=0.5)
        if iband == 0:
            label1 = r'$n(\varepsilon < 10\varepsilon_\text{th})$'
        elif iband > 0 and iband < nbands - 1:
            label1 = (r'$n(' + str(2**(iband - 1) * 10) +
                      r'\varepsilon_\text{th} < ' + r'\varepsilon < ' +
                      str(2**iband * 10) + r'\varepsilon_\text{th})$')
        else:
            label1 = (r'$n(\varepsilon > ' + str(2**(nbands - 2) * 10) +
                      r'\varepsilon_\text{th})$')
        ax.text(0.98,
                0.87,
                label1,
                color='k',
                fontsize=16,
                bbox=dict(facecolor='w',
                          alpha=0.75,
                          edgecolor='none',
                          boxstyle="round,pad=0.1"),
                horizontalalignment='right',
                verticalalignment='center',
                transform=ax.transAxes)
        twci = math.ceil((tframe * pic_info.dt_fields) / 0.1) * 0.1
        text1 = r'$t\Omega_{ci}=' + ("{%0.0f}" % twci) + '$'
        if iband == 0:
            # ax.set_title(text1, fontsize=16)
            xpos = (rect[2] + hgap * 0.5) / rect[2]
            ax.text(xpos,
                    1.1,
                    text1,
                    color='k',
                    fontsize=16,
                    bbox=dict(facecolor='w',
                              alpha=0.75,
                              edgecolor='none',
                              boxstyle="round,pad=0.1"),
                    horizontalalignment='center',
                    verticalalignment='center',
                    transform=ax.transAxes)

        rect_cbar = np.copy(rect)
        rect_cbar[0] += rect[2] + 0.01
        rect_cbar[2] = 0.007
        cbar_ax = fig.add_axes(rect_cbar)
        cbar = fig.colorbar(p1, cax=cbar_ax, extend='both')
        cbar.ax.tick_params(labelsize=12)

    ax = axs[band_break]
    rect = rects[band_break]
    vmin, vmax = -1.0, 1.0
    knorm = 100
    p1 = ax.imshow(vdot_kappa * knorm,
                   extent=[xmin, xmax, zmin, zmax],
                   vmin=vmin,
                   vmax=vmax,
                   cmap=plt.cm.seismic,
                   aspect='auto',
                   origin='lower',
                   interpolation='bicubic')
    # ax.contour(x, z, Ay, colors='k', linewidths=0.5)
    ax.tick_params(labelsize=12)
    label1 = r'$' + str(knorm) + r'\boldsymbol{v}\cdot\boldsymbol{\kappa}$'
    ax.text(0.98,
            0.87,
            label1,
            color='w',
            fontsize=16,
            bbox=dict(facecolor='k',
                      alpha=0.5,
                      edgecolor='none',
                      boxstyle="round,pad=0.1"),
            horizontalalignment='right',
            verticalalignment='center',
            transform=ax.transAxes)
    rect_cbar = np.copy(rect)
    rect_cbar[0] += rect[2] + 0.01
    rect_cbar[2] = 0.007
    cbar_ax = fig.add_axes(rect_cbar)
    cbar = fig.colorbar(p1, cax=cbar_ax, extend='both')
    cbar.set_ticks(np.linspace(-1, 1, num=5))
    cbar.ax.tick_params(labelsize=12)

    fdir = '../img/open_bc/rho_bands_2d/' + pic_run + '/'
    mkdir_p(fdir)
    fname = (fdir + 'nrho_bands_' + species + '_' + str(tframe) + ".jpg")
    fig.savefig(fname, dpi=200)

    if show_plot:
        plt.show()
    else:
        plt.close()
def contour_tratio_beta(plot_config, show_plot=True):
    """
    Plot contour of temperature ratio and parallel plasma beta
    """
    pic_run = plot_config["pic_run"]
    pic_run_dir = plot_config["pic_run_dir"]
    species = plot_config["species"]
    tframe = plot_config["tframe"]
    picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json'
    pic_info = read_data_from_json(picinfo_fname)

    fdir = '../data/temperature_anisotropy/' + pic_run + '/'
    fname = fdir + 'ftratio_bpara_' + species + '_' + str(tframe) + '.gda'
    fdata = np.fromfile(fname, dtype=np.float32)
    nbins_tratio = int(fdata[0])
    nbins_beta = int(fdata[1])
    tratio_bins_edge = fdata[2:nbins_tratio+3]
    beta_bins_edge = fdata[nbins_tratio+3:nbins_beta+nbins_tratio+4]
    tratio_bins_mid = 0.5 * (tratio_bins_edge[1:] + tratio_bins_edge[:-1])
    dtratio = np.diff(tratio_bins_edge)
    beta_bins_mid = 0.5 * (beta_bins_edge[1:] + beta_bins_edge[:-1])
    dbeta = np.diff(beta_bins_edge)
    ftratio_beta = fdata[nbins_beta+nbins_tratio+4:]
    ftratio_beta = ftratio_beta.reshape([nbins_beta, nbins_tratio]).T
    delta = np.dot(dtratio[:, None], dbeta[None, :])
    ftratio_beta /= delta
    # ftratio_beta[ftratio_beta <= 0] = np.nan
    tratio_min = tratio_bins_mid[0]
    tratio_max = tratio_bins_mid[-1]
    beta_min = beta_bins_mid[0]
    beta_max = beta_bins_mid[-1]

    # According to Bale et al. 2009,
    # T_\perp / T_\parallel = 1 + a/(\beta_\parallel - \beta_0)^b.
    # For mirror instability threshold, (a, b, \beta_0) = (0.77, 0.76, -0.016)
    # For oblique firehose instability threshold, (a, b, \beta_0) = (-1.4, 1.0, -0.11)
    tratio_firhose = 1 - 1.4 / (beta_bins_mid + 0.11)
    tratio_mirror = 1 + 0.77 / (beta_bins_mid + 0.016)**0.76
    tratio_firhose[tratio_firhose < 0] = np.nan

    fig = plt.figure(figsize=[3.25, 2.5])
    rect = [0.18, 0.16, 0.67, 0.8]
    ax = fig.add_axes(rect)
    ax.tick_params(bottom=True, top=True, left=True, right=True)
    ax.tick_params(axis='x', which='minor', direction='in', bottom=True, top=True)
    ax.tick_params(axis='x', which='major', direction='in', bottom=True, top=True)
    ax.tick_params(axis='y', which='minor', direction='in')
    ax.tick_params(axis='y', which='major', direction='in')

    im = ax.pcolormesh(beta_bins_mid, tratio_bins_mid, ftratio_beta,
                       cmap=plt.cm.jet, norm=LogNorm(vmin=1E0, vmax=1E12))
    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.plot(beta_bins_mid, tratio_firhose, color='k', linestyle='--')
    ax.plot(beta_bins_mid, tratio_mirror, color='k', linestyle='--')
    ax.set_xlim([1E-3, 1E3])
    ax.set_ylim([1E-2, 1E2])
    ax.tick_params(labelsize=8)
    ax.set_xlabel(r'$\beta_\parallel$', fontsize=10)
    ax.set_ylabel(r'$T_\perp/T_\parallel$', fontsize=10)

    rect_cbar = np.copy(rect)
    rect_cbar[0] += rect[2] + 0.02
    rect_cbar[2] = 0.02
    cbar_ax = fig.add_axes(rect_cbar)
    cbar = fig.colorbar(im, cax=cbar_ax)
    cbar.ax.tick_params(labelsize=8)

    fdir = '../img/brazil_plot/' + pic_run + '/'
    mkdir_p(fdir)
    fname = fdir + 'tratio_bpara_' + species + '_' + str(tframe) + '.jpg'
    fig.savefig(fname, dpi=300)

    if show_plot:
        plt.show()
    else:
        plt.close()
Esempio n. 48
0
def poincare_map_hui(plot_config):
    """
    """
    run_dir = plot_config['run_dir']
    run_name = plot_config['run_name']
    tframe = plot_config['tframe']
    fname = run_dir + 'data/poincare_map_' + str(tframe) + '.h5'
    fh = h5py.File(fname, 'r')
    grp = fh['poincare_map']
    dset = grp['xpos']
    sz = dset.shape
    xpos = np.zeros(sz, dtype=dset.dtype)
    ypos = np.zeros(sz, dtype=dset.dtype)
    zpos = np.zeros(sz, dtype=dset.dtype)
    dset.read_direct(xpos)
    dset = grp['ypos']
    dset.read_direct(ypos)
    dset = grp['zpos']
    dset.read_direct(zpos)
    fh.close()
    nh, nv = 101, 1
    i = 2
    xmin, xmax = 0, 1000
    COLORS = palettable.tableau.Tableau_10.mpl_colors
    # fig = plt.figure(figsize=[14, 5])
    fig = plt.figure(figsize=[10, 5])
    rect = [0.08, 0.11, 0.9, 0.86]
    ax = fig.add_axes(rect)
    ax.set_prop_cycle('color', COLORS)
    for j in range(0, nv):
        for i in range(0, nh):
            point = j * nh + i
            # rect[1] -= rect[3] + 0.01
            color = plt.cm.jet((point + 0.5) / float(nh * nv), 1)
            cond = xpos[point, :] < xmax
            ax.scatter(xpos[point, cond],
                       zpos[point, cond],
                       marker='o',
                       s=1,
                       color=COLORS[0])
            # p1 = ax.scatter(xpos[point, 0], zpos[point, 0], s=50,
            #                 color=COLORS[1])
            # # ax.tick_params(axis='x', labelbottom=False)
            # # ax.tick_params(axis='y', labelleft=False)
    ax.tick_params(bottom=True, top=False, left=True, right=True)
    ax.tick_params(axis='x', which='minor', direction='in', top=True)
    ax.tick_params(axis='x', which='major', direction='in', top=True)
    ax.tick_params(axis='y', which='minor', direction='in')
    ax.tick_params(axis='y', which='major', direction='in')
    ax.set_xlim([0, 1000])
    ax.set_ylim([-250, 250])
    # ax.set_xlim([0, 750])
    # ax.set_ylim([-125, 125])
    ax.set_xlabel(r'$x/d_e$', fontsize=16)
    ax.set_ylabel(r'$z/d_e$', fontsize=16, labelpad=0)
    ax.tick_params(labelsize=12)

    # fdir = '../img/poincare_map/tframe_' + str(tframe) + '/'
    # mkdir_p(fdir)
    # fname = fdir + 'poincare_map_' + str(point) + '.jpg'
    fdir = '../img/poincare_map/'
    mkdir_p(fdir)
    fname = fdir + 'poincare_map_' + str(tframe) + '.jpg'
    fig.savefig(fname, dpi=400)
    # plt.close()
    plt.show()
def plot_spectrum(plot_config):
    """Plot local spectrum
    """
    pic_run_dir = plot_config["pic_run_dir"]
    spect_dir = plot_config["spect_dir"]
    species = plot_config["species"]
    mpi_size = plot_config["mpi_size"]
    mpi_sizex = plot_config["mpi_sizex"]
    mpi_sizey = plot_config["mpi_sizey"]
    mpi_sizez = plot_config["mpi_sizez"]
    num_fold = plot_config["num_fold"]
    emin = plot_config["emin"]
    emax = plot_config["emax"]
    nbins = plot_config["nbins"]
    tframe = plot_config["tframe"]
    delog = (math.log10(emax) - math.log10(emin)) / (nbins - 1)
    emin = 10**(math.log10(emin) - delog) # adjust
    ebins = np.logspace(math.log10(emin), math.log10(emax), nbins + 1)
    ebins_mid = (ebins[1:] + ebins[:-1]) * 0.5
    debins = np.diff(ebins)
    tindex = tframe * plot_config["tinterval"]
    fdir = ('/net/scratch3/xiaocanli/reconnection/NERSC_ADAM/' +
            'LOCAL-SPECTRA-NEW/')
    fname = fdir + 'spectrum_' + species + '_' + str(tindex) + '.gda'
    fspect = np.fromfile(fname, dtype=np.float32)
    fspect = fspect.reshape((-1, mpi_sizey, mpi_sizex, nbins))
    fspect /= debins
    img_dir = fdir + 'img/'
    mkdir_p(img_dir)
    if tframe < 13:
        fig = plt.figure(figsize=[7, 5])
        rect = [0.12, 0.12, 0.85, 0.85]
        ax1 = fig.add_axes(rect)
        ax1.tick_params(bottom=True, top=True, left=True, right=True)
        ax1.tick_params(axis='x', which='minor', direction='in', top='on')
        ax1.tick_params(axis='x', which='major', direction='in')
        ax1.tick_params(axis='y', which='minor', direction='in', left='on')
        ax1.tick_params(axis='y', which='major', direction='in')
        ftot = fspect[8, mpi_sizey//2, mpi_sizex//2, :]
        fth = fit_thermal_core(ebins_mid, ftot)
        fnth = ftot - fth
        ntot, etot = accumulated_particle_info(ebins, ftot)
        nth, eth = accumulated_particle_info(ebins, fth)
        nnth, enth = accumulated_particle_info(ebins, fnth)
        frac_th = "{%0.2f}" % ((nth[-1] / ntot[-1]) * 100)
        frac_nth = "{%0.2f}" % ((nnth[-1] / ntot[-1]) * 100)
        ax1.loglog(ebins_mid, ftot, linewidth=2, label='total')
        label_th = r'thermal-core $(' + frac_th + '\%)$'
        ax1.loglog(ebins_mid, fth, linewidth=1, label=label_th)
        label_nth = r'rest $(' + frac_nth + '\%)$'
        ax1.loglog(ebins_mid[nbins//4:], fnth[nbins//4:],
                   linewidth=1, label=label_nth)
        ax1.set_xlim([1E-2, 5E0])
        ax1.set_ylim([1E1, 1E7])
        ax1.tick_params(labelsize=12)
        ax1.set_xlabel(r'$\gamma - 1$', fontsize=16)
        ax1.set_ylabel(r'$f(\gamma - 1)$', fontsize=16)
        ax1.legend(loc=3, prop={'size': 16}, ncol=1,
                   shadow=False, fancybox=False, frameon=False)
        fname = img_dir + 'local_spect_' + species + '_' + str(tindex) + '.pdf'
        fig.savefig(fname)
    else:
        fdir = img_dir + 'T.' + str(tindex) + '/'
        mkdir_p(fdir)
        for iz in [7, 8]:
            for iy in range(0, mpi_sizey, 32):
                for ix in [mpi_sizex//2-1, mpi_sizex//2]:
                    fig = plt.figure(figsize=[7, 5])
                    rect = [0.12, 0.12, 0.85, 0.85]
                    ax1 = fig.add_axes(rect)
                    ax1.tick_params(bottom=True, top=True, left=True, right=True)
                    ax1.tick_params(axis='x', which='minor', direction='in', top='on')
                    ax1.tick_params(axis='x', which='major', direction='in')
                    ax1.tick_params(axis='y', which='minor', direction='in', left='on')
                    ax1.tick_params(axis='y', which='major', direction='in')
                    ftot = fspect[iz, iy, ix, :]
                    fth = fit_thermal_core(ebins_mid, ftot)
                    fnth = ftot - fth
                    ntot, etot = accumulated_particle_info(ebins, ftot)
                    nth, eth = accumulated_particle_info(ebins, fth)
                    nnth, enth = accumulated_particle_info(ebins, fnth)
                    frac_th = "{%0.2f}" % ((nth[-1] / ntot[-1]) * 100)
                    frac_nth = "{%0.2f}" % ((nnth[-1] / ntot[-1]) * 100)
                    ax1.loglog(ebins_mid, ftot, linewidth=2, label='total')
                    label_th = r'thermal-core $(' + frac_th + '\%)$'
                    ax1.loglog(ebins_mid, fth, linewidth=1, label=label_th)
                    label_nth = r'rest $(' + frac_nth + '\%)$'
                    ax1.loglog(ebins_mid[nbins//4:], fnth[nbins//4:],
                               linewidth=1, label=label_nth)
                    ax1.set_xlim([1E-2, 5E0])
                    ax1.set_ylim([1E1, 1E7])
                    ax1.tick_params(labelsize=12)
                    ax1.set_xlabel(r'$\gamma - 1$', fontsize=16)
                    ax1.set_ylabel(r'$f(\gamma - 1)$', fontsize=16)
                    ax1.legend(loc=3, prop={'size': 16}, ncol=1,
                               shadow=False, fancybox=False, frameon=False)
                    fname = (fdir + 'local_spect_' + species + '_' +
                             str(tindex) + '_ix' + str(ix) + '_iy' + str(iy) +
                             '_iz' + str(iz) + '.pdf')
                    fig.savefig(fname)
                    plt.close()
    plt.show()