def plot_charge_neutrality(pic_info, current_time):
    """Plot compression related terms.

    Args:
        pic_info: namedtuple for the PIC simulation information.
        species: 'e' for electrons, 'i' for ions.
        current_time: current time frame.
    """
    kwargs = {
        "current_time": current_time,
        "xl": 0,
        "xr": 400,
        "zb": -100,
        "zt": 100
    }
    x, z, ne = read_2d_fields(pic_info, "../../data/ne.gda", **kwargs)
    x, z, ni = read_2d_fields(pic_info, "../../data/ni.gda", **kwargs)
    x, z, Ay = read_2d_fields(pic_info, "../../data/Ay.gda", **kwargs)
    nx, = x.shape
    nz, = z.shape
    width = 0.75
    height = 0.76
    xs = 0.12
    ys = 0.95 - height
    gap = 0.05
    fig = plt.figure(figsize=[10, 4])
    ax1 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": -1, "vmax": 1}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p1, cbar1 = plot_2d_contour(x, z,
                                (ni - ne) / (ne + ni), ax1, fig, **kwargs_plot)
    # p1.set_cmap(cmaps.inferno)
    p1.set_cmap(plt.cm.seismic)
    ax1.contour(
        x[0:nx:xstep],
        z[0:nz:zstep],
        Ay[0:nz:zstep, 0:nx:xstep],
        colors='black',
        linewidths=0.5)
    ax1.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=24)
    ax1.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=24)
    ax1.tick_params(labelsize=20)
    cbar1.ax.set_ylabel(r'$(n_i-n_e)/(n_i+n_e)$', fontdict=font, fontsize=24)
    # cbar1.set_ticks(np.arange(-0.1, 0.15, 0.1))
    cbar1.ax.tick_params(labelsize=20)
    if not os.path.isdir('../img/'):
        os.makedirs('../img/')
    fname = '../img/q_' + str(current_time).zfill(3) + '.jpg'
    fig.savefig(fname, dpi=200)
    plt.show()
def plot_charge_neutrality(pic_info, current_time):
    """Plot compression related terms.

    Args:
        pic_info: namedtuple for the PIC simulation information.
        species: 'e' for electrons, 'i' for ions.
        current_time: current time frame.
    """
    kwargs = {
        "current_time": current_time,
        "xl": 0,
        "xr": 400,
        "zb": -100,
        "zt": 100
    }
    x, z, ne = read_2d_fields(pic_info, "../../data/ne.gda", **kwargs)
    x, z, ni = read_2d_fields(pic_info, "../../data/ni.gda", **kwargs)
    x, z, Ay = read_2d_fields(pic_info, "../../data/Ay.gda", **kwargs)
    nx, = x.shape
    nz, = z.shape
    width = 0.75
    height = 0.76
    xs = 0.12
    ys = 0.95 - height
    gap = 0.05
    fig = plt.figure(figsize=[10, 4])
    ax1 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": -1, "vmax": 1}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p1, cbar1 = plot_2d_contour(x, z, (ni - ne) / (ne + ni), ax1, fig,
                                **kwargs_plot)
    # p1.set_cmap(cmaps.inferno)
    p1.set_cmap(plt.cm.seismic)
    ax1.contour(x[0:nx:xstep],
                z[0:nz:zstep],
                Ay[0:nz:zstep, 0:nx:xstep],
                colors='black',
                linewidths=0.5)
    ax1.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=24)
    ax1.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=24)
    ax1.tick_params(labelsize=20)
    cbar1.ax.set_ylabel(r'$(n_i-n_e)/(n_i+n_e)$', fontdict=font, fontsize=24)
    # cbar1.set_ticks(np.arange(-0.1, 0.15, 0.1))
    cbar1.ax.tick_params(labelsize=20)
    if not os.path.isdir('../img/'):
        os.makedirs('../img/')
    fname = '../img/q_' + str(current_time).zfill(3) + '.jpg'
    fig.savefig(fname, dpi=200)
    plt.show()
示例#3
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 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()
示例#5
0
def plot_ptl_traj(filename, pic_info, species, iptl, mint, maxt):
    """Plot particle trajectory information.

    Args:
        filename: the filename to read the data.
        pic_info: namedtuple for the PIC simulation information.
        species: particle species. 'e' for electron. 'i' for ion.
        iptl: particle ID.
        mint, maxt: minimum and maximum time for plotting.
    """
    ptl_traj = read_traj_data(filename)
    gama = np.sqrt(ptl_traj.ux**2 + ptl_traj.uy**2 + ptl_traj.uz**2 + 1.0)
    mime = pic_info.mime
    # de scale to di scale
    ptl_x = ptl_traj.x / math.sqrt(mime)
    ptl_y = ptl_traj.y / math.sqrt(mime)
    ptl_z = ptl_traj.z / math.sqrt(mime)
    # 1/wpe to 1/wci
    t = ptl_traj.t * pic_info.dtwci / pic_info.dtwpe

    xl, xr = 0, 50
    zb, zt = -20, 20
    kwargs = {"current_time": 65, "xl": xl, "xr": xr, "zb": zb, "zt": zt}
    fname = "../../data/uex.gda"
    x, z, uex = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/ne.gda"
    x, z, ne = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/uix.gda"
    x, z, uix = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/ni.gda"
    x, z, ni = read_2d_fields(pic_info, fname, **kwargs)
    ux = (uex * ne + uix * ni * pic_info.mime) / (ne + ni * pic_info.mime)
    x, z, Ay = read_2d_fields(pic_info, "../../data/Ay.gda", **kwargs)
    nx, = x.shape
    nz, = z.shape

    width = 8.0
    height = 8.0
    fig = plt.figure(figsize=[width, height])
    w1, h1 = 0.74, 0.42
    xs, ys = 0.13, 0.98 - h1
    ax1 = fig.add_axes([xs, ys, w1, h1])
    kwargs_plot = {
        "xstep": 2,
        "zstep": 2,
        "is_log": False,
        "vmin": -1.0,
        "vmax": 1.0
    }
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    va = 0.2  # Alfven speed
    im1, cbar1 = plot_2d_contour(x, z, ux / va, ax1, fig, **kwargs_plot)
    im1.set_cmap(plt.cm.seismic)
    ax1.contour(x[0:nx:xstep],
                z[0:nz:zstep],
                Ay[0:nz:zstep, 0:nx:xstep],
                colors='black',
                linewidths=0.5)
    ax1.tick_params(labelsize=20)
    ax1.tick_params(axis='x', labelbottom='off')
    ax1.set_xlim([xl, xr])
    ax1.set_ylim([zb, zt])
    ax1.set_ylabel(r'$z/d_i$', fontdict=font)
    cbar1.ax.tick_params(labelsize=20)
    cbar1.ax.set_ylabel(r'$u_x/V_A$', fontdict=font, fontsize=24)
    tstop = 1990
    p1 = ax1.plot(ptl_x[0:tstop], ptl_z[0:tstop], linewidth=2, color='k')

    gap = 0.04
    ys -= h1 + gap
    ax2 = fig.add_axes([xs, ys, w1 * 0.98 - 0.05 / width, h1])
    eth = pic_info.vthi**2 * 3
    p2 = ax2.plot(ptl_x[0:tstop], (gama[0:tstop] - 1.0) / eth,
                  color='k',
                  linewidth=2)
    ax2.set_xlabel(r'$x/d_i$', fontdict=font)
    ax2.set_ylabel(r'$E/E_{\text{thi}}$', fontdict=font)
    ax2.tick_params(labelsize=20)
    # ax2.tick_params(axis='x', labelbottom='off')
    xmin, xmax = ax1.get_xlim()
    ax2.set_xlim([xmin, xmax])

    if not os.path.isdir('../img/'):
        os.makedirs('../img/')
    fname = '../img/' + 'traj_' + species + '_' + str(iptl).zfill(4) + '_1.jpg'
    fig.savefig(fname, dpi=300)

    plt.show()
def plot_jy_guide():
    """Plot jy contour for the runs with guide field

    Args:
        run_name: the name of this run.
        root_dir: the root directory of this run.
        pic_info: PIC simulation information in a namedtuple.
    """
    cts = [40, 20, 20, 20, 30]
    var = 'ez'
    vmin, vmax = -0.2, 0.2
    ticks = np.arange(-0.2, 0.25, 0.1)
    cmap = plt.cm.get_cmap('seismic')
    label = r'$E_z$'
    # # cmap = cmaps.inferno
    # var = 'jy'
    # vmin, vmax = -0.2, 0.5
    # ticks = np.arange(-0.2, 0.6, 0.2)
    # cmap = plt.cm.get_cmap('jet')
    # label = r'$j_y$'
    # var = 'by'
    # vmin, vmax = -0.2, 0.5
    # ticks = np.arange(-0.2, 0.6, 0.2)
    # cmap = plt.cm.get_cmap('jet')
    # label = r'$B_y$'
    base_dirs, run_names = guide_field_runs()
    bdir = base_dirs[0]
    run_name = run_names[0]
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    xl, xr = 50, 150
    kwargs = {"current_time": cts[0], "xl": xl, "xr": xr, "zb": -10, "zt": 10}
    fname = bdir + 'data/' + var + '.gda'
    x, z, jy1 = read_2d_fields(pic_info, fname, **kwargs)
    fname = bdir + 'data/Ay.gda'
    x, z, Ay1 = read_2d_fields(pic_info, fname, **kwargs)
    kwargs = {"current_time": cts[1], "xl": xl, "xr": xr, "zb": -10, "zt": 10}
    bdir = base_dirs[1]
    run_name = run_names[1]
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    fname = bdir + 'data/' + var + '.gda'
    x, z, jy2 = read_2d_fields(pic_info, fname, **kwargs)
    fname = bdir + 'data/Ay.gda'
    x, z, Ay2 = read_2d_fields(pic_info, fname, **kwargs)
    kwargs = {"current_time": cts[2], "xl": xl, "xr": xr, "zb": -10, "zt": 10}
    bdir = base_dirs[2]
    run_name = run_names[2]
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    fname = bdir + 'data/' + var + '.gda'
    x, z, jy3 = read_2d_fields(pic_info, fname, **kwargs)
    fname = bdir + 'data/Ay.gda'
    x, z, Ay3 = read_2d_fields(pic_info, fname, **kwargs)
    kwargs = {"current_time": cts[3], "xl": xl, "xr": xr, "zb": -10, "zt": 10}
    bdir = base_dirs[3]
    run_name = run_names[3]
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    fname = bdir + 'data/' + var + '.gda'
    x, z, jy4 = read_2d_fields(pic_info, fname, **kwargs)
    fname = bdir + 'data/Ay.gda'
    x, z, Ay4 = read_2d_fields(pic_info, fname, **kwargs)

    kwargs = {"current_time": cts[4], "xl": xl, "xr": xr, "zb": -10, "zt": 10}
    bdir = base_dirs[4]
    run_name = run_names[4]
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    fname = bdir + 'data/' + var + '.gda'
    x, z, jy5 = read_2d_fields(pic_info, fname, **kwargs)
    fname = bdir + 'data/Ay.gda'
    x, z, Ay5 = read_2d_fields(pic_info, fname, **kwargs)
    nx, = x.shape
    nz, = z.shape

    width = 0.8
    height = 0.16
    xs = 0.1
    ys = 0.98 - height
    gap = 0.025
    fig = plt.figure(figsize=[10, 8])
    ax1 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": vmin, "vmax": vmax}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p1, cbar1 = plot_2d_contour(x, z, jy1, ax1, fig, **kwargs_plot)
    p1.set_cmap(cmap)
    ax1.contour(
        x[0:nx:xstep],
        z[0:nz:zstep],
        Ay1[0:nz:zstep, 0:nx:xstep],
        colors='black',
        linewidths=0.5)
    ax1.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=20)
    ax1.tick_params(labelsize=16)
    cbar1.ax.set_ylabel(label, fontdict=font, fontsize=20)
    cbar1.set_ticks(ticks)
    cbar1.ax.tick_params(labelsize=16)
    ax1.tick_params(axis='x', labelbottom='off')

    ys -= height + gap
    ax2 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": vmin, "vmax": vmax}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p2, cbar2 = plot_2d_contour(x, z, jy2, ax2, fig, **kwargs_plot)
    p2.set_cmap(cmap)
    ax2.contour(
        x[0:nx:xstep],
        z[0:nz:zstep],
        Ay2[0:nz:zstep, 0:nx:xstep],
        colors='black',
        linewidths=0.5)
    ax2.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=20)
    ax2.tick_params(labelsize=16)
    cbar2.ax.set_ylabel(label, fontdict=font, fontsize=20)
    cbar2.set_ticks(ticks)
    cbar2.ax.tick_params(labelsize=16)
    ax2.tick_params(axis='x', labelbottom='off')

    ys -= height + gap
    ax3 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": vmin, "vmax": vmax}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p3, cbar3 = plot_2d_contour(x, z, jy3, ax3, fig, **kwargs_plot)
    p3.set_cmap(cmap)
    ax3.contour(
        x[0:nx:xstep],
        z[0:nz:zstep],
        Ay3[0:nz:zstep, 0:nx:xstep],
        colors='black',
        linewidths=0.5)
    # ax3.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=20)
    ax3.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=20)
    ax3.tick_params(labelsize=16)
    cbar3.ax.set_ylabel(label, fontdict=font, fontsize=20)
    cbar3.set_ticks(ticks)
    cbar3.ax.tick_params(labelsize=16)
    ax3.tick_params(axis='x', labelbottom='off')

    ys -= height + gap
    ax4 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": vmin, "vmax": vmax}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p4, cbar4 = plot_2d_contour(x, z, jy4, ax4, fig, **kwargs_plot)
    p4.set_cmap(cmap)
    ax4.contour(
        x[0:nx:xstep],
        z[0:nz:zstep],
        Ay4[0:nz:zstep, 0:nx:xstep],
        colors='black',
        linewidths=0.5)
    # ax4.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=20)
    ax4.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=20)
    ax4.tick_params(labelsize=16)
    cbar4.ax.set_ylabel(label, fontdict=font, fontsize=20)
    cbar4.set_ticks(ticks)
    cbar4.ax.tick_params(labelsize=16)
    ax4.tick_params(axis='x', labelbottom='off')

    ys -= height + gap
    ax5 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": vmin, "vmax": vmax}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p5, cbar5 = plot_2d_contour(x, z, jy5, ax5, fig, **kwargs_plot)
    p5.set_cmap(cmap)
    ax5.contour(
        x[0:nx:xstep],
        z[0:nz:zstep],
        Ay5[0:nz:zstep, 0:nx:xstep],
        colors='black',
        linewidths=0.5)
    ax5.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=20)
    ax5.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=20)
    ax5.tick_params(labelsize=16)
    cbar5.ax.set_ylabel(label, fontdict=font, fontsize=20)
    cbar5.set_ticks(ticks)
    cbar5.ax.tick_params(labelsize=16)

    axs = [ax1, ax2, ax3, ax4, ax5]
    bgs = [0.0, 0.2, 0.5, 1.0, 4.0]
    for ax, bg in zip(axs, bgs):
        tname = r'$B_g = ' + str(bg) + '$'
        ax.text(
            0.02,
            0.8,
            tname,
            color='k',
            fontsize=24,
            bbox=dict(
                facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
            horizontalalignment='left',
            verticalalignment='center',
            transform=ax.transAxes)

    fname = '../img/thesis/' + var + '.jpg'
    fig.savefig(fname, dpi=200)

    plt.show()
def plot_jy_multi():
    """Plot the jy for multiple runs
    """
    base_dirs, run_names = ApJ_long_paper_runs()
    bdir = base_dirs[0]
    run_name = run_names[0]
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    kwargs = {"current_time": 11, "xl": 0, "xr": 200, "zb": -10, "zt": 10}
    fname = bdir + 'data/jy.gda'
    x, z, jy1 = read_2d_fields(pic_info, fname, **kwargs)
    fname = bdir + 'data/Ay.gda'
    x, z, Ay1 = read_2d_fields(pic_info, fname, **kwargs)
    bdir = base_dirs[1]
    run_name = run_names[1]
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    fname = bdir + 'data/jy.gda'
    x, z, jy2 = read_2d_fields(pic_info, fname, **kwargs)
    fname = bdir + 'data/Ay.gda'
    x, z, Ay2 = read_2d_fields(pic_info, fname, **kwargs)
    bdir = base_dirs[3]
    run_name = run_names[3]
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    fname = bdir + 'data/jy.gda'
    x, z, jy3 = read_2d_fields(pic_info, fname, **kwargs)
    fname = bdir + 'data/Ay.gda'
    x, z, Ay3 = read_2d_fields(pic_info, fname, **kwargs)
    nx, = x.shape
    nz, = z.shape

    width = 0.74
    height = 0.25
    xs = 0.13
    ys = 0.97 - height
    gap = 0.05
    fig = plt.figure(figsize=[7, 5])
    ax1 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": -0.5, "vmax": 0.5}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p1, cbar1 = plot_2d_contour(x, z, jy1, ax1, fig, **kwargs_plot)
    p1.set_cmap(plt.cm.get_cmap('seismic'))
    ax1.contour(
        x[0:nx:xstep],
        z[0:nz:zstep],
        Ay1[0:nz:zstep, 0:nx:xstep],
        colors='black',
        linewidths=0.5)
    ax1.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=20)
    ax1.tick_params(labelsize=16)
    cbar1.ax.set_ylabel(r'$j_y$', fontdict=font, fontsize=20)
    cbar1.set_ticks(np.arange(-0.4, 0.5, 0.2))
    cbar1.ax.tick_params(labelsize=16)
    ax1.tick_params(axis='x', labelbottom='off')

    ys -= height + gap
    ax2 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": -0.5, "vmax": 0.5}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p2, cbar2 = plot_2d_contour(x, z, jy2, ax2, fig, **kwargs_plot)
    p2.set_cmap(plt.cm.get_cmap('seismic'))
    ax2.contour(
        x[0:nx:xstep],
        z[0:nz:zstep],
        Ay2[0:nz:zstep, 0:nx:xstep],
        colors='black',
        linewidths=0.5)
    ax2.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=20)
    ax2.tick_params(labelsize=16)
    cbar2.ax.set_ylabel(r'$j_y$', fontdict=font, fontsize=20)
    cbar2.set_ticks(np.arange(-0.4, 0.5, 0.2))
    cbar2.ax.tick_params(labelsize=16)
    ax2.tick_params(axis='x', labelbottom='off')

    ys -= height + gap
    ax3 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": -1.0, "vmax": 1.0}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p3, cbar3 = plot_2d_contour(x, z, jy3, ax3, fig, **kwargs_plot)
    p3.set_cmap(plt.cm.get_cmap('seismic'))
    ax3.contour(
        x[0:nx:xstep],
        z[0:nz:zstep],
        Ay3[0:nz:zstep, 0:nx:xstep],
        colors='black',
        linewidths=0.5)
    ax3.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=20)
    ax3.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=20)
    ax3.tick_params(labelsize=16)
    cbar3.ax.set_ylabel(r'$j_y$', fontdict=font, fontsize=20)
    cbar3.set_ticks(np.arange(-1.0, 1.1, 0.5))
    cbar3.ax.tick_params(labelsize=16)

    ax1.text(
        0.02,
        0.78,
        r'R8 $\beta_e=0.2$',
        color='k',
        fontsize=20,
        bbox=dict(
            facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
        horizontalalignment='left',
        verticalalignment='center',
        transform=ax1.transAxes)
    ax2.text(
        0.02,
        0.78,
        r'R7 $\beta_e=0.07$',
        color='k',
        fontsize=20,
        bbox=dict(
            facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
        horizontalalignment='left',
        verticalalignment='center',
        transform=ax2.transAxes)
    ax3.text(
        0.02,
        0.78,
        r'R6 $\beta_e=0.007$',
        color='k',
        fontsize=20,
        bbox=dict(
            facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
        horizontalalignment='left',
        verticalalignment='center',
        transform=ax3.transAxes)

    fig.savefig('../img/jy_multi.jpg', dpi=300)

    plt.show()
示例#8
0
def cal_phi_parallel(pic_info):
    """Calculate parallel potential defined by Jan Egedal.

    Args:
        pic_info: namedtuple for the PIC simulation information.
    """
    kwargs = {"current_time": 160, "xl": 0, "xr": 200, "zb": -50, "zt": 50}
    x, z, Ay = contour_plots.read_2d_fields(pic_info, "../data/Ay.gda",
                                            **kwargs)
    x, z, Bx = contour_plots.read_2d_fields(pic_info, "../data/bx.gda",
                                            **kwargs)
    x, z, By = contour_plots.read_2d_fields(pic_info, "../data/by.gda",
                                            **kwargs)
    xarr, zarr, Bz = contour_plots.read_2d_fields(pic_info, "../data/bz.gda",
                                                  **kwargs)
    x, z, Ex = contour_plots.read_2d_fields(pic_info, "../data/ex.gda",
                                            **kwargs)
    x, z, Ey = contour_plots.read_2d_fields(pic_info, "../data/ey.gda",
                                            **kwargs)
    x, z, Ez = contour_plots.read_2d_fields(pic_info, "../data/ez.gda",
                                            **kwargs)
    absB = np.sqrt(Bx * Bx + By * By + Bz * Bz)
    Epara = (Ex * Bx + Ey * By + Ez * Bz) / absB
    etot = np.sqrt(Ex * Ex + Ey * Ey + Ez * Ez)
    nx, = x.shape
    nz, = z.shape
    print nx, nz

    width = 0.78
    height = 0.75
    xs = 0.14
    xe = 0.94 - xs
    ys = 0.9 - height
    #fig = plt.figure(figsize=(7,5))
    fig = plt.figure(figsize=(7, 2))
    ax1 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 2, "zstep": 2}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    #p1, cbar1 = contour_plots.plot_2d_contour(xarr, zarr, etot,
    #        ax1, fig, **kwargs_plot)
    #p1.set_cmap(plt.cm.seismic)
    cs = ax1.contour(xarr[0:nx:xstep],
                     zarr[0:nz:zstep],
                     Ay[0:nz:zstep, 0:nx:xstep],
                     colors='white',
                     linewidths=0.5,
                     levels=np.arange(150, 252, 1))
    xlist = []
    zlist = []
    dx_di = pic_info.dx_di
    dz_di = pic_info.dz_di
    fig, ax = plt.subplots()
    #fig, ax2 = plt.subplots()
    phi_parallel = np.zeros((nz, nx))
    #for csp in cs.collections[65:70]:
    for csp in cs.collections[0:10]:
        for p in csp.get_paths():
            v = p.vertices
            x = v[:, 0]
            z = v[:, 1]
            if (math.fabs(x[0] - x[-1]) > dx_di
                    or math.fabs(z[0] - z[-1]) > dz_di):
                xlist.extend(x)
                zlist.extend(z)
                lenx = len(x)
                phip = np.zeros(lenx)
                epara = np.zeros(lenx)
                if (x[-1] < x[0]):
                    x = x[::-1]
                    z = z[::-1]
                for i in range(1, lenx):
                    dx = x[i] - x[i - 1]
                    dz = z[i] - z[i - 1]
                    indices_bl, indices_tr, delta = grid_indices(
                        x[i] - xarr[0], 0, z[i] - zarr[0], nx, 1, nz, dx_di, 1,
                        dz_di)
                    ix1 = indices_bl[0]
                    iz1 = indices_bl[2]
                    ix2 = indices_tr[0]
                    iz2 = indices_tr[2]
                    offsetx = delta[0]
                    offsetz = delta[2]
                    v1 = (1.0 - offsetx) * (1.0 - offsetz)
                    v2 = offsetx * (1.0 - offsetz)
                    v3 = offsetx * offsetz
                    v4 = (1.0 - offsetx) * offsetz
                    bx = Bx[iz1, ix1] * v1 + Bx[iz1, ix2] * v2 + Bx[
                        iz2, ix2] * v3 + Bx[iz2, ix1] * v4
                    by = By[iz1, ix1] * v1 + By[iz1, ix2] * v2 + By[
                        iz2, ix2] * v3 + By[iz2, ix1] * v4
                    bz = Bz[iz1, ix1] * v1 + Bz[iz1, ix2] * v2 + Bz[
                        iz2, ix2] * v3 + Bz[iz2, ix1] * v4
                    ex = Ex[iz1, ix1] * v1 + Ex[iz1, ix2] * v2 + Ex[
                        iz2, ix2] * v3 + Ex[iz2, ix1] * v4
                    ey = Ey[iz1, ix1] * v1 + Ey[iz1, ix2] * v2 + Ey[
                        iz2, ix2] * v3 + Ey[iz2, ix1] * v4
                    ez = Ez[iz1, ix1] * v1 + Ez[iz1, ix2] * v2 + Ez[
                        iz2, ix2] * v3 + Ez[iz2, ix1] * v4
                    epara[i] = Epara[iz1,ix1]*v1 + Epara[iz1,ix2]*v2 + \
                            Epara[iz2,ix2]*v3 + Epara[iz2,ix1]*v4
                    dy = by * dx / bx
                    #btot = math.sqrt(bx*bx + by*by + bz*bz)
                    #ds = math.sqrt(dx*dx + dy*dy + dz*dz)
                    #print math.acos((bx*dx + by*dy + bz*dz) / (btot*ds))
                    phip[i] = phip[i - 1] + ex * dx + ey * dy + ez * dz
                    ix = int(math.floor(x[i] / dx_di))
                    iz = int(math.floor((z[i] - zarr[0]) / dz_di))
                    phi_parallel[iz, ix] = phip[i]
                ax.plot(x, phip)
                #ax.plot(x, epara)
    print np.max(phi_parallel), np.min(phi_parallel)
    fig = plt.figure(figsize=(7, 2))
    ax1 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 2, "zstep": 2}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p1, cbar1 = contour_plots.plot_2d_contour(xarr, zarr, phi_parallel, ax1,
                                              fig, **kwargs_plot)
    p1.set_cmap(plt.cm.seismic)
    plt.show()
示例#9
0
def parallel_potential(pic_info):
    """Calculate parallel potential defined by Jan Egedal.

    Args:
        pic_info: namedtuple for the PIC simulation information.
    """
    kwargs = {"current_time": 40, "xl": 0, "xr": 200, "zb": -50, "zt": 50}
    x, z, Ay = contour_plots.read_2d_fields(pic_info, "../data/Ay.gda",
                                            **kwargs)
    x, z, Ex = contour_plots.read_2d_fields(pic_info, "../data/ex.gda",
                                            **kwargs)
    x, z, Ey = contour_plots.read_2d_fields(pic_info, "../data/ey.gda",
                                            **kwargs)
    x, z, Ez = contour_plots.read_2d_fields(pic_info, "../data/ez.gda",
                                            **kwargs)
    x, z, Bx = contour_plots.read_2d_fields(pic_info, "../data/bx.gda",
                                            **kwargs)
    x, z, By = contour_plots.read_2d_fields(pic_info, "../data/by.gda",
                                            **kwargs)
    xarr, zarr, Bz = contour_plots.read_2d_fields(pic_info, "../data/bz.gda",
                                                  **kwargs)
    absB = np.sqrt(Bx**2 + By**2 + Bz**2)
    Epara = (Ex * Bx + Ey * By + Ez * Bz) / absB
    nx, = x.shape
    nz, = z.shape

    phi_parallel = np.zeros((nz, nx))
    dx_di = pic_info.dx_di
    dz_di = pic_info.dz_di
    #deltas = math.sqrt(dx_di**2 + dz_di**2)
    #hds = deltas * 0.5
    hmax = dx_di * 100
    h = hmax / 4.0
    # Cash-Karp parameters
    a = [0.0, 0.2, 0.3, 0.6, 1.0, 0.875]
    b = [[], [0.2], [3.0 / 40.0, 9.0 / 40.0], [0.3, -0.9, 1.2],
         [-11.0 / 54.0, 2.5, -70.0 / 27.0, 35.0 / 27.0],
         [
             1631.0 / 55296.0, 175.0 / 512.0, 575.0 / 13824.0,
             44275.0 / 110592.0, 253.0 / 4096.0
         ]]
    c = [37.0 / 378.0, 0.0, 250.0 / 621.0, 125.0 / 594.0, 0.0, 512.0 / 1771.0]
    dc = [
        c[0] - 2825.0 / 27648.0, c[1] - 0.0, c[2] - 18575.0 / 48384.0,
        c[3] - 13525.0 / 55296.0, c[4] - 277.00 / 14336.0, c[5] - 0.25
    ]

    def F(t, x, z):
        indices_bl, indices_tr, delta = grid_indices(x, 0, z, nx, 1, nz, dx_di,
                                                     1, dz_di)
        ix1 = indices_bl[0]
        iz1 = indices_bl[2]
        ix2 = indices_tr[0]
        iz2 = indices_tr[2]
        offsetx = delta[0]
        offsetz = delta[2]
        v1 = (1.0 - offsetx) * (1.0 - offsetz)
        v2 = offsetx * (1.0 - offsetz)
        v3 = offsetx * offsetz
        v4 = (1.0 - offsetx) * offsetz
        if (ix1 < nx and ix2 < nx and iz1 < nz and iz2 < nz):
            bx = Bx[iz1, ix1] * v1 + Bx[iz1, ix2] * v2 + Bx[
                iz2, ix2] * v3 + Bx[iz2, ix1] * v4
            by = By[iz1, ix1] * v1 + By[iz1, ix2] * v2 + By[
                iz2, ix2] * v3 + By[iz2, ix1] * v4
            bz = Bz[iz1, ix1] * v1 + Bz[iz1, ix2] * v2 + Bz[
                iz2, ix2] * v3 + Bz[iz2, ix1] * v4
            ex = Ex[iz1, ix1] * v1 + Ex[iz1, ix2] * v2 + Ex[
                iz2, ix2] * v3 + Ex[iz2, ix1] * v4
            ey = Ey[iz1, ix1] * v1 + Ey[iz1, ix2] * v2 + Ey[
                iz2, ix2] * v3 + Ey[iz2, ix1] * v4
            ez = Ez[iz1, ix1] * v1 + Ez[iz1, ix2] * v2 + Ez[
                iz2, ix2] * v3 + Ez[iz2, ix1] * v4
            absB = math.sqrt(bx**2 + bz**2)
            deltax1 = bx / absB
            deltay1 = by * deltax1 / bx
            deltaz1 = bz / absB
        else:
            ex = 0
            ey = 0
            ez = 0
            deltax1 = 0
            deltay1 = 0
            deltaz1 = 0
        return (deltax1, deltay1, deltaz1, ex, ey, ez)

    tol = 1e-5

    for i in range(2900, 3300):
        print i
        x0 = xarr[i] - xarr[0]
        #for k in range(0,nz,8):
        for k in range(950, 1098):
            z0 = zarr[k] - zarr[0]
            y = [x0, z0]
            nstep = 0
            xlist = [x0]
            zlist = [z0]
            t = 0
            x = x0
            z = z0
            while (x >= 0 and x <= (xarr[-1] - xarr[0]) and z >= 0 and z <=
                   (zarr[-1] - zarr[0]) and t < 4E2):
                # Compute k[i] function values.
                kx = [None] * 6
                ky = [None] * 6
                kz = [None] * 6
                kx[0], ky[0], kz[0], ex0, ey0, ez0 = F(t, x, z)
                kx[1], ky[1], kz[1], ex1, ey1, ez1 = F(
                    t + a[1] * h, x + h * (kx[0] * b[1][0]),
                    z + h * (kz[0] * b[1][0]))
                kx[2], ky[2], kz[2], ex2, ey2, ez2 = F(
                    t + a[2] * h, x + h * (kx[0] * b[2][0] + kx[1] * b[2][1]),
                    z + h * (kz[0] * b[2][0] + kz[1] * b[2][1]))
                kx[3], ky[3], kz[3], ex3, ey3, ez3 = F(
                    t + a[3] * h, x + h *
                    (kx[0] * b[3][0] + kx[1] * b[3][1] + kx[2] * b[3][2]), z +
                    h * (kz[0] * b[3][0] + kz[1] * b[3][1] + kz[2] * b[3][2]))
                kx[4], ky[4], kz[4], ex4, ey4, ez4 = F(
                    t + a[4] * h, x + h * (kx[0] * b[4][0] + kx[1] * b[4][1] +
                                           kx[2] * b[4][2] + kx[3] * b[4][3]),
                    z + h * (kz[0] * b[4][0] + kz[1] * b[4][1] +
                             kz[2] * b[4][2] + kz[3] * b[4][3]))
                kx[5], ky[5], kz[5], ex5, ey5, ez5 = F(
                    t + a[5] * h, x + h *
                    (kx[0] * b[5][0] + kx[1] * b[5][1] + kx[2] * b[5][2] +
                     kx[3] * b[5][3] + kx[4] * b[5][4]), z + h *
                    (kz[0] * b[5][0] + kz[1] * b[5][1] + kz[2] * b[5][2] +
                     kz[3] * b[5][3] + kz[4] * b[5][4]))

                # Estimate current error and current maximum error.
                E = norm([
                    h * (kx[0] * dc[0] + kx[1] * dc[1] + kx[2] * dc[2] +
                         kx[3] * dc[3] + kx[4] * dc[4] + kx[5] * dc[5]),
                    h * (kz[0] * dc[0] + kz[1] * dc[1] + kz[2] * dc[2] +
                         kz[3] * dc[3] + kz[4] * dc[4] + kz[5] * dc[5])
                ])
                Emax = tol * max(norm(y), 1.0)

                # Update solution if error is OK.
                if E < Emax:
                    t += h
                    dx = h * (kx[0] * c[0] + kx[1] * c[1] + kx[2] * c[2] +
                              kx[3] * c[3] + kx[4] * c[4] + kx[5] * c[5])
                    dy = h * (ky[0] * c[0] + ky[1] * c[1] + ky[2] * c[2] +
                              ky[3] * c[3] + ky[4] * c[4] + ky[5] * c[5])
                    dz = h * (kz[0] * c[0] + kz[1] * c[1] + kz[2] * c[2] +
                              kz[3] * c[3] + kz[4] * c[4] + kz[5] * c[5])
                    y[0] += dx
                    y[1] += dz
                    x = y[0]
                    z = y[1]
                    xlist.append(x)
                    zlist.append(z)
                    phi_parallel[k, i] += \
                            h*(kx[0]*c[0]*ex0+kx[1]*c[1]*ex1+kx[2]*c[2]*ex2+ \
                            kx[3]*c[3]*ex3+kx[4]*c[4]*ex4+kx[5]*c[5]*ex5) + \
                            h*(ky[0]*c[0]*ey0+ky[1]*c[1]*ey1+ky[2]*c[2]*ey2+ \
                            ky[3]*c[3]*ey3+ky[4]*c[4]*ey4+ky[5]*c[5]*ey5) + \
                            h*(kz[0]*c[0]*ez0+kz[1]*c[1]*ez1+kz[2]*c[2]*ez2+ \
                            kz[3]*c[3]*ez3+kz[4]*c[4]*ez4+kz[5]*c[5]*ez5)
                    #out += [(t, list(y))]

                # Update step size
                if E > 0.0:
                    h = min(hmax, 0.85 * h * (Emax / E)**0.2)
            if (t > 395):
                phi_parallel[k, i] = 0


#
#                deltax1, deltaz1, x1, z1, ex1, ez1 = middle_step_rk4(x, z, nx, nz,
#                        dx_di, dz_di, Bx, Bz, Ex, Ez, hds)
#                deltax2, deltaz2, x2, z2, ex2, ez2 = middle_step_rk4(x1, z1, nx, nz,
#                        dx_di, dz_di, Bx, Bz, Ex, Ez, hds)
#                deltax3, deltaz3, x3, z3, ex3, ez3 = middle_step_rk4(x, z, nx, nz,
#                        dx_di, dz_di, Bx, Bz, Ex, Ez, deltas)
#                deltax4, deltaz4, x4, z4, ex4, ez4 = middle_step_rk4(x, z, nx, nz,
#                        dx_di, dz_di, Bx, Bz, Ex, Ez, hds)
#
#                deltax = deltas/6 * (deltax1 + 2*deltax2 + 2*deltax3 + deltax4)
#                deltaz = deltas/6 * (deltaz1 + 2*deltaz2 + 2*deltaz3 + deltaz4)
#                x += deltax
#                z += deltaz
#                total_lengh += deltas
#                xlist.append(x)
#                zlist.append(z)
#                nstep += 1
#                phi_parallel[k, i] += deltas/6 * (ex1*deltax1 + ez1*deltaz1 +
#                        2.0*ex2*deltax2 + 2.0*ez2*deltaz2 +
#                        2.0*ex3*deltax3 + 2.0*ez3*deltaz3 +
#                        ex4*deltax4 + ez4*deltaz4)
#                length = math.sqrt((x-x0)**2 + (z-z0)**2)
#                if (length < dx_di and nstep > 20):
#                    phi_parallel[k, i] = 0
#                    break
#            #print k, nstep, total_lengh
#    phi_parallel = np.fromfile('phi_parallel.dat')
#    phi_parallel.tofile('phi_parallel.dat')
#    print np.max(phi_parallel), np.min(phi_parallel)
    width = 0.78
    height = 0.75
    xs = 0.14
    xe = 0.94 - xs
    ys = 0.9 - height
    #fig = plt.figure(figsize=(7,5))
    fig = plt.figure(figsize=(7, 2))
    ax1 = fig.add_axes([xs, ys, width, height])
    #kwargs_plot = {"xstep":2, "zstep":2, "vmin":-0.05, "vmax":0.05}
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": -0.2, "vmax": 0.2}
    #kwargs_plot = {"xstep":1, "zstep":1, "vmin":-0.05, "vmax":0.05}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    phi_parallel = np.reshape(phi_parallel, (nz, nx))
    p1, cbar1 = contour_plots.plot_2d_contour(xarr, zarr, phi_parallel, ax1,
                                              fig, **kwargs_plot)
    #    xmin = np.min(xarr)
    #    zmin = np.min(zarr)
    #    xmax = np.max(xarr)
    #    zmax = np.max(zarr)
    #    p1 = ax1.imshow(phi_parallel[0:nz:8, 0:nx:8], cmap=plt.cm.jet,
    #            extent=[xmin, xmax, zmin, zmax],
    #            aspect='auto', origin='lower',
    #            vmin=kwargs_plot["vmin"], vmax=kwargs_plot["vmax"],
    #            interpolation='quadric')
    p1.set_cmap(plt.cm.seismic)
    cs = ax1.contour(xarr[0:nx:xstep],
                     zarr[0:nz:zstep],
                     Ay[0:nz:zstep, 0:nx:xstep],
                     colors='black',
                     linewidths=0.5,
                     levels=np.arange(1, 250, 10))
    #cbar1.set_ticks(np.arange(-0.8, 1.0, 0.4))
    #ax1.tick_params(axis='x', labelbottom='off')
    plt.show()
示例#10
0
def bulk_energy(pic_info, species, current_time):
    """Bulk energy and internal energy.

    Args:
        pic_info: namedtuple for the PIC simulation information.
        species: 'e' for electrons, 'i' for ions.
        current_time: current time frame.
    """
    kwargs = {
        "current_time": current_time,
        "xl": 0,
        "xr": 200,
        "zb": -20,
        "zt": 20
    }
    fname = "../../data/u" + species + "x.gda"
    x, z, ux = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/u" + species + "y.gda"
    x, z, uy = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/u" + species + "z.gda"
    x, z, uz = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/n" + species + ".gda"
    x, z, nrho = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/p" + species + "-xx.gda"
    x, z, pxx = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/p" + species + "-yy.gda"
    x, z, pyy = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/p" + species + "-zz.gda"
    x, z, pzz = read_2d_fields(pic_info, fname, **kwargs)
    x, z, Ay = read_2d_fields(pic_info, "../../data/Ay.gda", **kwargs)

    if species == 'e':
        ptl_mass = 1.0
    else:
        ptl_mass = pic_info.mime

    internal_ene = (pxx + pyy + pzz) * 0.5
    bulk_ene = 0.5 * ptl_mass * nrho * (ux**2 + uy**2 + uz**2)
    # gama = 1.0 / np.sqrt(1.0 - (ux**2 + uy**2 + uz**2))
    # gama = np.sqrt(1.0 + ux**2 + uy**2 + uz**2)
    # bulk_ene2 = (gama - 1) * ptl_mass * nrho

    # print np.sum(bulk_ene), np.sum(bulk_ene2)

    nx, = x.shape
    nz, = z.shape
    width = 0.75
    height = 0.23
    xs = 0.12
    ys = 0.93 - height
    fig = plt.figure(figsize=[10, 6])
    ax1 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {
        "xstep": 1,
        "zstep": 1,
        "is_log": True,
        "vmin": 0.1,
        "vmax": 10.0
    }
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p1, cbar1 = plot_2d_contour(x, z, bulk_ene / internal_ene, ax1, fig,
                                **kwargs_plot)
    p1.set_cmap(plt.cm.seismic)
    ax1.contour(x[0:nx:xstep],
                z[0:nz:zstep],
                Ay[0:nz:zstep, 0:nx:xstep],
                colors='white',
                linewidths=0.5)
    ax1.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=24)
    # ax1.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=24)
    ax1.tick_params(axis='x', labelbottom='off')
    ax1.tick_params(labelsize=20)
    cbar1.ax.set_ylabel(r'$K/u$', fontdict=font, fontsize=24)
    cbar1.ax.tick_params(labelsize=20)

    t_wci = current_time * pic_info.dt_fields
    title = r'$t = ' + "{:10.1f}".format(t_wci) + '/\Omega_{ci}$'
    ax1.set_title(title, fontdict=font, fontsize=24)

    ys -= height + 0.05
    ax2 = fig.add_axes([xs, ys, width, height])
    if species == 'e':
        vmax = 0.2
    else:
        vmax = 0.8
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": 0, "vmax": vmax}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p2, cbar2 = plot_2d_contour(x, z, bulk_ene, ax2, fig, **kwargs_plot)
    p2.set_cmap(plt.cm.nipy_spectral)
    ax2.contour(x[0:nx:xstep],
                z[0:nz:zstep],
                Ay[0:nz:zstep, 0:nx:xstep],
                colors='white',
                linewidths=0.5)
    ax2.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=24)
    ax2.tick_params(axis='x', labelbottom='off')
    ax2.tick_params(labelsize=20)
    cbar2.ax.set_ylabel(r'$K$', fontdict=font, fontsize=24)
    if species == 'e':
        cbar2.set_ticks(np.arange(0, 0.2, 0.04))
    else:
        cbar2.set_ticks(np.arange(0, 0.9, 0.2))
    cbar2.ax.tick_params(labelsize=20)

    ys -= height + 0.05
    ax3 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": 0, "vmax": 0.8}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p3, cbar3 = plot_2d_contour(x, z, internal_ene, ax3, fig, **kwargs_plot)
    p3.set_cmap(plt.cm.nipy_spectral)
    ax3.contour(x[0:nx:xstep],
                z[0:nz:zstep],
                Ay[0:nz:zstep, 0:nx:xstep],
                colors='white',
                linewidths=0.5)
    ax3.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=24)
    ax3.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=24)
    ax3.tick_params(labelsize=20)
    cbar3.ax.set_ylabel(r'$u$', fontdict=font, fontsize=24)
    cbar3.set_ticks(np.arange(0, 0.9, 0.2))
    cbar3.ax.tick_params(labelsize=20)

    # plt.show()
    if not os.path.isdir('../img/'):
        os.makedirs('../img/')
    if not os.path.isdir('../img/img_bulk_internal/'):
        os.makedirs('../img/img_bulk_internal/')
    dir = '../img/img_bulk_internal/'
    fname = 'bulk_internal' + str(current_time).zfill(
        3) + '_' + species + '.jpg'
    fname = dir + fname
    fig.savefig(fname, dpi=400)
    plt.close()
def cal_phi_parallel(pic_info):
    """Calculate parallel potential defined by Jan Egedal.

    Args:
        pic_info: namedtuple for the PIC simulation information.
    """
    kwargs = {"current_time": 160, "xl": 0, "xr": 200, "zb": -50, "zt": 50}
    x, z, Ay = contour_plots.read_2d_fields(pic_info, "../data/Ay.gda",
                                            **kwargs)
    x, z, Bx = contour_plots.read_2d_fields(pic_info, "../data/bx.gda",
                                            **kwargs)
    x, z, By = contour_plots.read_2d_fields(pic_info, "../data/by.gda",
                                            **kwargs)
    xarr, zarr, Bz = contour_plots.read_2d_fields(pic_info, "../data/bz.gda",
                                                  **kwargs)
    x, z, Ex = contour_plots.read_2d_fields(pic_info, "../data/ex.gda",
                                            **kwargs)
    x, z, Ey = contour_plots.read_2d_fields(pic_info, "../data/ey.gda",
                                            **kwargs)
    x, z, Ez = contour_plots.read_2d_fields(pic_info, "../data/ez.gda",
                                            **kwargs)
    absB = np.sqrt(Bx * Bx + By * By + Bz * Bz)
    Epara = (Ex * Bx + Ey * By + Ez * Bz) / absB
    etot = np.sqrt(Ex * Ex + Ey * Ey + Ez * Ez)
    nx, = x.shape
    nz, = z.shape
    print nx, nz

    width = 0.78
    height = 0.75
    xs = 0.14
    xe = 0.94 - xs
    ys = 0.9 - height
    #fig = plt.figure(figsize=(7,5))
    fig = plt.figure(figsize=(7, 2))
    ax1 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 2, "zstep": 2}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    #p1, cbar1 = contour_plots.plot_2d_contour(xarr, zarr, etot, 
    #        ax1, fig, **kwargs_plot)
    #p1.set_cmap(plt.cm.seismic)
    cs = ax1.contour(
        xarr[0:nx:xstep],
        zarr[0:nz:zstep],
        Ay[0:nz:zstep, 0:nx:xstep],
        colors='white',
        linewidths=0.5,
        levels=np.arange(150, 252, 1))
    xlist = []
    zlist = []
    dx_di = pic_info.dx_di
    dz_di = pic_info.dz_di
    fig, ax = plt.subplots()
    #fig, ax2 = plt.subplots()
    phi_parallel = np.zeros((nz, nx))
    #for csp in cs.collections[65:70]:
    for csp in cs.collections[0:10]:
        for p in csp.get_paths():
            v = p.vertices
            x = v[:, 0]
            z = v[:, 1]
            if (math.fabs(x[0] - x[-1]) > dx_di or
                    math.fabs(z[0] - z[-1]) > dz_di):
                xlist.extend(x)
                zlist.extend(z)
                lenx = len(x)
                phip = np.zeros(lenx)
                epara = np.zeros(lenx)
                if (x[-1] < x[0]):
                    x = x[::-1]
                    z = z[::-1]
                for i in range(1, lenx):
                    dx = x[i] - x[i - 1]
                    dz = z[i] - z[i - 1]
                    indices_bl, indices_tr, delta = grid_indices(
                        x[i] - xarr[0], 0, z[i] - zarr[0], nx, 1, nz, dx_di, 1,
                        dz_di)
                    ix1 = indices_bl[0]
                    iz1 = indices_bl[2]
                    ix2 = indices_tr[0]
                    iz2 = indices_tr[2]
                    offsetx = delta[0]
                    offsetz = delta[2]
                    v1 = (1.0 - offsetx) * (1.0 - offsetz)
                    v2 = offsetx * (1.0 - offsetz)
                    v3 = offsetx * offsetz
                    v4 = (1.0 - offsetx) * offsetz
                    bx = Bx[iz1, ix1] * v1 + Bx[iz1, ix2] * v2 + Bx[
                        iz2, ix2] * v3 + Bx[iz2, ix1] * v4
                    by = By[iz1, ix1] * v1 + By[iz1, ix2] * v2 + By[
                        iz2, ix2] * v3 + By[iz2, ix1] * v4
                    bz = Bz[iz1, ix1] * v1 + Bz[iz1, ix2] * v2 + Bz[
                        iz2, ix2] * v3 + Bz[iz2, ix1] * v4
                    ex = Ex[iz1, ix1] * v1 + Ex[iz1, ix2] * v2 + Ex[
                        iz2, ix2] * v3 + Ex[iz2, ix1] * v4
                    ey = Ey[iz1, ix1] * v1 + Ey[iz1, ix2] * v2 + Ey[
                        iz2, ix2] * v3 + Ey[iz2, ix1] * v4
                    ez = Ez[iz1, ix1] * v1 + Ez[iz1, ix2] * v2 + Ez[
                        iz2, ix2] * v3 + Ez[iz2, ix1] * v4
                    epara[i] = Epara[iz1,ix1]*v1 + Epara[iz1,ix2]*v2 + \
                            Epara[iz2,ix2]*v3 + Epara[iz2,ix1]*v4
                    dy = by * dx / bx
                    #btot = math.sqrt(bx*bx + by*by + bz*bz)
                    #ds = math.sqrt(dx*dx + dy*dy + dz*dz)
                    #print math.acos((bx*dx + by*dy + bz*dz) / (btot*ds))
                    phip[i] = phip[i - 1] + ex * dx + ey * dy + ez * dz
                    ix = int(math.floor(x[i] / dx_di))
                    iz = int(math.floor((z[i] - zarr[0]) / dz_di))
                    phi_parallel[iz, ix] = phip[i]
                ax.plot(x, phip)
                #ax.plot(x, epara)
    print np.max(phi_parallel), np.min(phi_parallel)
    fig = plt.figure(figsize=(7, 2))
    ax1 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 2, "zstep": 2}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p1, cbar1 = contour_plots.plot_2d_contour(xarr, zarr, phi_parallel, ax1,
                                              fig, **kwargs_plot)
    p1.set_cmap(plt.cm.seismic)
    plt.show()
def plot_traj(filename, pic_info, species, iptl, mint, maxt):
    """Plot particle trajectory information.

    Args:
        filename: the filename to read the data.
        pic_info: namedtuple for the PIC simulation information.
        species: particle species. 'e' for electron. 'i' for ion.
        iptl: particle ID.
        mint, maxt: minimum and maximum time for plotting.
    """
    ptl_traj = read_traj_data(filename)
    gama = np.sqrt(ptl_traj.ux**2 + ptl_traj.uy**2 + ptl_traj.uz**2 + 1.0)
    mime = pic_info.mime
    # de scale to di scale
    ptl_x = ptl_traj.x / math.sqrt(mime)
    ptl_y = ptl_traj.y / math.sqrt(mime)
    ptl_z = ptl_traj.z / math.sqrt(mime)
    # 1/wpe to 1/wci
    t = ptl_traj.t * pic_info.dtwci / pic_info.dtwpe

    xl, xr = 0, 200
    zb, zt = -20, 20
    kwargs = {"current_time": 50, "xl": xl, "xr": xr, "zb": zb, "zt": zt}
    fname = "../../data/ey.gda"
    x, z, data_2d = read_2d_fields(pic_info, fname, **kwargs)
    x, z, Ay = read_2d_fields(pic_info, "../../data/Ay.gda", **kwargs)
    nx, = x.shape
    nz, = z.shape

    # p1 = ax1.plot(ptl_x, gama-1.0, color='k')
    # ax1.set_xlabel(r'$t\Omega_{ci}$', fontdict=font)
    # ax1.set_ylabel(r'$E/m_ic^2$', fontdict=font)
    # ax1.tick_params(labelsize=20)

    width = 14.0
    height = 8.0
    fig = plt.figure(figsize=[width, height])
    w1, h1 = 0.82, 0.27
    xs, ys = 0.10, 0.98 - h1
    ax1 = fig.add_axes([xs, ys, w1, h1])
    kwargs_plot = {
        "xstep": 2,
        "zstep": 2,
        "is_log": False,
        "vmin": -1.0,
        "vmax": 1.0
    }
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    im1, cbar1 = plot_2d_contour(x, z, data_2d, ax1, fig, **kwargs_plot)
    im1.set_cmap(plt.cm.seismic)
    ax1.contour(
        x[0:nx:xstep],
        z[0:nz:zstep],
        Ay[0:nz:zstep, 0:nx:xstep],
        colors='black',
        linewidths=0.5)
    ax1.tick_params(labelsize=20)
    ax1.tick_params(axis='x', labelbottom='off')
    ax1.set_xlim([xl, xr])
    ax1.set_ylim([zb, zt])
    ax1.set_ylabel(r'$z/d_i$', fontdict=font)
    cbar1.ax.tick_params(labelsize=20)
    cbar1.ax.set_ylabel(r'$B_y$', fontdict=font, fontsize=24)
    p1 = ax1.scatter(ptl_x, ptl_z, s=0.5)

    # ax2 = fig.add_axes([xs, ys, w1, h1])
    # p2 = ax2.plot(t, gama-1.0, color='k')
    # ax2.set_xlabel(r'$t\Omega_{ci}$', fontdict=font)
    # ax2.set_ylabel(r'$E/m_ic^2$', fontdict=font)
    # ax2.tick_params(labelsize=20)

    gap = 0.04
    ys -= h1 + gap
    ax2 = fig.add_axes([xs, ys, w1 * 0.98 - 0.05 / width, h1])
    p2 = ax2.plot(ptl_x, gama - 1.0, color='k')
    ax2.set_ylabel(r'$E/m_ic^2$', fontdict=font)
    ax2.tick_params(labelsize=20)
    ax2.tick_params(axis='x', labelbottom='off')
    xmin, xmax = ax2.get_xlim()

    ys -= h1 + gap
    ax3 = fig.add_axes([xs, ys, w1 * 0.98 - 0.05 / width, h1])
    p3 = ax3.plot(ptl_x, ptl_y, color='k')
    ax3.set_xlabel(r'$x/d_i$', fontdict=font)
    ax3.set_ylabel(r'$y/d_i$', fontdict=font)
    ax3.tick_params(labelsize=20)

    ax1.set_xlim([xmin, xmax])
    ax3.set_xlim([xmin, xmax])

    if not os.path.isdir('../img/'):
        os.makedirs('../img/')
    dir = '../img/img_traj_' + species + '/'
    if not os.path.isdir(dir):
        os.makedirs(dir)
    fname = dir + 'traj_' + species + '_' + str(iptl).zfill(4) + '_1.jpg'
    fig.savefig(fname, dpi=300)

    height = 15.0
    fig = plt.figure(figsize=[width, height])
    w1, h1 = 0.88, 0.135
    xs, ys = 0.10, 0.98 - h1
    gap = 0.025

    dt = t[1] - t[0]
    ct1 = int(mint / dt)
    ct2 = int(maxt / dt)

    ax1 = fig.add_axes([xs, ys, w1, h1])
    p1 = ax1.plot(t[ct1:ct2], gama[ct1:ct2] - 1.0, color='k')
    ax1.set_ylabel(r'$E/m_ic^2$', fontdict=font)
    ax1.tick_params(labelsize=20)
    ax1.tick_params(axis='x', labelbottom='off')
    ax1.plot([mint, maxt], [0, 0], '--', color='k')
    ax1.text(
        0.4,
        -0.07,
        r'$x$',
        color='red',
        fontsize=32,
        bbox=dict(
            facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
        horizontalalignment='center',
        verticalalignment='center',
        transform=ax1.transAxes)
    ax1.text(
        0.5,
        -0.07,
        r'$y$',
        color='green',
        fontsize=32,
        bbox=dict(
            facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
        horizontalalignment='center',
        verticalalignment='center',
        transform=ax1.transAxes)
    ax1.text(
        0.6,
        -0.07,
        r'$z$',
        color='blue',
        fontsize=32,
        bbox=dict(
            facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
        horizontalalignment='center',
        verticalalignment='center',
        transform=ax1.transAxes)

    ys -= h1 + gap
    ax2 = fig.add_axes([xs, ys, w1, h1])
    p21 = ax2.plot(t[ct1:ct2], ptl_traj.ux[ct1:ct2], color='r', label=r'u_x')
    p22 = ax2.plot(t[ct1:ct2], ptl_traj.uy[ct1:ct2], color='g', label=r'u_y')
    p23 = ax2.plot(t[ct1:ct2], ptl_traj.uz[ct1:ct2], color='b', label=r'u_z')
    ax2.plot([mint, maxt], [0, 0], '--', color='k')
    ax2.set_ylabel(r'$u_x, u_y, u_z$', fontdict=font)
    ax2.tick_params(labelsize=20)
    ax2.tick_params(axis='x', labelbottom='off')

    kernel = 9
    tmax = np.max(t)
    ys -= h1 + gap
    ax31 = fig.add_axes([xs, ys, w1, h1])
    ex = signal.medfilt(ptl_traj.ex, kernel_size=(kernel))
    p31 = ax31.plot(t[ct1:ct2], ex[ct1:ct2], color='r', label=r'E_x')
    ax31.set_ylabel(r'$E_x$', fontdict=font)
    ax31.tick_params(labelsize=20)
    ax31.tick_params(axis='x', labelbottom='off')
    ax31.plot([mint, maxt], [0, 0], '--', color='k')

    ys -= h1 + gap
    ax32 = fig.add_axes([xs, ys, w1, h1])
    ey = signal.medfilt(ptl_traj.ey, kernel_size=(kernel))
    p32 = ax32.plot(t[ct1:ct2], ey[ct1:ct2], color='g', label=r'E_y')
    ax32.set_ylabel(r'$E_y$', fontdict=font)
    ax32.tick_params(labelsize=20)
    ax32.tick_params(axis='x', labelbottom='off')
    ax32.plot([mint, maxt], [0, 0], '--', color='k')

    ys -= h1 + gap
    ax33 = fig.add_axes([xs, ys, w1, h1])
    ez = signal.medfilt(ptl_traj.ez, kernel_size=(kernel))
    p33 = ax33.plot(t[ct1:ct2], ez[ct1:ct2], color='b', label=r'E_z')
    ax33.set_ylabel(r'$E_z$', fontdict=font)
    ax33.tick_params(labelsize=20)
    ax33.tick_params(axis='x', labelbottom='off')
    ax33.plot([mint, maxt], [0, 0], '--', color='k')

    ys -= h1 + gap
    ax4 = fig.add_axes([xs, ys, w1, h1])
    p41 = ax4.plot(t[ct1:ct2], ptl_traj.bx[ct1:ct2], color='r', label=r'B_x')
    p42 = ax4.plot(t[ct1:ct2], ptl_traj.by[ct1:ct2], color='g', label=r'B_y')
    p43 = ax4.plot(t[ct1:ct2], ptl_traj.bz[ct1:ct2], color='b', label=r'B_z')
    ax4.set_xlabel(r'$t\Omega_{ci}$', fontdict=font)
    ax4.set_ylabel(r'$B_x, B_y, B_z$', fontdict=font)
    ax4.tick_params(labelsize=20)
    ax4.plot([mint, maxt], [0, 0], '--', color='k')
    ax1.set_xlim([mint, maxt])
    ax2.set_xlim([mint, maxt])
    ax31.set_xlim([mint, maxt])
    ax32.set_xlim([mint, maxt])
    ax33.set_xlim([mint, maxt])
    ax4.set_xlim([mint, maxt])

    fname = dir + 'traj_' + species + '_' + str(iptl).zfill(4) + '_2.jpg'
    fig.savefig(fname, dpi=300)

    height = 6.0
    fig = plt.figure(figsize=[width, height])
    w1, h1 = 0.88, 0.4
    xs, ys = 0.10, 0.97 - h1
    gap = 0.05

    dt = t[1] - t[0]
    ct1 = int(mint / dt)
    ct2 = int(maxt / dt)

    if species == 'e':
        charge = -1.0
    else:
        charge = 1.0
    nt, = t.shape
    jdote_x = ptl_traj.ux * ptl_traj.ex * charge / gama
    jdote_y = ptl_traj.uy * ptl_traj.ey * charge / gama
    jdote_z = ptl_traj.uz * ptl_traj.ez * charge / gama
    # jdote_x = (ptl_traj.uy * ptl_traj.bz / gama - 
    #            ptl_traj.uz * ptl_traj.by / gama + ptl_traj.ex) * charge
    # jdote_y = (ptl_traj.uz * ptl_traj.bx / gama - 
    #            ptl_traj.ux * ptl_traj.bz / gama + ptl_traj.ey) * charge
    # jdote_z = (ptl_traj.ux * ptl_traj.by / gama - 
    #            ptl_traj.uy * ptl_traj.bx / gama + ptl_traj.ez) * charge
    dt = np.zeros(nt)
    dt[0:nt - 1] = np.diff(t)
    jdote_x_cum = np.cumsum(jdote_x) * dt
    jdote_y_cum = np.cumsum(jdote_y) * dt
    jdote_z_cum = np.cumsum(jdote_z) * dt
    jdote_tot_cum = jdote_x_cum + jdote_y_cum + jdote_z_cum

    ax1 = fig.add_axes([xs, ys, w1, h1])
    p1 = ax1.plot(t[ct1:ct2], jdote_x[ct1:ct2], color='r')
    p2 = ax1.plot(t[ct1:ct2], jdote_y[ct1:ct2], color='g')
    p3 = ax1.plot(t[ct1:ct2], jdote_z[ct1:ct2], color='b')
    ax1.tick_params(labelsize=20)
    ax1.tick_params(axis='x', labelbottom='off')
    ax1.plot([mint, maxt], [0, 0], '--', color='k')
    if species == 'e':
        charge = '-e'
    else:
        charge = 'e'
    text1 = r'$' + charge + 'u_x' + 'E_x' + '$'
    ax1.text(
        0.1,
        0.1,
        text1,
        color='red',
        fontsize=32,
        bbox=dict(
            facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
        horizontalalignment='center',
        verticalalignment='center',
        transform=ax1.transAxes)
    text2 = r'$' + charge + 'u_y' + 'E_y' + '$'
    ax1.text(
        0.2,
        0.1,
        text2,
        color='green',
        fontsize=32,
        bbox=dict(
            facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
        horizontalalignment='center',
        verticalalignment='center',
        transform=ax1.transAxes)
    text3 = r'$' + charge + 'u_z' + 'E_z' + '$'
    ax1.text(
        0.3,
        0.1,
        text3,
        color='blue',
        fontsize=32,
        bbox=dict(
            facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
        horizontalalignment='center',
        verticalalignment='center',
        transform=ax1.transAxes)

    ys -= h1 + gap
    ax2 = fig.add_axes([xs, ys, w1, h1])
    p1 = ax2.plot(t[ct1:ct2], jdote_x_cum[ct1:ct2], color='r')
    p2 = ax2.plot(t[ct1:ct2], jdote_y_cum[ct1:ct2], color='g')
    p3 = ax2.plot(t[ct1:ct2], jdote_z_cum[ct1:ct2], color='b')
    p4 = ax2.plot(t[ct1:ct2], jdote_tot_cum[ct1:ct2], color='k')
    ax2.tick_params(labelsize=20)
    ax2.set_xlabel(r'$t\Omega_{ci}$', fontdict=font)
    ax2.plot([mint, maxt], [0, 0], '--', color='k')

    plt.show()
def trace_field_line(pic_info):
    """Calculate parallel potential defined by Jan Egedal.

    Args:
        pic_info: namedtuple for the PIC simulation information.
    """
    kwargs = {"current_time": 40, "xl": 0, "xr": 200, "zb": -50, "zt": 50}
    x, z, Ay = contour_plots.read_2d_fields(pic_info, "../data/Ay.gda",
                                            **kwargs)
    x, z, Bx = contour_plots.read_2d_fields(pic_info, "../data/bx.gda",
                                            **kwargs)
    x, z, Bz = contour_plots.read_2d_fields(pic_info, "../data/bz.gda",
                                            **kwargs)
    xarr, zarr, Bz = contour_plots.read_2d_fields(pic_info, "../data/bz.gda",
                                                  **kwargs)
    x, z, Ex = contour_plots.read_2d_fields(pic_info, "../data/ex.gda",
                                            **kwargs)
    x, z, Ez = contour_plots.read_2d_fields(pic_info, "../data/ez.gda",
                                            **kwargs)
    nx, = x.shape
    nz, = z.shape
    print nx, nz

    x0 = 199.0
    z0 = 45.0

    i = int(x0 / pic_info.dx_di)
    k = int(z0 / pic_info.dz_di)
    #    x0 = xarr[i]
    #    z0 = zarr[k] - zarr[0]
    #    nstep = 0
    #    xlist = [x0]
    #    zlist = [z0]
    #    dx_di = pic_info.dx_di
    #    dz_di = pic_info.dz_di
    #    deltas = math.sqrt(dx_di**2 + dz_di**2)*0.1
    #    hds = deltas * 0.5
    #    total_lengh = 0
    #    x = x0
    #    z = z0
    #    while (x > xarr[0] and x < xarr[-1] and z > 0
    #            and z < (zarr[-1]-zarr[0]) and total_lengh < 1E2):
    #        deltax1, deltaz1, x1, z1, ex, ez = middle_step_rk4(x, z, nx, nz, 
    #                dx_di, dz_di, Bx, Bz, Ex, Ez, hds)
    #        deltax2, deltaz2, x2, z2, ex, ez = middle_step_rk4(x1, z1, nx, nz,
    #                dx_di, dz_di, Bx, Bz, Ex, Ez, hds)
    #        deltax3, deltaz3, x3, z3, ex, ez = middle_step_rk4(x, z, nx, nz, 
    #                dx_di, dz_di, Bx, Bz, Ex, Ez, deltas)
    #        deltax4, deltaz4, x4, z4, ex, ez = middle_step_rk4(x, z, nx, nz, 
    #                dx_di, dz_di, Bx, Bz, Ex, Ez, hds)
    #            
    #        x += deltas/6 * (deltax1 + 2*deltax2 + 2*deltax3 + deltax4)
    #        z += deltas/6 * (deltaz1 + 2*deltaz2 + 2*deltaz3 + deltaz4)
    #        total_lengh += deltas
    #        xlist.append(x)
    #        zlist.append(z)
    #        nstep += 1
    #        length = math.sqrt((x-x0)**2 + (z-z0)**2)
    #        if (length < dx_di and nstep > 20):
    #            print length
    #            break

    dx_di = pic_info.dx_di
    dz_di = pic_info.dz_di
    #deltas = math.sqrt(dx_di**2 + dz_di**2)
    #hds = deltas * 0.5
    hmax = dx_di * 100
    h = hmax / 4.0
    # Cash-Karp parameters
    a = [0.0, 0.2, 0.3, 0.6, 1.0, 0.875]
    b = [[], [0.2], [3.0 / 40.0, 9.0 / 40.0], [0.3, -0.9, 1.2],
         [-11.0 / 54.0, 2.5, -70.0 / 27.0, 35.0 / 27.0], [
             1631.0 / 55296.0, 175.0 / 512.0, 575.0 / 13824.0, 44275.0 /
             110592.0, 253.0 / 4096.0
         ]]
    c = [37.0 / 378.0, 0.0, 250.0 / 621.0, 125.0 / 594.0, 0.0, 512.0 / 1771.0]
    dc = [
        c[0] - 2825.0 / 27648.0, c[1] - 0.0, c[2] - 18575.0 / 48384.0,
        c[3] - 13525.0 / 55296.0, c[4] - 277.00 / 14336.0, c[5] - 0.25
    ]

    def F(t, x, z):
        indices_bl, indices_tr, delta = grid_indices(x, 0, z, nx, 1, nz, dx_di,
                                                     1, dz_di)
        ix1 = indices_bl[0]
        iz1 = indices_bl[2]
        ix2 = indices_tr[0]
        iz2 = indices_tr[2]
        offsetx = delta[0]
        offsetz = delta[2]
        v1 = (1.0 - offsetx) * (1.0 - offsetz)
        v2 = offsetx * (1.0 - offsetz)
        v3 = offsetx * offsetz
        v4 = (1.0 - offsetx) * offsetz
        if (ix1 < nx and ix2 < nx and iz1 < nz and iz2 < nz):
            bx = Bx[iz1, ix1] * v1 + Bx[iz1, ix2] * v2 + Bx[
                iz2, ix2] * v3 + Bx[iz2, ix1] * v4
            bz = Bz[iz1, ix1] * v1 + Bz[iz1, ix2] * v2 + Bz[
                iz2, ix2] * v3 + Bz[iz2, ix1] * v4
            ex = Ex[iz1, ix1] * v1 + Ex[iz1, ix2] * v2 + Ex[
                iz2, ix2] * v3 + Ex[iz2, ix1] * v4
            ez = Ez[iz1, ix1] * v1 + Ez[iz1, ix2] * v2 + Ez[
                iz2, ix2] * v3 + Ez[iz2, ix1] * v4
            absB = math.sqrt(bx**2 + bz**2)
            deltax1 = bx / absB
            deltaz1 = bz / absB
        else:
            ex = 0
            ez = 0
            deltax1 = 0
            deltaz1 = 0
        return (deltax1, deltaz1, ex, ez)

    tol = 1e-5

    x0 = xarr[i] - xarr[0]
    z0 = zarr[k] - zarr[0]
    y = [x0, z0]
    nstep = 0
    xlist = [x0]
    zlist = [z0]
    t = 0
    x = x0
    z = z0
    while (x > 0 and x < (xarr[-1] - xarr[0]) and z > 0 and
           z < (zarr[-1] - zarr[0]) and t < 4E2):
        # Compute k[i] function values.
        kx = [None] * 6
        kz = [None] * 6
        kx[0], kz[0], ex0, ez0 = F(t, x, z)
        kx[1], kz[1], ex1, ez1 = F(t + a[1] * h, x + h * (kx[0] * b[1][0]),
                                   z + h * (kz[0] * b[1][0]))
        kx[2], kz[2], ex2, ez2 = F(t + a[2] * h,
                                   x + h * (kx[0] * b[2][0] + kx[1] * b[2][1]),
                                   z + h * (kz[0] * b[2][0] + kz[1] * b[2][1]))
        kx[3], kz[3], ex3, ez3 = F(
            t + a[3] * h,
            x + h * (kx[0] * b[3][0] + kx[1] * b[3][1] + kx[2] * b[3][2]),
            z + h * (kz[0] * b[3][0] + kz[1] * b[3][1] + kz[2] * b[3][2]))
        kx[4], kz[4], ex4, ez4 = F(t + a[4] * h,
                                   x + h * (kx[0] * b[4][0] + kx[1] * b[4][1] +
                                            kx[2] * b[4][2] + kx[3] * b[4][3]),
                                   z + h * (kz[0] * b[4][0] + kz[1] * b[4][1] +
                                            kz[2] * b[4][2] + kz[3] * b[4][3]))
        kx[5], kz[5], ex5, ez5 = F(
            t + a[5] * h,
            x + h * (kx[0] * b[5][0] + kx[1] * b[5][1] + kx[2] * b[5][2] +
                     kx[3] * b[5][3] + kx[4] * b[5][4]),
            z + h * (kz[0] * b[5][0] + kz[1] * b[5][1] + kz[2] * b[5][2] +
                     kz[3] * b[5][3] + kz[4] * b[5][4]))

        # Estimate current error and current maximum error.
        E = norm([
            h * (kx[0] * dc[0] + kx[1] * dc[1] + kx[2] * dc[2] + kx[3] * dc[3]
                 + kx[4] * dc[4] + kx[5] * dc[5]),
            h * (kz[0] * dc[0] + kz[1] * dc[1] + kz[2] * dc[2] + kz[3] * dc[3]
                 + kz[4] * dc[4] + kz[5] * dc[5])
        ])
        Emax = tol * max(norm(y), 1.0)

        # Update solution if error is OK.
        if E < Emax:
            t += h
            y[0] += h * (kx[0] * c[0] + kx[1] * c[1] + kx[2] * c[2] + kx[3] *
                         c[3] + kx[4] * c[4] + kx[5] * c[5])
            y[1] += h * (kz[0] * c[0] + kz[1] * c[1] + kz[2] * c[2] + kz[3] *
                         c[3] + kz[4] * c[4] + kz[5] * c[5])
            x = y[0]
            z = y[1]
            xlist.append(x)
            zlist.append(z)
            #out += [(t, list(y))]

        # Update step size
        if E > 0.0:
            h = min(hmax, 0.85 * h * (Emax / E)**0.2)

    width = 0.78
    height = 0.75
    xs = 0.14
    xe = 0.94 - xs
    ys = 0.9 - height
    #fig = plt.figure(figsize=(7,5))
    fig = plt.figure(figsize=(7, 2))
    ax1 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 2, "zstep": 2}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p1, cbar1 = contour_plots.plot_2d_contour(xarr, zarr, Ay, ax1, fig,
                                              **kwargs_plot)
    p1.set_cmap(plt.cm.seismic)
    #    cs = ax1.contour(xarr[0:nx:xstep], zarr[0:nz:zstep], Ay[0:nz:zstep, 0:nx:xstep], 
    #            colors='white', linewidths=0.5, levels=np.arange(0, 252, 1))
    p2 = ax1.plot(xlist, zlist + zarr[0], color='black')
    #cbar1.set_ticks(np.arange(-0.8, 1.0, 0.4))
    #ax1.tick_params(axis='x', labelbottom='off')
    plt.show()
def plot_average_energy(pic_info, species, current_time):
    """Plot plasma beta and number density.

    Args:
        pic_info: namedtuple for the PIC simulation information.
        species: 'e' for electrons, 'i' for ions.
        current_time: current time frame.
    """
    kwargs = {
        "current_time": current_time,
        "xl": 0,
        "xr": 80,
        "zb": -20,
        "zt": 20
    }
    fname = "../../data/n" + species + ".gda"
    x, z, num_rho = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/p" + species + "-xx.gda"
    x, z, pxx = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/p" + species + "-yy.gda"
    x, z, pyy = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/p" + species + "-zz.gda"
    x, z, pzz = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/u" + species + "x.gda"
    x, z, ux = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/u" + species + "y.gda"
    x, z, uy = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/u" + species + "z.gda"
    x, z, uz = read_2d_fields(pic_info, fname, **kwargs)
    x, z, Ay = read_2d_fields(pic_info, "../../data/Ay.gda", **kwargs)
    if species == 'e':
        ptl_mass = 1
    else:
        ptl_mass = pic_info.mime
    ene_avg = (pxx + pyy + pzz) / (2.0*num_rho) + \
              0.5*(ux*ux + uy*uy + uz*uz)*ptl_mass
    nx, = x.shape
    nz, = z.shape
    width = 0.78
    height = 0.78
    xs = 0.12
    ys = 0.92 - height
    fig = plt.figure(figsize=[10, 5])
    ax1 = fig.add_axes([xs, ys, width, height])
    if species == 'e':
        vmax = 0.2
    else:
        vmax = 1.4
    kwargs_plot = {
        "xstep": 2,
        "zstep": 2,
        "is_log": False,
        "vmin": 0.0,
        "vmax": vmax
    }
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p1, cbar1 = plot_2d_contour(x, z, ene_avg, ax1, fig, **kwargs_plot)
    # p1.set_cmap(plt.cm.seismic)
    ax1.contour(
        x[0:nx:xstep],
        z[0:nz:zstep],
        Ay[0:nz:zstep, 0:nx:xstep],
        colors='black',
        linewidths=0.5)
    ax1.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=24)
    ax1.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=24)
    ax1.tick_params(labelsize=20)
    fname = r'$E_{avg}$'
    cbar1.ax.set_ylabel(fname, fontdict=font, fontsize=24)
    # cbar1.set_ticks(np.arange(0.0, 0.22, 0.05))
    # cbar1.ax.set_yticklabels(['$0.2$', '$1.0$', '$5.0$'])
    cbar1.ax.tick_params(labelsize=20)

    t_wci = current_time * pic_info.dt_fields
    title = r'$t = ' + "{:10.1f}".format(t_wci) + '/\Omega_{ci}$'
    ax1.set_title(title, fontdict=font, fontsize=24)

    if not os.path.isdir('../img_num_rho/'):
        os.makedirs('../img_num_rho/')
    fname = '../img_num_rho/ene_avg_' + species + '_' + \
            str(current_time).zfill(3) + '.jpg'
    fig.savefig(fname, dpi=300)

    plt.show()
def number_density_along_cut(current_time, coords, lcorner, weights):
    """Particle number density along a cut.

    Args:
        current_time: current time frame.
        coords: the coordinates of the points along the cut.
        lcorner: the indices of the lower left of the cells in which
            the line points are.
        weights: the weight for 2D linear interpolation.
    """
    xl, xr = 45, 80
    zb, zt = -10, 10
    kwargs = {
        "current_time": current_time,
        "xl": xl,
        "xr": xr,
        "zb": zb,
        "zt": zt
    }
    fname = '../../data/ne.gda'
    x, z, ne = read_2d_fields(pic_info, fname, **kwargs)
    fname = '../../data/ni.gda'
    x, z, ni = read_2d_fields(pic_info, fname, **kwargs)

    tmp, npoints = lcorner.shape
    dists = np.zeros(npoints)
    for i in range(npoints):
        dists[i] = math.sqrt((coords[1, i] - coords[1, 0])**2 + (
            coords[0, i] - coords[0, 0])**2)
    ne_total = np.zeros(npoints)
    ni_total = np.zeros(npoints)

    xshift = math.floor(xl / pic_info.dx_di)
    zshift = math.floor((zb + pic_info.lz_di * 0.5) / pic_info.dz_di)
    lcorner[0, :] -= xshift
    lcorner[1, :] -= zshift

    nbands = 10
    # for iband in range(1, nbands+1):
    for iband in range(1, 2):
        fname = '../../data/eEB' + str(iband).zfill(2) + '.gda'
        x, z, eEB = read_2d_fields(pic_info, fname, **kwargs)
        fname = '../../data/iEB' + str(iband).zfill(2) + '.gda'
        x, z, iEB = read_2d_fields(pic_info, fname, **kwargs)
        x, z, Ay = read_2d_fields(pic_info, "../../data/Ay.gda", **kwargs)
        nrho_band_e = eEB * ne
        nrho_band_i = iEB * ni

        ne_line = np.zeros(npoints)
        ni_line = np.zeros(npoints)
        for i in range(npoints):
            ne_line[i] += nrho_band_e[lcorner[1, i], lcorner[0, i]] * weights[
                0, i]
            ne_line[i] += nrho_band_e[lcorner[1, i], lcorner[0, i] +
                                      1] * weights[1, i]
            ne_line[i] += nrho_band_e[lcorner[1, i] + 1, lcorner[0, i] +
                                      1] * weights[2, i]
            ne_line[i] += nrho_band_e[lcorner[1, i] + 1, lcorner[
                0, i]] * weights[3, i]
            ni_line[i] += nrho_band_i[lcorner[1, i], lcorner[0, i]] * weights[
                0, i]
            ni_line[i] += nrho_band_i[lcorner[1, i], lcorner[0, i] +
                                      1] * weights[1, i]
            ni_line[i] += nrho_band_i[lcorner[1, i] + 1, lcorner[0, i] +
                                      1] * weights[2, i]
            ni_line[i] += nrho_band_i[lcorner[1, i] + 1, lcorner[
                0, i]] * weights[3, i]

        ne_total += ne_line
        ni_total += ni_line

        nx, = x.shape
        nz, = z.shape
        width = 0.78
        height = 0.78
        xs = 0.12
        ys = 0.92 - height
        fig = plt.figure(figsize=[10, 5])
        ax1 = fig.add_axes([xs, ys, width, height])
        # vmax = math.floor(np.max(nrho_band_i) / 0.1 - 1.0) * 0.1
        kwargs_plot = {"xstep": 1, "zstep": 1, "is_log": False}
        xstep = kwargs_plot["xstep"]
        zstep = kwargs_plot["zstep"]
        ixs = 0
        p1, cbar1 = plot_2d_contour(x[ixs:nx], z, nrho_band_e[:, ixs:nx], ax1,
                                    fig, **kwargs_plot)
        # p1.set_cmap(plt.cm.seismic)
        ax1.contour(
            x[ixs:nx:xstep],
            z[0:nz:zstep],
            Ay[0:nz:zstep, ixs:nx:xstep],
            colors='black',
            linewidths=0.5)
        ax1.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=24)
        ax1.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=24)
        ax1.tick_params(labelsize=20)
        cbar1.ax.set_ylabel(r'$n_e$', fontdict=font, fontsize=24)
        # cbar1.set_ticks(np.arange(0.0, 0.2, 0.04))
        # cbar1.ax.set_yticklabels(['$0.2$', '$1.0$', '$5.0$'])
        cbar1.ax.tick_params(labelsize=20)
        p2 = ax1.plot(coords[0, :], coords[1, :], color='white', linewidth=2)
        ax1.text(
            coords[0, -1] + 1.0,
            coords[1, -1] - 1.0,
            'B',
            color='white',
            fontsize=24,
            bbox=dict(
                facecolor='none', alpha=1.0, edgecolor='none', pad=10.0))
        ax1.text(
            coords[0, 0] - 2.5,
            coords[1, 0] - 1.0,
            'A',
            color='white',
            fontsize=24,
            bbox=dict(
                facecolor='none', alpha=1.0, edgecolor='none', pad=10.0))
        fname = '../img_nrho_band/nrho_e_' + str(iband).zfill(2) + '.jpg'
        fig.savefig(fname, dpi=300)

        fig = plt.figure(figsize=[10, 5])
        ax1 = fig.add_axes([xs, ys, width, height])
        kwargs_plot = {"xstep": 1, "zstep": 1, "is_log": False}
        xstep = kwargs_plot["xstep"]
        zstep = kwargs_plot["zstep"]
        p1, cbar1 = plot_2d_contour(x[ixs:nx], z, nrho_band_i[:, ixs:nx], ax1,
                                    fig, **kwargs_plot)
        # p1.set_cmap(plt.cm.seismic)
        ax1.contour(
            x[ixs:nx:xstep],
            z[0:nz:zstep],
            Ay[0:nz:zstep, ixs:nx:xstep],
            colors='black',
            linewidths=0.5)
        ax1.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=24)
        ax1.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=24)
        ax1.tick_params(labelsize=20)
        cbar1.ax.set_ylabel(r'$n_i$', fontdict=font, fontsize=24)
        # cbar1.set_ticks(np.arange(0.0, 0.4, 0.1))
        # cbar1.ax.set_yticklabels(['$0.2$', '$1.0$', '$5.0$'])
        cbar1.ax.tick_params(labelsize=20)
        p2 = ax1.plot(coords[0, :], coords[1, :], color='white', linewidth=2)
        ax1.text(
            coords[0, -1] + 1.0,
            coords[1, -1] - 1.0,
            'B',
            color='white',
            fontsize=24,
            bbox=dict(
                facecolor='none', alpha=1.0, edgecolor='none', pad=10.0))
        ax1.text(
            coords[0, 0] - 2.5,
            coords[1, 0] - 1.0,
            'A',
            color='white',
            fontsize=24,
            bbox=dict(
                facecolor='none', alpha=1.0, edgecolor='none', pad=10.0))
        fname = '../img_nrho_band/nrho_i_' + str(iband).zfill(2) + '.jpg'
        fig.savefig(fname, dpi=300)

        t_wci = current_time * pic_info.dt_fields
        title = r'$t = ' + "{:10.1f}".format(t_wci) + '/\Omega_{ci}$'
        ax1.set_title(title, fontdict=font, fontsize=24)

        fig = plt.figure(figsize=[7, 5])
        width = 0.69
        height = 0.8
        xs = 0.16
        ys = 0.95 - height
        ax = fig.add_axes([xs, ys, width, height])
        ax.plot(dists, ne_line, color='r', linewidth=2, label='Electron')
        ax.set_xlim([np.min(dists), np.max(dists)])
        ax.set_xlabel(r'Length/$d_i$', fontdict=font, fontsize=24)
        ax.set_ylabel(r'$n_e$', fontdict=font, fontsize=24, color='r')
        ax.text(
            0.0,
            -0.13,
            'A',
            color='black',
            fontsize=24,
            bbox=dict(
                facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
            horizontalalignment='center',
            verticalalignment='center',
            transform=ax.transAxes)
        ax.text(
            1.0,
            -0.13,
            'B',
            color='black',
            fontsize=24,
            bbox=dict(
                facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
            horizontalalignment='center',
            verticalalignment='center',
            transform=ax.transAxes)
        ax.set_xlim([np.min(dists), np.max(dists)])
        ax.tick_params(labelsize=20)
        for tl in ax.get_yticklabels():
            tl.set_color('r')
        ax1 = ax.twinx()
        ax1.plot(dists, ni_line, color='b', linewidth=2, label='Ion')
        ax1.set_ylabel(r'$n_i$', fontdict=font, fontsize=24, color='b')
        ax1.tick_params(labelsize=20)
        ax1.set_xlim([np.min(dists), np.max(dists)])
        for tl in ax1.get_yticklabels():
            tl.set_color('b')
        # ax.legend(loc=2, prop={'size':24}, ncol=1,
        #         shadow=False, fancybox=False, frameon=False)
        fname = '../img_nrho_band/nei_' + str(current_time).zfill(3) + \
                '_' + str(iband).zfill(2) + '.eps'
        fig.savefig(fname)

        # plt.show()
        plt.close('all')

    # p1 = plt.plot(ne_total/ni_total, linewidth=2)
    plt.show()
示例#16
0
def plot_jy_guide():
    """Plot jy contour for the runs with guide field

    Args:
        run_name: the name of this run.
        root_dir: the root directory of this run.
        pic_info: PIC simulation information in a namedtuple.
    """
    cts = [40, 20, 20, 20, 30]
    var = 'ez'
    vmin, vmax = -0.2, 0.2
    ticks = np.arange(-0.2, 0.25, 0.1)
    cmap = plt.cm.get_cmap('seismic')
    label = r'$E_z$'
    # # cmap = cmaps.inferno
    # var = 'jy'
    # vmin, vmax = -0.2, 0.5
    # ticks = np.arange(-0.2, 0.6, 0.2)
    # cmap = plt.cm.get_cmap('jet')
    # label = r'$j_y$'
    # var = 'by'
    # vmin, vmax = -0.2, 0.5
    # ticks = np.arange(-0.2, 0.6, 0.2)
    # cmap = plt.cm.get_cmap('jet')
    # label = r'$B_y$'
    base_dirs, run_names = guide_field_runs()
    bdir = base_dirs[0]
    run_name = run_names[0]
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    xl, xr = 50, 150
    kwargs = {"current_time": cts[0], "xl": xl, "xr": xr, "zb": -10, "zt": 10}
    fname = bdir + 'data/' + var + '.gda'
    x, z, jy1 = read_2d_fields(pic_info, fname, **kwargs)
    fname = bdir + 'data/Ay.gda'
    x, z, Ay1 = read_2d_fields(pic_info, fname, **kwargs)
    kwargs = {"current_time": cts[1], "xl": xl, "xr": xr, "zb": -10, "zt": 10}
    bdir = base_dirs[1]
    run_name = run_names[1]
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    fname = bdir + 'data/' + var + '.gda'
    x, z, jy2 = read_2d_fields(pic_info, fname, **kwargs)
    fname = bdir + 'data/Ay.gda'
    x, z, Ay2 = read_2d_fields(pic_info, fname, **kwargs)
    kwargs = {"current_time": cts[2], "xl": xl, "xr": xr, "zb": -10, "zt": 10}
    bdir = base_dirs[2]
    run_name = run_names[2]
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    fname = bdir + 'data/' + var + '.gda'
    x, z, jy3 = read_2d_fields(pic_info, fname, **kwargs)
    fname = bdir + 'data/Ay.gda'
    x, z, Ay3 = read_2d_fields(pic_info, fname, **kwargs)
    kwargs = {"current_time": cts[3], "xl": xl, "xr": xr, "zb": -10, "zt": 10}
    bdir = base_dirs[3]
    run_name = run_names[3]
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    fname = bdir + 'data/' + var + '.gda'
    x, z, jy4 = read_2d_fields(pic_info, fname, **kwargs)
    fname = bdir + 'data/Ay.gda'
    x, z, Ay4 = read_2d_fields(pic_info, fname, **kwargs)

    kwargs = {"current_time": cts[4], "xl": xl, "xr": xr, "zb": -10, "zt": 10}
    bdir = base_dirs[4]
    run_name = run_names[4]
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    fname = bdir + 'data/' + var + '.gda'
    x, z, jy5 = read_2d_fields(pic_info, fname, **kwargs)
    fname = bdir + 'data/Ay.gda'
    x, z, Ay5 = read_2d_fields(pic_info, fname, **kwargs)
    nx, = x.shape
    nz, = z.shape

    width = 0.8
    height = 0.16
    xs = 0.1
    ys = 0.98 - height
    gap = 0.025
    fig = plt.figure(figsize=[10, 8])
    ax1 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": vmin, "vmax": vmax}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p1, cbar1 = plot_2d_contour(x, z, jy1, ax1, fig, **kwargs_plot)
    p1.set_cmap(cmap)
    ax1.contour(x[0:nx:xstep],
                z[0:nz:zstep],
                Ay1[0:nz:zstep, 0:nx:xstep],
                colors='black',
                linewidths=0.5)
    ax1.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=20)
    ax1.tick_params(labelsize=16)
    cbar1.ax.set_ylabel(label, fontdict=font, fontsize=20)
    cbar1.set_ticks(ticks)
    cbar1.ax.tick_params(labelsize=16)
    ax1.tick_params(axis='x', labelbottom='off')

    ys -= height + gap
    ax2 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": vmin, "vmax": vmax}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p2, cbar2 = plot_2d_contour(x, z, jy2, ax2, fig, **kwargs_plot)
    p2.set_cmap(cmap)
    ax2.contour(x[0:nx:xstep],
                z[0:nz:zstep],
                Ay2[0:nz:zstep, 0:nx:xstep],
                colors='black',
                linewidths=0.5)
    ax2.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=20)
    ax2.tick_params(labelsize=16)
    cbar2.ax.set_ylabel(label, fontdict=font, fontsize=20)
    cbar2.set_ticks(ticks)
    cbar2.ax.tick_params(labelsize=16)
    ax2.tick_params(axis='x', labelbottom='off')

    ys -= height + gap
    ax3 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": vmin, "vmax": vmax}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p3, cbar3 = plot_2d_contour(x, z, jy3, ax3, fig, **kwargs_plot)
    p3.set_cmap(cmap)
    ax3.contour(x[0:nx:xstep],
                z[0:nz:zstep],
                Ay3[0:nz:zstep, 0:nx:xstep],
                colors='black',
                linewidths=0.5)
    # ax3.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=20)
    ax3.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=20)
    ax3.tick_params(labelsize=16)
    cbar3.ax.set_ylabel(label, fontdict=font, fontsize=20)
    cbar3.set_ticks(ticks)
    cbar3.ax.tick_params(labelsize=16)
    ax3.tick_params(axis='x', labelbottom='off')

    ys -= height + gap
    ax4 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": vmin, "vmax": vmax}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p4, cbar4 = plot_2d_contour(x, z, jy4, ax4, fig, **kwargs_plot)
    p4.set_cmap(cmap)
    ax4.contour(x[0:nx:xstep],
                z[0:nz:zstep],
                Ay4[0:nz:zstep, 0:nx:xstep],
                colors='black',
                linewidths=0.5)
    # ax4.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=20)
    ax4.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=20)
    ax4.tick_params(labelsize=16)
    cbar4.ax.set_ylabel(label, fontdict=font, fontsize=20)
    cbar4.set_ticks(ticks)
    cbar4.ax.tick_params(labelsize=16)
    ax4.tick_params(axis='x', labelbottom='off')

    ys -= height + gap
    ax5 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": vmin, "vmax": vmax}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p5, cbar5 = plot_2d_contour(x, z, jy5, ax5, fig, **kwargs_plot)
    p5.set_cmap(cmap)
    ax5.contour(x[0:nx:xstep],
                z[0:nz:zstep],
                Ay5[0:nz:zstep, 0:nx:xstep],
                colors='black',
                linewidths=0.5)
    ax5.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=20)
    ax5.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=20)
    ax5.tick_params(labelsize=16)
    cbar5.ax.set_ylabel(label, fontdict=font, fontsize=20)
    cbar5.set_ticks(ticks)
    cbar5.ax.tick_params(labelsize=16)

    axs = [ax1, ax2, ax3, ax4, ax5]
    bgs = [0.0, 0.2, 0.5, 1.0, 4.0]
    for ax, bg in zip(axs, bgs):
        tname = r'$B_g = ' + str(bg) + '$'
        ax.text(0.02,
                0.8,
                tname,
                color='k',
                fontsize=24,
                bbox=dict(facecolor='none',
                          alpha=1.0,
                          edgecolor='none',
                          pad=10.0),
                horizontalalignment='left',
                verticalalignment='center',
                transform=ax.transAxes)

    fname = '../img/thesis/' + var + '.jpg'
    fig.savefig(fname, dpi=200)

    plt.show()
示例#17
0
def plot_jy_multi():
    """Plot the jy for multiple runs
    """
    base_dirs, run_names = ApJ_long_paper_runs()
    bdir = base_dirs[0]
    run_name = run_names[0]
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    kwargs = {"current_time": 11, "xl": 0, "xr": 200, "zb": -10, "zt": 10}
    fname = bdir + 'data/jy.gda'
    x, z, jy1 = read_2d_fields(pic_info, fname, **kwargs)
    fname = bdir + 'data/Ay.gda'
    x, z, Ay1 = read_2d_fields(pic_info, fname, **kwargs)
    bdir = base_dirs[1]
    run_name = run_names[1]
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    fname = bdir + 'data/jy.gda'
    x, z, jy2 = read_2d_fields(pic_info, fname, **kwargs)
    fname = bdir + 'data/Ay.gda'
    x, z, Ay2 = read_2d_fields(pic_info, fname, **kwargs)
    bdir = base_dirs[3]
    run_name = run_names[3]
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    fname = bdir + 'data/jy.gda'
    x, z, jy3 = read_2d_fields(pic_info, fname, **kwargs)
    fname = bdir + 'data/Ay.gda'
    x, z, Ay3 = read_2d_fields(pic_info, fname, **kwargs)
    nx, = x.shape
    nz, = z.shape

    width = 0.74
    height = 0.25
    xs = 0.13
    ys = 0.97 - height
    gap = 0.05
    fig = plt.figure(figsize=[7, 5])
    ax1 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": -0.5, "vmax": 0.5}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p1, cbar1 = plot_2d_contour(x, z, jy1, ax1, fig, **kwargs_plot)
    p1.set_cmap(plt.cm.get_cmap('seismic'))
    ax1.contour(x[0:nx:xstep],
                z[0:nz:zstep],
                Ay1[0:nz:zstep, 0:nx:xstep],
                colors='black',
                linewidths=0.5)
    ax1.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=20)
    ax1.tick_params(labelsize=16)
    cbar1.ax.set_ylabel(r'$j_y$', fontdict=font, fontsize=20)
    cbar1.set_ticks(np.arange(-0.4, 0.5, 0.2))
    cbar1.ax.tick_params(labelsize=16)
    ax1.tick_params(axis='x', labelbottom='off')

    ys -= height + gap
    ax2 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": -0.5, "vmax": 0.5}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p2, cbar2 = plot_2d_contour(x, z, jy2, ax2, fig, **kwargs_plot)
    p2.set_cmap(plt.cm.get_cmap('seismic'))
    ax2.contour(x[0:nx:xstep],
                z[0:nz:zstep],
                Ay2[0:nz:zstep, 0:nx:xstep],
                colors='black',
                linewidths=0.5)
    ax2.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=20)
    ax2.tick_params(labelsize=16)
    cbar2.ax.set_ylabel(r'$j_y$', fontdict=font, fontsize=20)
    cbar2.set_ticks(np.arange(-0.4, 0.5, 0.2))
    cbar2.ax.tick_params(labelsize=16)
    ax2.tick_params(axis='x', labelbottom='off')

    ys -= height + gap
    ax3 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": -1.0, "vmax": 1.0}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p3, cbar3 = plot_2d_contour(x, z, jy3, ax3, fig, **kwargs_plot)
    p3.set_cmap(plt.cm.get_cmap('seismic'))
    ax3.contour(x[0:nx:xstep],
                z[0:nz:zstep],
                Ay3[0:nz:zstep, 0:nx:xstep],
                colors='black',
                linewidths=0.5)
    ax3.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=20)
    ax3.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=20)
    ax3.tick_params(labelsize=16)
    cbar3.ax.set_ylabel(r'$j_y$', fontdict=font, fontsize=20)
    cbar3.set_ticks(np.arange(-1.0, 1.1, 0.5))
    cbar3.ax.tick_params(labelsize=16)

    ax1.text(0.02,
             0.78,
             r'R8 $\beta_e=0.2$',
             color='k',
             fontsize=20,
             bbox=dict(facecolor='none', alpha=1.0, edgecolor='none',
                       pad=10.0),
             horizontalalignment='left',
             verticalalignment='center',
             transform=ax1.transAxes)
    ax2.text(0.02,
             0.78,
             r'R7 $\beta_e=0.07$',
             color='k',
             fontsize=20,
             bbox=dict(facecolor='none', alpha=1.0, edgecolor='none',
                       pad=10.0),
             horizontalalignment='left',
             verticalalignment='center',
             transform=ax2.transAxes)
    ax3.text(0.02,
             0.78,
             r'R6 $\beta_e=0.007$',
             color='k',
             fontsize=20,
             bbox=dict(facecolor='none', alpha=1.0, edgecolor='none',
                       pad=10.0),
             horizontalalignment='left',
             verticalalignment='center',
             transform=ax3.transAxes)

    fig.savefig('../img/jy_multi.jpg', dpi=300)

    plt.show()
示例#18
0
def plot_traj(filename, pic_info, species, iptl, mint, maxt):
    """Plot particle trajectory information.

    Args:
        filename: the filename to read the data.
        pic_info: namedtuple for the PIC simulation information.
        species: particle species. 'e' for electron. 'i' for ion.
        iptl: particle ID.
        mint, maxt: minimum and maximum time for plotting.
    """
    ptl_traj = read_traj_data(filename)
    gama = np.sqrt(ptl_traj.ux**2 + ptl_traj.uy**2 + ptl_traj.uz**2 + 1.0)
    mime = pic_info.mime
    # de scale to di scale
    ptl_x = ptl_traj.x / math.sqrt(mime)
    ptl_y = ptl_traj.y / math.sqrt(mime)
    ptl_z = ptl_traj.z / math.sqrt(mime)
    # 1/wpe to 1/wci
    t = ptl_traj.t * pic_info.dtwci / pic_info.dtwpe

    xl, xr = 0, 200
    zb, zt = -20, 20
    kwargs = {"current_time": 50, "xl": xl, "xr": xr, "zb": zb, "zt": zt}
    fname = "../../data/ey.gda"
    x, z, data_2d = read_2d_fields(pic_info, fname, **kwargs)
    x, z, Ay = read_2d_fields(pic_info, "../../data/Ay.gda", **kwargs)
    nx, = x.shape
    nz, = z.shape

    # p1 = ax1.plot(ptl_x, gama-1.0, color='k')
    # ax1.set_xlabel(r'$t\Omega_{ci}$', fontdict=font)
    # ax1.set_ylabel(r'$E/m_ic^2$', fontdict=font)
    # ax1.tick_params(labelsize=20)

    width = 14.0
    height = 8.0
    fig = plt.figure(figsize=[width, height])
    w1, h1 = 0.82, 0.27
    xs, ys = 0.10, 0.98 - h1
    ax1 = fig.add_axes([xs, ys, w1, h1])
    kwargs_plot = {
        "xstep": 2,
        "zstep": 2,
        "is_log": False,
        "vmin": -1.0,
        "vmax": 1.0
    }
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    im1, cbar1 = plot_2d_contour(x, z, data_2d, ax1, fig, **kwargs_plot)
    im1.set_cmap(plt.cm.seismic)
    ax1.contour(x[0:nx:xstep],
                z[0:nz:zstep],
                Ay[0:nz:zstep, 0:nx:xstep],
                colors='black',
                linewidths=0.5)
    ax1.tick_params(labelsize=20)
    ax1.tick_params(axis='x', labelbottom='off')
    ax1.set_xlim([xl, xr])
    ax1.set_ylim([zb, zt])
    ax1.set_ylabel(r'$z/d_i$', fontdict=font)
    cbar1.ax.tick_params(labelsize=20)
    cbar1.ax.set_ylabel(r'$B_y$', fontdict=font, fontsize=24)
    p1 = ax1.scatter(ptl_x, ptl_z, s=0.5)

    # ax2 = fig.add_axes([xs, ys, w1, h1])
    # p2 = ax2.plot(t, gama-1.0, color='k')
    # ax2.set_xlabel(r'$t\Omega_{ci}$', fontdict=font)
    # ax2.set_ylabel(r'$E/m_ic^2$', fontdict=font)
    # ax2.tick_params(labelsize=20)

    gap = 0.04
    ys -= h1 + gap
    ax2 = fig.add_axes([xs, ys, w1 * 0.98 - 0.05 / width, h1])
    p2 = ax2.plot(ptl_x, gama - 1.0, color='k')
    ax2.set_ylabel(r'$E/m_ic^2$', fontdict=font)
    ax2.tick_params(labelsize=20)
    ax2.tick_params(axis='x', labelbottom='off')
    xmin, xmax = ax2.get_xlim()

    ys -= h1 + gap
    ax3 = fig.add_axes([xs, ys, w1 * 0.98 - 0.05 / width, h1])
    p3 = ax3.plot(ptl_x, ptl_y, color='k')
    ax3.set_xlabel(r'$x/d_i$', fontdict=font)
    ax3.set_ylabel(r'$y/d_i$', fontdict=font)
    ax3.tick_params(labelsize=20)

    ax1.set_xlim([xmin, xmax])
    ax3.set_xlim([xmin, xmax])

    if not os.path.isdir('../img/'):
        os.makedirs('../img/')
    dir = '../img/img_traj_' + species + '/'
    if not os.path.isdir(dir):
        os.makedirs(dir)
    fname = dir + 'traj_' + species + '_' + str(iptl).zfill(4) + '_1.jpg'
    fig.savefig(fname, dpi=300)

    height = 15.0
    fig = plt.figure(figsize=[width, height])
    w1, h1 = 0.88, 0.135
    xs, ys = 0.10, 0.98 - h1
    gap = 0.025

    dt = t[1] - t[0]
    ct1 = int(mint / dt)
    ct2 = int(maxt / dt)

    ax1 = fig.add_axes([xs, ys, w1, h1])
    p1 = ax1.plot(t[ct1:ct2], gama[ct1:ct2] - 1.0, color='k')
    ax1.set_ylabel(r'$E/m_ic^2$', fontdict=font)
    ax1.tick_params(labelsize=20)
    ax1.tick_params(axis='x', labelbottom='off')
    ax1.plot([mint, maxt], [0, 0], '--', color='k')
    ax1.text(0.4,
             -0.07,
             r'$x$',
             color='red',
             fontsize=32,
             bbox=dict(facecolor='none', alpha=1.0, edgecolor='none',
                       pad=10.0),
             horizontalalignment='center',
             verticalalignment='center',
             transform=ax1.transAxes)
    ax1.text(0.5,
             -0.07,
             r'$y$',
             color='green',
             fontsize=32,
             bbox=dict(facecolor='none', alpha=1.0, edgecolor='none',
                       pad=10.0),
             horizontalalignment='center',
             verticalalignment='center',
             transform=ax1.transAxes)
    ax1.text(0.6,
             -0.07,
             r'$z$',
             color='blue',
             fontsize=32,
             bbox=dict(facecolor='none', alpha=1.0, edgecolor='none',
                       pad=10.0),
             horizontalalignment='center',
             verticalalignment='center',
             transform=ax1.transAxes)

    ys -= h1 + gap
    ax2 = fig.add_axes([xs, ys, w1, h1])
    p21 = ax2.plot(t[ct1:ct2], ptl_traj.ux[ct1:ct2], color='r', label=r'u_x')
    p22 = ax2.plot(t[ct1:ct2], ptl_traj.uy[ct1:ct2], color='g', label=r'u_y')
    p23 = ax2.plot(t[ct1:ct2], ptl_traj.uz[ct1:ct2], color='b', label=r'u_z')
    ax2.plot([mint, maxt], [0, 0], '--', color='k')
    ax2.set_ylabel(r'$u_x, u_y, u_z$', fontdict=font)
    ax2.tick_params(labelsize=20)
    ax2.tick_params(axis='x', labelbottom='off')

    kernel = 9
    tmax = np.max(t)
    ys -= h1 + gap
    ax31 = fig.add_axes([xs, ys, w1, h1])
    ex = signal.medfilt(ptl_traj.ex, kernel_size=(kernel))
    p31 = ax31.plot(t[ct1:ct2], ex[ct1:ct2], color='r', label=r'E_x')
    ax31.set_ylabel(r'$E_x$', fontdict=font)
    ax31.tick_params(labelsize=20)
    ax31.tick_params(axis='x', labelbottom='off')
    ax31.plot([mint, maxt], [0, 0], '--', color='k')

    ys -= h1 + gap
    ax32 = fig.add_axes([xs, ys, w1, h1])
    ey = signal.medfilt(ptl_traj.ey, kernel_size=(kernel))
    p32 = ax32.plot(t[ct1:ct2], ey[ct1:ct2], color='g', label=r'E_y')
    ax32.set_ylabel(r'$E_y$', fontdict=font)
    ax32.tick_params(labelsize=20)
    ax32.tick_params(axis='x', labelbottom='off')
    ax32.plot([mint, maxt], [0, 0], '--', color='k')

    ys -= h1 + gap
    ax33 = fig.add_axes([xs, ys, w1, h1])
    ez = signal.medfilt(ptl_traj.ez, kernel_size=(kernel))
    p33 = ax33.plot(t[ct1:ct2], ez[ct1:ct2], color='b', label=r'E_z')
    ax33.set_ylabel(r'$E_z$', fontdict=font)
    ax33.tick_params(labelsize=20)
    ax33.tick_params(axis='x', labelbottom='off')
    ax33.plot([mint, maxt], [0, 0], '--', color='k')

    ys -= h1 + gap
    ax4 = fig.add_axes([xs, ys, w1, h1])
    p41 = ax4.plot(t[ct1:ct2], ptl_traj.bx[ct1:ct2], color='r', label=r'B_x')
    p42 = ax4.plot(t[ct1:ct2], ptl_traj.by[ct1:ct2], color='g', label=r'B_y')
    p43 = ax4.plot(t[ct1:ct2], ptl_traj.bz[ct1:ct2], color='b', label=r'B_z')
    ax4.set_xlabel(r'$t\Omega_{ci}$', fontdict=font)
    ax4.set_ylabel(r'$B_x, B_y, B_z$', fontdict=font)
    ax4.tick_params(labelsize=20)
    ax4.plot([mint, maxt], [0, 0], '--', color='k')
    ax1.set_xlim([mint, maxt])
    ax2.set_xlim([mint, maxt])
    ax31.set_xlim([mint, maxt])
    ax32.set_xlim([mint, maxt])
    ax33.set_xlim([mint, maxt])
    ax4.set_xlim([mint, maxt])

    fname = dir + 'traj_' + species + '_' + str(iptl).zfill(4) + '_2.jpg'
    fig.savefig(fname, dpi=300)

    height = 6.0
    fig = plt.figure(figsize=[width, height])
    w1, h1 = 0.88, 0.4
    xs, ys = 0.10, 0.97 - h1
    gap = 0.05

    dt = t[1] - t[0]
    ct1 = int(mint / dt)
    ct2 = int(maxt / dt)

    if species == 'e':
        charge = -1.0
    else:
        charge = 1.0
    nt, = t.shape
    jdote_x = ptl_traj.ux * ptl_traj.ex * charge / gama
    jdote_y = ptl_traj.uy * ptl_traj.ey * charge / gama
    jdote_z = ptl_traj.uz * ptl_traj.ez * charge / gama
    # jdote_x = (ptl_traj.uy * ptl_traj.bz / gama -
    #            ptl_traj.uz * ptl_traj.by / gama + ptl_traj.ex) * charge
    # jdote_y = (ptl_traj.uz * ptl_traj.bx / gama -
    #            ptl_traj.ux * ptl_traj.bz / gama + ptl_traj.ey) * charge
    # jdote_z = (ptl_traj.ux * ptl_traj.by / gama -
    #            ptl_traj.uy * ptl_traj.bx / gama + ptl_traj.ez) * charge
    dt = np.zeros(nt)
    dt[0:nt - 1] = np.diff(t)
    jdote_x_cum = np.cumsum(jdote_x) * dt
    jdote_y_cum = np.cumsum(jdote_y) * dt
    jdote_z_cum = np.cumsum(jdote_z) * dt
    jdote_tot_cum = jdote_x_cum + jdote_y_cum + jdote_z_cum

    ax1 = fig.add_axes([xs, ys, w1, h1])
    p1 = ax1.plot(t[ct1:ct2], jdote_x[ct1:ct2], color='r')
    p2 = ax1.plot(t[ct1:ct2], jdote_y[ct1:ct2], color='g')
    p3 = ax1.plot(t[ct1:ct2], jdote_z[ct1:ct2], color='b')
    ax1.tick_params(labelsize=20)
    ax1.tick_params(axis='x', labelbottom='off')
    ax1.plot([mint, maxt], [0, 0], '--', color='k')
    if species == 'e':
        charge = '-e'
    else:
        charge = 'e'
    text1 = r'$' + charge + 'u_x' + 'E_x' + '$'
    ax1.text(0.1,
             0.1,
             text1,
             color='red',
             fontsize=32,
             bbox=dict(facecolor='none', alpha=1.0, edgecolor='none',
                       pad=10.0),
             horizontalalignment='center',
             verticalalignment='center',
             transform=ax1.transAxes)
    text2 = r'$' + charge + 'u_y' + 'E_y' + '$'
    ax1.text(0.2,
             0.1,
             text2,
             color='green',
             fontsize=32,
             bbox=dict(facecolor='none', alpha=1.0, edgecolor='none',
                       pad=10.0),
             horizontalalignment='center',
             verticalalignment='center',
             transform=ax1.transAxes)
    text3 = r'$' + charge + 'u_z' + 'E_z' + '$'
    ax1.text(0.3,
             0.1,
             text3,
             color='blue',
             fontsize=32,
             bbox=dict(facecolor='none', alpha=1.0, edgecolor='none',
                       pad=10.0),
             horizontalalignment='center',
             verticalalignment='center',
             transform=ax1.transAxes)

    ys -= h1 + gap
    ax2 = fig.add_axes([xs, ys, w1, h1])
    p1 = ax2.plot(t[ct1:ct2], jdote_x_cum[ct1:ct2], color='r')
    p2 = ax2.plot(t[ct1:ct2], jdote_y_cum[ct1:ct2], color='g')
    p3 = ax2.plot(t[ct1:ct2], jdote_z_cum[ct1:ct2], color='b')
    p4 = ax2.plot(t[ct1:ct2], jdote_tot_cum[ct1:ct2], color='k')
    ax2.tick_params(labelsize=20)
    ax2.set_xlabel(r'$t\Omega_{ci}$', fontdict=font)
    ax2.plot([mint, maxt], [0, 0], '--', color='k')

    plt.show()
def bulk_energy(pic_info, species, current_time):
    """Bulk energy and internal energy.

    Args:
        pic_info: namedtuple for the PIC simulation information.
        species: 'e' for electrons, 'i' for ions.
        current_time: current time frame.
    """
    kwargs = {
        "current_time": current_time,
        "xl": 0,
        "xr": 200,
        "zb": -20,
        "zt": 20
    }
    fname = "../../data/u" + species + "x.gda"
    x, z, ux = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/u" + species + "y.gda"
    x, z, uy = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/u" + species + "z.gda"
    x, z, uz = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/n" + species + ".gda"
    x, z, nrho = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/p" + species + "-xx.gda"
    x, z, pxx = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/p" + species + "-yy.gda"
    x, z, pyy = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/p" + species + "-zz.gda"
    x, z, pzz = read_2d_fields(pic_info, fname, **kwargs)
    x, z, Ay = read_2d_fields(pic_info, "../../data/Ay.gda", **kwargs)

    if species == 'e':
        ptl_mass = 1.0
    else:
        ptl_mass = pic_info.mime

    internal_ene = (pxx + pyy + pzz) * 0.5
    bulk_ene = 0.5 * ptl_mass * nrho * (ux**2 + uy**2 + uz**2)
    # gama = 1.0 / np.sqrt(1.0 - (ux**2 + uy**2 + uz**2))
    # gama = np.sqrt(1.0 + ux**2 + uy**2 + uz**2)
    # bulk_ene2 = (gama - 1) * ptl_mass * nrho

    # print np.sum(bulk_ene), np.sum(bulk_ene2)

    nx, = x.shape
    nz, = z.shape
    width = 0.75
    height = 0.23
    xs = 0.12
    ys = 0.93 - height
    fig = plt.figure(figsize=[10, 6])
    ax1 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {
        "xstep": 1,
        "zstep": 1,
        "is_log": True,
        "vmin": 0.1,
        "vmax": 10.0
    }
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p1, cbar1 = plot_2d_contour(x, z, bulk_ene / internal_ene, ax1, fig,
                                **kwargs_plot)
    p1.set_cmap(plt.cm.seismic)
    ax1.contour(
        x[0:nx:xstep],
        z[0:nz:zstep],
        Ay[0:nz:zstep, 0:nx:xstep],
        colors='white',
        linewidths=0.5)
    ax1.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=24)
    # ax1.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=24)
    ax1.tick_params(axis='x', labelbottom='off')
    ax1.tick_params(labelsize=20)
    cbar1.ax.set_ylabel(r'$K/u$', fontdict=font, fontsize=24)
    cbar1.ax.tick_params(labelsize=20)

    t_wci = current_time * pic_info.dt_fields
    title = r'$t = ' + "{:10.1f}".format(t_wci) + '/\Omega_{ci}$'
    ax1.set_title(title, fontdict=font, fontsize=24)

    ys -= height + 0.05
    ax2 = fig.add_axes([xs, ys, width, height])
    if species == 'e':
        vmax = 0.2
    else:
        vmax = 0.8
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": 0, "vmax": vmax}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p2, cbar2 = plot_2d_contour(x, z, bulk_ene, ax2, fig, **kwargs_plot)
    p2.set_cmap(plt.cm.nipy_spectral)
    ax2.contour(
        x[0:nx:xstep],
        z[0:nz:zstep],
        Ay[0:nz:zstep, 0:nx:xstep],
        colors='white',
        linewidths=0.5)
    ax2.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=24)
    ax2.tick_params(axis='x', labelbottom='off')
    ax2.tick_params(labelsize=20)
    cbar2.ax.set_ylabel(r'$K$', fontdict=font, fontsize=24)
    if species == 'e':
        cbar2.set_ticks(np.arange(0, 0.2, 0.04))
    else:
        cbar2.set_ticks(np.arange(0, 0.9, 0.2))
    cbar2.ax.tick_params(labelsize=20)

    ys -= height + 0.05
    ax3 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": 0, "vmax": 0.8}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p3, cbar3 = plot_2d_contour(x, z, internal_ene, ax3, fig, **kwargs_plot)
    p3.set_cmap(plt.cm.nipy_spectral)
    ax3.contour(
        x[0:nx:xstep],
        z[0:nz:zstep],
        Ay[0:nz:zstep, 0:nx:xstep],
        colors='white',
        linewidths=0.5)
    ax3.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=24)
    ax3.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=24)
    ax3.tick_params(labelsize=20)
    cbar3.ax.set_ylabel(r'$u$', fontdict=font, fontsize=24)
    cbar3.set_ticks(np.arange(0, 0.9, 0.2))
    cbar3.ax.tick_params(labelsize=20)

    # plt.show()
    if not os.path.isdir('../img/'):
        os.makedirs('../img/')
    if not os.path.isdir('../img/img_bulk_internal/'):
        os.makedirs('../img/img_bulk_internal/')
    dir = '../img/img_bulk_internal/'
    fname = 'bulk_internal' + str(current_time).zfill(
        3) + '_' + species + '.jpg'
    fname = dir + fname
    fig.savefig(fname, dpi=400)
    plt.close()
def plot_particle_drift(pic_info, species, current_time):
    """Plot compression related terms.

    Args:
        pic_info: namedtuple for the PIC simulation information.
        species: 'e' for electrons, 'i' for ions.
        current_time: current time frame.
    """
    print(current_time)

    width = 0.75
    height = 0.11
    xs = 0.12
    ys = 0.98 - height
    gap = 0.025

    if species == 'i':
        vmin = -0.5
        vmax = 0.5
    else:
        vmin = -0.8
        vmax = 0.8
    fig = plt.figure(figsize=[10, 14])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": vmin, "vmax": vmax}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]

    ratio = pic_info.particle_interval / pic_info.fields_interval

    ct = (current_time + 1) * ratio
    kwargs = {"current_time": ct, "xl": 0, "xr": 200, "zb": -50, "zt": 50}
    x, z, Ay = read_2d_fields(pic_info, "../../data/Ay.gda", **kwargs)
    nx, = x.shape
    nz, = z.shape
    zl = nz / 4
    zt = nz - zl

    nbands = 5
    data_sum = np.zeros((nbands, nx))
    data_acc = np.zeros((nbands, nx))

    nb = 0
    kwargs = {
        "current_time": current_time,
        "xl": 0,
        "xr": 200,
        "zb": -50,
        "zt": 50
    }
    for iband in range(1, nbands + 1):
        fname = "../../data1/jpara_dote_" + species + "_" + str(iband).zfill(
            2) + ".gda"
        x, z, jpara_dote = read_2d_fields(pic_info, fname, **kwargs)
        fname = "../../data1/jperp_dote_" + species + "_" + str(iband).zfill(
            2) + ".gda"
        x, z, jperp_dote = read_2d_fields(pic_info, fname, **kwargs)
        data = jpara_dote + jperp_dote

        nk = 5
        kernel = np.ones((nk, nk)) / float(nk * nk)
        data = signal.convolve2d(data, kernel, mode='same')
        ax1 = fig.add_axes([xs, ys, width, height])
        p1, cbar1 = plot_2d_contour(x, z[zl:zt], data[zl:zt:zstep, 0:nx:xstep],
                                    ax1, fig, **kwargs_plot)
        p1.set_cmap(plt.cm.seismic)
        ax1.contour(
            x[0:nx:xstep],
            z[zl:zt:zstep],
            Ay[zl:zt:zstep, 0:nx:xstep],
            colors='black',
            linewidths=0.5)
        ax1.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=24)
        ax1.tick_params(labelsize=20)
        ax1.tick_params(axis='x', labelbottom='off')
        cbar1.ax.tick_params(labelsize=20)
        if species == 'i':
            cbar1.set_ticks(np.arange(-0.4, 0.5, 0.2))
        else:
            cbar1.set_ticks(np.arange(-0.8, 0.9, 0.4))
        ys -= height + gap
        data_sum[nb, :] = np.sum(data, axis=0)
        data_acc[nb, :] = np.cumsum(data_sum[nb, :])
        nb += 1

    dv = pic_info.dx_di * pic_info.dz_di * pic_info.mime
    data_sum *= dv
    data_acc *= dv

    ys0 = 0.1
    height0 = ys + height - ys0
    w1, h1 = fig.get_size_inches()
    width0 = width * 0.98 - 0.05 / w1
    ax1 = fig.add_axes([xs, ys0, width0, height0])
    for i in range(nb):
        fname = 'Band' + str(i + 1).zfill(2)
        # ax1.plot(x, data_sum[i, :], linewidth=2, label=fname)
        ax1.plot(x, data_acc[i, :], linewidth=2, label=fname)

    ax1.tick_params(labelsize=20)
    ax1.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=24)
    ax1.set_ylabel(r'Accumulation', fontdict=font, fontsize=24)
    ax1.legend(
        loc=2,
        prop={'size': 20},
        ncol=1,
        shadow=False,
        fancybox=False,
        frameon=False)

    if not os.path.isdir('../img/'):
        os.makedirs('../img/')
    if not os.path.isdir('../img/img_particle_drift/'):
        os.makedirs('../img/img_particle_drift/')
    fname = 'ene_gain_' + str(current_time).zfill(3) + '_' + species + '.jpg'
    fname = '../img/img_particle_drift/' + fname
    fig.savefig(fname, dpi=200)
    # plt.close()
    plt.show()
def parallel_potential(pic_info):
    """Calculate parallel potential defined by Jan Egedal.

    Args:
        pic_info: namedtuple for the PIC simulation information.
    """
    kwargs = {"current_time": 40, "xl": 0, "xr": 200, "zb": -50, "zt": 50}
    x, z, Ay = contour_plots.read_2d_fields(pic_info, "../data/Ay.gda",
                                            **kwargs)
    x, z, Ex = contour_plots.read_2d_fields(pic_info, "../data/ex.gda",
                                            **kwargs)
    x, z, Ey = contour_plots.read_2d_fields(pic_info, "../data/ey.gda",
                                            **kwargs)
    x, z, Ez = contour_plots.read_2d_fields(pic_info, "../data/ez.gda",
                                            **kwargs)
    x, z, Bx = contour_plots.read_2d_fields(pic_info, "../data/bx.gda",
                                            **kwargs)
    x, z, By = contour_plots.read_2d_fields(pic_info, "../data/by.gda",
                                            **kwargs)
    xarr, zarr, Bz = contour_plots.read_2d_fields(pic_info, "../data/bz.gda",
                                                  **kwargs)
    absB = np.sqrt(Bx**2 + By**2 + Bz**2)
    Epara = (Ex * Bx + Ey * By + Ez * Bz) / absB
    nx, = x.shape
    nz, = z.shape

    phi_parallel = np.zeros((nz, nx))
    dx_di = pic_info.dx_di
    dz_di = pic_info.dz_di
    #deltas = math.sqrt(dx_di**2 + dz_di**2)
    #hds = deltas * 0.5
    hmax = dx_di * 100
    h = hmax / 4.0
    # Cash-Karp parameters
    a = [0.0, 0.2, 0.3, 0.6, 1.0, 0.875]
    b = [[], [0.2], [3.0 / 40.0, 9.0 / 40.0], [0.3, -0.9, 1.2],
         [-11.0 / 54.0, 2.5, -70.0 / 27.0, 35.0 / 27.0], [
             1631.0 / 55296.0, 175.0 / 512.0, 575.0 / 13824.0, 44275.0 /
             110592.0, 253.0 / 4096.0
         ]]
    c = [37.0 / 378.0, 0.0, 250.0 / 621.0, 125.0 / 594.0, 0.0, 512.0 / 1771.0]
    dc = [
        c[0] - 2825.0 / 27648.0, c[1] - 0.0, c[2] - 18575.0 / 48384.0,
        c[3] - 13525.0 / 55296.0, c[4] - 277.00 / 14336.0, c[5] - 0.25
    ]

    def F(t, x, z):
        indices_bl, indices_tr, delta = grid_indices(x, 0, z, nx, 1, nz, dx_di,
                                                     1, dz_di)
        ix1 = indices_bl[0]
        iz1 = indices_bl[2]
        ix2 = indices_tr[0]
        iz2 = indices_tr[2]
        offsetx = delta[0]
        offsetz = delta[2]
        v1 = (1.0 - offsetx) * (1.0 - offsetz)
        v2 = offsetx * (1.0 - offsetz)
        v3 = offsetx * offsetz
        v4 = (1.0 - offsetx) * offsetz
        if (ix1 < nx and ix2 < nx and iz1 < nz and iz2 < nz):
            bx = Bx[iz1, ix1] * v1 + Bx[iz1, ix2] * v2 + Bx[
                iz2, ix2] * v3 + Bx[iz2, ix1] * v4
            by = By[iz1, ix1] * v1 + By[iz1, ix2] * v2 + By[
                iz2, ix2] * v3 + By[iz2, ix1] * v4
            bz = Bz[iz1, ix1] * v1 + Bz[iz1, ix2] * v2 + Bz[
                iz2, ix2] * v3 + Bz[iz2, ix1] * v4
            ex = Ex[iz1, ix1] * v1 + Ex[iz1, ix2] * v2 + Ex[
                iz2, ix2] * v3 + Ex[iz2, ix1] * v4
            ey = Ey[iz1, ix1] * v1 + Ey[iz1, ix2] * v2 + Ey[
                iz2, ix2] * v3 + Ey[iz2, ix1] * v4
            ez = Ez[iz1, ix1] * v1 + Ez[iz1, ix2] * v2 + Ez[
                iz2, ix2] * v3 + Ez[iz2, ix1] * v4
            absB = math.sqrt(bx**2 + bz**2)
            deltax1 = bx / absB
            deltay1 = by * deltax1 / bx
            deltaz1 = bz / absB
        else:
            ex = 0
            ey = 0
            ez = 0
            deltax1 = 0
            deltay1 = 0
            deltaz1 = 0
        return (deltax1, deltay1, deltaz1, ex, ey, ez)

    tol = 1e-5

    for i in range(2900, 3300):
        print i
        x0 = xarr[i] - xarr[0]
        #for k in range(0,nz,8):
        for k in range(950, 1098):
            z0 = zarr[k] - zarr[0]
            y = [x0, z0]
            nstep = 0
            xlist = [x0]
            zlist = [z0]
            t = 0
            x = x0
            z = z0
            while (x >= 0 and x <= (xarr[-1] - xarr[0]) and z >= 0 and
                   z <= (zarr[-1] - zarr[0]) and t < 4E2):
                # Compute k[i] function values.
                kx = [None] * 6
                ky = [None] * 6
                kz = [None] * 6
                kx[0], ky[0], kz[0], ex0, ey0, ez0 = F(t, x, z)
                kx[1], ky[1], kz[1], ex1, ey1, ez1 = F(
                    t + a[1] * h, x + h * (kx[0] * b[1][0]),
                    z + h * (kz[0] * b[1][0]))
                kx[2], ky[2], kz[2], ex2, ey2, ez2 = F(
                    t + a[2] * h, x + h * (kx[0] * b[2][0] + kx[1] * b[2][1]),
                    z + h * (kz[0] * b[2][0] + kz[1] * b[2][1]))
                kx[3], ky[3], kz[3], ex3, ey3, ez3 = F(
                    t + a[3] * h, x + h *
                    (kx[0] * b[3][0] + kx[1] * b[3][1] + kx[2] * b[3][2]),
                    z + h *
                    (kz[0] * b[3][0] + kz[1] * b[3][1] + kz[2] * b[3][2]))
                kx[4], ky[4], kz[4], ex4, ey4, ez4 = F(
                    t + a[4] * h, x + h * (kx[0] * b[4][0] + kx[1] * b[4][1] +
                                           kx[2] * b[4][2] + kx[3] * b[4][3]),
                    z + h * (kz[0] * b[4][0] + kz[1] * b[4][1] + kz[2] *
                             b[4][2] + kz[3] * b[4][3]))
                kx[5], ky[5], kz[5], ex5, ey5, ez5 = F(
                    t + a[5] * h,
                    x + h * (kx[0] * b[5][0] + kx[1] * b[5][1] + kx[2] *
                             b[5][2] + kx[3] * b[5][3] + kx[4] * b[5][4]),
                    z + h * (kz[0] * b[5][0] + kz[1] * b[5][1] + kz[2] *
                             b[5][2] + kz[3] * b[5][3] + kz[4] * b[5][4]))

                # Estimate current error and current maximum error.
                E = norm([
                    h * (kx[0] * dc[0] + kx[1] * dc[1] + kx[2] * dc[2] + kx[3]
                         * dc[3] + kx[4] * dc[4] + kx[5] * dc[5]),
                    h * (kz[0] * dc[0] + kz[1] * dc[1] + kz[2] * dc[2] + kz[3]
                         * dc[3] + kz[4] * dc[4] + kz[5] * dc[5])
                ])
                Emax = tol * max(norm(y), 1.0)

                # Update solution if error is OK.
                if E < Emax:
                    t += h
                    dx = h * (kx[0] * c[0] + kx[1] * c[1] + kx[2] * c[2] +
                              kx[3] * c[3] + kx[4] * c[4] + kx[5] * c[5])
                    dy = h * (ky[0] * c[0] + ky[1] * c[1] + ky[2] * c[2] +
                              ky[3] * c[3] + ky[4] * c[4] + ky[5] * c[5])
                    dz = h * (kz[0] * c[0] + kz[1] * c[1] + kz[2] * c[2] +
                              kz[3] * c[3] + kz[4] * c[4] + kz[5] * c[5])
                    y[0] += dx
                    y[1] += dz
                    x = y[0]
                    z = y[1]
                    xlist.append(x)
                    zlist.append(z)
                    phi_parallel[k, i] += \
                            h*(kx[0]*c[0]*ex0+kx[1]*c[1]*ex1+kx[2]*c[2]*ex2+ \
                            kx[3]*c[3]*ex3+kx[4]*c[4]*ex4+kx[5]*c[5]*ex5) + \
                            h*(ky[0]*c[0]*ey0+ky[1]*c[1]*ey1+ky[2]*c[2]*ey2+ \
                            ky[3]*c[3]*ey3+ky[4]*c[4]*ey4+ky[5]*c[5]*ey5) + \
                            h*(kz[0]*c[0]*ez0+kz[1]*c[1]*ez1+kz[2]*c[2]*ez2+ \
                            kz[3]*c[3]*ez3+kz[4]*c[4]*ez4+kz[5]*c[5]*ez5)
                    #out += [(t, list(y))]

                # Update step size
                if E > 0.0:
                    h = min(hmax, 0.85 * h * (Emax / E)**0.2)
            if (t > 395):
                phi_parallel[k, i] = 0

#
#                deltax1, deltaz1, x1, z1, ex1, ez1 = middle_step_rk4(x, z, nx, nz, 
#                        dx_di, dz_di, Bx, Bz, Ex, Ez, hds)
#                deltax2, deltaz2, x2, z2, ex2, ez2 = middle_step_rk4(x1, z1, nx, nz,
#                        dx_di, dz_di, Bx, Bz, Ex, Ez, hds)
#                deltax3, deltaz3, x3, z3, ex3, ez3 = middle_step_rk4(x, z, nx, nz, 
#                        dx_di, dz_di, Bx, Bz, Ex, Ez, deltas)
#                deltax4, deltaz4, x4, z4, ex4, ez4 = middle_step_rk4(x, z, nx, nz, 
#                        dx_di, dz_di, Bx, Bz, Ex, Ez, hds)
#                    
#                deltax = deltas/6 * (deltax1 + 2*deltax2 + 2*deltax3 + deltax4)
#                deltaz = deltas/6 * (deltaz1 + 2*deltaz2 + 2*deltaz3 + deltaz4)
#                x += deltax
#                z += deltaz
#                total_lengh += deltas
#                xlist.append(x)
#                zlist.append(z)
#                nstep += 1
#                phi_parallel[k, i] += deltas/6 * (ex1*deltax1 + ez1*deltaz1 +
#                        2.0*ex2*deltax2 + 2.0*ez2*deltaz2 +
#                        2.0*ex3*deltax3 + 2.0*ez3*deltaz3 +
#                        ex4*deltax4 + ez4*deltaz4)
#                length = math.sqrt((x-x0)**2 + (z-z0)**2)
#                if (length < dx_di and nstep > 20):
#                    phi_parallel[k, i] = 0
#                    break
#            #print k, nstep, total_lengh
#    phi_parallel = np.fromfile('phi_parallel.dat')
#    phi_parallel.tofile('phi_parallel.dat')
#    print np.max(phi_parallel), np.min(phi_parallel)
    width = 0.78
    height = 0.75
    xs = 0.14
    xe = 0.94 - xs
    ys = 0.9 - height
    #fig = plt.figure(figsize=(7,5))
    fig = plt.figure(figsize=(7, 2))
    ax1 = fig.add_axes([xs, ys, width, height])
    #kwargs_plot = {"xstep":2, "zstep":2, "vmin":-0.05, "vmax":0.05}
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": -0.2, "vmax": 0.2}
    #kwargs_plot = {"xstep":1, "zstep":1, "vmin":-0.05, "vmax":0.05}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    phi_parallel = np.reshape(phi_parallel, (nz, nx))
    p1, cbar1 = contour_plots.plot_2d_contour(xarr, zarr, phi_parallel, ax1,
                                              fig, **kwargs_plot)
    #    xmin = np.min(xarr)
    #    zmin = np.min(zarr)
    #    xmax = np.max(xarr)
    #    zmax = np.max(zarr)
    #    p1 = ax1.imshow(phi_parallel[0:nz:8, 0:nx:8], cmap=plt.cm.jet,
    #            extent=[xmin, xmax, zmin, zmax],
    #            aspect='auto', origin='lower',
    #            vmin=kwargs_plot["vmin"], vmax=kwargs_plot["vmax"],
    #            interpolation='quadric')
    p1.set_cmap(plt.cm.seismic)
    cs = ax1.contour(
        xarr[0:nx:xstep],
        zarr[0:nz:zstep],
        Ay[0:nz:zstep, 0:nx:xstep],
        colors='black',
        linewidths=0.5,
        levels=np.arange(1, 250, 10))
    #cbar1.set_ticks(np.arange(-0.8, 1.0, 0.4))
    #ax1.tick_params(axis='x', labelbottom='off')
    plt.show()
def plot_ptl_traj(filename, pic_info, species, iptl, mint, maxt):
    """Plot particle trajectory information.

    Args:
        filename: the filename to read the data.
        pic_info: namedtuple for the PIC simulation information.
        species: particle species. 'e' for electron. 'i' for ion.
        iptl: particle ID.
        mint, maxt: minimum and maximum time for plotting.
    """
    ptl_traj = read_traj_data(filename)
    gama = np.sqrt(ptl_traj.ux**2 + ptl_traj.uy**2 + ptl_traj.uz**2 + 1.0)
    mime = pic_info.mime
    # de scale to di scale
    ptl_x = ptl_traj.x / math.sqrt(mime)
    ptl_y = ptl_traj.y / math.sqrt(mime)
    ptl_z = ptl_traj.z / math.sqrt(mime)
    # 1/wpe to 1/wci
    t = ptl_traj.t * pic_info.dtwci / pic_info.dtwpe

    xl, xr = 0, 50
    zb, zt = -20, 20
    kwargs = {"current_time": 65, "xl": xl, "xr": xr, "zb": zb, "zt": zt}
    fname = "../../data/uex.gda"
    x, z, uex = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/ne.gda"
    x, z, ne = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/uix.gda"
    x, z, uix = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/ni.gda"
    x, z, ni = read_2d_fields(pic_info, fname, **kwargs)
    ux = (uex * ne + uix * ni * pic_info.mime) / (ne + ni * pic_info.mime)
    x, z, Ay = read_2d_fields(pic_info, "../../data/Ay.gda", **kwargs)
    nx, = x.shape
    nz, = z.shape

    width = 8.0
    height = 8.0
    fig = plt.figure(figsize=[width, height])
    w1, h1 = 0.74, 0.42
    xs, ys = 0.13, 0.98 - h1
    ax1 = fig.add_axes([xs, ys, w1, h1])
    kwargs_plot = {
        "xstep": 2,
        "zstep": 2,
        "is_log": False,
        "vmin": -1.0,
        "vmax": 1.0
    }
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    va = 0.2  # Alfven speed
    im1, cbar1 = plot_2d_contour(x, z, ux / va, ax1, fig, **kwargs_plot)
    im1.set_cmap(plt.cm.seismic)
    ax1.contour(
        x[0:nx:xstep],
        z[0:nz:zstep],
        Ay[0:nz:zstep, 0:nx:xstep],
        colors='black',
        linewidths=0.5)
    ax1.tick_params(labelsize=20)
    ax1.tick_params(axis='x', labelbottom='off')
    ax1.set_xlim([xl, xr])
    ax1.set_ylim([zb, zt])
    ax1.set_ylabel(r'$z/d_i$', fontdict=font)
    cbar1.ax.tick_params(labelsize=20)
    cbar1.ax.set_ylabel(r'$u_x/V_A$', fontdict=font, fontsize=24)
    tstop = 1990
    p1 = ax1.plot(ptl_x[0:tstop], ptl_z[0:tstop], linewidth=2, color='k')

    gap = 0.04
    ys -= h1 + gap
    ax2 = fig.add_axes([xs, ys, w1 * 0.98 - 0.05 / width, h1])
    eth = pic_info.vthi**2 * 3
    p2 = ax2.plot(
        ptl_x[0:tstop], (gama[0:tstop] - 1.0) / eth, color='k', linewidth=2)
    ax2.set_xlabel(r'$x/d_i$', fontdict=font)
    ax2.set_ylabel(r'$E/E_{\text{thi}}$', fontdict=font)
    ax2.tick_params(labelsize=20)
    # ax2.tick_params(axis='x', labelbottom='off')
    xmin, xmax = ax1.get_xlim()
    ax2.set_xlim([xmin, xmax])

    if not os.path.isdir('../img/'):
        os.makedirs('../img/')
    fname = '../img/' + 'traj_' + species + '_' + str(iptl).zfill(4) + '_1.jpg'
    fig.savefig(fname, dpi=300)

    plt.show()
def number_density_along_cut(current_time, coords, lcorner, weights):
    """Particle number density along a cut.

    Args:
        current_time: current time frame.
        coords: the coordinates of the points along the cut.
        lcorner: the indices of the lower left of the cells in which
            the line points are.
        weights: the weight for 2D linear interpolation.
    """
    xl, xr = 45, 80
    zb, zt = -10, 10
    kwargs = {
        "current_time": current_time,
        "xl": xl,
        "xr": xr,
        "zb": zb,
        "zt": zt
    }
    fname = '../../data/ne.gda'
    x, z, ne = read_2d_fields(pic_info, fname, **kwargs)
    fname = '../../data/ni.gda'
    x, z, ni = read_2d_fields(pic_info, fname, **kwargs)

    tmp, npoints = lcorner.shape
    dists = np.zeros(npoints)
    for i in range(npoints):
        dists[i] = math.sqrt((coords[1, i] - coords[1, 0])**2 +
                             (coords[0, i] - coords[0, 0])**2)
    ne_total = np.zeros(npoints)
    ni_total = np.zeros(npoints)

    xshift = math.floor(xl / pic_info.dx_di)
    zshift = math.floor((zb + pic_info.lz_di * 0.5) / pic_info.dz_di)
    lcorner[0, :] -= xshift
    lcorner[1, :] -= zshift

    nbands = 10
    # for iband in range(1, nbands+1):
    for iband in range(1, 2):
        fname = '../../data/eEB' + str(iband).zfill(2) + '.gda'
        x, z, eEB = read_2d_fields(pic_info, fname, **kwargs)
        fname = '../../data/iEB' + str(iband).zfill(2) + '.gda'
        x, z, iEB = read_2d_fields(pic_info, fname, **kwargs)
        x, z, Ay = read_2d_fields(pic_info, "../../data/Ay.gda", **kwargs)
        nrho_band_e = eEB * ne
        nrho_band_i = iEB * ni

        ne_line = np.zeros(npoints)
        ni_line = np.zeros(npoints)
        for i in range(npoints):
            ne_line[i] += nrho_band_e[lcorner[1, i],
                                      lcorner[0, i]] * weights[0, i]
            ne_line[i] += nrho_band_e[lcorner[1, i],
                                      lcorner[0, i] + 1] * weights[1, i]
            ne_line[i] += nrho_band_e[lcorner[1, i] + 1,
                                      lcorner[0, i] + 1] * weights[2, i]
            ne_line[i] += nrho_band_e[lcorner[1, i] + 1,
                                      lcorner[0, i]] * weights[3, i]
            ni_line[i] += nrho_band_i[lcorner[1, i],
                                      lcorner[0, i]] * weights[0, i]
            ni_line[i] += nrho_band_i[lcorner[1, i],
                                      lcorner[0, i] + 1] * weights[1, i]
            ni_line[i] += nrho_band_i[lcorner[1, i] + 1,
                                      lcorner[0, i] + 1] * weights[2, i]
            ni_line[i] += nrho_band_i[lcorner[1, i] + 1,
                                      lcorner[0, i]] * weights[3, i]

        ne_total += ne_line
        ni_total += ni_line

        nx, = x.shape
        nz, = z.shape
        width = 0.78
        height = 0.78
        xs = 0.12
        ys = 0.92 - height
        fig = plt.figure(figsize=[10, 5])
        ax1 = fig.add_axes([xs, ys, width, height])
        # vmax = math.floor(np.max(nrho_band_i) / 0.1 - 1.0) * 0.1
        kwargs_plot = {"xstep": 1, "zstep": 1, "is_log": False}
        xstep = kwargs_plot["xstep"]
        zstep = kwargs_plot["zstep"]
        ixs = 0
        p1, cbar1 = plot_2d_contour(x[ixs:nx], z, nrho_band_e[:, ixs:nx], ax1,
                                    fig, **kwargs_plot)
        # p1.set_cmap(plt.cm.seismic)
        ax1.contour(x[ixs:nx:xstep],
                    z[0:nz:zstep],
                    Ay[0:nz:zstep, ixs:nx:xstep],
                    colors='black',
                    linewidths=0.5)
        ax1.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=24)
        ax1.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=24)
        ax1.tick_params(labelsize=20)
        cbar1.ax.set_ylabel(r'$n_e$', fontdict=font, fontsize=24)
        # cbar1.set_ticks(np.arange(0.0, 0.2, 0.04))
        # cbar1.ax.set_yticklabels(['$0.2$', '$1.0$', '$5.0$'])
        cbar1.ax.tick_params(labelsize=20)
        p2 = ax1.plot(coords[0, :], coords[1, :], color='white', linewidth=2)
        ax1.text(coords[0, -1] + 1.0,
                 coords[1, -1] - 1.0,
                 'B',
                 color='white',
                 fontsize=24,
                 bbox=dict(facecolor='none',
                           alpha=1.0,
                           edgecolor='none',
                           pad=10.0))
        ax1.text(coords[0, 0] - 2.5,
                 coords[1, 0] - 1.0,
                 'A',
                 color='white',
                 fontsize=24,
                 bbox=dict(facecolor='none',
                           alpha=1.0,
                           edgecolor='none',
                           pad=10.0))
        fname = '../img_nrho_band/nrho_e_' + str(iband).zfill(2) + '.jpg'
        fig.savefig(fname, dpi=300)

        fig = plt.figure(figsize=[10, 5])
        ax1 = fig.add_axes([xs, ys, width, height])
        kwargs_plot = {"xstep": 1, "zstep": 1, "is_log": False}
        xstep = kwargs_plot["xstep"]
        zstep = kwargs_plot["zstep"]
        p1, cbar1 = plot_2d_contour(x[ixs:nx], z, nrho_band_i[:, ixs:nx], ax1,
                                    fig, **kwargs_plot)
        # p1.set_cmap(plt.cm.seismic)
        ax1.contour(x[ixs:nx:xstep],
                    z[0:nz:zstep],
                    Ay[0:nz:zstep, ixs:nx:xstep],
                    colors='black',
                    linewidths=0.5)
        ax1.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=24)
        ax1.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=24)
        ax1.tick_params(labelsize=20)
        cbar1.ax.set_ylabel(r'$n_i$', fontdict=font, fontsize=24)
        # cbar1.set_ticks(np.arange(0.0, 0.4, 0.1))
        # cbar1.ax.set_yticklabels(['$0.2$', '$1.0$', '$5.0$'])
        cbar1.ax.tick_params(labelsize=20)
        p2 = ax1.plot(coords[0, :], coords[1, :], color='white', linewidth=2)
        ax1.text(coords[0, -1] + 1.0,
                 coords[1, -1] - 1.0,
                 'B',
                 color='white',
                 fontsize=24,
                 bbox=dict(facecolor='none',
                           alpha=1.0,
                           edgecolor='none',
                           pad=10.0))
        ax1.text(coords[0, 0] - 2.5,
                 coords[1, 0] - 1.0,
                 'A',
                 color='white',
                 fontsize=24,
                 bbox=dict(facecolor='none',
                           alpha=1.0,
                           edgecolor='none',
                           pad=10.0))
        fname = '../img_nrho_band/nrho_i_' + str(iband).zfill(2) + '.jpg'
        fig.savefig(fname, dpi=300)

        t_wci = current_time * pic_info.dt_fields
        title = r'$t = ' + "{:10.1f}".format(t_wci) + '/\Omega_{ci}$'
        ax1.set_title(title, fontdict=font, fontsize=24)

        fig = plt.figure(figsize=[7, 5])
        width = 0.69
        height = 0.8
        xs = 0.16
        ys = 0.95 - height
        ax = fig.add_axes([xs, ys, width, height])
        ax.plot(dists, ne_line, color='r', linewidth=2, label='Electron')
        ax.set_xlim([np.min(dists), np.max(dists)])
        ax.set_xlabel(r'Length/$d_i$', fontdict=font, fontsize=24)
        ax.set_ylabel(r'$n_e$', fontdict=font, fontsize=24, color='r')
        ax.text(0.0,
                -0.13,
                'A',
                color='black',
                fontsize=24,
                bbox=dict(facecolor='none',
                          alpha=1.0,
                          edgecolor='none',
                          pad=10.0),
                horizontalalignment='center',
                verticalalignment='center',
                transform=ax.transAxes)
        ax.text(1.0,
                -0.13,
                'B',
                color='black',
                fontsize=24,
                bbox=dict(facecolor='none',
                          alpha=1.0,
                          edgecolor='none',
                          pad=10.0),
                horizontalalignment='center',
                verticalalignment='center',
                transform=ax.transAxes)
        ax.set_xlim([np.min(dists), np.max(dists)])
        ax.tick_params(labelsize=20)
        for tl in ax.get_yticklabels():
            tl.set_color('r')
        ax1 = ax.twinx()
        ax1.plot(dists, ni_line, color='b', linewidth=2, label='Ion')
        ax1.set_ylabel(r'$n_i$', fontdict=font, fontsize=24, color='b')
        ax1.tick_params(labelsize=20)
        ax1.set_xlim([np.min(dists), np.max(dists)])
        for tl in ax1.get_yticklabels():
            tl.set_color('b')
        # ax.legend(loc=2, prop={'size':24}, ncol=1,
        #         shadow=False, fancybox=False, frameon=False)
        fname = '../img_nrho_band/nei_' + str(current_time).zfill(3) + \
                '_' + str(iband).zfill(2) + '.eps'
        fig.savefig(fname)

        # plt.show()
        plt.close('all')

    # p1 = plt.plot(ne_total/ni_total, linewidth=2)
    plt.show()
def bulk_energy_change_rate(pic_info, species, current_time):
    """Bulk energy change rate.

    Args:
        pic_info: namedtuple for the PIC simulation information.
        species: 'e' for electrons, 'i' for ions.
        current_time: current time frame.
    """
    kwargs = {
        "current_time": current_time - 1,
        "xl": 0,
        "xr": 200,
        "zb": -15,
        "zt": 15
    }
    fname = "../../data/u" + species + "x.gda"
    x, z, ux = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/u" + species + "y.gda"
    x, z, uy = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/u" + species + "z.gda"
    x, z, uz = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/n" + species + ".gda"
    x, z, nrho = read_2d_fields(pic_info, fname, **kwargs)

    if species == 'e':
        ptl_mass = 1.0
    else:
        ptl_mass = pic_info.mime

    bulk_ene1 = 0.5 * ptl_mass * nrho * (ux**2 + uy**2 + uz**2)

    kwargs = {
        "current_time": current_time + 1,
        "xl": 0,
        "xr": 200,
        "zb": -15,
        "zt": 15
    }
    fname = "../../data/u" + species + "x.gda"
    x, z, ux = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/u" + species + "y.gda"
    x, z, uy = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/u" + species + "z.gda"
    x, z, uz = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/n" + species + ".gda"
    x, z, nrho = read_2d_fields(pic_info, fname, **kwargs)

    bulk_ene2 = 0.5 * ptl_mass * nrho * (ux**2 + uy**2 + uz**2)

    kwargs = {
        "current_time": current_time,
        "xl": 0,
        "xr": 200,
        "zb": -15,
        "zt": 15
    }
    x, z, Ay = read_2d_fields(pic_info, "../../data/Ay.gda", **kwargs)

    bulk_ene_rate = bulk_ene2 - bulk_ene1

    nx, = x.shape
    nz, = z.shape
    width = 0.75
    height = 0.7
    xs = 0.12
    ys = 0.9 - height
    fig = plt.figure(figsize=[10, 4])
    ax1 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": 0.1, "vmax": -0.1}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p1, cbar1 = plot_2d_contour(x, z, bulk_ene_rate, ax1, fig, **kwargs_plot)
    p1.set_cmap(plt.cm.seismic)
    ax1.contour(
        x[0:nx:xstep],
        z[0:nz:zstep],
        Ay[0:nz:zstep, 0:nx:xstep],
        colors='black',
        linewidths=0.5)
    ax1.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=24)
    ax1.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=24)
    ax1.tick_params(labelsize=24)
    cbar1.ax.set_ylabel(r'$K/u$', fontdict=font, fontsize=24)
    cbar1.ax.tick_params(labelsize=24)

    t_wci = current_time * pic_info.dt_fields
    title = r'$t = ' + "{:10.1f}".format(t_wci) + '/\Omega_{ci}$'
    ax1.set_title(title, fontdict=font, fontsize=24)

    plt.show()
def plot_average_energy(pic_info, species, current_time):
    """Plot plasma beta and number density.

    Args:
        pic_info: namedtuple for the PIC simulation information.
        species: 'e' for electrons, 'i' for ions.
        current_time: current time frame.
    """
    kwargs = {
        "current_time": current_time,
        "xl": 0,
        "xr": 80,
        "zb": -20,
        "zt": 20
    }
    fname = "../../data/n" + species + ".gda"
    x, z, num_rho = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/p" + species + "-xx.gda"
    x, z, pxx = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/p" + species + "-yy.gda"
    x, z, pyy = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/p" + species + "-zz.gda"
    x, z, pzz = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/u" + species + "x.gda"
    x, z, ux = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/u" + species + "y.gda"
    x, z, uy = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/u" + species + "z.gda"
    x, z, uz = read_2d_fields(pic_info, fname, **kwargs)
    x, z, Ay = read_2d_fields(pic_info, "../../data/Ay.gda", **kwargs)
    if species == 'e':
        ptl_mass = 1
    else:
        ptl_mass = pic_info.mime
    ene_avg = (pxx + pyy + pzz) / (2.0*num_rho) + \
              0.5*(ux*ux + uy*uy + uz*uz)*ptl_mass
    nx, = x.shape
    nz, = z.shape
    width = 0.78
    height = 0.78
    xs = 0.12
    ys = 0.92 - height
    fig = plt.figure(figsize=[10, 5])
    ax1 = fig.add_axes([xs, ys, width, height])
    if species == 'e':
        vmax = 0.2
    else:
        vmax = 1.4
    kwargs_plot = {
        "xstep": 2,
        "zstep": 2,
        "is_log": False,
        "vmin": 0.0,
        "vmax": vmax
    }
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p1, cbar1 = plot_2d_contour(x, z, ene_avg, ax1, fig, **kwargs_plot)
    # p1.set_cmap(plt.cm.seismic)
    ax1.contour(x[0:nx:xstep],
                z[0:nz:zstep],
                Ay[0:nz:zstep, 0:nx:xstep],
                colors='black',
                linewidths=0.5)
    ax1.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=24)
    ax1.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=24)
    ax1.tick_params(labelsize=20)
    fname = r'$E_{avg}$'
    cbar1.ax.set_ylabel(fname, fontdict=font, fontsize=24)
    # cbar1.set_ticks(np.arange(0.0, 0.22, 0.05))
    # cbar1.ax.set_yticklabels(['$0.2$', '$1.0$', '$5.0$'])
    cbar1.ax.tick_params(labelsize=20)

    t_wci = current_time * pic_info.dt_fields
    title = r'$t = ' + "{:10.1f}".format(t_wci) + '/\Omega_{ci}$'
    ax1.set_title(title, fontdict=font, fontsize=24)

    if not os.path.isdir('../img_num_rho/'):
        os.makedirs('../img_num_rho/')
    fname = '../img_num_rho/ene_avg_' + species + '_' + \
            str(current_time).zfill(3) + '.jpg'
    fig.savefig(fname, dpi=300)

    plt.show()
示例#26
0
def trace_field_line(pic_info):
    """Calculate parallel potential defined by Jan Egedal.

    Args:
        pic_info: namedtuple for the PIC simulation information.
    """
    kwargs = {"current_time": 40, "xl": 0, "xr": 200, "zb": -50, "zt": 50}
    x, z, Ay = contour_plots.read_2d_fields(pic_info, "../data/Ay.gda",
                                            **kwargs)
    x, z, Bx = contour_plots.read_2d_fields(pic_info, "../data/bx.gda",
                                            **kwargs)
    x, z, Bz = contour_plots.read_2d_fields(pic_info, "../data/bz.gda",
                                            **kwargs)
    xarr, zarr, Bz = contour_plots.read_2d_fields(pic_info, "../data/bz.gda",
                                                  **kwargs)
    x, z, Ex = contour_plots.read_2d_fields(pic_info, "../data/ex.gda",
                                            **kwargs)
    x, z, Ez = contour_plots.read_2d_fields(pic_info, "../data/ez.gda",
                                            **kwargs)
    nx, = x.shape
    nz, = z.shape
    print nx, nz

    x0 = 199.0
    z0 = 45.0

    i = int(x0 / pic_info.dx_di)
    k = int(z0 / pic_info.dz_di)
    #    x0 = xarr[i]
    #    z0 = zarr[k] - zarr[0]
    #    nstep = 0
    #    xlist = [x0]
    #    zlist = [z0]
    #    dx_di = pic_info.dx_di
    #    dz_di = pic_info.dz_di
    #    deltas = math.sqrt(dx_di**2 + dz_di**2)*0.1
    #    hds = deltas * 0.5
    #    total_lengh = 0
    #    x = x0
    #    z = z0
    #    while (x > xarr[0] and x < xarr[-1] and z > 0
    #            and z < (zarr[-1]-zarr[0]) and total_lengh < 1E2):
    #        deltax1, deltaz1, x1, z1, ex, ez = middle_step_rk4(x, z, nx, nz,
    #                dx_di, dz_di, Bx, Bz, Ex, Ez, hds)
    #        deltax2, deltaz2, x2, z2, ex, ez = middle_step_rk4(x1, z1, nx, nz,
    #                dx_di, dz_di, Bx, Bz, Ex, Ez, hds)
    #        deltax3, deltaz3, x3, z3, ex, ez = middle_step_rk4(x, z, nx, nz,
    #                dx_di, dz_di, Bx, Bz, Ex, Ez, deltas)
    #        deltax4, deltaz4, x4, z4, ex, ez = middle_step_rk4(x, z, nx, nz,
    #                dx_di, dz_di, Bx, Bz, Ex, Ez, hds)
    #
    #        x += deltas/6 * (deltax1 + 2*deltax2 + 2*deltax3 + deltax4)
    #        z += deltas/6 * (deltaz1 + 2*deltaz2 + 2*deltaz3 + deltaz4)
    #        total_lengh += deltas
    #        xlist.append(x)
    #        zlist.append(z)
    #        nstep += 1
    #        length = math.sqrt((x-x0)**2 + (z-z0)**2)
    #        if (length < dx_di and nstep > 20):
    #            print length
    #            break

    dx_di = pic_info.dx_di
    dz_di = pic_info.dz_di
    #deltas = math.sqrt(dx_di**2 + dz_di**2)
    #hds = deltas * 0.5
    hmax = dx_di * 100
    h = hmax / 4.0
    # Cash-Karp parameters
    a = [0.0, 0.2, 0.3, 0.6, 1.0, 0.875]
    b = [[], [0.2], [3.0 / 40.0, 9.0 / 40.0], [0.3, -0.9, 1.2],
         [-11.0 / 54.0, 2.5, -70.0 / 27.0, 35.0 / 27.0],
         [
             1631.0 / 55296.0, 175.0 / 512.0, 575.0 / 13824.0,
             44275.0 / 110592.0, 253.0 / 4096.0
         ]]
    c = [37.0 / 378.0, 0.0, 250.0 / 621.0, 125.0 / 594.0, 0.0, 512.0 / 1771.0]
    dc = [
        c[0] - 2825.0 / 27648.0, c[1] - 0.0, c[2] - 18575.0 / 48384.0,
        c[3] - 13525.0 / 55296.0, c[4] - 277.00 / 14336.0, c[5] - 0.25
    ]

    def F(t, x, z):
        indices_bl, indices_tr, delta = grid_indices(x, 0, z, nx, 1, nz, dx_di,
                                                     1, dz_di)
        ix1 = indices_bl[0]
        iz1 = indices_bl[2]
        ix2 = indices_tr[0]
        iz2 = indices_tr[2]
        offsetx = delta[0]
        offsetz = delta[2]
        v1 = (1.0 - offsetx) * (1.0 - offsetz)
        v2 = offsetx * (1.0 - offsetz)
        v3 = offsetx * offsetz
        v4 = (1.0 - offsetx) * offsetz
        if (ix1 < nx and ix2 < nx and iz1 < nz and iz2 < nz):
            bx = Bx[iz1, ix1] * v1 + Bx[iz1, ix2] * v2 + Bx[
                iz2, ix2] * v3 + Bx[iz2, ix1] * v4
            bz = Bz[iz1, ix1] * v1 + Bz[iz1, ix2] * v2 + Bz[
                iz2, ix2] * v3 + Bz[iz2, ix1] * v4
            ex = Ex[iz1, ix1] * v1 + Ex[iz1, ix2] * v2 + Ex[
                iz2, ix2] * v3 + Ex[iz2, ix1] * v4
            ez = Ez[iz1, ix1] * v1 + Ez[iz1, ix2] * v2 + Ez[
                iz2, ix2] * v3 + Ez[iz2, ix1] * v4
            absB = math.sqrt(bx**2 + bz**2)
            deltax1 = bx / absB
            deltaz1 = bz / absB
        else:
            ex = 0
            ez = 0
            deltax1 = 0
            deltaz1 = 0
        return (deltax1, deltaz1, ex, ez)

    tol = 1e-5

    x0 = xarr[i] - xarr[0]
    z0 = zarr[k] - zarr[0]
    y = [x0, z0]
    nstep = 0
    xlist = [x0]
    zlist = [z0]
    t = 0
    x = x0
    z = z0
    while (x > 0 and x < (xarr[-1] - xarr[0]) and z > 0 and z <
           (zarr[-1] - zarr[0]) and t < 4E2):
        # Compute k[i] function values.
        kx = [None] * 6
        kz = [None] * 6
        kx[0], kz[0], ex0, ez0 = F(t, x, z)
        kx[1], kz[1], ex1, ez1 = F(t + a[1] * h, x + h * (kx[0] * b[1][0]),
                                   z + h * (kz[0] * b[1][0]))
        kx[2], kz[2], ex2, ez2 = F(t + a[2] * h,
                                   x + h * (kx[0] * b[2][0] + kx[1] * b[2][1]),
                                   z + h * (kz[0] * b[2][0] + kz[1] * b[2][1]))
        kx[3], kz[3], ex3, ez3 = F(
            t + a[3] * h,
            x + h * (kx[0] * b[3][0] + kx[1] * b[3][1] + kx[2] * b[3][2]),
            z + h * (kz[0] * b[3][0] + kz[1] * b[3][1] + kz[2] * b[3][2]))
        kx[4], kz[4], ex4, ez4 = F(
            t + a[4] * h, x + h * (kx[0] * b[4][0] + kx[1] * b[4][1] +
                                   kx[2] * b[4][2] + kx[3] * b[4][3]),
            z + h * (kz[0] * b[4][0] + kz[1] * b[4][1] + kz[2] * b[4][2] +
                     kz[3] * b[4][3]))
        kx[5], kz[5], ex5, ez5 = F(
            t + a[5] * h,
            x + h * (kx[0] * b[5][0] + kx[1] * b[5][1] + kx[2] * b[5][2] +
                     kx[3] * b[5][3] + kx[4] * b[5][4]),
            z + h * (kz[0] * b[5][0] + kz[1] * b[5][1] + kz[2] * b[5][2] +
                     kz[3] * b[5][3] + kz[4] * b[5][4]))

        # Estimate current error and current maximum error.
        E = norm([
            h * (kx[0] * dc[0] + kx[1] * dc[1] + kx[2] * dc[2] +
                 kx[3] * dc[3] + kx[4] * dc[4] + kx[5] * dc[5]),
            h * (kz[0] * dc[0] + kz[1] * dc[1] + kz[2] * dc[2] +
                 kz[3] * dc[3] + kz[4] * dc[4] + kz[5] * dc[5])
        ])
        Emax = tol * max(norm(y), 1.0)

        # Update solution if error is OK.
        if E < Emax:
            t += h
            y[0] += h * (kx[0] * c[0] + kx[1] * c[1] + kx[2] * c[2] +
                         kx[3] * c[3] + kx[4] * c[4] + kx[5] * c[5])
            y[1] += h * (kz[0] * c[0] + kz[1] * c[1] + kz[2] * c[2] +
                         kz[3] * c[3] + kz[4] * c[4] + kz[5] * c[5])
            x = y[0]
            z = y[1]
            xlist.append(x)
            zlist.append(z)
            #out += [(t, list(y))]

        # Update step size
        if E > 0.0:
            h = min(hmax, 0.85 * h * (Emax / E)**0.2)

    width = 0.78
    height = 0.75
    xs = 0.14
    xe = 0.94 - xs
    ys = 0.9 - height
    #fig = plt.figure(figsize=(7,5))
    fig = plt.figure(figsize=(7, 2))
    ax1 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 2, "zstep": 2}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p1, cbar1 = contour_plots.plot_2d_contour(xarr, zarr, Ay, ax1, fig,
                                              **kwargs_plot)
    p1.set_cmap(plt.cm.seismic)
    #    cs = ax1.contour(xarr[0:nx:xstep], zarr[0:nz:zstep], Ay[0:nz:zstep, 0:nx:xstep],
    #            colors='white', linewidths=0.5, levels=np.arange(0, 252, 1))
    p2 = ax1.plot(xlist, zlist + zarr[0], color='black')
    #cbar1.set_ticks(np.arange(-0.8, 1.0, 0.4))
    #ax1.tick_params(axis='x', labelbottom='off')
    plt.show()
示例#27
0
def bulk_energy_change_rate(pic_info, species, current_time):
    """Bulk energy change rate.

    Args:
        pic_info: namedtuple for the PIC simulation information.
        species: 'e' for electrons, 'i' for ions.
        current_time: current time frame.
    """
    kwargs = {
        "current_time": current_time - 1,
        "xl": 0,
        "xr": 200,
        "zb": -15,
        "zt": 15
    }
    fname = "../../data/u" + species + "x.gda"
    x, z, ux = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/u" + species + "y.gda"
    x, z, uy = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/u" + species + "z.gda"
    x, z, uz = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/n" + species + ".gda"
    x, z, nrho = read_2d_fields(pic_info, fname, **kwargs)

    if species == 'e':
        ptl_mass = 1.0
    else:
        ptl_mass = pic_info.mime

    bulk_ene1 = 0.5 * ptl_mass * nrho * (ux**2 + uy**2 + uz**2)

    kwargs = {
        "current_time": current_time + 1,
        "xl": 0,
        "xr": 200,
        "zb": -15,
        "zt": 15
    }
    fname = "../../data/u" + species + "x.gda"
    x, z, ux = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/u" + species + "y.gda"
    x, z, uy = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/u" + species + "z.gda"
    x, z, uz = read_2d_fields(pic_info, fname, **kwargs)
    fname = "../../data/n" + species + ".gda"
    x, z, nrho = read_2d_fields(pic_info, fname, **kwargs)

    bulk_ene2 = 0.5 * ptl_mass * nrho * (ux**2 + uy**2 + uz**2)

    kwargs = {
        "current_time": current_time,
        "xl": 0,
        "xr": 200,
        "zb": -15,
        "zt": 15
    }
    x, z, Ay = read_2d_fields(pic_info, "../../data/Ay.gda", **kwargs)

    bulk_ene_rate = bulk_ene2 - bulk_ene1

    nx, = x.shape
    nz, = z.shape
    width = 0.75
    height = 0.7
    xs = 0.12
    ys = 0.9 - height
    fig = plt.figure(figsize=[10, 4])
    ax1 = fig.add_axes([xs, ys, width, height])
    kwargs_plot = {"xstep": 1, "zstep": 1, "vmin": 0.1, "vmax": -0.1}
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    p1, cbar1 = plot_2d_contour(x, z, bulk_ene_rate, ax1, fig, **kwargs_plot)
    p1.set_cmap(plt.cm.seismic)
    ax1.contour(x[0:nx:xstep],
                z[0:nz:zstep],
                Ay[0:nz:zstep, 0:nx:xstep],
                colors='black',
                linewidths=0.5)
    ax1.set_ylabel(r'$z/d_i$', fontdict=font, fontsize=24)
    ax1.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=24)
    ax1.tick_params(labelsize=24)
    cbar1.ax.set_ylabel(r'$K/u$', fontdict=font, fontsize=24)
    cbar1.ax.tick_params(labelsize=24)

    t_wci = current_time * pic_info.dt_fields
    title = r'$t = ' + "{:10.1f}".format(t_wci) + '/\Omega_{ci}$'
    ax1.set_title(title, fontdict=font, fontsize=24)

    plt.show()