예제 #1
0
def get_exhaust_boundary(plot_config, mhd_config, show_plot=True):
    """Get the exhaust boundary for the reconnection layer

    Args:
        plot_config: plot configuration in dictionary
        mhd_config: MHD simulation configuration
    """
    tframe = plot_config["tframe"]
    nx = mhd_config["nx"][0] + 4
    ny = mhd_config["ny"][0] + 4
    dx = mhd_config["dx"][0]
    dy = mhd_config["dy"][0]
    fpath = plot_config["mhd_run_dir"] + 'bin_data/'
    fname = fpath + 'mhd_data_' + str(tframe).zfill(4)
    mhd_fields = np.fromfile(fname, dtype=np.float32)
    mhd_fields = mhd_fields.reshape((ny, nx, 8))
    bx = mhd_fields[:, :, 4]
    by = mhd_fields[:, :, 5]
    bz = mhd_fields[:, :, 6]

    xmin, = mhd_config["xmin"]
    xmax, = mhd_config["xmax"]
    ymin, = mhd_config["ymin"]
    ymax, = mhd_config["ymax"]
    nx_mhd, = mhd_config["nx"]
    ny_mhd, = mhd_config["ny"]
    lx_mhd = xmax - xmin
    ly_mhd = ymax - ymin
    dx = lx_mhd / nx_mhd
    dy = ly_mhd / nx_mhd
    xmin_grid = xmin - 2 * dx
    xmax_grid = xmax + 2 * dx
    ymin_grid = ymin - 2 * dy
    ymax_grid = ymax + 2 * dy
    lx_grid = xmax_grid - xmin_grid
    ly_grid = ymax_grid - ymin_grid
    xclose1, xclose2 = 0, lx_mhd  # Starting point for closed fieldline
    xpos = np.linspace(lx_mhd - dx * 0.1, 0.6 * lx_mhd, 4)
    while abs(xclose1 - xclose2) > dx * 0.1 or xclose1 == xclose2:
        xclose1 = xclose2
        for ix, x0 in enumerate(xpos):
            # print("Starting x-position: %f" % x0)
            xlist, ylist = trace_field_line(bx, by, x0, 0, lx_grid, ly_grid)
            if np.any(xlist < 0.5 * lx_mhd) and ylist.max() < 0.5 * ly_mhd:
                break
        xclose2 = x0
        xpos = np.linspace(xpos[ix - 1], xpos[ix], 4)
    xlist, ylist = trace_field_line(bx, by, xpos[0], 0, lx_grid, ly_grid)

    fdir = '../data/' + plot_config["mhd_run"] + '/exhaust_boundary/'
    mkdir_p(fdir)

    xz = np.asarray([xlist, ylist])
    fname = fdir + 'xz_right_' + str(tframe) + '.dat'
    xz.tofile(fname)
    xz = np.asarray([lx_mhd - xlist, ylist])
    fname = fdir + 'xz_left_' + str(tframe) + '.dat'
    xz.tofile(fname)
예제 #2
0
def plot_alpha_distribution(mhd_run_info, tstart, tend):
    """Plot the distribution power index alpha

    Args:
        mhd_run_info: information of the MHD run
        log_bin: whether to use logarithm scale
        show_plot: whether to show plot
    """
    fig = plt.figure(figsize=[7, 5])
    rect = [0.13, 0.13, 0.7, 0.8]
    ax = fig.add_axes(rect)
    fdir = "../data/pindex_dist/" + mhd_run_info["run_name"] + "/"
    nframes = tend - tstart + 1
    for tframe in range(tstart, tend + 1):
        fname = fdir + "pindex_dist_" + str(tframe) + ".dat"
        data = np.fromfile(fname)
        dsize, = data.shape
        abins = data[:dsize // 2]
        fdist = data[dsize // 2:]
        color = plt.cm.jet((tframe - tstart) / float(nframes), 1)
        ax.plot(abins, fdist, color=color, linewidth=2)

    mhd_config = mhd_data.read_mhd_config(mhd_run_info["config_name"],
                                          mhd_run_info["mhd_code"])
    tmin = tstart * mhd_config.dt_out / (mhd_config.xmax - mhd_config.xmin)
    tmax = tend * mhd_config.dt_out / (mhd_config.xmax - mhd_config.xmin)
    rect[0] += rect[2] + 0.01
    rect[2] = 0.04
    cax = fig.add_axes(rect)
    sm = plt.cm.ScalarMappable(cmap=plt.cm.jet,
                               norm=plt.Normalize(vmin=tmin, vmax=tmax))
    # fake up the array of the scalar mappable. Urgh...
    sm._A = []
    cbar = fig.colorbar(sm, cax=cax)
    cbar.set_label(r'$t/\tau_A$', fontsize=20)
    cbar.ax.tick_params(labelsize=16)

    ax.tick_params(labelsize=16)
    ax.set_xlabel(r'$\alpha$', fontsize=20)
    ax.set_ylabel(r'$f(\alpha)$', fontsize=20)
    fpath = '../img/pindex_dist/'
    mkdir_p(fpath)
    plt.savefig(fpath + 'pindex_dist_' + mhd_run_info["run_name"] + '.pdf')
    plt.show()
def momentum_energy_distributions(plot_config, power_test=True):
    """Plot momentum and energy distributions

    Args:
        plot_config: plotting configuration
        power_test: test for power-law fitting
    """
    rect = [0.16, 0.15, 0.8, 0.8]
    fig1 = plt.figure(figsize=[7, 5])
    ax1 = fig1.add_axes(rect)
    fig2 = plt.figure(figsize=[7, 5])
    ax2 = fig2.add_axes(rect)

    fdir = '../img/spectrum/' + plot_config["run_name"] + '/'
    mkdir_p(fdir)

    tmax = plot_config["tmax"]
    tmin = plot_config["tmin"]
    kwargs = {
        "color": 'r',
        "show_plot": False,
        "plot_power": False,
        "power_test": power_test
    }
    for tframe in range(tmin, tmax):
        color = plt.cm.jet((tframe - tmin) / float(tmax - tmin), 1)
        kwargs["color"] = color
        kwargs["plot_power"] = False if tframe < tmax - 1 else True
        # kwargs["plot_power"] = False
        plot_particle_distributions(tframe, ax1, ax2, plot_config, **kwargs)
    fp_name = 'fp_time_1.pdf'
    fe_name = 'fe_time_1.pdf'

    fig1.savefig(fdir + fp_name)
    fig2.savefig(fdir + fe_name)

    plt.show()
예제 #4
0
def spatial_distribution_multi(plot_config, mhd_config, show_plot=True):
    """Plot spatial distributions for multiple energy band

    Args:
        plot_config: plot configuration in dictionary
        mhd_config: MHD simulation configuration
    """
    mpl.rc('text', usetex=True)
    fig = plt.figure(figsize=[10, 10])
    rect0 = [0.08, 0.52, 0.40, 0.40]
    rect = np.copy(rect0)
    hgap, vgap = 0.04, 0.02
    run_name = plot_config["run_name"]
    tframe_str = str(plot_config["tframe"]).zfill(4)
    nx, = plot_config["nx"]
    ny, = plot_config["ny"]
    fname = '../data/' + run_name + '/fxy-' + tframe_str + '_sum.dat'
    fdata = np.fromfile(fname)
    nx, = plot_config["nx"]
    ny, = plot_config["ny"]
    print("data size: %d %d" % (nx, ny))
    dists = fdata.reshape([fdata.shape[0] // (nx * ny), -1])
    print("Total number of particles: %d" % np.sum(dists))

    axs = [None] * 4
    ims = [None] * 4
    vmin = plot_config['nmin']
    vmax = plot_config['nmax']
    sizes = [
        mhd_config["xmin"][0], mhd_config["xmax"][0], mhd_config["ymin"][0],
        mhd_config["ymax"][0]
    ]
    for i, j in itertools.product(range(2), range(2)):
        rect[0] = rect0[0] + (hgap + rect0[2]) * i
        rect[1] = rect0[1] - (vgap + rect0[3]) * j
        eband = j * 2 + i + 1
        fband = dists[eband, :]
        fnorm = 4**(eband - 1)
        fband = np.reshape(fband, (ny, nx)) * fnorm
        fband += vmin * 0.01
        print("min, max and mean of the data: %f %f %f %f" %
              (np.min(fband), np.max(fband), np.mean(fband), np.std(fband)))
        axs[eband - 1] = fig.add_axes(rect)
        ims[eband - 1] = axs[eband - 1].imshow(fband,
                                               cmap=plt.cm.viridis,
                                               aspect='auto',
                                               origin='lower',
                                               extent=sizes,
                                               norm=LogNorm(vmin=vmin,
                                                            vmax=vmax),
                                               interpolation='bicubic')
        axs[eband - 1].tick_params(labelsize=16)
        fig_text = str(fnorm) + r'$n($' + figure_text(eband) + r'$)$'
        color = 'k' if eband == 0 else 'w'
        axs[eband - 1].text(0.02,
                            0.9,
                            fig_text,
                            color=color,
                            fontsize=20,
                            bbox=dict(facecolor='none',
                                      alpha=1.0,
                                      edgecolor='none',
                                      pad=10.0),
                            horizontalalignment='left',
                            verticalalignment='bottom',
                            transform=axs[eband - 1].transAxes)

    axs[2].set_xlabel(r'$x$', fontsize=20)
    axs[3].set_xlabel(r'$x$', fontsize=20)
    axs[0].set_ylabel(r'$y$', fontsize=20)
    axs[2].set_ylabel(r'$y$', fontsize=20)

    axs[0].tick_params(axis='x', labelbottom=False)
    axs[1].tick_params(axis='x', labelbottom=False)
    axs[1].tick_params(axis='y', labelleft=False)
    axs[3].tick_params(axis='y', labelleft=False)

    rect[0] = rect0[0] + rect0[2] * 2 + hgap + 0.01
    rect[2] = 0.015
    rect[3] = rect0[3] * 2 + vgap
    rect[1] += rect[3] * 0.25
    rect[3] *= 0.5
    cbar_ax = fig.add_axes(rect)
    cbar1 = fig.colorbar(ims[0], cax=cbar_ax, extend='both')
    cbar1.ax.tick_params(labelsize=16)

    tva = mhd_config["dt_out"][0] * plot_config["tframe"] / mhd_config["ly"][0]
    title = r'$t = ' + "{:10.1f}".format(tva) + r'\tau_A$'
    title += ' (frame: %d)' % plot_config["tframe"]
    fig.suptitle(title, fontsize=24)

    fdir = '../img/nrho/' + run_name + '/'
    mkdir_p(fdir)
    fname = fdir + 'nrho_bands_' + tframe_str + '.jpg'
    fig.savefig(fname, dpi=200)

    if show_plot:
        plt.show()
    else:
        plt.close()
예제 #5
0
def spatial_distribution_mhd_field_multi(plot_config,
                                         mhd_config,
                                         show_plot=True):
    """Plot spatial distribution for multi energy bands and corresponding MHD fields

    Args:
        plot_config: plot configuration in dictionary
        mhd_config: MHD simulation configuration
    """
    # L0 = 75.0  # in Mm
    L0 = 200.0  # in Mm

    tframe = plot_config["tframe"]

    nx = mhd_config["nx"][0] + 4
    ny = mhd_config["ny"][0] + 4
    dx = mhd_config["dx"][0]
    dy = mhd_config["dy"][0]
    fpath = plot_config["mhd_run_dir"] + 'bin_data/'
    fname = fpath + 'mhd_data_' + str(tframe).zfill(4)
    mhd_fields = np.fromfile(fname, dtype=np.float32)
    mhd_fields = mhd_fields.reshape((ny, nx, 8))
    bx = mhd_fields[:, :, 4]
    by = mhd_fields[:, :, 5]
    jz = np.gradient(by, dx, axis=1) - np.gradient(bx, dy, axis=0)

    fig = plt.figure(figsize=[24, 6])
    rect0 = [0.04, 0.1, 0.145, 0.83]
    rect = np.copy(rect0)
    hgap = 0.015
    ax = fig.add_axes(rect)
    sizes = [
        mhd_config["xmin"][0], mhd_config["xmax"][0], mhd_config["ymin"][0],
        mhd_config["ymax"][0]
    ]
    sizes = np.asarray(sizes) * L0
    # fdata = [:, nx//4:nx*3//4]
    fdata = jz
    img = ax.imshow(fdata,
                    extent=sizes,
                    cmap=plt.cm.seismic,
                    vmin=-500,
                    vmax=500,
                    aspect='auto',
                    origin='lower',
                    interpolation='bicubic')
    ax.tick_params(labelsize=12)
    ax.set_xlabel(r'$x$/Mm', fontsize=16)
    ax.set_ylabel(r'$y$ (Mm)', fontsize=16)

    rect_cbar = np.copy(rect)
    rect_cbar[0] += 0.01
    rect_cbar[2] = 0.005
    rect_cbar[1] = 0.4
    rect_cbar[3] = 0.3
    cbar_ax = fig.add_axes(rect_cbar)
    cbar = fig.colorbar(img, cax=cbar_ax, extend="both")
    cbar.ax.tick_params(labelsize=10, color='k')
    cbar.ax.yaxis.set_tick_params(color='k')
    cbar.outline.set_edgecolor('k')
    plt.setp(plt.getp(cbar.ax.axes, 'yticklabels'), color='k')
    fig_text = r'$j_z$'
    # cbar.ax.set_ylabel(fig_text, fontsize=12, color='w')
    ax.text(0.05,
            0.95,
            fig_text,
            color='k',
            fontsize=16,
            horizontalalignment='left',
            verticalalignment='center',
            transform=ax.transAxes)

    fnorms = [1, 2, 4, 32]

    tframe_str = str(tframe).zfill(4)
    run_name = plot_config["run_name"]
    fname = '../data/' + run_name + '/fxy-' + tframe_str + '_sum.dat'
    fdata = np.fromfile(fname)
    nx, = plot_config["nx"]
    ny, = plot_config["ny"]
    nbands = int(fdata[0])
    pbins_edges = fdata[1:nbands + 2]
    pinit = 0.1
    pbins_edges /= pinit
    ebins_edges = pbins_edges**2
    print("data size: %d %d" % (nx, ny))
    ndp, = fdata.shape
    dists = fdata[nbands + 2:].reshape([(ndp - nbands - 2) // (nx * ny), -1])
    print("Total number of particles: %d" % np.sum(dists))

    fband_ycuts = []
    bands, bande = plot_config["high_bands"]
    for iband, eband in enumerate(range(bands, bande + 1)):
        fband = dists[eband, :]
        print("particle number in band %d: %d" % (eband, np.sum(fband)))
        print("min, max, mean, and std: %f %f %f %f" %
              (np.min(fband), np.max(fband), np.mean(fband), np.std(fband)))
        fband *= fnorms[iband]
        fband = np.reshape(fband, (ny, nx))
        # fband = fband[:, nx//4:nx*3//4]
        _, nxl = fband.shape
        fdata_cut = np.mean(fband[:, nxl // 2 - 3:nxl // 2 + 4], axis=1)
        fband_ycuts.append(fdata_cut)
        rect[0] += rect[2] + hgap
        ax = fig.add_axes(rect)
        vmin = plot_config['nmin']
        vmax = plot_config['nmax']
        img = ax.imshow(
            fband + 0.1 * vmin,
            cmap=plt.cm.viridis,
            aspect='auto',
            origin='lower',
            extent=sizes,
            # vmin=vmin, vmax=vmax,
            norm=LogNorm(vmin=vmin, vmax=vmax),
            interpolation='bicubic')
        ax.tick_params(labelsize=12)
        ax.set_xlabel(r'$x$ (Mm)', fontsize=16)
        ax.tick_params(axis='y', labelleft=False)

        rect_cbar = np.copy(rect)
        rect_cbar[0] += 0.01
        rect_cbar[2] = 0.005
        rect_cbar[1] = 0.4
        rect_cbar[3] = 0.3
        cbar_ax = fig.add_axes(rect_cbar)
        cbar = fig.colorbar(img, cax=cbar_ax, extend="both")
        cbar.ax.tick_params(labelsize=10, color='w')
        cbar.ax.yaxis.set_tick_params(color='w')
        cbar.outline.set_edgecolor('w')
        plt.setp(plt.getp(cbar.ax.axes, 'yticklabels'), color='w')
        norm = fnorms[iband]
        e0 = plot_config["e0"]
        enel = "{%0.0f}" % (ebins_edges[eband] * e0)
        eneh = "{%0.0f}" % (ebins_edges[eband + 1] * e0)
        ftext = (r'$' + enel + r'$keV' + r'$' + r'< \varepsilon <' + eneh +
                 r'$keV')
        if norm > 1:
            fig_text = r'$' + str(fnorms[iband]) + 'n($' + ftext + r'$)$'
        else:
            fig_text = r'$n($' + ftext + r'$)$'
        # cbar.ax.set_ylabel(fig_text, fontsize=12, color='w')
        ax.text(0.05,
                0.95,
                fig_text,
                color='white',
                fontsize=12,
                horizontalalignment='left',
                verticalalignment='center',
                transform=ax.transAxes)

    rect[0] += rect[2] + hgap
    ax = fig.add_axes(rect)
    ygrid = np.linspace(sizes[2], sizes[3], ny)
    for iband, fband_y in enumerate(fband_ycuts):
        label = r'$' + str(iband + 1) + '$'
        ax.semilogx(fband_y, ygrid, nonposx="mask", label=label)
    ax.legend(loc=1,
              prop={'size': 16},
              ncol=1,
              shadow=False,
              fancybox=False,
              frameon=False)
    ax.grid()
    ax.set_xlim([1E-1, 1E3])
    ax.set_xticks(np.logspace(-1, 3, num=5))
    ax.set_xlabel('Density', fontsize=16)
    ax.tick_params(axis='y', labelleft=False)
    # fname = '../data/' + run_name + '/fp-' + str(tframe).zfill(4) + '_sum.dat'
    # data = np.fromfile(fname, dtype=np.float64)
    # dsz, = data.shape
    # nbins = dsz // 2
    # pinit = 0.1
    # pmom = data[0:nbins] / pinit
    # elog = pmom**2
    # elog *= plot_config["e0"]  # to keV
    # fname = '../data/' + run_name + '/fp_local_' + tframe_str + '_sum.dat'
    # fdata = np.fromfile(fname).reshape([ny, nx, -1])
    # fpy = np.sum(fdata, axis=1)
    # Xn, Yn = np.meshgrid(elog, ygrid)
    # img = ax.pcolormesh(Xn, Yn, fpy, cmap=plt.cm.plasma,
    #                     norm=LogNorm(vmin=vmin, vmax=vmax))
    # ax.set_xlim([1E0, 1E3])
    # ax.set_xscale('log')

    ax.set_ylim(sizes[2:])
    ax.tick_params(labelsize=12)

    mhd_time = mhd_config["dt_out"][0] * tframe
    tva = mhd_time * L0
    title = r'$t = ' + "{:10.1f}".format(tva) + r'\text{ s}$'
    plt.suptitle(title, fontsize=20)

    fdir = '../img/nrho/' + run_name + '/'
    mkdir_p(fdir)
    fname = fdir + 'nrho_jz_' + str(tframe) + '.jpg'
    fig.savefig(fname, dpi=200)

    if show_plot:
        plt.show()
    else:
        plt.close()
예제 #6
0
def spatial_distribution_mhd_field(plot_config, mhd_config, show_plot=True):
    """Plot spatial distribution for one energy band and corresponding MHD fields

    Args:
        plot_config: plot configuration in dictionary
        mhd_config: MHD simulation configuration
    """
    # tframes = [100, 125, 160]
    fig = plt.figure(figsize=[4, 4])
    rect0 = [0.13, 0.12, 0.4, 0.8]
    rect = np.copy(rect0)
    hgap = 0.03
    # L0 = 75.0  # in Mm
    L0 = 200.0  # in Mm

    tframe = plot_config["tframe"]
    tframe_str = str(tframe).zfill(4)
    eband = plot_config["eband"]
    run_name = plot_config["run_name"]
    fname = '../data/' + run_name + '/fxy-' + tframe_str + '_sum.dat'
    fdata = np.fromfile(fname)
    nx, = plot_config["nx"]
    ny, = plot_config["ny"]
    print("data size: %d %d" % (nx, ny))
    dists = fdata.reshape([fdata.shape[0] // (nx * ny), -1])
    print("Total number of particles: %d" % np.sum(dists))

    fband = dists[eband, :]
    print("particle number in band %d: %d" % (eband, np.sum(fband)))
    fband = np.reshape(fband, (ny, nx))
    fband = fband[:, nx // 4:nx * 3 // 4]
    print("min, max, mean, and std: %f %f %f %f" %
          (np.min(fband), np.max(fband), np.mean(fband), np.std(fband)))

    nx = mhd_config["nx"][0] + 4
    ny = mhd_config["ny"][0] + 4
    dx = mhd_config["dx"][0]
    dy = mhd_config["dy"][0]
    fpath = plot_config["mhd_run_dir"] + 'bin_data/'
    fname = fpath + 'mhd_data_' + str(tframe).zfill(4)
    mhd_fields = np.fromfile(fname, dtype=np.float32)
    mhd_fields = mhd_fields.reshape((ny, nx, 8))
    bx = mhd_fields[:, :, 4]
    by = mhd_fields[:, :, 5]
    jz = np.gradient(by, dx, axis=1) - np.gradient(bx, dy, axis=0)
    rect = np.copy(rect0)
    ax = fig.add_axes(rect)
    sizes = [
        0.5 * mhd_config["xmin"][0], 0.5 * mhd_config["xmax"][0],
        mhd_config["ymin"][0], mhd_config["ymax"][0]
    ]
    sizes = np.asarray(sizes) * L0
    img = ax.imshow(jz[:, nx // 4:nx * 3 // 4],
                    extent=sizes,
                    cmap=plt.cm.seismic,
                    vmin=-500,
                    vmax=500,
                    aspect='auto',
                    origin='lower',
                    interpolation='bicubic')
    ax.tick_params(labelsize=10)
    ax.set_xlabel(r'$x$/Mm', fontsize=12)
    ax.set_ylabel(r'$y$ (Mm)', fontsize=12)

    rect_cbar = np.copy(rect)
    rect_cbar[0] += 0.02
    rect_cbar[2] = 0.015
    rect_cbar[1] = 0.4
    rect_cbar[3] = 0.3
    cbar_ax = fig.add_axes(rect_cbar)
    cbar = fig.colorbar(img, cax=cbar_ax, extend="both")
    cbar.ax.tick_params(labelsize=10, color='k')
    cbar.ax.yaxis.set_tick_params(color='k')
    cbar.outline.set_edgecolor('k')
    plt.setp(plt.getp(cbar.ax.axes, 'yticklabels'), color='k')
    fig_text = r'$j_z$'
    # cbar.ax.set_ylabel(fig_text, fontsize=12, color='w')
    ax.text(0.05,
            0.95,
            fig_text,
            color='k',
            fontsize=12,
            horizontalalignment='left',
            verticalalignment='center',
            transform=ax.transAxes)

    rect[0] += rect[2] + hgap
    ax = fig.add_axes(rect)
    vmin = plot_config['nmin']
    vmax = plot_config['nmax']
    sizes = [
        0.5 * mhd_config["xmin"][0], 0.5 * mhd_config["xmax"][0],
        mhd_config["ymin"][0], mhd_config["ymax"][0]
    ]
    sizes = np.asarray(sizes) * L0
    img = ax.imshow(
        fband + 0.1 * vmin,
        cmap=plt.cm.viridis,
        aspect='auto',
        origin='lower',
        extent=sizes,
        # vmin=vmin, vmax=vmax,
        norm=LogNorm(vmin=vmin, vmax=vmax),
        interpolation='bicubic')
    ax.tick_params(labelsize=10)
    ax.set_xlabel(r'$x$ (Mm)', fontsize=12)
    ax.tick_params(axis='y', labelleft=False)
    mhd_time = mhd_config["dt_out"][0] * tframe
    tva = mhd_time * L0
    title = r'$t = ' + "{:10.1f}".format(tva) + r'\text{ s}$'
    plt.suptitle(title, fontsize=12)

    rect_cbar = np.copy(rect)
    rect_cbar[0] += 0.02
    rect_cbar[2] = 0.015
    rect_cbar[1] = 0.4
    rect_cbar[3] = 0.3
    cbar_ax = fig.add_axes(rect_cbar)
    cbar = fig.colorbar(img, cax=cbar_ax, extend="both")
    cbar.ax.tick_params(labelsize=10, color='w')
    cbar.ax.yaxis.set_tick_params(color='w')
    cbar.outline.set_edgecolor('w')
    plt.setp(plt.getp(cbar.ax.axes, 'yticklabels'), color='w')
    fig_text = r'$n($' + figure_text(eband) + r'$)$'
    # cbar.ax.set_ylabel(fig_text, fontsize=12, color='w')
    ax.text(0.05,
            0.95,
            fig_text,
            color='white',
            fontsize=12,
            horizontalalignment='left',
            verticalalignment='center',
            transform=ax.transAxes)

    fdir = '../img/nrho/' + run_name + '/'
    mkdir_p(fdir)
    fname = fdir + 'nrho_jz_' + str(eband) + '.pdf'
    # fig.savefig(fname, dpi=200)

    if show_plot:
        plt.show()
    else:
        plt.close()
예제 #7
0
def spatial_distribution_tri_frames(plot_config, mhd_config, show_plot=True):
    """Plot particle spatial distribution for one energy band for three frames

    Args:
        plot_config: plot configuration in dictionary
        mhd_config: MHD simulation configuration
    """
    # tframes = [100, 125, 160]
    tframes = [147, 190, 201]
    fig = plt.figure(figsize=[6, 4])
    rect0 = [0.1, 0.12, 0.24, 0.8]
    rect = np.copy(rect0)
    hgap = 0.02
    # L0 = 75.0  # in Mm
    L0 = 200.0  # in Mm
    for iframe, tframe in enumerate(tframes):
        tframe_str = str(tframe).zfill(4)
        eband = plot_config["eband"]
        run_name = plot_config["run_name"]
        fname = '../data/' + run_name + '/fxy-' + tframe_str + '_sum.dat'
        fdata = np.fromfile(fname)
        nx, = plot_config["nx"]
        ny, = plot_config["ny"]
        print("data size: %d %d" % (nx, ny))
        dists = fdata.reshape([fdata.shape[0] // (nx * ny), -1])
        print("Total number of particles: %d" % np.sum(dists))

        fband = dists[eband, :]
        print("particle number in band %d: %d" % (eband, np.sum(fband)))
        fband = np.reshape(fband, (ny, nx))
        fband = fband[:, nx // 4:nx * 3 // 4]
        print("min, max, mean, and std: %f %f %f %f" %
              (np.min(fband), np.max(fband), np.mean(fband), np.std(fband)))

        rect[0] = rect0[0] + (rect[2] + hgap) * iframe
        ax = fig.add_axes(rect)
        vmin = plot_config['nmin']
        vmax = plot_config['nmax']
        sizes = [
            0.5 * mhd_config["xmin"][0], 0.5 * mhd_config["xmax"][0],
            mhd_config["ymin"][0], mhd_config["ymax"][0]
        ]
        sizes = np.asarray(sizes) * L0
        img = ax.imshow(
            fband + 0.1 * vmin,
            cmap=plt.cm.viridis,
            aspect='auto',
            origin='lower',
            extent=sizes,
            # vmin=vmin, vmax=vmax,
            norm=LogNorm(vmin=vmin, vmax=vmax),
            interpolation='bicubic')
        ax.tick_params(labelsize=10)
        if iframe > 0:
            ax.tick_params(axis='y', labelleft=False)
        else:
            ax.set_ylabel(r'$y$ (Mm)', fontsize=12)
        ax.set_xlabel(r'$x$ (Mm)', fontsize=12)
        mhd_time = mhd_config["dt_out"][0] * tframe
        tva = mhd_time * L0
        title = r'$t = ' + "{:10.1f}".format(tva) + r'\text{ s}$'
        plt.title(title, fontsize=12)

    rect[0] += rect[2] + 0.01
    rect[2] = 0.02
    rect[1] += rect[3] * 0.125
    rect[3] *= 0.75
    cbar_ax = fig.add_axes(rect)
    cbar1 = fig.colorbar(img, cax=cbar_ax, extend='both')
    cbar1.ax.tick_params(labelsize=10)
    fig_text = r'$n($' + figure_text(eband) + r'$)$'
    cbar1.ax.set_ylabel(fig_text, fontsize=12)

    fdir = '../img/nrho/' + run_name + '/'
    mkdir_p(fdir)
    fname = fdir + 'nrho_tri_frames_' + str(eband) + '.pdf'
    fig.savefig(fname, dpi=200)

    if show_plot:
        plt.show()
    else:
        plt.close()
예제 #8
0
def spatial_distribution_band(plot_config, mhd_config, show_plot=True):
    """Plot particle spatial distribution for one energy band

    Args:
        plot_config: plot configuration in dictionary
        mhd_config: MHD simulation configuration
    """
    tframe_str = str(plot_config["tframe"]).zfill(4)
    eband = plot_config["eband"]
    run_name = plot_config["run_name"]
    fname = '../data/' + run_name + '/fxy-' + tframe_str + '_sum.dat'
    fdata = np.fromfile(fname)
    nx, = plot_config["nx"]
    ny, = plot_config["ny"]
    print("data size: %d %d" % (nx, ny))
    dists = fdata.reshape([fdata.shape[0] // (nx * ny), -1])
    print("Total number of particles: %d" % np.sum(dists))

    fband = dists[eband, :]
    print("particle number in band %d: %d" % (eband, np.sum(fband)))
    fband = np.reshape(fband, (ny, nx))
    print("min, max, mean, and std: %f %f %f %f" %
          (np.min(fband), np.max(fband), np.mean(fband), np.std(fband)))

    fig = plt.figure(figsize=[7, 6.5])
    rect = [0.1, 0.12, 0.78, 0.84]
    ax = fig.add_axes(rect)
    vmin = plot_config['nmin']
    vmax = plot_config['nmax']
    sizes = [
        mhd_config["xmin"][0], mhd_config["xmax"][0], mhd_config["ymin"][0],
        mhd_config["ymax"][0]
    ]
    img = ax.imshow(
        fband + 0.1 * vmin,
        cmap=plt.cm.hot,
        aspect='auto',
        origin='lower',
        extent=sizes,
        # vmin=vmin, vmax=vmax,
        norm=LogNorm(vmin=vmin, vmax=vmax),
        interpolation='bicubic')
    ax.tick_params(labelsize=12)
    fig_text = figure_text(eband)
    ax.text(0.02,
            0.9,
            fig_text,
            color='k',
            fontsize=20,
            bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0),
            horizontalalignment='left',
            verticalalignment='bottom',
            transform=ax.transAxes)

    ax.set_xlabel(r'$x$', fontsize=16)
    ax.set_ylabel(r'$y$', fontsize=16)

    rect[0] += rect[2] + 0.01
    rect[2] = 0.02
    rect[1] += rect[3] * 0.25
    rect[3] *= 0.5
    cbar_ax = fig.add_axes(rect)
    cbar1 = fig.colorbar(img, cax=cbar_ax, extend='both')
    cbar1.ax.tick_params(labelsize=16)

    fdir = '../img/nrho/' + run_name + '/'
    mkdir_p(fdir)
    fname = fdir + 'nrho_' + tframe_str + '_' + str(eband) + '.jpg'
    fig.savefig(fname, dpi=200)

    if show_plot:
        plt.show()
    else:
        plt.close()
예제 #9
0
def reduce_mhd_data(plot_config, mhd_config, mhd_run_info):
    """Reduce MHD data size

    Args:
        plot_config: plot configuration in dictionary
        mhd_config: MHD simulation configuration
        mhd_run_info: information of the MHD run
    """
    run_type = plot_config["run_type"]
    if run_type == "Fan-Early":
        rho0 = 1.2E10  # cm^-3
        b0 = 50  # Gauss
        T0 = 6.0E6  # K
        beta0 = 0.1
        nrx, nry = 64, 32
    if run_type == "Harris_UMN":
        rho0 = 1.0E9  # cm^-3
        b0 = 50  # Gauss
        T0 = 1.0E6  # K
        beta0 = 0.1
        nrx, nry = 64, 64
    tframe = plot_config["tframe"]
    xmesh, ymesh, data = mhd_data.read_fields_data(mhd_run_info, tframe)
    ny, nx = xmesh.shape
    mhd_box = [xmesh[0, 0], xmesh[0, -1], ymesh[0, 0], ymesh[-1, 0], nx, ny]
    rho = data[:, :, 0].T
    pre = data[:, :, 1].T
    bx = data[:, :, 5].T
    by = data[:, :, 6].T
    bz = data[:, :, 7].T
    rho = rho.reshape(ny // nry, nry, nx // nrx, nrx)
    pre = pre.reshape(ny // nry, nry, nx // nrx, nrx)
    bx = bx.reshape(ny // nry, nry, nx // nrx, nrx)
    by = by.reshape(ny // nry, nry, nx // nrx, nrx)
    bz = bz.reshape(ny // nry, nry, nx // nrx, nrx)
    rho_r = np.mean(np.mean(rho, axis=3), axis=1)
    pre_r = np.mean(np.mean(pre, axis=3), axis=1)
    bx_r = np.mean(np.mean(bx, axis=3), axis=1)
    by_r = np.mean(np.mean(by, axis=3), axis=1)
    bz_r = np.mean(np.mean(bz, axis=3), axis=1)
    absB_r = np.sqrt(bx_r**2 + by_r**2 + bz_r**2)
    T_r = pre_r / rho_r / (beta0 * 0.5)
    rho_r *= rho0
    bx *= b0
    by *= b0
    bz *= b0
    absB_r *= b0
    T_r *= T0

    nxr = nx // nrx
    nyr = ny // nry

    fdir = plot_config["mhd_run_dir"] + "data_reduced/"
    mkdir_p(fdir)
    fname = fdir + 'rho_' + str(tframe) + '.dat'
    rho_r[:, nxr // 2:].tofile(fname)
    fname = fdir + 'T_' + str(tframe) + '.dat'
    T_r[:, nxr // 2:].tofile(fname)
    fname = fdir + 'bx_' + str(tframe) + '.dat'
    bx_r[:, nxr // 2:].tofile(fname)
    fname = fdir + 'by_' + str(tframe) + '.dat'
    by_r[:, nxr // 2:].tofile(fname)
    fname = fdir + 'bz_' + str(tframe) + '.dat'
    bz_r[:, nxr // 2:].tofile(fname)
    fname = fdir + 'absB_' + str(tframe) + '.dat'
    absB_r[:, nxr // 2:].tofile(fname)
예제 #10
0
def ptl_traj(mhd_run_info, sde_run, mhd_config, config):
    """Plot particle trajectory

    Args:
        mhd_run_info: information of the MHD run
        sde_run: SDE run name
        mhd_config: MHD configuration
        config: additional configuration
    """
    fpath = "../data/traj_data/"
    opath = "../img/ptl_traj/" + mhd_run_info["run_name"] + '/' + sde_run + '/'
    mkdir_p(opath)
    fname = (fpath + mhd_run_info["run_name"] + '/' + sde_run +
             "/tracked_particle_points_" + str(config["mpi_rank"]).zfill(4) +
             ".dat")
    nptl = traj.get_nptl(fname)
    ptl = traj.read_ptl_traj(fname, nptl, config["ptl_index"])
    ptl = np.array([list(item) for item in ptl])
    ptl = traj.boundary_cross(ptl)
    xptl = ptl[:-1, 0]
    yptl = ptl[:-1, 1]
    pptl = ptl[:-1, 2]
    tptl = ptl[:-1, 4]
    ptl_range = [np.min(xptl), np.max(xptl), np.min(yptl), np.max(yptl)]

    fig = plt.figure(figsize=[20, 10])
    rect = [0.05, 0.12, 0.15, 0.8]
    hgap = 0.06

    # tframe = config["tframes"][0]
    # mhd_time = mhd_config["dt_out"][0] * tframe
    # # find the closed time point
    # tindex, _ = traj.find_nearest(tptl, mhd_time)
    # mhd_box, rho = traj.read_mhd_data(mhd_run_info, tframe)
    # prange, mhd_data = traj.adjust_mhd_data(mhd_box, rho, ptl_range)
    tindices = []

    for (i, tframe) in enumerate(config["tframes"]):
        mhd_time = mhd_config["dt_out"][0] * tframe
        tva = mhd_time / mhd_config["ly"][0]  # in Alfven crossing time
        title = r'$t = ' + "{:10.1f}".format(tva) + r'\tau_A$'

        # find the closed time point
        tindex, _ = traj.find_nearest(tptl, mhd_time)
        tindices.append(tindex)
        mhd_box, rho = traj.read_mhd_data(mhd_run_info, tframe)
        prange, mhd_data = traj.adjust_mhd_data(mhd_box, rho, ptl_range)

        ax = fig.add_axes(rect)
        if i > 0:
            ax.tick_params(axis='y', labelleft='off')
        ylabeling = False if i > 0 else True
        img = ax.imshow(mhd_data,
                        extent=prange,
                        vmin=0.5,
                        vmax=3.0,
                        cmap=plt.cm.viridis,
                        aspect='auto',
                        origin='lower')
        traj.plot_particle_2d(('x', xptl), ('y', yptl), ax, tindex, ylabeling)
        ax.set_xlim(prange[:2])
        ax.set_ylim(prange[2:])
        plt.title(title, fontsize=24)
        rect[0] += rect[2] + 0.015

    rect[2] = 0.015
    cbar_ax = fig.add_axes(rect)
    cbar = fig.colorbar(img, cax=cbar_ax)
    cbar.ax.tick_params(labelsize=16)
    cbar.ax.set_xlabel(r'$\rho$', fontsize=24)
    cbar.ax.xaxis.set_label_position('top')

    tindices = np.asarray(tindices)
    rect[0] += rect[2] + 0.07
    rect[2] = 0.17
    ax1 = fig.add_axes(rect)
    traj.plot_particle_2d(('x', xptl), ('p', pptl), ax1, tindices[0])
    for tindex in tindices[1:]:
        ax1.plot(xptl[tindex],
                 pptl[tindex],
                 marker='o',
                 markersize=10,
                 color="red")

    rect[0] += rect[2] + 0.015
    ax2 = fig.add_axes(rect)
    ax2.tick_params(axis='y', labelleft='off')
    tptl /= mhd_config["ly"][0]  # in Alfven crossing time
    traj.plot_particle_2d(('t', tptl), ('p', pptl),
                          ax2,
                          tindices[0],
                          ylabeling=False)
    for tindex in tindices[1:]:
        ax2.plot(tptl[tindex],
                 pptl[tindex],
                 marker='o',
                 markersize=10,
                 color="red")

    out_dir = '../img/apj_parker/'
    mkdir_p(out_dir)
    fig_name = (out_dir + "ptl_" + str(config["mpi_rank"]) + "_" +
                str(config["ptl_index"]) + ".jpg")
    fig.savefig(fig_name, dpi=200)

    plt.show()
예제 #11
0
def calc_shear_params(plot_config, mhd_config, show_plot=True):
    """calculate flow shear parameters

    Args:
        plot_config: plot configuration in dictionary
        mhd_config: MHD simulation configuration
    """
    L0 = 200.0  # in Mm

    tframe = plot_config["tframe"]
    nx = mhd_config["nx"][0] + 4
    ny = mhd_config["ny"][0] + 4
    dx = mhd_config["dx"][0]
    dy = mhd_config["dy"][0]
    fpath = plot_config["mhd_run_dir"] + 'bin_data/'
    fname = fpath + 'mhd_data_' + str(tframe).zfill(4)
    mhd_fields = np.fromfile(fname, dtype=np.float32)
    mhd_fields = mhd_fields.reshape((ny, nx, 8))
    vx = mhd_fields[:, :, 0]
    vy = mhd_fields[:, :, 1]
    dvx_dx = np.gradient(vx, axis=1)
    dvx_dy = np.gradient(vx, axis=0)
    dvy_dx = np.gradient(vy, axis=1)
    dvy_dy = np.gradient(vy, axis=0)
    divv = dvx_dx + dvy_dy
    gshear = ((2 * (dvx_dy + dvy_dx)**2 + 4 * (dvx_dx**2 + dvy_dy**2)) / 30 -
              (2 * divv**2 / 45))
    print("Min and Max of shear parameter: %f, %f" %
          (gshear.min(), gshear.max()))
    print("Min and Max of compression: %f, %f" % (divv.min(), divv.max()))

    fig = plt.figure(figsize=[8, 8])
    rect0 = [0.1, 0.1, 0.4, 0.85]
    rect = np.copy(rect0)
    hgap = 0.03
    rect = np.copy(rect0)
    ax = fig.add_axes(rect)
    sizes = [
        mhd_config["xmin"][0], 0.25 * mhd_config["xmax"][0],
        mhd_config["ymin"][0], mhd_config["ymax"][0]
    ]
    sizes = np.asarray(sizes) * L0
    xs = 3 * nx // 8
    fdata = gshear[:, xs:(nx - xs)]
    xgrid = np.linspace(sizes[0], sizes[1], nx - xs * 2)
    ygrid = np.linspace(sizes[2], sizes[3], ny)
    nx_grid, = xgrid.shape
    ny_grid, = ygrid.shape
    img = ax.imshow(
        fdata,
        extent=sizes,
        cmap=plt.cm.viridis,
        # norm=LogNorm(vmin=1E2, vmax=1E3),
        vmin=0,
        vmax=1E-3,
        aspect='auto',
        origin='lower',
        interpolation='none')
    ax.tick_params(labelsize=12)
    ax.set_xlabel(r'$x$/Mm', fontsize=16)
    ax.set_ylabel(r'$y$ (Mm)', fontsize=16)

    rect_cbar = np.copy(rect)
    rect_cbar[0] += 0.02
    rect_cbar[2] = 0.015
    rect_cbar[1] = 0.4
    rect_cbar[3] = 0.3
    cbar_ax = fig.add_axes(rect_cbar)
    cbar = fig.colorbar(img, cax=cbar_ax, extend="both")
    cbar.ax.tick_params(labelsize=10, color='w')
    cbar.ax.yaxis.set_tick_params(color='w')
    cbar.outline.set_edgecolor('w')
    plt.setp(plt.getp(cbar.ax.axes, 'yticklabels'), color='w')
    fig_text = r'$\Gamma$'
    ax.text(0.05,
            0.95,
            fig_text,
            color='w',
            fontsize=16,
            horizontalalignment='left',
            verticalalignment='center',
            transform=ax.transAxes)

    rect[0] += rect[2] + hgap
    ax = fig.add_axes(rect)
    fdata = divv[:, xs:(nx - xs)]
    img = ax.imshow(
        fdata,
        extent=sizes,
        cmap=plt.cm.seismic,
        # norm=LogNorm(vmin=1E2, vmax=1E3),
        vmin=-1E-2,
        vmax=1E-2,
        aspect='auto',
        origin='lower',
        interpolation='none')
    ax.tick_params(labelsize=12)
    ax.set_xlabel(r'$x$/Mm', fontsize=16)
    ax.tick_params(axis='y', labelleft=False)

    rect_cbar = np.copy(rect)
    rect_cbar[0] += 0.02
    rect_cbar[2] = 0.015
    rect_cbar[1] = 0.4
    rect_cbar[3] = 0.3
    cbar_ax = fig.add_axes(rect_cbar)
    cbar = fig.colorbar(img, cax=cbar_ax, extend="both")
    cbar.ax.tick_params(labelsize=10, color='k')
    cbar.ax.yaxis.set_tick_params(color='k')
    cbar.outline.set_edgecolor('k')
    plt.setp(plt.getp(cbar.ax.axes, 'yticklabels'), color='k')
    fig_text = r'$\Delta\cdot\boldsymbol{V}$'
    ax.text(0.05,
            0.95,
            fig_text,
            color='k',
            fontsize=16,
            horizontalalignment='left',
            verticalalignment='center',
            transform=ax.transAxes)

    fdir = '../img/shear_params/' + plot_config["mhd_run"] + '/'
    mkdir_p(fdir)
    # fname = fdir + 'shear_params_' + str(tframe) + '.jpg'
    # fig.savefig(fname, dpi=200)

    if show_plot:
        plt.show()
    else:
        plt.close()
예제 #12
0
def plot_correlation_length(plot_config, mhd_config, show_plot=True):
    """Plot the turbulence correlation length

    Args:
        plot_config: plot configuration in dictionary
        mhd_config: MHD simulation configuration
    """
    L0 = 200.0  # in Mm

    tframe = plot_config["tframe"]
    nx = mhd_config["nx"][0] + 4
    ny = mhd_config["ny"][0] + 4
    dx = mhd_config["dx"][0]
    dy = mhd_config["dy"][0]
    xmin, = mhd_config["xmin"]
    xmax, = mhd_config["xmax"]
    ymin, = mhd_config["ymin"]
    ymax, = mhd_config["ymax"]
    nx_mhd, = mhd_config["nx"]
    ny_mhd, = mhd_config["ny"]
    lx_mhd = xmax - xmin
    ly_mhd = ymax - ymin
    dx = lx_mhd / nx_mhd
    dy = ly_mhd / nx_mhd
    xmin_grid = xmin - 2 * dx
    xmax_grid = xmax + 2 * dx
    ymin_grid = ymin - 2 * dy
    ymax_grid = ymax + 2 * dy
    lx_grid = xmax_grid - xmin_grid
    ly_grid = ymax_grid - ymin_grid
    xmhd = np.linspace(0.5 * dx, lx_mhd - 0.5 * dx, nx_mhd)
    ymhd = np.linspace(0.5 * dy, ly_mhd - 0.5 * dy, ny_mhd)
    xgrid = np.linspace(-1.5 * dx, lx_mhd + 1.5 * dx, nx)
    ygrid = np.linspace(-1.5 * dy, ly_mhd + 1.5 * dy, ny)

    fdir = '../data/' + plot_config["mhd_run"] + '/exhaust_boundary/'
    fname = fdir + 'xz_right_' + str(tframe) + '.dat'
    xlist_right, ylist_right = np.fromfile(fname).reshape([2, -1])
    fname = fdir + 'xz_left_' + str(tframe) + '.dat'
    xlist_left, ylist_left = np.fromfile(fname).reshape([2, -1])
    if not np.all(xlist_right > xlist_left):
        iy_max = np.argmax(ylist_right)
        xlist_right = np.copy(xlist_right[:iy_max + 1])
        ylist_right = np.copy(ylist_right[:iy_max + 1])
        xlist_left = lx_mhd - xlist_right
        ylist_left = np.copy(ylist_right)

    fpath = plot_config["mhd_run_dir"] + 'bin_data/'
    fname = fpath + 'lc_' + str(tframe).zfill(4)
    lc = np.fromfile(fname, dtype=np.float32).reshape([ny, nx])

    fig = plt.figure(figsize=[5.5, 8])
    rect0 = [0.15, 0.1, 0.8, 0.85]
    rect = np.copy(rect0)
    hgap = 0.03
    rect = np.copy(rect0)
    ax = fig.add_axes(rect)
    sizes = [xmin_grid, xmax_grid, ymin_grid, ymax_grid]
    sizes = np.asarray(sizes) * L0

    ax.plot(xlist_left * L0,
            ylist_left * L0,
            color='w',
            linewidth=1,
            linestyle='-')
    ax.plot(xlist_right * L0,
            ylist_right * L0,
            color='w',
            linewidth=1,
            linestyle='-')
    img = ax.imshow(lc,
                    extent=sizes,
                    cmap=plt.cm.viridis,
                    norm=LogNorm(vmin=1E2, vmax=5E4),
                    aspect='auto',
                    origin='lower',
                    interpolation='bicubic')

    rect_cbar = np.copy(rect)
    rect_cbar[0] += 0.02
    rect_cbar[2] = 0.02
    rect_cbar[1] = 0.4
    rect_cbar[3] = 0.3
    cbar_ax = fig.add_axes(rect_cbar)
    cbar = fig.colorbar(img, cax=cbar_ax, extend="both")
    cbar.ax.tick_params(labelsize=10, color='w')
    cbar.ax.yaxis.set_tick_params(color='w')
    cbar.outline.set_edgecolor('w')
    plt.setp(plt.getp(cbar.ax.axes, 'yticklabels'), color='w')
    fig_text = r'$L_c/\text{km}$'
    cbar_ax.set_ylabel(fig_text, fontsize=16, color='w')
    # ax.text(0.05, 0.95, fig_text, color='white', fontsize=12,
    #         horizontalalignment='left', verticalalignment='center',
    #         transform=ax.transAxes)

    mhd_time = mhd_config["dt_out"][0] * tframe
    tva = mhd_time * L0
    title = r'$t = ' + "{:10.1f}".format(tva) + r'\text{ s}$'
    plt.suptitle(title, fontsize=20)

    ax.set_xlim(sizes[:2])
    ax.set_ylim(sizes[2:])
    ax.tick_params(labelsize=12)
    ax.set_xlabel(r'$x$/Mm', fontsize=16)
    ax.set_ylabel(r'$y$ (Mm)', fontsize=16)

    fdir = '../img/lc/' + plot_config["mhd_run"] + '/'
    mkdir_p(fdir)
    fname = fdir + 'lc_' + str(tframe) + '.jpg'
    fig.savefig(fname, dpi=200)

    if show_plot:
        plt.show()
    else:
        plt.close()
예제 #13
0
def inject_at_jz(plot_config, mhd_config, show_plot=True):
    """inject particles where current density is large

    Args:
        plot_config: plot configuration in dictionary
        mhd_config: MHD simulation configuration
    """
    L0 = 200.0  # in Mm

    tframe = plot_config["tframe"]
    nx = mhd_config["nx"][0] + 4
    ny = mhd_config["ny"][0] + 4
    dx = mhd_config["dx"][0]
    dy = mhd_config["dy"][0]
    fpath = plot_config["mhd_run_dir"] + 'bin_data/'
    fname = fpath + 'mhd_data_' + str(tframe).zfill(4)
    mhd_fields = np.fromfile(fname, dtype=np.float32)
    mhd_fields = mhd_fields.reshape((ny, nx, 8))
    bx = mhd_fields[:, :, 4]
    by = mhd_fields[:, :, 5]
    bz = mhd_fields[:, :, 6]
    jx = np.gradient(bz, dy, axis=0)
    jy = -np.gradient(bz, dx, axis=1)
    jz = np.gradient(by, dx, axis=1) - np.gradient(bx, dy, axis=0)
    absj = np.sqrt(jx**2 + jy**2 + jz**2)

    fig = plt.figure(figsize=[4, 8])
    rect0 = [0.15, 0.1, 0.8, 0.85]
    rect = np.copy(rect0)
    hgap = 0.03
    rect = np.copy(rect0)
    ax = fig.add_axes(rect)
    sizes = [
        0.5 * mhd_config["xmin"][0], 0.5 * mhd_config["xmax"][0],
        mhd_config["ymin"][0], mhd_config["ymax"][0]
    ]
    sizes = np.asarray(sizes) * L0
    xs = nx // 4
    fdata = absj[:, xs:(nx - xs)]
    xgrid = np.linspace(sizes[0], sizes[1], nx - xs * 2)
    ygrid = np.linspace(sizes[2], sizes[3], ny)
    nx_grid, = xgrid.shape
    ny_grid, = ygrid.shape
    img = ax.imshow(
        fdata,
        extent=sizes,
        cmap=plt.cm.viridis,
        # norm=LogNorm(vmin=1E2, vmax=1E3),
        vmin=4E2,
        vmax=1E3,
        aspect='auto',
        origin='lower',
        interpolation='none')
    # absj_maxy = np.argmax(fdata[:, nx_grid//2])
    # fdata_maxx = np.argmax(fdata, axis=1)
    # cond = (nx_grid-fdata_maxx-fdata_maxx) < 32
    # condy = np.logical_and(ygrid > 10, ygrid < 50)
    # cond = np.logical_and(cond, condy)
    # ax.plot(xgrid[fdata_maxx][cond], ygrid[cond], color='k')
    # ax.plot(xgrid[nx_grid-fdata_maxx-1][cond], ygrid[cond], color='k')
    ax.tick_params(labelsize=12)
    ax.set_xlabel(r'$x$/Mm', fontsize=16)
    ax.set_ylabel(r'$y$ (Mm)', fontsize=16)

    rect_cbar = np.copy(rect)
    rect_cbar[0] += 0.02
    rect_cbar[2] = 0.03
    rect_cbar[1] = 0.4
    rect_cbar[3] = 0.3
    cbar_ax = fig.add_axes(rect_cbar)
    cbar = fig.colorbar(img, cax=cbar_ax, extend="both")
    cbar.ax.tick_params(labelsize=10, color='w')
    cbar.ax.yaxis.set_tick_params(color='w')
    cbar.outline.set_edgecolor('w')
    plt.setp(plt.getp(cbar.ax.axes, 'yticklabels'), color='w')
    fig_text = r'$|\boldsymbol{j}|$'
    ax.text(0.05,
            0.95,
            fig_text,
            color='w',
            fontsize=16,
            horizontalalignment='left',
            verticalalignment='center',
            transform=ax.transAxes)

    # nbins = 100
    # jbins = np.logspace(-1, 3, nbins+1)
    # jbins_mid = 0.5 * (jbins[1:] + jbins[:-1])
    # jdist, _ = np.histogram(absj, bins=jbins)
    # plt.loglog(jbins_mid, jdist)

    fdir = '../img/inject_jz/' + plot_config["mhd_run"] + '/'
    mkdir_p(fdir)
    fname = fdir + 'jz_' + str(tframe) + '.jpg'
    fig.savefig(fname, dpi=200)

    if show_plot:
        plt.show()
    else:
        plt.close()
예제 #14
0
def reduce_local_dist(plot_config, mhd_config, show_plot=True):
    """Reduce local particle spatial distribution

    Args:
        plot_config: plot configuration in dictionary
        mhd_config: MHD simulation configuration
    """
    run_name = plot_config["run_name"]
    run_type = plot_config["run_type"]
    tframe = plot_config["tframe"]
    # Normalization parameters depend on runs
    if run_type == "Fan-Early":
        rho0 = 1.2E10  # cm^-3
        L0 = 5.0E9  # in cm
        nrx, nry, nrp = 4, 2, 4
    elif run_type == "Bin-Fan":
        rho0 = 1.0E9  # cm^-3
        L0 = 6.2E9  # in cm
        nrx, nry, nrp = 1, 1, 4
    elif run_type == "Harris_UMN":
        rho0 = 1.0E9  # cm^-3
        L0 = 2.5E9  # in cm
        nrx, nry, nrp = 4, 4, 1

    # Dimensions for local spectra
    nx, = plot_config["nx"]
    ny, = plot_config["ny"]
    nxr = nx // nrx
    nyr = ny // nry
    xstart = nxr // 2

    # Read and reduce the local energy spectra
    tframe_str = str(tframe).zfill(4)
    fname = '../data/' + run_name + '/fp_local_' + tframe_str + '_sum.dat'
    fdata = np.fromfile(fname)
    npp = fdata.shape[0] // (nx * ny)
    fdata = fdata.reshape([ny, nx, npp])
    print("Total number of particles: %d" % np.sum(fdata))
    print("data size: %d %d %d (C-order)" % fdata.shape)
    dists = fdata.reshape(ny // nry, nry, nx // nrx, nrx, npp // nrp, nrp)
    dists_r = np.sum(np.sum(np.sum(dists, axis=5), axis=3), axis=1)
    print("reduced data size: %d %d %d (C-order)" % dists_r.shape)

    # Momentum bins (simulation unit)
    pmin = 1E-2
    pmax = 1E1
    p0 = 1E-1
    pmom = np.logspace(math.log10(pmin), math.log10(pmax), npp + 1)
    pmom_mid = (pmom[:-1] + pmom[1:]) * 0.5
    dpmom = np.diff(pmom)
    pmom_r = pmom[::nrp]
    pmom_mid_r = (pmom_r[:-1] + pmom_r[1:]) * 0.5
    dpmom_r = np.diff(pmom_r)
    fmom_r = dists_r * pmom_mid_r / dpmom_r  # f(p)p^3
    fene_r = fmom_r / pmom_mid_r * 2  # f(p)p or f(e)

    # Normalized energy bins
    ene0 = 1.0  # 1keV
    ene_shift = 1.0  # parameter to adjust the energy of the injected particles
    elog_r = ene0 * pmom_r**2 / p0**2  # in keV
    elog_r *= ene_shift  # shift the injection energy
    elog_mid_r = (elog_r[:-1] + elog_r[1:]) * 0.5
    delog_r = np.diff(elog_r)

    # Normalize the spectrum
    # We assume the initially inject particles are about 5% of all particles
    nptl_tot_real = L0**2 * rho0
    ene_cut = 10 * ene0  # about 1% of the simulated particles
    cutoff, _ = find_nearest(pmom, math.sqrt(ene_cut) * p0)
    cutoff_r = cutoff // nrp
    nptl_tot = np.sum(fdata)
    nptl_above_cutoff = np.sum(fdata[:, :, cutoff:])
    fnorm = nptl_tot_real * 0.05 / nptl_tot
    fnorm *= nxr * nyr / L0**2
    print("Assuming nonthermal start from %f keV" %
          ((pmom[cutoff]**2 * ene_shift) / p0**2))
    print("Total Number of particles: %d" % nptl_tot)
    print("Number of particles above break: %d" % nptl_above_cutoff)
    print("Non-thermal fraction: %f" % (nptl_above_cutoff / nptl_tot))

    if plot_config["check_dist"]:
        # Plot the spatial distribution of the high-energy electrons
        L0_Mm = L0 / 1E8  # to Mm
        dists_r *= fnorm
        dist_2d = np.sum(dists_r[:, :, cutoff_r + 1:], axis=2)
        if run_type == "Fan-Early":
            rect = [0.12, 0.10, 0.7, 0.85]
            fig = plt.figure(figsize=[7, 10])
            ax1 = fig.add_axes(rect)
            extent_box = [L0_Mm * 0.5, L0_Mm, 0, L0_Mm]
            vmin, vmax = 0, 1E9
        elif run_type == "Bin-Fan":
            rect = [0.12, 0.12, 0.7, 0.85]
            fig = plt.figure(figsize=[8, 7])
            ax1 = fig.add_axes(rect)
            extent_box = [0, L0_Mm, 0, L0_Mm]
            vmin, vmax = 0, 1E9
        if run_type == "Harris_UMN":
            rect = [0.12, 0.10, 0.68, 0.85]
            fig = plt.figure(figsize=[7, 10])
            ax1 = fig.add_axes(rect)
            extent_box = [L0_Mm * 0.5, L0_Mm, 0, L0_Mm]
            vmin, vmax = 0, 2E7
        img = ax1.imshow(dist_2d[:, xstart:],
                         cmap=plt.cm.inferno,
                         vmin=vmin,
                         vmax=vmax,
                         extent=extent_box,
                         aspect='auto',
                         origin='lower',
                         interpolation='bicubic')
        ecut = elog_r[cutoff_r + 1]
        ecut_s = "{%0.1f}" % ecut
        label1 = r'$\varepsilon > ' + ecut_s + '$ keV'
        ax1.text(0.05,
                 0.95,
                 label1,
                 color='white',
                 fontsize=24,
                 horizontalalignment='left',
                 verticalalignment='center',
                 transform=ax1.transAxes)
        ax1.set_xlabel(r'$x$/Mm', fontdict=FONT, fontsize=24)
        ax1.set_ylabel(r'$y$/Mm', fontdict=FONT, fontsize=24)
        ax1.tick_params(labelsize=20)
        rect[0] += rect[2] + 0.02
        rect[2] = 0.04
        cbar_ax = fig.add_axes(rect)
        cbar = fig.colorbar(img, cax=cbar_ax)
        cbar.ax.tick_params(labelsize=16)
        cbar.ax.set_ylabel(r'$\rho$ (cm$^{-3}$)', fontsize=24)
        fdir = '../img/fp_local/' + run_name + '/'
        mkdir_p(fdir)
        fname = fdir + "fp_local_reduced_" + str(tframe) + ".jpg"
        fig.savefig(fname, dpi=200)

    # Save the reduced spectrum
    fdir = '../data/' + run_name + '/reduced/'
    mkdir_p(fdir)
    fname = fdir + "fe_local_reduced_" + str(tframe) + ".dat"
    fene_r *= fnorm  # normalize to real number density
    fene_r *= 0.5 * p0**2 / (ene0 * ene_shift)  # normalize to keV^-1
    fene_r[:, xstart:, :].tofile(fname)

    if plot_config["check_dist"]:
        # Check the saved local spectrum
        fdata = np.fromfile(fname)
        fdata = fdata.reshape([nyr, nxr - xstart, -1])
        fene_r = fdata * delog_r[np.newaxis, np.newaxis, :]
        dist_2d = np.sum(fene_r[:, :, cutoff_r + 1:], axis=2)
        rect = [0.12, 0.10, 0.68, 0.85]
        fig = plt.figure(figsize=[7, 10])
        ax1 = fig.add_axes(rect)
        img = ax1.imshow(dist_2d,
                         cmap=plt.cm.inferno,
                         vmin=vmin,
                         vmax=vmax,
                         extent=extent_box,
                         aspect='auto',
                         origin='lower',
                         interpolation='bicubic')

        if show_plot:
            plt.show()
        else:
            plt.close('all')
예제 #15
0
def plot_reduced_mhd(plot_config, mhd_config, mhd_run_info, show_plot=True):
    """Plot reduced MHD data
    """
    run_type = plot_config["run_type"]
    if run_type == "Fan-Early":
        rho0 = 1.2E10  # cm^-3
        b0 = 50  # Gauss
        T0 = 6.0E6  # K
        L0 = 5.0E9  # in cm
        nrx, nry = 64, 32
    elif run_type == "Harris_UMN":
        rho0 = 1.0E9  # cm^-3
        b0 = 50  # Gauss
        T0 = 1.0E6  # K
        L0 = 2.5E9  # in cm
        nrx, nry = 64, 64
    va = calc_va(b0, rho0)  # in m/s
    time_norm = L0 / (va * 1E2)
    rho_norm = 1.0E9  # cm^-3
    bnorm = 50  # Gauss
    Tnorm = 1.0E6  # K
    nx, = mhd_config["nx"]
    ny, = mhd_config["ny"]
    nxr = nx // nrx
    nyr = ny // nry
    fdir = plot_config["mhd_run_dir"] + "data_reduced/"
    tframe = plot_config["tframe"]
    L0_Mm = L0 / 1E8
    extent_box = [0, L0_Mm * 0.5, 0, L0_Mm]

    fig = plt.figure(figsize=[7, 5])
    rect = [0.09, 0.13, 0.28, 0.8]
    hgap, vgap = 0.02, 0.02

    fname = fdir + 'rho_' + str(tframe) + '.dat'
    fdata = np.fromfile(fname, dtype=np.float32)
    fdata = fdata.reshape((nyr, nxr // 2))
    ax = fig.add_axes(rect)
    img = ax.imshow(fdata / rho_norm,
                    extent=extent_box,
                    cmap=plt.cm.plasma,
                    aspect='auto',
                    origin='lower',
                    interpolation='bicubic',
                    vmin=1,
                    vmax=10)
    ax.tick_params(labelsize=12)
    ax.set_xlabel(r'$x$/Mm', fontsize=16)
    ax.set_ylabel(r'$y$/Mm', fontsize=16)
    ax.tick_params(bottom=True, top=False, left=True, right=True)
    ax.tick_params(axis='x', which='minor', direction='in', top=True)
    ax.tick_params(axis='x', which='major', direction='in', top=True)
    ax.tick_params(axis='y', which='minor', direction='in')
    ax.tick_params(axis='y', which='major', direction='in')
    rect_cbar = np.copy(rect)
    rect_cbar[0] += 0.02
    rect_cbar[2] = 0.015
    rect_cbar[1] = 0.4
    rect_cbar[3] = 0.3
    cbar_ax = fig.add_axes(rect_cbar)
    cbar = fig.colorbar(img, cax=cbar_ax)
    cbar.set_label(r'$\rho (10^9\text{cm}^{-3})$', color='w', fontsize=12)
    cbar.ax.yaxis.set_tick_params(color='w')
    cbar.outline.set_edgecolor('w')
    plt.setp(plt.getp(cbar.ax.axes, 'yticklabels'), color='w')
    cbar.ax.tick_params(labelsize=12, color='w')

    rect[0] += rect[2] + hgap
    fname = fdir + 'T_' + str(tframe) + '.dat'
    fdata = np.fromfile(fname, dtype=np.float32)
    fdata = fdata.reshape((nyr, nxr // 2))
    ax = fig.add_axes(rect)
    img = ax.imshow(fdata / Tnorm,
                    extent=extent_box,
                    cmap=plt.cm.viridis,
                    aspect='auto',
                    origin='lower',
                    interpolation='bicubic',
                    vmin=0.1,
                    vmax=10)
    ax.tick_params(labelsize=12)
    ax.tick_params(axis='y', labelleft=False)
    ax.set_xlabel(r'$x$/Mm', fontsize=16)
    time = mhd_config["dt_out"][0] * time_norm * tframe
    tname = "Time: %0.1f s" % time
    plt.title(tname, fontsize=16)
    ax.tick_params(bottom=True, top=False, left=True, right=True)
    ax.tick_params(axis='x', which='minor', direction='in', top=True)
    ax.tick_params(axis='x', which='major', direction='in', top=True)
    ax.tick_params(axis='y', which='minor', direction='in')
    ax.tick_params(axis='y', which='major', direction='in')
    rect_cbar = np.copy(rect)
    rect_cbar[0] += 0.02
    rect_cbar[2] = 0.015
    rect_cbar[1] = 0.4
    rect_cbar[3] = 0.3
    cbar_ax = fig.add_axes(rect_cbar)
    cbar = fig.colorbar(img, cax=cbar_ax)
    cbar.set_label(r'$T (10^6\text{K})$', color='w', fontsize=12)
    cbar.ax.yaxis.set_tick_params(color='w')
    cbar.outline.set_edgecolor('w')
    plt.setp(plt.getp(cbar.ax.axes, 'yticklabels'), color='w')
    cbar.ax.tick_params(labelsize=12, color='w')

    rect[0] += rect[2] + hgap
    fname = fdir + 'absB_' + str(tframe) + '.dat'
    fdata = np.fromfile(fname, dtype=np.float32)
    fdata = fdata.reshape((nyr, nxr // 2))
    ax = fig.add_axes(rect)
    img = ax.imshow(fdata / bnorm,
                    extent=extent_box,
                    cmap=plt.cm.plasma,
                    aspect='auto',
                    origin='lower',
                    interpolation='bicubic',
                    vmin=0.0,
                    vmax=2.0)
    ax.tick_params(labelsize=12)
    ax.tick_params(axis='y', labelleft=False)
    ax.set_xlabel(r'$x$/Mm', fontsize=16)
    ax.tick_params(bottom=True, top=False, left=True, right=True)
    ax.tick_params(axis='x', which='minor', direction='in', top=True)
    ax.tick_params(axis='x', which='major', direction='in', top=True)
    ax.tick_params(axis='y', which='minor', direction='in')
    ax.tick_params(axis='y', which='major', direction='in')
    rect_cbar = np.copy(rect)
    rect_cbar[0] += 0.02
    rect_cbar[2] = 0.015
    rect_cbar[1] = 0.4
    rect_cbar[3] = 0.3
    cbar_ax = fig.add_axes(rect_cbar)
    cbar = fig.colorbar(img, cax=cbar_ax)
    cbar.set_label(r'$B (\text{50 Gauss})$', color='w', fontsize=12)
    cbar.ax.yaxis.set_tick_params(color='w')
    cbar.outline.set_edgecolor('w')
    plt.setp(plt.getp(cbar.ax.axes, 'yticklabels'), color='w')
    cbar.ax.tick_params(labelsize=12, color='w')

    img_dir = '../img/' + mhd_run_info["run_name"] + '/mhd_fields_reduced/'
    mkdir_p(img_dir)
    fname = img_dir + 'mhd_fields_' + str(tframe) + '.jpg'
    fig.savefig(fname, dpi=400)
    if not show_plot:
        plt.close()
    if show_plot:
        plt.show()
def plot_dist_2d(plot_config, mhd_config, show_plot=True):
    """Plot 2D spatial distribution

    Args:
        plot_config: plot configuration in dictionary
        mhd_config: MHD simulation configuration
    """
    tframe = plot_config["tframe"]
    nreduce = plot_config["nreduce"]
    nr_mhd, = mhd_config["nx"]  # r
    nt_mhd, = mhd_config["ny"]  # theta
    np_mhd, = mhd_config["nz"]  # phi
    nrr = nr_mhd // nreduce
    ntr = nt_mhd // nreduce
    npr = np_mhd // nreduce

    mhd_run_dir = plot_config["mhd_run_dir"]
    fname = mhd_run_dir + "bin_data/xpos.dat"
    rpos = np.fromfile(fname)
    fname = mhd_run_dir + "bin_data/ypos.dat"
    tpos = np.fromfile(fname)
    fname = mhd_run_dir + "bin_data/zpos.dat"
    ppos = np.fromfile(fname)

    ng = 2  # number of ghost cells
    rpos_r = rpos[ng:-ng:nreduce]
    tpos_r = tpos[ng:-ng:nreduce] + math.pi * 0.5
    ppos_r = ppos[ng:-ng:nreduce]

    run_name = plot_config["run_name"]
    tframe_str = str(tframe).zfill(4)
    fname = '../data/' + run_name + '/fxy-' + tframe_str + '_sum.dat'
    fdata = np.fromfile(fname).reshape([-1, npr, ntr, nrr])
    p3d, t3d, r3d = np.meshgrid(ppos_r, tpos_r, rpos_r, indexing='ij')
    fdata /= r3d**2 * np.sin(t3d)
    nbands, _, _, _ = fdata.shape
    fdata_phi = np.sum(fdata, axis=1)
    fdata_theta = np.sum(fdata, axis=2)

    fname = '../data/' + run_name + '/fp-' + str(tframe).zfill(4) + '_sum.dat'
    data = np.fromfile(fname, dtype=np.float64)
    dsz, = data.shape
    nbins = dsz // 2
    pinit = 0.1
    pmom = data[0:nbins]
    pmin, pmax = pmom[0], pmom[-1]
    emin = pmin**2 / pinit**2
    emax = pmax**2 / pinit**2
    ebins_edges = np.logspace(math.log10(emin), math.log10(emax), nbands + 1)
    nmin, nmax = 10, 2E3

    rr, tt = np.meshgrid(rpos_r, tpos_r)
    xx = rr * np.cos(tt)
    yy = rr * np.sin(tt)

    fnorms = [1, 4, 16, 64]

    fig = plt.figure(figsize=[15, 10])
    rect0 = [0.07, 0.55, 0.40, 0.40]
    hgap, vgap = 0.05, 0.05
    bands, bande = plot_config["high_bands"]
    for iband, eband in enumerate(range(bands, bande + 1)):
        row = iband // 2
        col = iband % 2
        rect = np.copy(rect0)
        rect[0] = rect0[0] + col * (rect0[2] + hgap)
        rect[1] = rect0[1] - row * (rect0[3] + vgap)
        ax = fig.add_axes(rect)
        fdata_sum = fdata_phi[eband] * fnorms[iband]
        fdata1 = fdata_sum + 1E-5
        im = ax.pcolormesh(xx, yy, fdata1, norm=LogNorm(vmin=nmin, vmax=nmax))
        ax.tick_params(labelsize=12)
        if row == 1:
            ax.set_xlabel(r'$x/R_e$', fontsize=16)
        else:
            ax.tick_params(axis='x', labelleft=False)
        if col == 0:
            ax.set_ylabel(r'$y/R_e$', fontsize=16)
        else:
            ax.tick_params(axis='y', labelleft=False)
        norm = fnorms[iband]
        e0 = plot_config["e0"]
        enel = "{%0.0f}" % (ebins_edges[eband] * e0)
        eneh = "{%0.0f}" % (ebins_edges[eband + 1] * e0)
        ftext = (r'$' + enel + r'$keV' + r'$' + r'< \varepsilon <' + eneh +
                 r'$keV')
        if norm > 1:
            fig_text = r'$' + str(fnorms[iband]) + 'n($' + ftext + r'$)$'
        else:
            fig_text = r'$n($' + ftext + r'$)$'
        ax.text(0.05,
                0.85,
                fig_text,
                color='white',
                fontsize=12,
                horizontalalignment='left',
                verticalalignment='center',
                transform=ax.transAxes)
    rect_cbar = np.copy(rect0)
    rect_cbar[0] += rect0[2] * 2 + hgap + 0.02
    rect_cbar[2] = 0.01
    rect_cbar[1] = rect0[1] - vgap - rect0[3] * 0.5
    rect_cbar[3] = rect0[3] + vgap
    cbar_ax = fig.add_axes(rect_cbar)
    cbar1 = fig.colorbar(im, cax=cbar_ax, extend='both')
    cbar1.ax.tick_params(labelsize=16)

    L0 = 6.9634E8  # m
    v0 = 1E3  # m/s
    t0 = L0 / v0
    tva = mhd_config["dt_out"][0] * t0
    title = 'Frame: %d' % plot_config["tframe"]
    fig.suptitle(title, fontsize=24)

    fdir = '../img/nrho/' + run_name + '/'
    mkdir_p(fdir)
    fname = fdir + 'nrho_bands_phi_' + tframe_str + '.jpg'
    fig.savefig(fname)

    rr, pp = np.meshgrid(rpos_r, ppos_r)
    xx = rr * np.sin(pp)
    yy = rr * np.cos(pp)

    fnorms = [1, 4, 16, 64]

    fig = plt.figure(figsize=[15, 10])
    rect0 = [0.07, 0.55, 0.40, 0.40]
    hgap, vgap = 0.05, 0.05
    bands, bande = plot_config["high_bands"]
    for iband, eband in enumerate(range(bands, bande + 1)):
        row = iband // 2
        col = iband % 2
        rect = np.copy(rect0)
        rect[0] = rect0[0] + col * (rect0[2] + hgap)
        rect[1] = rect0[1] - row * (rect0[3] + vgap)
        ax = fig.add_axes(rect)
        fdata_sum = fdata_theta[eband] * fnorms[iband]
        fdata1 = fdata_sum + 1E-5
        im = ax.pcolormesh(xx, yy, fdata1, norm=LogNorm(vmin=nmin, vmax=nmax))
        ax.tick_params(labelsize=12)
        if row == 1:
            ax.set_xlabel(r'$x/R_e$', fontsize=16)
        else:
            ax.tick_params(axis='x', labelleft=False)
        if col == 0:
            ax.set_ylabel(r'$z/R_e$', fontsize=16)
        else:
            ax.tick_params(axis='y', labelleft=False)
        norm = fnorms[iband]
        e0 = plot_config["e0"]
        enel = "{%0.0f}" % (ebins_edges[eband] * e0)
        eneh = "{%0.0f}" % (ebins_edges[eband + 1] * e0)
        ftext = (r'$' + enel + r'$keV' + r'$' + r'< \varepsilon <' + eneh +
                 r'$keV')
        if norm > 1:
            fig_text = r'$' + str(fnorms[iband]) + 'n($' + ftext + r'$)$'
        else:
            fig_text = r'$n($' + ftext + r'$)$'
        ax.text(0.05,
                0.7,
                fig_text,
                color='white',
                fontsize=12,
                horizontalalignment='left',
                verticalalignment='center',
                transform=ax.transAxes)
    rect_cbar = np.copy(rect0)
    rect_cbar[0] += rect0[2] * 2 + hgap + 0.02
    rect_cbar[2] = 0.01
    rect_cbar[1] = rect0[1] - vgap - rect0[3] * 0.5
    rect_cbar[3] = rect0[3] + vgap
    cbar_ax = fig.add_axes(rect_cbar)
    cbar1 = fig.colorbar(im, cax=cbar_ax, extend='both')
    cbar1.ax.tick_params(labelsize=16)

    L0 = 6.9634E8  # m
    v0 = 1E3  # m/s
    t0 = L0 / v0
    tva = mhd_config["dt_out"][0] * t0
    title = 'Frame: %d' % plot_config["tframe"]
    fig.suptitle(title, fontsize=24)

    fdir = '../img/nrho/' + run_name + '/'
    mkdir_p(fdir)
    fname = fdir + 'nrho_bands_theta_' + tframe_str + '.jpg'
    fig.savefig(fname)

    if show_plot:
        plt.show()
    else:
        plt.close("all")
def plot_ptl_traj(mhd_run_info, sde_run, tframe, mhd_config, mpi_size):
    """Plot particle trajectories

    Args:
        mhd_run_info: information of the MHD run
        sde_run: SDE run name
        tframe: time frame
    """
    mhd_box, rho = read_mhd_data(mhd_run_info, tframe)

    mhd_time = mhd_config["dt_out"][0] * tframe
    tva = mhd_time / mhd_config["ly"][0]  # in Alfven crossing time
    title = r'$t = ' + "{:10.1f}".format(tva) + r'\tau_A$'
    title += ' (frame: %d)' % tframe

    fpath = "../data/traj_data/"
    opath = "../img/ptl_traj/" + mhd_run_info["run_name"] + '/' + sde_run + '/'
    mkdir_p(opath)
    for mpi_rank in range(mpi_size):
        fname = (fpath + mhd_run_info["run_name"] + '/' + sde_run +
                 "/tracked_particle_points_" + str(mpi_rank).zfill(4) + ".dat")
        nptl = get_nptl(fname)
        odir1 = opath + "mpi_rank_" + str(mpi_rank) + "/"
        mkdir_p(odir1)
        for ptl_index in range(nptl - 2, nptl):
            ptl = read_ptl_traj(fname, nptl, ptl_index)
            ptl = np.array([list(item) for item in ptl])
            ptl = boundary_cross(ptl)
            xptl = ptl[:-1, 0]
            yptl = ptl[:-1, 1]
            pptl = ptl[:-1, 2]
            tptl = ptl[:-1, 4]
            ptl_range = [
                np.min(xptl),
                np.max(xptl),
                np.min(yptl),
                np.max(yptl)
            ]

            # find the closed time point
            tindex, _ = find_nearest(tptl, mhd_time)

            prange, mhd_data = adjust_mhd_data(mhd_box, rho, ptl_range)

            fig = plt.figure(figsize=[20, 10])
            rect = [0.05, 0.12, 0.2, 0.8]
            hgap = 0.06
            ax = fig.add_axes(rect)
            img = ax.imshow(mhd_data,
                            extent=prange,
                            vmin=0.5,
                            vmax=3.0,
                            cmap=plt.cm.viridis,
                            aspect='auto',
                            origin='lower')
            plot_particle_2d(('x', xptl), ('y', yptl), ax, tindex)
            ax.set_xlim(prange[:2])
            ax.set_ylim(prange[2:])

            rect[0] += rect[2] + 0.01
            rect[2] = 0.015
            cbar_ax = fig.add_axes(rect)
            cbar = fig.colorbar(img, cax=cbar_ax)
            cbar.ax.tick_params(labelsize=16)
            cbar.ax.set_xlabel(r'$\rho$', fontsize=24)
            cbar.ax.xaxis.set_label_position('top')

            rect[0] += rect[2] + hgap
            rect[2] = 0.29
            ax1 = fig.add_axes(rect)
            plot_particle_2d(('x', xptl), ('p', pptl), ax1, tindex)

            rect[0] += rect[2] + hgap
            ax2 = fig.add_axes(rect)
            plot_particle_2d(('t', tptl), ('p', pptl), ax2, tindex)

            fig.suptitle(title, fontsize=24)

            out_dir = odir1 + "ptl_" + str(ptl_index) + "/"
            mkdir_p(out_dir)
            fig_name = out_dir + "tframe_" + str(tframe) + ".jpg"
            fig.savefig(fig_name, dpi=200)

            # plt.show()
            plt.close()
예제 #18
0
def spatial_distribution_band(plot_config, mhd_config, show_plot=True):
    """Plot particle spatial distribution for one energy band

    Args:
        plot_config: plot configuration in dictionary
        mhd_config: MHD simulation configuration
    """
    fig = plt.figure(figsize=[12, 8])
    rect = [0.07, 0.12, 0.25, 0.8]
    axs = []
    mpl.rcParams['contour.negative_linestyle'] = 'solid'
    for tframe in plot_config["tframes"]:
        tframe_str = str(tframe).zfill(4)
        eband = plot_config["eband"]
        run_name = plot_config["run_name"]
        fname = '../data/' + run_name + '/fxy-' + tframe_str + '_sum.dat'
        fdata = np.fromfile(fname)
        nx, = plot_config["nx"]
        ny, = plot_config["ny"]
        nx_mhd = mhd_config["nx"][0]
        ny_mhd = mhd_config["ny"][0]
        az = read_az(plot_config["mhd_run_dir"], nx_mhd, ny_mhd, tframe)
        xgrid = np.linspace(mhd_config["xmin"], mhd_config["xmax"],
                            mhd_config["nx"])
        ygrid = np.linspace(mhd_config["ymin"], mhd_config["ymax"],
                            mhd_config["ny"])
        print("data size: %d %d" % (nx, ny))
        dists = fdata.reshape([fdata.shape[0] // (nx * ny), -1])
        print("Total number of particles: %d" % np.sum(dists))

        fband = dists[eband, :]
        print("particle number in band %d: %d" % (eband, fband.size))
        fband = np.reshape(fband, (ny, nx))
        print("min, max, mean, and std: %f %f %f %f" %
              (np.min(fband), np.max(fband), np.mean(fband), np.std(fband)))

        ax = fig.add_axes(rect)
        axs.append(ax)
        vmin, vmax = 0.1, 1E1
        lx = mhd_config["xmax"][0] - mhd_config["xmin"][0]
        sizes = [
            mhd_config["xmin"][0] + lx * 0.5, mhd_config["xmax"][0],
            mhd_config["ymin"][0], mhd_config["ymax"][0]
        ]
        img = ax.imshow(
            fband[:, nx // 2:],
            cmap=plt.cm.viridis,
            aspect='auto',
            origin='lower',
            extent=sizes,
            # vmin=vmin, vmax=vmax,
            norm=LogNorm(vmin=vmin, vmax=vmax),
            interpolation='bicubic')
        level_az = np.linspace(np.min(az[nx_mhd // 2:, :]),
                               np.max(az[nx_mhd // 2:, :]), 15)
        ax.contour(xgrid[nx_mhd // 2:],
                   ygrid,
                   az[nx_mhd // 2:, :].T,
                   colors='black',
                   linewidths=0.5,
                   levels=level_az)
        ax.tick_params(labelsize=16)
        rect[0] += rect[2] + 0.03
        ax.set_xlabel(r'$x$', fontsize=20)
        tva = mhd_config["dt_out"][0] * tframe / mhd_config["ly"][0]
        title = r'$t = ' + "{:10.1f}".format(tva) + r'\tau_A$'
        plt.title(title, fontsize=24)

    axs[0].set_ylabel(r'$y$', fontsize=20)
    axs[1].tick_params(axis='y', labelleft='off')
    axs[2].tick_params(axis='y', labelleft='off')

    rect[0] -= 0.01
    rect[2] = 0.02
    cbar_ax = fig.add_axes(rect)
    cbar1 = fig.colorbar(img, cax=cbar_ax)
    cbar1.ax.tick_params(labelsize=16)
    fig_text = figure_text(eband)
    title = r"$n($" + fig_text + r"$)$"
    cbar1.ax.set_ylabel(title, fontsize=24)

    fdir = '../img/apj_parker/'
    mkdir_p(fdir)
    tstr = ""
    for tframe in plot_config["tframes"]:
        tstr += str(tframe) + "_"
    fname = fdir + 'nrho_' + tstr + str(eband) + '.jpg'
    fig.savefig(fname, dpi=200)

    if show_plot:
        plt.show()
    else:
        plt.close()
def energy_distributions_bg(config, sde_run):
    """Plot energy distributions for runs with different guide field

    Args:
        config: plotting configurations
        sde_run: stochastic integration with specific diffusion coefficient
    """
    rect = [0.15, 0.15, 0.8, 0.8]
    fig1 = plt.figure(figsize=[7, 5])
    ax = fig1.add_axes(rect)

    fdir = '../img/spectrum/spectra_bg/'
    mkdir_p(fdir)

    mhd_runs = [
        "S1E5_beta01_bg00", "S1E5_beta01_bg02", "S1E5_beta01_bg05",
        "S1E5_beta01_bg10"
    ]

    run_labels = [r"$B_g=0.0$", r"$B_g=0.2$", r"$B_g=0.5$", r"$B_g=1.0$"]
    line_styles = ['--', '-.', ':']
    ax.set_prop_cycle('color', COLORS)

    plots = []
    power_plots = []
    for index, mhd_run in enumerate(mhd_runs):
        run_name = mhd_run + "/" + sde_run
        plot_config = config[run_name]
        tframe = str(plot_config["tmax"]).zfill(4)
        fname = '../data/' + run_name + '/fp-' + tframe + '_sum.dat'
        data = np.fromfile(fname, dtype=np.float64)
        dsz, = data.shape
        nbins = dsz // 2
        pinit = 0.1
        pmom = data[0:nbins] / pinit
        elog = pmom**2
        fmom = data[nbins:] * pmom / np.gradient(pmom)
        fene = fmom / pmom**2
        plot1, = ax.loglog(elog, fene, linewidth=2, label=run_labels[index])
        plots.append(plot1)
        npow = len(plot_config["power_low"])
        if index != 1:
            for i in range(npow):
                sindex = plot_config["power_low"][i]
                eindex = plot_config["power_high"][i]
                erange = elog[sindex:eindex]
                popt, _ = curve_fit(func_power, erange, fene[sindex:eindex])
                pindex = popt[0]
                pconst = popt[1] * 3
                fpower = func_power(erange, pindex, pconst)
                power_index = "{%0.2f}" % pindex
                tname = r'$\sim\varepsilon^{' + power_index + '}$'
                plot2, = ax.loglog(erange,
                                   fpower,
                                   linewidth=2,
                                   color=COLORS[index],
                                   linestyle=line_styles[i],
                                   label=tname)
                power_plots.append(plot2)

    leg1 = ax.legend(handles=plots,
                     loc=1,
                     prop={'size': 20},
                     ncol=1,
                     shadow=False,
                     fancybox=False,
                     frameon=False)
    ax.add_artist(leg1)
    ax.legend(handles=power_plots,
              loc=3,
              prop={'size': 20},
              ncol=1,
              shadow=False,
              fancybox=False,
              frameon=False)
    ax.set_xlim([1E-1, 2E2])
    ax.set_ylim([1E-2, 1E7])
    ax.set_yticks(np.logspace(-1, 7, num=5))
    ax.set_xlabel(r'$\varepsilon/\varepsilon_0$', fontsize=24)
    ax.set_ylabel(r'$f(\varepsilon)$', fontsize=24)
    ax.tick_params(labelsize=20)
    fe_name = "fe_" + sde_run + ".pdf"
    fig1.savefig(fdir + fe_name)
    plt.show()
예제 #20
0
def rhessi18(plot_config, mhd_config, show_plot=True):
    """Plot spatial distributions for multiple energy band

    Args:
        plot_config: plot configuration in dictionary
        mhd_config: MHD simulation configuration
    """
    # mpl.rc('text', usetex=True)
    fig = plt.figure(figsize=[15, 15])
    rect0 = [0.07, 0.53, 0.41, 0.42]
    rect = np.copy(rect0)
    hgap, vgap = 0.04, 0.05
    run_name = plot_config["run_name"]
    tframe_str = str(plot_config["tframe"]).zfill(4)
    nx, = plot_config["nx"]
    ny, = plot_config["ny"]
    fname = '../data/' + run_name + '/fxy-' + tframe_str + '_sum.dat'
    fdata = np.fromfile(fname)
    nx, = plot_config["nx"]
    ny, = plot_config["ny"]
    print("data size: %d %d" % (nx, ny))
    dists = fdata.reshape([fdata.shape[0] // (nx * ny), -1])
    print("Total number of particles: %d" % np.sum(dists))

    axs = [None] * 4
    ims = [None] * 4
    vmin = plot_config['nmin']
    vmax = plot_config['nmax']
    sizes = [
        mhd_config["xmin"][0], mhd_config["xmax"][0], mhd_config["ymin"][0],
        mhd_config["ymax"][0]
    ]
    lnorm = 75.0  # in Mm
    sizes = np.asarray(sizes) * lnorm

    # High-energy particle distributions
    for i in range(2):
        rect[0] = rect0[0] + (hgap + rect0[2]) * i
        eband = i + 3
        fband = dists[eband, :]
        fnorm = 4**(eband - 3)
        fband = np.reshape(fband, (ny, nx)) * fnorm
        fband += vmin * 0.01
        print("min, max and mean of the data: %f %f %f %f" %
              (np.min(fband), np.max(fband), np.mean(fband), np.std(fband)))
        axs[i] = fig.add_axes(rect)
        ims[i] = axs[i].imshow(fband,
                               cmap=plt.cm.plasma,
                               aspect='auto',
                               origin='lower',
                               extent=sizes,
                               norm=LogNorm(vmin=vmin, vmax=vmax),
                               interpolation='bicubic')
        axs[i].tick_params(labelsize=16)
        if fnorm > 1:
            fig_text = r'$' + str(fnorm) + r'$' + r'$n($' + figure_text(
                eband) + r'$)$'
        else:
            fig_text = r'$n($' + figure_text(eband) + r'$)$'
        color = 'k' if eband == 0 else 'w'
        axs[i].text(0.02,
                    0.92,
                    fig_text,
                    color=color,
                    fontsize=20,
                    bbox=dict(facecolor='none',
                              alpha=1.0,
                              edgecolor='none',
                              pad=10.0),
                    horizontalalignment='left',
                    verticalalignment='bottom',
                    transform=axs[i].transAxes)

    rect_cbar = np.copy(rect0)
    rect_cbar[0] = rect0[0] + rect0[2] * 2 + 0.05
    rect_cbar[2] = 0.015
    cbar_ax = fig.add_axes(rect_cbar)
    cbar1 = fig.colorbar(ims[0], cax=cbar_ax, extend='both')
    cbar1.ax.tick_params(labelsize=16)

    # Current density
    mhd_run_dir = plot_config["mhd_run_dir"]
    fpath = mhd_run_dir + 'bin_data/'
    fname = fpath + 'mhd_data_' + tframe_str
    nx = mhd_config["nx"][0] + 4
    ny = mhd_config["ny"][0] + 4
    dxm = mhd_config["dx"][0]
    dym = mhd_config["dy"][0]
    mhd_fields = np.fromfile(fname, dtype=np.float32)
    mhd_fields = mhd_fields.reshape((ny, nx, 8))
    bx = mhd_fields[:, :, 4]
    by = mhd_fields[:, :, 5]
    jz = np.gradient(by, dxm, axis=1) - np.gradient(bx, dym, axis=0)
    rect[1] = rect0[1] - rect0[3] - vgap
    rect[0] = rect0[0]
    axs[2] = fig.add_axes(rect)
    ims[2] = axs[2].imshow(jz,
                           cmap=plt.cm.seismic,
                           aspect='auto',
                           origin='lower',
                           extent=sizes,
                           vmin=-500,
                           vmax=500,
                           interpolation='none')
    axs[2].tick_params(labelsize=16)
    axs[2].text(0.02,
                0.92,
                r'$j_z/j_0$',
                color='k',
                fontsize=20,
                bbox=dict(facecolor='none',
                          alpha=1.0,
                          edgecolor='none',
                          pad=10.0),
                horizontalalignment='left',
                verticalalignment='bottom',
                transform=axs[2].transAxes)

    nyr = 4
    center = np.zeros(2)
    nx_mhd = mhd_config['nx'][0]
    ny_mhd = mhd_config['ny'][0]
    dx_mhd = mhd_config['dx'][0]
    dy_mhd = mhd_config['dy'][0]
    COLORS = palettable.tableau.Tableau_10.mpl_colors
    lenx = nx_mhd * dx_mhd * 0.5 * lnorm
    for iy in range(nyr):
        center[0] = 0
        center[1] = (ny_mhd * (iy + 0.5) / nyr) * dy_mhd * lnorm
        leny = (ny_mhd / nyr) * dy_mhd * lnorm - 1
        plot_box(center, lenx, leny, axs[2], COLORS[iy])

    rect_cbar = np.copy(rect)
    rect_cbar[0] = rect[0] + 0.02
    rect_cbar[2] = 0.015
    rect_cbar[1] += rect_cbar[3] * 0.25
    rect_cbar[3] *= 0.5
    cbar_ax = fig.add_axes(rect_cbar)
    cbar2 = fig.colorbar(ims[2], cax=cbar_ax, extend='both')
    cbar2.ax.tick_params(labelsize=16)

    # Local spectrum
    with open('config/spectrum_config_10ta.json', 'r') as file_handler:
        config = json.load(file_handler)
    sde_run_config = config[run_name]
    nreduce = sde_run_config["nreduce"]
    nx = mhd_config["nx"][0] // nreduce
    ny = mhd_config["ny"][0] // nreduce

    fname = '../data/' + run_name + '/fp_local_' + tframe_str + '_sum.dat'
    fdata = np.fromfile(fname)
    npp = fdata.shape[0] // (nx * ny)
    fdata = fdata.reshape([ny, nx, npp])
    print("Total number of particles: %d" % np.sum(fdata))
    print("data size: %d %d %d (C-order)" % fdata.shape)
    xs, xe = nx // 4, nx * 3 // 4
    fdata_bin = fdata[:, xs:xe, :].reshape(nyr, -1, nx, npp)
    fdata_r = np.sum(np.sum(fdata_bin, axis=1), axis=1)

    p0 = 0.1  # initial particle momentum
    pmom = np.logspace(-2, 1, npp + 1) / p0
    pmom_mid = (pmom[:-1] + pmom[1:]) * 0.5
    dpmom = np.diff(pmom)
    elog = pmom**2
    elog_mid = (elog[:-1] + elog[1:]) * 0.5

    rect[0] = rect0[0] + rect0[2] + hgap
    axs[3] = fig.add_axes(rect)
    axs[3].tick_params(labelsize=16)
    for iy in range(nyr):
        fmom = fdata_r[iy] * pmom_mid / dpmom  # f(p)p^3
        fene = fmom / pmom_mid * 2  # f(p)p or f(e)
        fene[fene == 0] = np.nan
        axs[3].loglog(elog_mid, fene, linewidth=2, color=COLORS[iy])
    axs[3].set_xlim(1E-1, 1E4)
    axs[3].set_ylim(1E-2, 5E7)

    axs[1].tick_params(axis='y', labelleft=False)
    axs[0].set_ylabel(r'$y/$Mm', fontsize=20)
    axs[1].set_xlabel(r'$x/$Mm', fontsize=20)
    axs[2].set_xlabel(r'$x/$Mm', fontsize=20)
    axs[2].set_ylabel(r'$y/$Mm', fontsize=20)
    axs[3].set_xlabel(r'$\varepsilon/$keV', fontsize=20)

    tva = mhd_config["dt_out"][0] * plot_config["tframe"] / mhd_config["ly"][0]
    title = r'$t = ' + "{:10.1f}".format(tva) + r'\tau_A$'
    title += ' (frame: %d)' % plot_config["tframe"]
    fig.suptitle(title, fontsize=24)

    fdir = '../img/nrho_absj_spectra/' + run_name + '/'
    mkdir_p(fdir)
    fname = fdir + 'nrho_absj_specta_' + tframe_str + '.jpg'
    fig.savefig(fname)

    if show_plot:
        plt.show()
    else:
        plt.close()