def read_field_data(self):
     """Read 2D field
     """
     self.xl, self.xr = self.field_range[0:2]
     self.zb, self.zt = self.field_range[2:4]
     kwargs = {
         "current_time": self.ct_field,
         "xl": self.xl,
         "xr": self.xr,
         "zb": self.zb,
         "zt": self.zt
     }
     fname_field = self.root_dir + 'data/' + self.var_field + '.gda'
     fname_Ay = self.root_dir + 'data/Ay.gda'
     self.x1, self.z1, data = read_2d_fields(self.pic_info, fname_field,
                                             **kwargs)
     ng = 5
     kernel = np.ones((ng, ng)) / float(ng * ng)
     self.fdata1 = signal.convolve2d(data, kernel)
     self.x1, self.z1, self.Ay1 = read_2d_fields(self.pic_info, fname_Ay,
                                                 **kwargs)
     self.nx1, = self.x1.shape
     self.nz1, = self.z1.shape
     self.xmax1 = np.max(self.x1)
     self.zmax1 = np.max(self.z1)
     self.xmin1 = np.min(self.x1)
     self.zmin1 = np.min(self.z1)
def calc_force_charge_efield_single(job_id, drange):
    print job_id
    ct = job_id
    data_dir = '../data/force/'
    mkdir_p(data_dir)
    force_single = np.zeros(3)
    kwargs = {"current_time": ct, "xl": 0, "xr": 200, "zb": -50, "zt": 50}
    fname1 = root_dir + 'data/ne.gda'
    x, z, ne_all = read_2d_fields(pic_info, fname1, **kwargs)
    fname2 = root_dir + 'data/ni.gda'
    x, z, ni_all = read_2d_fields(pic_info, fname2, **kwargs)
    fname = root_dir + 'data/ex.gda'
    x, z, ex_all = read_2d_fields(pic_info, fname, **kwargs)
    fname = root_dir + 'data/ey.gda'
    x, z, ey_all = read_2d_fields(pic_info, fname, **kwargs)
    fname = root_dir + 'data/ez.gda'
    x, z, ez_all = read_2d_fields(pic_info, fname, **kwargs)
    nx, = x.shape
    nz, = z.shape
    xs = int(drange[0] * nx)
    xe = int(drange[1] * nx)
    zs = int(drange[2] * nz)
    ze = int(drange[3] * nz)
    ne = ne_all[zs:ze, xs:xe]
    ni = ni_all[zs:ze, xs:xe]
    ex = ex_all[zs:ze, xs:xe]
    ey = ey_all[zs:ze, xs:xe]
    ez = ez_all[zs:ze, xs:xe]
    ntot = ni - ne
    force_single[0] = np.sum(ntot * ex)
    force_single[1] = np.sum(ntot * ey)
    force_single[2] = np.sum(ntot * ez)
    fname = data_dir + 'force_' + str(ct) + '.dat'
    force_single.tofile(fname)
Esempio n. 3
0
def get_temperature_cut(run_name, root_dir, pic_info, ct):
    """get temperature cut along a line
    """
    kwargs = {"current_time": ct, "xl": 0, "xr": 200, "zb": -1, "zt": 1}
    fnames_e = ['pe-xx', 'pe-yy', 'pe-zz', 'ne']
    fnames_i = ['pi-xx', 'pi-yy', 'pi-zz', 'ni']
    pe = 0.0
    pi = 0.0
    for name in fnames_e[0:3]:
        fname = root_dir + 'data/' + name + '.gda'
        x, z, data = read_2d_fields(pic_info, fname, **kwargs)
        pe += data
    fname = root_dir + 'data/' + fnames_e[3] + '.gda'
    x, z, nrho = read_2d_fields(pic_info, fname, **kwargs)
    te = pe / nrho / 3.0
    for name in fnames_i[0:3]:
        fname = root_dir + 'data/' + name + '.gda'
        x, z, data = read_2d_fields(pic_info, fname, **kwargs)
        pi += data
    fname = root_dir + 'data/' + fnames_i[3] + '.gda'
    x, z, nrho = read_2d_fields(pic_info, fname, **kwargs)
    ti = pi / nrho / 3.0
    nx, = x.shape
    nz, = z.shape
    return (x, z, te[nz / 2, :], ti[nz / 2, :])
def get_temperature_cut(run_name, root_dir, pic_info, ct):
    """get temperature cut along a line
    """
    kwargs = {"current_time": ct, "xl": 0, "xr": 200, "zb": -1, "zt": 1}
    fnames_e = ['pe-xx', 'pe-yy', 'pe-zz', 'ne']
    fnames_i = ['pi-xx', 'pi-yy', 'pi-zz', 'ni']
    pe = 0.0
    pi = 0.0
    for name in fnames_e[0:3]:
        fname = root_dir + 'data/' + name + '.gda'
        x, z, data = read_2d_fields(pic_info, fname, **kwargs)
        pe += data
    fname = root_dir + 'data/' + fnames_e[3] + '.gda'
    x, z, nrho = read_2d_fields(pic_info, fname, **kwargs)
    te = pe / nrho / 3.0
    for name in fnames_i[0:3]:
        fname = root_dir + 'data/' + name + '.gda'
        x, z, data = read_2d_fields(pic_info, fname, **kwargs)
        pi += data
    fname = root_dir + 'data/' + fnames_i[3] + '.gda'
    x, z, nrho = read_2d_fields(pic_info, fname, **kwargs)
    ti = pi / nrho / 3.0
    nx, = x.shape
    nz, = z.shape
    return (x, z, te[nz / 2, :], ti[nz / 2, :])
def calc_force_charge_efield_single(job_id, drange):
    print job_id
    ct = job_id
    data_dir = '../data/force/'
    mkdir_p(data_dir)
    force_single = np.zeros(3)
    kwargs = {"current_time": ct, "xl": 0, "xr": 200, "zb": -50, "zt": 50}
    fname1 = root_dir + 'data/ne.gda'
    x, z, ne_all = read_2d_fields(pic_info, fname1, **kwargs)
    fname2 = root_dir + 'data/ni.gda'
    x, z, ni_all = read_2d_fields(pic_info, fname2, **kwargs)
    fname = root_dir + 'data/ex.gda'
    x, z, ex_all = read_2d_fields(pic_info, fname, **kwargs)
    fname = root_dir + 'data/ey.gda'
    x, z, ey_all = read_2d_fields(pic_info, fname, **kwargs)
    fname = root_dir + 'data/ez.gda'
    x, z, ez_all = read_2d_fields(pic_info, fname, **kwargs)
    nx, = x.shape
    nz, = z.shape
    xs = int(drange[0] * nx)
    xe = int(drange[1] * nx)
    zs = int(drange[2] * nz)
    ze = int(drange[3] * nz)
    ne = ne_all[zs:ze, xs:xe]
    ni = ni_all[zs:ze, xs:xe]
    ex = ex_all[zs:ze, xs:xe]
    ey = ey_all[zs:ze, xs:xe]
    ez = ez_all[zs:ze, xs:xe]
    ntot = ni - ne
    force_single[0] = np.sum(ntot * ex)
    force_single[1] = np.sum(ntot * ey)
    force_single[2] = np.sum(ntot * ez)
    fname = data_dir + 'force_' + str(ct) + '.dat'
    force_single.tofile(fname)
Esempio n. 6
0
 def read_field_data(self):
     """Read 2D field
     """
     self.xl, self.xr = self.field_range[0:2]
     self.zb, self.zt = self.field_range[2:4]
     kwargs = {
         "current_time": self.ct_field,
         "xl": self.xl,
         "xr": self.xr,
         "zb": self.zb,
         "zt": self.zt
     }
     fname_field = self.root_dir + 'data/' + self.var_field + '.gda'
     fname_Ay = self.root_dir + 'data/Ay.gda'
     self.x1, self.z1, data = read_2d_fields(self.pic_info, fname_field,
                                             **kwargs)
     ng = 5
     kernel = np.ones((ng, ng)) / float(ng * ng)
     self.fdata1 = signal.convolve2d(data, kernel)
     self.x1, self.z1, self.Ay1 = read_2d_fields(self.pic_info, fname_Ay,
                                                 **kwargs)
     self.nx1, = self.x1.shape
     self.nz1, = self.z1.shape
     self.xmax1 = np.max(self.x1)
     self.zmax1 = np.max(self.z1)
     self.xmin1 = np.min(self.x1)
     self.zmin1 = np.min(self.z1)
def read_and_plot(ct, filename):
    """
    Read 2D field and do contour plot.

    Args:
        ct: current time frame.
        filename: the file name including its path.
    """
    kwargs = {"current_time": ct, "xl": 0, "xr": 200, "zb": -50, "zt": 50}
    x, z, num_rho = read_2d_fields(pic_info, filename, **kwargs)
    x, z, Ay = read_2d_fields(pic_info, "../data/Ay.gda", **kwargs)

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

    kwargs_plot = {
        "xstep": 2,
        "zstep": 2,
        "is_log": True,
        "vmin": -1,
        "vmax": 1
    }
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    data = num_rho[0:nz:zstep, 0:nx:xstep]
    print "Maximum and minimum of the data: ", np.max(data), np.min(data)

    im1 = ax1.imshow(
        data,
        cmap=plt.cm.seismic,
        extent=[xmin, xmax, zmin, zmax],
        aspect='auto',
        origin='lower',
        vmin=kwargs_plot["vmin"],
        vmax=kwargs_plot["vmax"],
        interpolation='bicubic')
    # norm=LogNorm(vmin=kwargs_plot["vmin"], 
    #     vmax=kwargs_plot["vmax"]))
    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=32)
    ax1.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=32)
    ax1.tick_params(labelsize=32)

    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=32)

    return im1
def read_and_plot(ct, filename):
    """
    Read 2D field and do contour plot.

    Args:
        ct: current time frame.
        filename: the file name including its path.
    """
    kwargs = {"current_time": ct, "xl": 0, "xr": 200, "zb": -50, "zt": 50}
    x, z, num_rho = read_2d_fields(pic_info, filename, **kwargs)
    x, z, Ay = read_2d_fields(pic_info, "../data/Ay.gda", **kwargs)

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

    kwargs_plot = {
        "xstep": 2,
        "zstep": 2,
        "is_log": True,
        "vmin": -1,
        "vmax": 1
    }
    xstep = kwargs_plot["xstep"]
    zstep = kwargs_plot["zstep"]
    data = num_rho[0:nz:zstep, 0:nx:xstep]
    print "Maximum and minimum of the data: ", np.max(data), np.min(data)

    im1 = ax1.imshow(data,
                     cmap=plt.cm.seismic,
                     extent=[xmin, xmax, zmin, zmax],
                     aspect='auto',
                     origin='lower',
                     vmin=kwargs_plot["vmin"],
                     vmax=kwargs_plot["vmax"],
                     interpolation='bicubic')
    # norm=LogNorm(vmin=kwargs_plot["vmin"],
    #     vmax=kwargs_plot["vmax"]))
    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=32)
    ax1.set_xlabel(r'$x/d_i$', fontdict=font, fontsize=32)
    ax1.tick_params(labelsize=32)

    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=32)

    return im1
def check_exb(run_dir, pic_info, tframe):
    """
    Check calculated ExB drift
    """
    kwargs = {"current_time": tframe, "xl": 0, "xr": pic_info.lx_di,
              "zb": -0.5 * pic_info.lz_di, "zt": 0.5 * pic_info.lz_di}
    size_one_frame = pic_info.nx * pic_info.nz * 4
    fname = run_dir + "data1/vexb_x.gda"
    x, z, vexbx1 = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data1/vexb_y.gda"
    x, z, vexby1 = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data1/vexb_z.gda"
    x, z, vexbz1 = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data/ex.gda"
    x, z, ex = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data/ey.gda"
    x, z, ey = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data/ez.gda"
    x, z, ez = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data/bx.gda"
    x, z, bx = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data/by.gda"
    x, z, by = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data/bz.gda"
    x, z, bz = read_2d_fields(pic_info, fname, **kwargs)
    ib2 = 1.0 / (bx**2 + by**2 + bz**2)
    vexbx2 = (ey * bz - ez * by) * ib2
    vexby2 = (ez * bx - ex * bz) * ib2
    vexbz2 = (ex * by - ey * bx) * ib2
    p1 = plt.imshow(vexbz2 - vexbz1, cmap=plt.cm.jet,
                    # extent=[xmin, xmax, zmin, zmax],
                    # vmin=vmin, vmax=vmax,
                    aspect='auto', origin='lower',
                    interpolation='bicubic')
    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()
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()
Esempio n. 12
0
def smooth_emf(run_dir, pic_info, emf_name, tframe, coords):
    """
    Smooth electric and magnetic field
    """
    kwargs = {
        "current_time": tframe,
        "xl": 0,
        "xr": pic_info.lx_di,
        "zb": -0.5 * pic_info.lz_di,
        "zt": 0.5 * pic_info.lz_di
    }
    size_one_frame = pic_info.nx * pic_info.nz * 4
    # fname = run_dir + "data/original_data/" + emf_name + ".gda"
    fname = run_dir + "data1/original_data/" + emf_name + ".gda"
    statinfo = os.stat(fname)
    file_size = statinfo.st_size
    if file_size < size_one_frame * (tframe + 1):
        return
    else:
        x, z, fdata = read_2d_fields(pic_info, fname, **kwargs)
    sigma = 5
    fdata = median_filter(fdata, sigma)
    # fname = run_dir + "data/" + emf_name + ".gda"
    fname = run_dir + "data1/" + emf_name + ".gda"
    with open(fname, 'a+') as f:
        offset = size_one_frame * tframe
        f.seek(offset, os.SEEK_SET)
        fdata.tofile(f)
def histogram_field(pic_info, var_name, fname, **kwargs):
    """Plot a histogram of a field.

    Args:
        pic_info: namedtuple for the PIC simulation information.
        var_name: variable name.
        fname: file name.
    """
    x, z, field_data = read_2d_fields(pic_info, fname, **kwargs)
    dmax = np.max(field_data)
    dmin = np.min(field_data)
    dmin = -100.0
    dmax = 100.0
    nb = 1000
    print np.sum(field_data)
    bins = np.linspace(dmin, dmax, nb)
    hist, bin_edges = np.histogram(field_data, bins)
    print np.sum(hist)
    print 'Maximum and Minimum of the field: ', dmax, dmin
    fig = plt.figure(figsize=[7, 5])
    width = 0.8
    height = 0.8
    ax = fig.add_axes([0.12, 0.15, width, height])
    hist_f = np.array(hist, dtype=np.float64)
    hist_f /= np.max(hist_f)
    p1 = ax.semilogy(bins[:nb - 1], hist_f, linewidth=2)
    ax.tick_params(labelsize=16)
    ax.set_xlabel(var_name, fontdict=font, fontsize=20)
    qname = r'$f($' + var_name + '$)$'
    ax.set_ylabel(qname, fontdict=font, fontsize=20)
    plt.show()
def histogram_field(pic_info, var_name, fname, **kwargs):
    """Plot a histogram of a field.

    Args:
        pic_info: namedtuple for the PIC simulation information.
        var_name: variable name.
        fname: file name.
    """
    x, z, field_data = read_2d_fields(pic_info, fname, **kwargs)
    dmax = np.max(field_data)
    dmin = np.min(field_data)
    dmin = -100.0
    dmax = 100.0
    nb = 1000
    print np.sum(field_data)
    bins = np.linspace(dmin, dmax, nb)
    hist, bin_edges = np.histogram(field_data, bins)
    print np.sum(hist)
    print 'Maximum and Minimum of the field: ', dmax, dmin
    fig = plt.figure(figsize=[7, 5])
    width = 0.8
    height = 0.8
    ax = fig.add_axes([0.12, 0.15, width, height])
    hist_f = np.array(hist, dtype=np.float64)
    hist_f /= np.max(hist_f)
    p1 = ax.semilogy(bins[:nb - 1], hist_f, linewidth=2)
    ax.tick_params(labelsize=16)
    ax.set_xlabel(var_name, fontdict=font, fontsize=20)
    qname = r'$f($' + var_name + '$)$'
    ax.set_ylabel(qname, fontdict=font, fontsize=20)
    plt.show()
def calc_reconnection_rate(base_dir):
    """Calculate reconnection rate.

    Args:
        base_dir: the directory base.
    """
    pic_info = pic_information.get_pic_info(base_dir)
    ntf = pic_info.ntf
    phi = np.zeros(ntf)
    fname = base_dir + 'data/Ay.gda'
    for ct in range(ntf):
        kwargs = {"current_time": ct, "xl": 0, "xr": 200, "zb": -1, "zt": 1}
        x, z, Ay = read_2d_fields(pic_info, fname, **kwargs)
        nz, = z.shape
        # max_ay = np.max(np.sum(Ay[nz/2-1:nz/2+1, :], axis=0)/2)
        # min_ay = np.min(np.sum(Ay[nz/2-1:nz/2+1, :], axis=0)/2)
        max_ay = np.max(Ay[nz / 2 - 1:nz / 2 + 1, :])
        min_ay = np.min(Ay[nz / 2 - 1:nz / 2 + 1, :])
        phi[ct] = max_ay - min_ay
    nk = 3
    phi = signal.medfilt(phi, kernel_size=nk)
    dtwpe = pic_info.dtwpe
    dtwce = pic_info.dtwce
    dtwci = pic_info.dtwci
    mime = pic_info.mime
    dtf_wpe = pic_info.dt_fields * dtwpe / dtwci
    reconnection_rate = np.gradient(phi) / dtf_wpe
    b0 = pic_info.b0
    va = dtwce * math.sqrt(1.0 / mime) / dtwpe
    reconnection_rate /= b0 * va
    reconnection_rate[-1] = reconnection_rate[-2]
    tfields = pic_info.tfields

    return (tfields, reconnection_rate)
def calc_reconnection_rate(base_dir):
    """Calculate reconnection rate.

    Args:
        base_dir: the directory base.
    """
    pic_info = pic_information.get_pic_info(base_dir)
    ntf = pic_info.ntf
    phi = np.zeros(ntf)
    fname = base_dir + 'data/Ay.gda'
    for ct in range(ntf):
        kwargs = {"current_time": ct, "xl": 0, "xr": 200, "zb": -1, "zt": 1}
        x, z, Ay = read_2d_fields(pic_info, fname, **kwargs)
        nz, = z.shape
        # max_ay = np.max(np.sum(Ay[nz/2-1:nz/2+1, :], axis=0)/2)
        # min_ay = np.min(np.sum(Ay[nz/2-1:nz/2+1, :], axis=0)/2)
        max_ay = np.max(Ay[nz / 2 - 1:nz / 2 + 1, :])
        min_ay = np.min(Ay[nz / 2 - 1:nz / 2 + 1, :])
        phi[ct] = max_ay - min_ay
    nk = 3
    phi = signal.medfilt(phi, kernel_size=nk)
    dtwpe = pic_info.dtwpe
    dtwce = pic_info.dtwce
    dtwci = pic_info.dtwci
    mime = pic_info.mime
    dtf_wpe = pic_info.dt_fields * dtwpe / dtwci
    reconnection_rate = np.gradient(phi) / dtf_wpe
    b0 = pic_info.b0
    va = dtwce * math.sqrt(1.0 / mime) / dtwpe
    reconnection_rate /= b0 * va
    reconnection_rate[-1] = reconnection_rate[-2]
    tfields = pic_info.tfields

    return (tfields, reconnection_rate)
def values_along_cut(fname, current_time, lcorner, weights):
    """Values along a straight cut.

    Args:
        fname: the filename of the data.
        current_time: current time frame.
        lcorner: the indices of the lower left of the cells in which
            the line points are.
        weights: the weight for 2D linear interpolation.
    Returns:
        dvalue: the values of the data along a cut.
    """
    kwargs = {
        "current_time": current_time,
        "xl": 0,
        "xr": 200,
        "zb": -50,
        "zt": 50
    }
    x, z, data = read_2d_fields(pic_info, fname, **kwargs)
    tmp, npoints = lcorner.shape
    dvalue = np.zeros(npoints)
    for i in range(npoints):
        dvalue[i] += data[lcorner[1, i], lcorner[0, i]] * weights[0, i]
        dvalue[i] += data[lcorner[1, i], lcorner[0, i] + 1] * weights[1, i]
        dvalue[i] += data[lcorner[1, i] + 1, lcorner[0, i] + 1] * weights[2, i]
        dvalue[i] += data[lcorner[1, i] + 1, lcorner[0, i]] * weights[3, i]

    return dvalue
def values_along_cut(fname, current_time, lcorner, weights):
    """Values along a straight cut.

    Args:
        fname: the filename of the data.
        current_time: current time frame.
        lcorner: the indices of the lower left of the cells in which
            the line points are.
        weights: the weight for 2D linear interpolation.
    Returns:
        dvalue: the values of the data along a cut.
    """
    kwargs = {
        "current_time": current_time,
        "xl": 0,
        "xr": 200,
        "zb": -50,
        "zt": 50
    }
    x, z, data = read_2d_fields(pic_info, fname, **kwargs)
    tmp, npoints = lcorner.shape
    dvalue = np.zeros(npoints)
    for i in range(npoints):
        dvalue[i] += data[lcorner[1, i], lcorner[0, i]] * weights[0, i]
        dvalue[i] += data[lcorner[1, i], lcorner[0, i] + 1] * weights[1, i]
        dvalue[i] += data[lcorner[1, i] + 1, lcorner[0, i] + 1] * weights[2, i]
        dvalue[i] += data[lcorner[1, i] + 1, lcorner[0, i]] * weights[3, i]

    return dvalue
Esempio n. 19
0
def bulk_energy_distribution(pic_info, species):
    """Get the distribution of bulk flow energy.

    Args:
        pic_info: namedtuple for the PIC simulation information.
        species: 'e' for electrons, 'i' for ions.
    """
    if species == 'e':
        ptl_mass = 1.0
    else:
        ptl_mass = pic_info.mime

    nbins = 100
    ebins, nrho_bins = set_energy_density_bins(nbins)

    ntf = pic_info.ntf
    ehist = np.zeros((ntf, nbins - 1))
    erho_hist = np.zeros((ntf, nbins - 1))
    nhist = np.zeros((ntf, nbins - 1))
    for ct in range(ntf):
        kwargs = {"current_time": ct, "xl": 0, "xr": 200, "zb": -50, "zt": 50}
        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)
        bene = 0.5 * ptl_mass * (ux * ux + uy * uy + uz * uz)
        bene_density = 0.5 * ptl_mass * nrho * (ux * ux + uy * uy + uz * uz)
        ehist[ct, :], bin_edges = np.histogram(bene, bins=ebins, density=True)
        erho_hist[ct, :], bin_edges = np.histogram(bene_density,
                                                   bins=ebins,
                                                   density=True)
        nhist[ct, :], bin_edges = np.histogram(nrho,
                                               bins=nrho_bins,
                                               density=True)
    f = open('../data/bulk_energy.dat', 'w')
    np.savetxt(f, ehist)
    f.close()
    f = open('../data/bulk_energy_density.dat', 'w')
    np.savetxt(f, erho_hist)
    f.close()
    f = open('../data/number_density.dat', 'w')
    np.savetxt(f, nhist)
    f.close()
def bulk_energy_distribution(pic_info, species):
    """Get the distribution of bulk flow energy.

    Args:
        pic_info: namedtuple for the PIC simulation information.
        species: 'e' for electrons, 'i' for ions.
    """
    if species == 'e':
        ptl_mass = 1.0
    else:
        ptl_mass = pic_info.mime

    nbins = 100
    ebins, nrho_bins = set_energy_density_bins(nbins)

    ntf = pic_info.ntf
    ehist = np.zeros((ntf, nbins - 1))
    erho_hist = np.zeros((ntf, nbins - 1))
    nhist = np.zeros((ntf, nbins - 1))
    for ct in range(ntf):
        kwargs = {"current_time": ct, "xl": 0, "xr": 200, "zb": -50, "zt": 50}
        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)
        bene = 0.5 * ptl_mass * (ux * ux + uy * uy + uz * uz)
        bene_density = 0.5 * ptl_mass * nrho * (ux * ux + uy * uy + uz * uz)
        ehist[ct, :], bin_edges = np.histogram(bene, bins=ebins, density=True)
        erho_hist[ct, :], bin_edges = np.histogram(
            bene_density, bins=ebins, density=True)
        nhist[ct, :], bin_edges = np.histogram(
            nrho, bins=nrho_bins, density=True)
    f = open('../data/bulk_energy.dat', 'w')
    np.savetxt(f, ehist)
    f.close()
    f = open('../data/bulk_energy_density.dat', 'w')
    np.savetxt(f, erho_hist)
    f.close()
    f = open('../data/number_density.dat', 'w')
    np.savetxt(f, nhist)
    f.close()
Esempio n. 21
0
def smooth_interp_emf(run_dir, pic_info, eb_field_name, tframe, coords):
    """
    Smooth electric and magnetic field and also interpolate them to
    grid locations where hydro quantities are.
    """
    kwargs = {
        "current_time": tframe,
        "xl": 0,
        "xr": pic_info.lx_di,
        "zb": -0.5 * pic_info.lz_di,
        "zt": 0.5 * pic_info.lz_di
    }
    size_one_frame = pic_info.nx * pic_info.nz * 4
    fname = run_dir + "data/" + eb_field_name + "_original.gda"
    statinfo = os.stat(fname)
    file_size = statinfo.st_size
    if file_size < size_one_frame * (tframe + 1):
        return
    else:
        x, z, fdata = read_2d_fields(pic_info, fname, **kwargs)
    if 'ex' in eb_field_name or 'bz' in eb_field_name:
        f = MultilinearInterpolator(coords["smin_ex_bz"],
                                    coords["smax_ex_bz"],
                                    coords["orders"],
                                    dtype=np.float32)
    elif 'ez' in eb_field_name or 'bx' in eb_field_name:
        f = MultilinearInterpolator(coords["smin_ez_bx"],
                                    coords["smax_ez_bx"],
                                    coords["orders"],
                                    dtype=np.float32)
    elif 'ey' in eb_field_name:
        f = MultilinearInterpolator(coords["smin_h"],
                                    coords["smax_h"],
                                    coords["orders"],
                                    dtype=np.float32)
    else:
        f = MultilinearInterpolator(coords["smin_by"],
                                    coords["smax_by"],
                                    coords["orders"],
                                    dtype=np.float32)
    f.set_values(np.atleast_2d(np.transpose(fdata).flatten()))
    nx = pic_info.nx
    nz = pic_info.nz
    fdata = f(coords["coord"])
    fdata = np.transpose(f(coords["coord"]).reshape((nx, nz)))
    # only smooth electric field
    if any(ename in eb_field_name for ename in ['ex', 'ey', 'ez']):
        sigma = 3
        fdata = gaussian_filter(fdata, sigma)
    fname = run_dir + "data/" + eb_field_name + ".gda"
    with open(fname, 'a+') as f:
        offset = size_one_frame * tframe
        f.seek(offset, os.SEEK_SET)
        fdata.tofile(f)
 def update_field(self, val):
     self.ct = self.field_slider.val
     kwargs = {
         "current_time": self.ct,
         "xl": 0,
         "xr": 400,
         "zb": -100,
         "zt": 100
     }
     fname = '../../data/' + var_field + '.gda'
     x, z, self.fdata = read_2d_fields(self.pic_info, fname, **kwargs)
     self.im1.set_data(self.fdata)
     self.fig.canvas.draw_idle()
 def plot_extra_contour(self):
     if (self.xmax_b > self.pic_info.lx_di):
         ex = self.xmax_b - self.pic_info.lx_di
         kwargs = {
             "current_time": self.ct,
             "xl": 0,
             "xr": ex,
             "zb": self.field_range[2],
             "zt": self.field_range[3]
         }
         fname_field = '../../data/' + self.var_field + '.gda'
         fname_Ay = '../../data/Ay.gda'
         x, z, fdata = read_2d_fields(self.pic_info, fname_field, **kwargs)
         ng = 5
         kernel = np.ones((ng, ng)) / float(ng * ng)
         fdata = signal.convolve2d(fdata, kernel)
         x, z, Ay = read_2d_fields(self.pic_info, fname_Ay, **kwargs)
         nx, = x.shape
         nz, = z.shape
         ex_grid = ex / self.pic_info.dx_di + 1
         xmin = self.pic_info.lx_di
         xmax = xmin + ex
         self.im1 = self.xz_axis.imshow(
             fdata[0:nz:self.zst, 0:nx:self.xst],
             cmap=self.cmap,
             extent=[xmin, xmax, self.zmin1, self.zmax1],
             aspect='auto',
             origin='lower',
             vmin=-self.vmax,
             vmax=self.vmax,
             interpolation='bicubic')
         x += xmin
         self.xz_axis.contour(
             x[0:nx:self.xst],
             z[0:nz:self.zst],
             Ay[0:nz:self.zst, 0:nx:self.xst],
             colors='black',
             linewidths=0.5,
             levels=self.levels)
Esempio n. 24
0
def check_exb(run_dir, pic_info, tframe):
    """
    Check calculated ExB drift
    """
    kwargs = {
        "current_time": tframe,
        "xl": 0,
        "xr": pic_info.lx_di,
        "zb": -0.5 * pic_info.lz_di,
        "zt": 0.5 * pic_info.lz_di
    }
    size_one_frame = pic_info.nx * pic_info.nz * 4
    fname = run_dir + "data1/vexb_x.gda"
    x, z, vexbx1 = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data1/vexb_y.gda"
    x, z, vexby1 = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data1/vexb_z.gda"
    x, z, vexbz1 = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data/ex.gda"
    x, z, ex = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data/ey.gda"
    x, z, ey = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data/ez.gda"
    x, z, ez = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data/bx.gda"
    x, z, bx = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data/by.gda"
    x, z, by = read_2d_fields(pic_info, fname, **kwargs)
    fname = run_dir + "data/bz.gda"
    x, z, bz = read_2d_fields(pic_info, fname, **kwargs)
    ib2 = 1.0 / (bx**2 + by**2 + bz**2)
    vexbx2 = (ey * bz - ez * by) * ib2
    vexby2 = (ez * bx - ex * bz) * ib2
    vexbz2 = (ex * by - ey * bx) * ib2
    p1 = plt.imshow(
        vexbz2 - vexbz1,
        cmap=plt.cm.jet,
        # extent=[xmin, xmax, zmin, zmax],
        # vmin=vmin, vmax=vmax,
        aspect='auto',
        origin='lower',
        interpolation='bicubic')
    plt.show()
def calc_avg_bfield(pic_info, ct, run_name, xm, base_dir='../../'):
    """Calculate the average magnetic field in the shock downstream

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

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

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

    data_dir = '../data/b_average/'
    mkdir_p(data_dir)
    fname = data_dir + 'bavg_' + str(ct) + '.txt'
    bavg.tofile(fname)
 def plot_extra_contour(self):
     if (self.xmax_b > self.pic_info.lx_di):
         ex = self.xmax_b - self.pic_info.lx_di
         kwargs = {
             "current_time": self.ct,
             "xl": 0,
             "xr": ex,
             "zb": self.field_range[2],
             "zt": self.field_range[3]
         }
         fname_field = '../../data/' + self.var_field + '.gda'
         fname_Ay = '../../data/Ay.gda'
         x, z, fdata = read_2d_fields(self.pic_info, fname_field, **kwargs)
         ng = 5
         kernel = np.ones((ng, ng)) / float(ng * ng)
         fdata = signal.convolve2d(fdata, kernel)
         x, z, Ay = read_2d_fields(self.pic_info, fname_Ay, **kwargs)
         nx, = x.shape
         nz, = z.shape
         ex_grid = ex / self.pic_info.dx_di + 1
         xmin = self.pic_info.lx_di
         xmax = xmin + ex
         self.im1 = self.xz_axis.imshow(
             fdata[0:nz:self.zst, 0:nx:self.xst],
             cmap=self.cmap,
             extent=[xmin, xmax, self.zmin1, self.zmax1],
             aspect='auto',
             origin='lower',
             vmin=-self.vmax,
             vmax=self.vmax,
             interpolation='bicubic')
         x += xmin
         self.xz_axis.contour(x[0:nx:self.xst],
                              z[0:nz:self.zst],
                              Ay[0:nz:self.zst, 0:nx:self.xst],
                              colors='black',
                              linewidths=0.5,
                              levels=self.levels)
def calc_avg_bfield(pic_info, ct, run_name, xm, base_dir='../../'):
    """Calculate the average magnetic field in the shock downstream

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

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

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

    data_dir = '../data/b_average/'
    mkdir_p(data_dir)
    fname = data_dir + 'bavg_' + str(ct) + '.txt'
    bavg.tofile(fname)
 def update(self, val):
     ct = self.slider.val
     ratio = self.pic_info.particle_interval / self.pic_info.fields_interval
     kwargs = {
         "current_time": ct * ratio,
         "xl": 0,
         "xr": 200,
         "zb": -50,
         "zt": 50
     }
     fname = "../../data/by.gda"
     x, z, data = read_2d_fields(self.pic_info, fname, **kwargs)
     self.im1.set_data(data)
     self.fig.canvas.draw_idle()
def plot_particle_phase_distribution(pic_info, ct, base_dir, run_name, species,
                                     shock_pos):
    """
    """
    particle_interval = pic_info.particle_interval
    tratio = particle_interval / pic_info.fields_interval
    ptl_tindex = ct * particle_interval / tratio
    xmin, xmax = 0, pic_info.lx_di
    xmin, xmax = 0, 105
    zmin, zmax = -0.5 * pic_info.lz_di, 0.5 * pic_info.lz_di
    kwargs = {
        "current_time": ct,
        "xl": xmin,
        "xr": xmax,
        "zb": zmin,
        "zt": zmax
    }
    fname = base_dir + 'data1/vex.gda'
    x, z, vel = read_2d_fields(pic_info, fname, **kwargs)
    # nx, = x.shape
    # nz, = z.shape
    # data_cum = np.sum(vel, axis=0) / nz
    # data_grad = np.abs(np.gradient(data_cum))
    # xs = 5
    # max_index = np.argmax(data_grad[xs:])
    # xm = x[max_index]
    xm = x[shock_pos]
    max_index = shock_pos

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

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

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

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

    # plt.show()
    plt.close("all")
Esempio n. 30
0
 def update(self, val):
     ct = self.slider.val
     ratio = self.pic_info.particle_interval / self.pic_info.fields_interval
     kwargs = {
         "current_time": ct * ratio,
         "xl": 0,
         "xr": 200,
         "zb": -50,
         "zt": 50
     }
     fname = "../../data/by.gda"
     x, z, data = read_2d_fields(self.pic_info, fname, **kwargs)
     self.im1.set_data(data)
     self.fig.canvas.draw_idle()
def smooth_interp_emf(run_dir, pic_info, eb_field_name, tframe, coords):
    """
    Smooth electric and magnetic field and also interpolate them to
    grid locations where hydro quantities are.
    """
    kwargs = {"current_time": tframe, "xl": 0, "xr": pic_info.lx_di,
              "zb": -0.5 * pic_info.lz_di, "zt": 0.5 * pic_info.lz_di}
    size_one_frame = pic_info.nx * pic_info.nz * 4
    fname = run_dir + "data/" + eb_field_name + "_original.gda"
    statinfo = os.stat(fname)
    file_size = statinfo.st_size
    if file_size < size_one_frame * (tframe + 1):
        return
    else:
        x, z, fdata = read_2d_fields(pic_info, fname, **kwargs)
    if 'ex' in eb_field_name or 'bz' in eb_field_name:
        f = MultilinearInterpolator(coords["smin_ex_bz"],
                                    coords["smax_ex_bz"],
                                    coords["orders"],
                                    dtype=np.float32)
    elif 'ez' in eb_field_name or 'bx' in eb_field_name:
        f = MultilinearInterpolator(coords["smin_ez_bx"],
                                    coords["smax_ez_bx"],
                                    coords["orders"],
                                    dtype=np.float32)
    elif 'ey' in eb_field_name:
        f = MultilinearInterpolator(coords["smin_h"],
                                    coords["smax_h"],
                                    coords["orders"],
                                    dtype=np.float32)
    else:
        f = MultilinearInterpolator(coords["smin_by"],
                                    coords["smax_by"],
                                    coords["orders"],
                                    dtype=np.float32)
    f.set_values(np.atleast_2d(np.transpose(fdata).flatten()))
    nx = pic_info.nx
    nz = pic_info.nz
    fdata = f(coords["coord"])
    fdata = np.transpose(f(coords["coord"]).reshape((nx, nz)))
    # only smooth electric field
    if any(ename in eb_field_name for ename in ['ex', 'ey', 'ez']):
        sigma = 3
        fdata = gaussian_filter(fdata, sigma)
    fname = run_dir + "data/" + eb_field_name + ".gda"
    with open(fname, 'a+') as f:
        offset = size_one_frame * tframe
        f.seek(offset, os.SEEK_SET)
        fdata.tofile(f)
def plot_particle_trajectory(fnames, species, pic_info):
    """Plot particle trajectory.

    Args:
        fnames: file names for the trajectory files.
        species: particle species.
        pic_info: particle information namedtuple.
    """
    init_ft = 190
    nptl = len(fnames)
    var_field = 'ey'
    var_name = '$E_y$'
    kwargs = {"current_time": init_ft, "xl": 0, "xr": 200, "zb": -50, "zt": 50}
    fname = '../../data/' + var_field + '.gda'
    x, z, data = read_2d_fields(pic_info, fname, **kwargs)
    ng = 3
    kernel = np.ones((ng, ng)) / float(ng * ng)
    data = signal.convolve2d(data, kernel)
    fname = '../../data/Ay.gda'
    x, z, Ay = read_2d_fields(pic_info, fname, **kwargs)
    iptl = 393
    fig_v = ParticleTrajectory(nptl, iptl, x, z, data, Ay, init_ft, var_field,
                               var_name, species, fnames)
    plt.show()
Esempio n. 33
0
def plot_particle_trajectory(fnames, species, pic_info):
    """Plot particle trajectory.

    Args:
        fnames: file names for the trajectory files.
        species: particle species.
        pic_info: particle information namedtuple.
    """
    init_ft = 190
    nptl = len(fnames)
    var_field = 'ey'
    var_name = '$E_y$'
    kwargs = {"current_time": init_ft, "xl": 0, "xr": 200, "zb": -50, "zt": 50}
    fname = '../../data/' + var_field + '.gda'
    x, z, data = read_2d_fields(pic_info, fname, **kwargs)
    ng = 3
    kernel = np.ones((ng, ng)) / float(ng * ng)
    data = signal.convolve2d(data, kernel)
    fname = '../../data/Ay.gda'
    x, z, Ay = read_2d_fields(pic_info, fname, **kwargs)
    iptl = 393
    fig_v = ParticleTrajectory(nptl, iptl, x, z, data, Ay, init_ft, var_field,
                               var_name, species, fnames)
    plt.show()
    def read_field_data(self):
        self.xl, self.xr = self.field_range[0, 0:2]
        self.zb, self.zt = self.field_range[0, 2:4]
        kwargs = {
            "current_time": self.ct[0],
            "xl": self.xl,
            "xr": self.xr,
            "zb": self.zb,
            "zt": self.zt
        }
        fname_field = '../../data/' + self.var_field + '.gda'
        fname_Ay = '../../data/Ay.gda'
        self.x1, self.z1, data = read_2d_fields(self.pic_info, fname_field,
                                                **kwargs)
        ng = 5
        kernel = np.ones((ng, ng)) / float(ng * ng)
        self.fdata1 = signal.convolve2d(data, kernel)
        self.x1, self.z1, self.Ay1 = read_2d_fields(self.pic_info, fname_Ay,
                                                    **kwargs)
        self.nx1, = self.x1.shape
        self.nz1, = self.z1.shape

        self.xl, self.xr = self.field_range[1, 0:2]
        self.zb, self.zt = self.field_range[1, 2:4]
        kwargs = {
            "current_time": self.ct[1],
            "xl": self.xl,
            "xr": self.xr,
            "zb": self.zb,
            "zt": self.zt
        }
        self.x2, self.z2, data = read_2d_fields(self.pic_info, fname_field,
                                                **kwargs)
        self.fdata2 = signal.convolve2d(data, kernel)
        self.x2, self.z2, self.Ay2 = read_2d_fields(self.pic_info, fname_Ay,
                                                    **kwargs)
        self.nx2, = self.x2.shape
        self.nz2, = self.z2.shape

        self.xl, self.xr = self.field_range[2, 0:2]
        self.zb, self.zt = self.field_range[2, 2:4]
        kwargs = {
            "current_time": self.ct[2],
            "xl": self.xl,
            "xr": self.xr,
            "zb": self.zb,
            "zt": self.zt
        }
        self.x3, self.z3, data = read_2d_fields(self.pic_info, fname_field,
                                                **kwargs)
        self.fdata3 = signal.convolve2d(data, kernel)
        self.x3, self.z3, self.Ay3 = read_2d_fields(self.pic_info, fname_Ay,
                                                    **kwargs)
        self.nx3, = self.x3.shape
        self.nz3, = self.z3.shape
    def read_field_data(self):
        self.xl, self.xr = self.field_range[0, 0:2]
        self.zb, self.zt = self.field_range[0, 2:4]
        kwargs = {
            "current_time": self.ct[0],
            "xl": self.xl,
            "xr": self.xr,
            "zb": self.zb,
            "zt": self.zt
        }
        fname_field = '../../data/' + self.var_field + '.gda'
        fname_Ay = '../../data/Ay.gda'
        self.x1, self.z1, data = read_2d_fields(self.pic_info, fname_field,
                                                **kwargs)
        ng = 5
        kernel = np.ones((ng, ng)) / float(ng * ng)
        self.fdata1 = signal.convolve2d(data, kernel)
        self.x1, self.z1, self.Ay1 = read_2d_fields(self.pic_info, fname_Ay,
                                                    **kwargs)
        self.nx1, = self.x1.shape
        self.nz1, = self.z1.shape

        self.xl, self.xr = self.field_range[1, 0:2]
        self.zb, self.zt = self.field_range[1, 2:4]
        kwargs = {
            "current_time": self.ct[1],
            "xl": self.xl,
            "xr": self.xr,
            "zb": self.zb,
            "zt": self.zt
        }
        self.x2, self.z2, data = read_2d_fields(self.pic_info, fname_field,
                                                **kwargs)
        self.fdata2 = signal.convolve2d(data, kernel)
        self.x2, self.z2, self.Ay2 = read_2d_fields(self.pic_info, fname_Ay,
                                                    **kwargs)
        self.nx2, = self.x2.shape
        self.nz2, = self.z2.shape

        self.xl, self.xr = self.field_range[2, 0:2]
        self.zb, self.zt = self.field_range[2, 2:4]
        kwargs = {
            "current_time": self.ct[2],
            "xl": self.xl,
            "xr": self.xr,
            "zb": self.zb,
            "zt": self.zt
        }
        self.x3, self.z3, data = read_2d_fields(self.pic_info, fname_field,
                                                **kwargs)
        self.fdata3 = signal.convolve2d(data, kernel)
        self.x3, self.z3, self.Ay3 = read_2d_fields(self.pic_info, fname_Ay,
                                                    **kwargs)
        self.nx3, = self.x3.shape
        self.nz3, = self.z3.shape
Esempio n. 36
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 shock_current_sheet():
    """
    """
    ct = 370
    cts = range(10, pic_info.ntf - 1, tratio)
    ixs = range(pic_info.topology_x)
    shock_loc = np.genfromtxt(
        '../data/shock_pos/shock_pos.txt', dtype=np.int32)
    xmin, xmax = 0, 105
    zmin, zmax = -0.5 * pic_info.lz_di, 0.5 * pic_info.lz_di
    kwargs = {
        "current_time": ct,
        "xl": xmin,
        "xr": xmax,
        "zb": zmin,
        "zt": zmax
    }
    fname = base_dir + 'data1/vex.gda'
    x, z, vx = read_2d_fields(pic_info, fname, **kwargs)
    xm = x[shock_loc[ct]]
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 smooth_emf(run_dir, pic_info, emf_name, tframe, coords):
    """
    Smooth electric and magnetic field
    """
    kwargs = {"current_time": tframe, "xl": 0, "xr": pic_info.lx_di,
              "zb": -0.5 * pic_info.lz_di, "zt": 0.5 * pic_info.lz_di}
    size_one_frame = pic_info.nx * pic_info.nz * 4
    # fname = run_dir + "data/original_data/" + emf_name + ".gda"
    fname = run_dir + "data1/original_data/" + emf_name + ".gda"
    statinfo = os.stat(fname)
    file_size = statinfo.st_size
    if file_size < size_one_frame * (tframe + 1):
        return
    else:
        x, z, fdata = read_2d_fields(pic_info, fname, **kwargs)
    sigma = 5
    fdata = median_filter(fdata, sigma)
    # fname = run_dir + "data/" + emf_name + ".gda"
    fname = run_dir + "data1/" + emf_name + ".gda"
    with open(fname, 'a+') as f:
        offset = size_one_frame * tframe
        f.seek(offset, os.SEEK_SET)
        fdata.tofile(f)
def plot_ne_jdote(pic_info, root_dir, run_name, current_time):
    """
    Plot electron number density and jdote

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

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

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

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

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

    jdote /= pic_info.b0 * va

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

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

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

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

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

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

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

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

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

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

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

    fdir = '../img/img_apjl/ne_jdote/' + run_name + '/'
    mkdir_p(fdir)
    fname = fdir + 'ne_jdote_' + str(current_time) + '.jpg'
    fig.savefig(fname, dpi=200)
    plt.close()
Esempio n. 41
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()
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()
Esempio n. 43
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()
Esempio n. 44
0
def calc_exb(run_dir, run_name, tframe, coords):
    """Calculate ExB drift velocity

    Args:
        run_dir: PIC run directory
        run_name: PIC run name
        trame: time frame
        coords: coordinates for different fields
    """
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    nx = pic_info.nx
    nz = pic_info.nz
    kwargs = {"current_time": tframe, "xl": 0, "xr": pic_info.lx_di,
              "zb": -0.5 * pic_info.lz_di, "zt": 0.5 * pic_info.lz_di}
    size_one_frame = pic_info.nx * pic_info.nz * 4
    sigma = 3
    fname = run_dir + "data/bx.gda"
    _, _, bx = read_2d_fields(pic_info, fname, **kwargs)
    f = MultilinearInterpolator(coords["smin_ez_bx"],
                                coords["smax_ez_bx"],
                                coords["orders"],
                                dtype=np.float32)
    f.set_values(np.atleast_2d(np.transpose(bx).flatten()))
    bx = np.transpose(f(coords["coord"]).reshape((nx, nz)))

    fname = run_dir + "data/by.gda"
    _, _, by = read_2d_fields(pic_info, fname, **kwargs)
    f = MultilinearInterpolator(coords["smin_by"],
                                coords["smax_by"],
                                coords["orders"],
                                dtype=np.float32)
    f.set_values(np.atleast_2d(np.transpose(by).flatten()))
    by = np.transpose(f(coords["coord"]).reshape((nx, nz)))

    fname = run_dir + "data/bz.gda"
    _, _, bz = read_2d_fields(pic_info, fname, **kwargs)
    f = MultilinearInterpolator(coords["smin_ex_bz"],
                                coords["smax_ex_bz"],
                                coords["orders"],
                                dtype=np.float32)
    f.set_values(np.atleast_2d(np.transpose(bz).flatten()))
    bz = np.transpose(f(coords["coord"]).reshape((nx, nz)))

    fname = run_dir + "data/ex.gda"
    _, _, ex = read_2d_fields(pic_info, fname, **kwargs)
    ex = gaussian_filter(ex, sigma)
    f = MultilinearInterpolator(coords["smin_ex_bz"],
                                coords["smax_ex_bz"],
                                coords["orders"],
                                dtype=np.float32)
    f.set_values(np.atleast_2d(np.transpose(ex).flatten()))
    ex = np.transpose(f(coords["coord"]).reshape((nx, nz)))

    fname = run_dir + "data/ey.gda"
    _, _, ey = read_2d_fields(pic_info, fname, **kwargs)
    ey = gaussian_filter(ey, sigma)
    f = MultilinearInterpolator(coords["smin_h"],
                                coords["smax_h"],
                                coords["orders"],
                                dtype=np.float32)
    f.set_values(np.atleast_2d(np.transpose(ey).flatten()))
    ey = np.transpose(f(coords["coord"]).reshape((nx, nz)))

    fname = run_dir + "data/ez.gda"
    _, _, ez = read_2d_fields(pic_info, fname, **kwargs)
    ez = gaussian_filter(ez, sigma)
    f = MultilinearInterpolator(coords["smin_ez_bx"],
                                coords["smax_ez_bx"],
                                coords["orders"],
                                dtype=np.float32)
    f.set_values(np.atleast_2d(np.transpose(ez).flatten()))
    ez = np.transpose(f(coords["coord"]).reshape((nx, nz)))

    ib2 = 1.0 / (bx**2 + by**2 + bz**2)
    exb_x = (ey * bz - ez * by) * ib2
    exb_y = (ez * bx - ex * bz) * ib2
    exb_z = (ex * by - ey * bx) * ib2

    fname = run_dir + "data/exb_x.gda"
    with open(fname, 'a+') as f:
        offset = size_one_frame * tframe
        f.seek(offset, os.SEEK_SET)
        exb_x.tofile(f)

    fname = run_dir + "data/exb_y.gda"
    with open(fname, 'a+') as f:
        offset = size_one_frame * tframe
        f.seek(offset, os.SEEK_SET)
        exb_y.tofile(f)

    fname = run_dir + "data/exb_z.gda"
    with open(fname, 'a+') as f:
        offset = size_one_frame * tframe
        f.seek(offset, os.SEEK_SET)
        exb_z.tofile(f)
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 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 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_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 calc_power_spectrum_vel(pic_info,
                            ct,
                            species,
                            run_name,
                            shock_pos,
                            base_dir='../../'):
    """Calculate power spectrum using velocities

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

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

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

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

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

    plt.show()
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()
Esempio n. 51
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()
Esempio n. 52
0
def rho_bands_2d(plot_config, show_plot=True):
    """Plot densities for energetic particles in the 2D simulation
    """
    pic_run = plot_config["pic_run"]
    species = plot_config["species"]
    tframe = plot_config["tframe"]
    picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    pic_run_dir = pic_info.run_dir
    if species == 'e':
        vth = pic_info.vthe
    else:
        vth = pic_info.vthi
    nbins = 1000
    ndata = nbins + 3  # including magnetic field
    tindex = pic_info.particle_interval * tframe
    gama = 1.0 / math.sqrt(1.0 - 3 * vth**2)
    eth = gama - 1.0
    ebins = np.logspace(-6, 4, nbins)
    ebins /= eth
    xmin, xmax = 0, pic_info.lx_di
    zmin, zmax = -pic_info.lz_di * 0.5, pic_info.lz_di * 0.5
    nx, nz = pic_info.nx, pic_info.nz
    smime = math.sqrt(pic_info.mime)
    dx_de = pic_info.dx_di * smime
    dy_de = pic_info.dy_di * smime
    dz_de = pic_info.dz_di * smime
    kwargs = {
        "current_time": tframe,
        "xl": 0,
        "xr": pic_info.lx_di,
        "zb": -pic_info.lz_di,
        "zt": pic_info.lz_di
    }
    # fname = pic_run_dir + "data/Ay.gda"
    # x, z, Ay = read_2d_fields(pic_info, fname, **kwargs)
    fname = pic_run_dir + "data/bx.gda"
    x, z, bx = read_2d_fields(pic_info, fname, **kwargs)
    fname = pic_run_dir + "data/by.gda"
    x, z, by = read_2d_fields(pic_info, fname, **kwargs)
    fname = pic_run_dir + "data/bz.gda"
    x, z, bz = read_2d_fields(pic_info, fname, **kwargs)
    ib = 1.0 / np.sqrt(bx**2 + by**2 + bz**2)
    bx = bx * ib
    by = by * ib
    bz = bz * ib
    kappax = (bx * np.gradient(bx, axis=1) / dx_de +
              bz * np.gradient(bx, axis=0) / dz_de)
    kappay = (bx * np.gradient(by, axis=1) / dx_de +
              bz * np.gradient(by, axis=0) / dz_de)
    kappaz = (bx * np.gradient(bz, axis=1) / dx_de +
              bz * np.gradient(bz, axis=0) / dz_de)

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

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

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

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

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

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

    if show_plot:
        plt.show()
    else:
        plt.close()
Esempio n. 53
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 calc_power_spectrum_mag(pic_info,
                            ct,
                            run_name,
                            shock_pos,
                            base_dir='../../'):
    """calculate power spectrum using magnetic fields

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

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

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

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

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

    # plt.show()
    plt.close()
def calc_power_spectrum(pic_info,
                        ct,
                        species,
                        run_name,
                        xmin,
                        xmax,
                        base_dir='../../',
                        single_file=True):
    """Calculate power spectrum of compressible mode and incompressible mode

    Args:
        pic_info: namedtuple for the PIC simulation information.
        ct: current time frame.
        species: particle species
        run_name: the simulation run name
        xmin, xmax: the spatial range of the field data
        base_dir: the root directory of the run
    """
    zmin, zmax = -0.5 * pic_info.lz_di, 0.5 * pic_info.lz_di
    if single_file:
        kwargs = {
            "current_time": ct,
            "xl": xmin,
            "xr": xmax,
            "zb": zmin,
            "zt": zmax
        }
        fname = base_dir + 'data1/v' + species + 'x.gda'
        x, z, vx = read_2d_fields(pic_info, fname, **kwargs)
        fname = base_dir + 'data1/v' + species + 'y.gda'
        x, z, vy = read_2d_fields(pic_info, fname, **kwargs)
        fname = base_dir + 'data1/v' + species + 'z.gda'
        x, z, vz = read_2d_fields(pic_info, fname, **kwargs)
    else:
        kwargs = {
            "current_time": 0,
            "xl": xmin,
            "xr": xmax,
            "zb": zmin,
            "zt": zmax
        }
        tframe = str(fields_interval * ct)
        fname = base_dir + 'data/vex_' + tframe + '.gda'
        fname = base_dir + 'data/v' + species + 'x_' + tframe + '.gda'
        x, z, vx = read_2d_fields(pic_info, fname, **kwargs)
        fname = base_dir + 'data/v' + species + 'y_' + tframe + '.gda'
        x, z, vy = read_2d_fields(pic_info, fname, **kwargs)
        fname = base_dir + 'data/v' + species + 'z_' + tframe + '.gda'
        x, z, vz = read_2d_fields(pic_info, fname, **kwargs)
    nx, = x.shape
    nz, = z.shape
    smime = math.sqrt(pic_info.mime)
    lx = np.max(x) - np.min(x)
    lz = np.max(z) - np.min(z)

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

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

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

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

    kxs, kzs = np.meshgrid(kx[:nx // 2 + 1], kz)
    ks = np.sqrt(kxs * kxs + kzs * kzs)
    kmin, kmax = np.min(ks), np.max(ks)
    kmin = 1E-2
    kmin_log = math.log10(kmin)
    kmax_log = math.log10(kmax)
    # kbins = np.linspace(kmin, kmax, 256, endpoint=True)
    kbins = 10**np.linspace(kmin_log, kmax_log, 39, endpoint=True)
    ps, kbins_edges = np.histogram(ks, bins=kbins, weights=v2_k * ks)
    ps_para, kbins_edges = np.histogram(ks, bins=kbins, weights=v2_kpara * ks)
    ps_perp, kbins_edges = np.histogram(ks, bins=kbins, weights=v2_kperp * ks)
    power1 = ps / np.diff(kbins_edges)
    power2 = ps_para / np.diff(kbins_edges)
    power3 = ps_perp / np.diff(kbins_edges)
    # print power1
    # print (power1 + 1E-5) / (power2 + power3 + 1E-5)
    # print (np.sum(ps)) / (np.sum(ps_para) + np.sum(ps_perp))
    # print (np.sum(ps*np.diff(kbins_edges)))
    # print (np.sum(ps_para*np.diff(kbins_edges)))
    # print (np.sum(ps_perp*np.diff(kbins_edges)))
    return (kbins_edges, power1, power2, power3)
Esempio n. 56
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()
Esempio n. 57
0
        self.valtext.set_text(self.valfmt % discrete_val)
        if self.drawon:
            self.ax.figure.canvas.draw()
        self.val = discrete_val
        if self.previous_val != discrete_val:
            self.previous_val = discrete_val
            if not self.eventson:
                return
            for cid, func in self.observers.iteritems():
                func(discrete_val)


if __name__ == '__main__':
    # pic_info = pic_information.get_pic_info('../../')
    base_directory = '/net/scratch2/guofan/for_Xiaocan/sigma100-lx300/'
    run_name = 'sigma100-lx300'
    picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json'
    pic_info = read_data_from_json(picinfo_fname)
    ratio = pic_info.particle_interval / pic_info.fields_interval
    ct = 5
    kwargs = {"current_time": 40, "xl": 0, "xr": 300, "zb": -75, "zt": 75}
    fname = base_directory + "/data/bx.gda"
    x, z, bx = read_2d_fields(pic_info, fname, **kwargs)
    fname = base_directory + "/data/by.gda"
    x, z, by = read_2d_fields(pic_info, fname, **kwargs)
    fname = base_directory + "/data/bz.gda"
    x, z, bz = read_2d_fields(pic_info, fname, **kwargs)
    data = np.sqrt(bx * bx + by * by + bz * bz)
    fig_v = viewer_2d(data, x, z, pic_info, base_directory)
    plt.show()
def calc_power_spectrum_vel_comp(pic_info,
                                 ct,
                                 species,
                                 run_name,
                                 xshock,
                                 base_dir='../../',
                                 single_file=True):
    """Calculate power spectrum of compressible mode and incompressible mode

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

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

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

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

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

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

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

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

    plt.close()