def energy_spectrum_multi(bg, spect_info, species='e'): """Plot energy spectra for runs with different guide field """ if species == 'h': species = 'H' bg_str = str(int(bg * 10)).zfill(2) mimes = np.asarray([25, 100, 400]) tmaxs = np.asarray([114, 114, 102]) fig = plt.figure(figsize=[7, 5]) ax = fig.add_axes([0.15, 0.15, 0.8, 0.8]) COLORS = palettable.tableau.Tableau_10.mpl_colors ax.set_prop_cycle('color', COLORS) for mime, tmax in zip(mimes, tmaxs): run_name = "mime" + str(mime) + "_beta002_bg" + bg_str picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json' pic_info = read_data_from_json(picinfo_fname) if species == 'e': vth = pic_info.vthe else: vth = pic_info.vthi gama = 1.0 / math.sqrt(1.0 - 3 * vth**2) eth = gama - 1.0 fdir = '../data/spectra/' + run_name + '/' fname = fdir + 'spectrum-' + species.lower() + '.' + str(tmax) flog = np.fromfile(fname) emin_log = math.log10(spect_info["emin"]) emax_log = math.log10(spect_info["emax"]) elog = 10**(np.linspace(emin_log, emax_log, spect_info["nbins"])) flog *= np.gradient(elog) elog /= eth flog /= np.gradient(elog) nptot = pic_info.nx * pic_info.ny * pic_info.nz * pic_info.nppc flog /= nptot ltext = r"$m_i/m_e=" + str(mime) + "$" ax.loglog(elog, flog, linewidth=3, label=ltext) ax.legend(loc=3, prop={'size': 16}, ncol=1, shadow=False, fancybox=False, frameon=False) if species == 'e': ax.set_xlim([3E-1, 5E2]) else: ax.set_xlim([3E-1, 1E3]) ax.set_ylim([1E-11, 1E0]) ax.set_yticks(np.logspace(-10, 0, num=6)) ax.set_xlabel(r'$\varepsilon/\varepsilon_\text{th}$', fontdict=FONT, fontsize=20) ax.set_ylabel(r'$f(\varepsilon)$', fontdict=FONT, fontsize=20) ax.tick_params(labelsize=16) fpath = "../img/img_high_mime/spectra/" mkdir_p(fpath) fname = fpath + "spect_bg" + bg_str + "_" + species + ".pdf" fig.savefig(fname) plt.show()
def plot_beta_dist(plot_config, show_plot=True): """ Plot plasma beta distribution """ pic_run = plot_config["pic_run"] pic_run_dir = plot_config["pic_run_dir"] species = plot_config["species"] tframe = plot_config["tframe"] picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) tinit = pic_info.vthe**2 beta_init = tinit * 2 / pic_info.b0**2 fdir = '../data/temperature_anisotropy/' + pic_run + '/' fname = fdir + 'fbpara_' + species + '_' + str(tframe) + '.gda' fdata = np.fromfile(fname, dtype=np.float32) nbins_beta = int(fdata[0]) beta_bins_edge = fdata[1:nbins_beta+2] beta_bins_mid = 0.5 * (beta_bins_edge[1:] + beta_bins_edge[:-1]) beta_bins_mid /= beta_init dtemp = np.diff(beta_bins_edge) fbpara = fdata[nbins_beta+2:] / dtemp fname = fdir + 'fbperp_' + species + '_' + str(tframe) + '.gda' fdata = np.fromfile(fname, dtype=np.float32) fbperp = fdata[nbins_beta+2:] / dtemp fig = plt.figure(figsize=[3.25, 2.5]) rect = [0.16, 0.16, 0.79, 0.8] ax = fig.add_axes(rect) ax.set_prop_cycle('color', COLORS) ax.tick_params(bottom=True, top=True, left=True, right=True) ax.tick_params(axis='x', which='minor', direction='in', bottom=True, top=True) ax.tick_params(axis='x', which='major', direction='in', bottom=True, top=True) ax.tick_params(axis='y', which='minor', direction='in') ax.tick_params(axis='y', which='major', direction='in') ax.loglog(beta_bins_mid, fbpara, linewidth=1, label=r'$\beta_\parallel$') ax.loglog(beta_bins_mid, fbperp, linewidth=1, label=r'$\beta_\perp$') ax.legend(loc=1, prop={'size': 10}, ncol=1, shadow=False, fancybox=False, frameon=False) ax.set_xlim([1E-1, 1E5]) ax.tick_params(labelsize=8) ax.set_xlabel(r'$\beta/\beta_0$', fontsize=10) ax.set_ylabel(r'$f(\beta)$', fontsize=10) fdir = '../img/beta_dist/' + pic_run + '/' mkdir_p(fdir) fname = fdir + 'beta_dist_' + species + '_' + str(tframe) + '.pdf' fig.savefig(fname) if show_plot: plt.show() else: plt.close()
def plot_tratio_dist(plot_config, show_plot=True): """ Plot the distribution of the ratio between Tperp and Tpara """ pic_run = plot_config["pic_run"] pic_run_dir = plot_config["pic_run_dir"] species = plot_config["species"] tframe = plot_config["tframe"] picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) fdir = '../data/temperature_anisotropy/' + pic_run + '/' fname = fdir + 'ftratio_' + species + '_' + str(tframe) + '.gda' fdata = np.fromfile(fname, dtype=np.float32) nbins_tratio = int(fdata[0]) tratio_bins_edge = fdata[1:nbins_tratio + 2] tratio_bins_mid = 0.5 * (tratio_bins_edge[1:] + tratio_bins_edge[:-1]) dtemp = np.diff(tratio_bins_edge) ftratio = fdata[nbins_tratio + 2:] / dtemp fig = plt.figure(figsize=[3.25, 2.5]) rect = [0.16, 0.16, 0.79, 0.8] ax = fig.add_axes(rect) ax.set_prop_cycle('color', COLORS) ax.tick_params(bottom=True, top=True, left=True, right=True) ax.tick_params(axis='x', which='minor', direction='in', bottom=True, top=True) ax.tick_params(axis='x', which='major', direction='in', bottom=True, top=True) ax.tick_params(axis='y', which='minor', direction='in') ax.tick_params(axis='y', which='major', direction='in') ax.loglog(tratio_bins_mid, ftratio, linewidth=1) ax.set_xlim([5E-2, 2E1]) ax.tick_params(labelsize=8) ax.set_xlabel(r'$T_\perp/T_\parallel$', fontsize=10) ax.set_ylabel(r'$f(T_\perp/T_\parallel)$', fontsize=10) fdir = '../img/tratio_dist/' + pic_run + '/' mkdir_p(fdir) fname = fdir + 'tratio_dist_' + species + '_' + str(tframe) + '.pdf' fig.savefig(fname) if show_plot: plt.show() else: plt.close()
def main(): """business logic for when running this module as the primary one!""" args = get_cmd_args() run_name = args.run_name run_dir = args.run_dir picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json' pic_info = read_data_from_json(picinfo_fname) if args.multi_frames: ncores = multiprocessing.cpu_count() tframes = range(pic_info.ntf) Parallel(n_jobs=ncores)(delayed(process_input)(run_dir, run_name, tframe) for tframe in tframes) else: combine_energy_spectrum(run_dir, run_name, args.tframe, species=args.species)
def main(): """business logic for when running this module as the primary one!""" args = get_cmd_args() run_name = args.run_name run_dir = args.run_dir picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json' pic_info = read_data_from_json(picinfo_fname) if args.multi_frames: ncores = multiprocessing.cpu_count() tframes = range(pic_info.ntf) Parallel(n_jobs=ncores)( delayed(process_input)(run_dir, run_name, tframe) for tframe in tframes) else: combine_energy_spectrum(run_dir, run_name, args.tframe, species=args.species)
def plot_tratio_dist(plot_config, show_plot=True): """ Plot the distribution of the ratio between Tperp and Tpara """ pic_run = plot_config["pic_run"] pic_run_dir = plot_config["pic_run_dir"] species = plot_config["species"] tframe = plot_config["tframe"] picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) fdir = '../data/temperature_anisotropy/' + pic_run + '/' fname = fdir + 'ftratio_' + species + '_' + str(tframe) + '.gda' fdata = np.fromfile(fname, dtype=np.float32) nbins_tratio = int(fdata[0]) tratio_bins_edge = fdata[1:nbins_tratio+2] tratio_bins_mid = 0.5 * (tratio_bins_edge[1:] + tratio_bins_edge[:-1]) dtemp = np.diff(tratio_bins_edge) ftratio = fdata[nbins_tratio+2:] / dtemp fig = plt.figure(figsize=[3.25, 2.5]) rect = [0.16, 0.16, 0.79, 0.8] ax = fig.add_axes(rect) ax.set_prop_cycle('color', COLORS) ax.tick_params(bottom=True, top=True, left=True, right=True) ax.tick_params(axis='x', which='minor', direction='in', bottom=True, top=True) ax.tick_params(axis='x', which='major', direction='in', bottom=True, top=True) ax.tick_params(axis='y', which='minor', direction='in') ax.tick_params(axis='y', which='major', direction='in') ax.loglog(tratio_bins_mid, ftratio, linewidth=1) ax.set_xlim([5E-2, 2E1]) ax.tick_params(labelsize=8) ax.set_xlabel(r'$T_\perp/T_\parallel$', fontsize=10) ax.set_ylabel(r'$f(T_\perp/T_\parallel)$', fontsize=10) fdir = '../img/tratio_dist/' + pic_run + '/' mkdir_p(fdir) fname = fdir + 'tratio_dist_' + species + '_' + str(tframe) + '.pdf' fig.savefig(fname) if show_plot: plt.show() else: plt.close()
def combine_energy_spectrum(run_dir, run_name, tframe, species='e'): """Combine particle energy spectrum from different mpi_rank Args: run_dir: PIC simulation directory run_name: PIC simulation run name tframe: time frame species: 'e' for electrons, 'H' for ions """ picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json' pic_info = read_data_from_json(picinfo_fname) interval = pic_info.fields_interval mpi_size = pic_info.topology_x * pic_info.topology_y * pic_info.topology_z rank = 0 ndata = (NBINS + 3) if INCLUDE_BFIELDS else NBINS tindex = tframe * interval fname_pre = run_dir + 'hydro/T.' + str(tindex) if species == 'h': species = 'H' fname_pre += '/spectrum-' + species + 'hydro.' + str(tindex) fname = fname_pre + '.' + str(rank) fdata = np.fromfile(fname, dtype=np.float32) dsz, = fdata.shape nzone = dsz // ndata for rank in range(1, mpi_size): fname = fname_pre + '.' + str(rank) fdata += np.fromfile(fname, dtype=np.float32) print("number of zones: %d" % nzone) flog_tot = np.zeros(NBINS) for i in range(nzone): if INCLUDE_BFIELDS: flog = fdata[i*ndata+3:(i+1)*ndata] else: flog = fdata[i*ndata:(i+1)*ndata] flog_tot += flog emin_log = math.log10(EMIN) emax_log = math.log10(EMAX) elog = 10**(np.linspace(emin_log, emax_log, NBINS)) delog = np.gradient(elog) flog_tot /= delog fdir = '../data/spectra/' + run_name + '/' mkdir_p(fdir) fname = fdir + 'spectrum-' + species.lower() + '.' + str(tframe) flog_tot.tofile(fname)
def combine_energy_spectrum(run_dir, run_name, tframe, species='e'): """Combine particle energy spectrum from different mpi_rank Args: run_dir: PIC simulation directory run_name: PIC simulation run name tframe: time frame species: 'e' for electrons, 'H' for ions """ picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json' pic_info = read_data_from_json(picinfo_fname) interval = pic_info.fields_interval mpi_size = pic_info.topology_x * pic_info.topology_y * pic_info.topology_z rank = 0 ndata = (NBINS + 3) if INCLUDE_BFIELDS else NBINS tindex = tframe * interval fname_pre = run_dir + 'hydro/T.' + str(tindex) if species == 'h': species = 'H' fname_pre += '/spectrum-' + species + 'hydro.' + str(tindex) fname = fname_pre + '.' + str(rank) fdata = np.fromfile(fname, dtype=np.float32) dsz, = fdata.shape nzone = dsz // ndata for rank in range(1, mpi_size): fname = fname_pre + '.' + str(rank) fdata += np.fromfile(fname, dtype=np.float32) print("number of zones: %d" % nzone) flog_tot = np.zeros(NBINS) for i in range(nzone): if INCLUDE_BFIELDS: flog = fdata[i * ndata + 3:(i + 1) * ndata] else: flog = fdata[i * ndata:(i + 1) * ndata] flog_tot += flog emin_log = math.log10(EMIN) emax_log = math.log10(EMAX) elog = 10**(np.linspace(emin_log, emax_log, NBINS)) delog = np.gradient(elog) flog_tot /= delog fdir = '../data/spectra/' + run_name + '/' mkdir_p(fdir) fname = fdir + 'spectrum-' + species.lower() + '.' + str(tframe) flog_tot.tofile(fname)
def plot_spectrum(plot_config, show_plot=True): """Plot power spectrum Args: plot_config: plot configuration """ pic_run = plot_config["pic_run"] pic_run_dir = plot_config["pic_run_dir"] tframe = plot_config["tframe"] var_name = plot_config["var_name"] picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) tratio = pic_info.particle_interval / pic_info.fields_interval tindex = tframe * pic_info.fields_interval fname = pic_run_dir + "vkappa_spectrum/" + var_name + str(tindex) + ".kx" fx = np.fromfile(fname, dtype=np.float32) fname = pic_run_dir + "vkappa_spectrum/" + var_name + str(tindex) + ".ky" fy = np.fromfile(fname, dtype=np.float32) fname = pic_run_dir + "vkappa_spectrum/" + var_name + str(tindex) + ".kz" fz = np.fromfile(fname, dtype=np.float32) fx = fx.reshape((2, -1)) fy = fy.reshape((2, -1)) fz = fz.reshape((2, -1)) fig = plt.figure(figsize=[7, 5]) ax = fig.add_axes([0.17, 0.15, 0.75, 0.8]) ax.loglog(fx[0, :], fx[1, :], linewidth=2, label=r'$x$') ax.loglog(fy[0, :], fy[1, :], linewidth=2, label=r'$y$') ax.loglog(fz[0, :], fz[1, :], linewidth=2, label=r'$z$') ax.legend(loc=1, prop={'size': 16}, ncol=1, shadow=False, fancybox=False, frameon=False) ax.tick_params(labelsize=16) ax.set_xlabel(r'$k_x, k_y, k_z (d_e^{-1})$', fontsize=20) ax.set_ylabel(r'$f(k_x), f(k_y), f(k_z)$', fontsize=20) fdir = '../img/power_spectrum_vkappa/' + pic_run + '/' mkdir_p(fdir) fname = fdir + var_name + "_" + str(tindex).zfill(5) + ".pdf" fig.savefig(fname) if show_plot: plt.show() else: plt.close()
def plot_energy_spectrum(run_name, spect_info, species='e', show_plot=True): """Plot particle energy spectrum Args: run_name: PIC simulation run name species: 'e' for electrons, 'H' for ions spect_info: dictionary for spectra information """ picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json' pic_info = read_data_from_json(picinfo_fname) if species == 'h': species = 'H' # ntf = spect_info["tmax"] ntf = pic_info.ntf if species == 'e': vth = pic_info.vthe else: vth = pic_info.vthi gama = 1.0 / math.sqrt(1.0 - 3 * vth**2) eth = gama - 1.0 emin_log = math.log10(spect_info["emin"]) emax_log = math.log10(spect_info["emax"]) nbins = spect_info["nbins"] elog = 10**(np.linspace(emin_log, emax_log, nbins)) elog /= eth nptot = pic_info.nx * pic_info.ny * pic_info.nz * pic_info.nppc tframes = range(0, ntf - 1) nframes = len(tframes) flogs = np.zeros((nframes, nbins)) fig = plt.figure(figsize=[7, 5]) rect = [0.14, 0.16, 0.82, 0.8] ax = fig.add_axes(rect) for iframe, tframe in enumerate(tframes): print("Time frame: %d" % tframe) fdir = '../data/spectra/' + run_name + '/' fname = fdir + 'spectrum-' + species.lower() + '.' + str(tframe) flog = np.fromfile(fname) flog /= nptot color = plt.cm.jet(tframe/float(ntf), 1) flogs[iframe, :] = flog # ax.loglog(elog, flog, linewidth=2, color=color) # fmin = np.min(flogs[np.nonzero(flogs)]) fmin = 1E-9 flogs += fmin fdata = np.diff(np.log10(flogs[:, 400:600]), axis=0).T ng = 3 kernel = np.ones((ng,ng)) / float(ng*ng) fdata = signal.convolve2d(fdata, kernel, mode='same') ax.imshow(fdata, vmin=-1E-1, vmax=1E-1, cmap=plt.cm.seismic, origin='lower', interpolation='bicubic') # if species == 'e': # ax.set_xlim([1E0, 5E2]) # ax.set_ylim([1E-9, 1E2]) # else: # ax.set_xlim([1E0, 2E3]) # ax.set_ylim([1E-7, 1E4]) ax.tick_params(bottom=True, top=True, left=True, right=False) ax.tick_params(axis='x', which='minor', direction='in') ax.tick_params(axis='x', which='major', direction='in') ax.tick_params(axis='y', which='minor', direction='in') ax.tick_params(axis='y', which='major', direction='in') ax.set_xlabel(r'$\varepsilon/\varepsilon_\text{th}$', fontdict=FONT, fontsize=20) ax.set_ylabel(r'$f(\varepsilon)$', fontdict=FONT, fontsize=20) ax.tick_params(labelsize=16) ename = 'electron' if species == 'e' else 'ion' fpath = "../img/img_high_mime/spectra/" + ename + "/" mkdir_p(fpath) fname = fpath + "spect_time_" + run_name + "_" + species + ".pdf" fig.savefig(fname) if show_plot: plt.show() else: plt.close()
def plot_power_spectrum(plot_config, show_plot=True): """Plot power spectrum for one variable at one time frame Args: plot_config: plot configuration """ pic_run = plot_config["pic_run"] pic_run_dir = plot_config["pic_run_dir"] tframe = plot_config["tframe"] var_name = plot_config["var_name"] picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) tindex = tframe * pic_info.fields_interval fdir = '../data/power_spectrum/' + pic_run + '/power_spectrum_' + var_name + '/' labels = var_labels() var_label = labels[var_name] fname = fdir + var_name + str(tindex) + '.kx' kx, fkx = read_power_spectrum(fname) fname = fdir + var_name + str(tindex) + '.ky' ky, fky = read_power_spectrum(fname) fname = fdir + var_name + str(tindex) + '.kz' kz, fkz = read_power_spectrum(fname) fname = fdir + var_name + str(tindex) + '.para' kpara, fkpara = read_power_spectrum(fname) fname = fdir + var_name + str(tindex) + '.perp' kperp, fkperp = read_power_spectrum(fname) smime = math.sqrt(pic_info.mime) dx_de = pic_info.dx_di * smime dy_de = pic_info.dy_di * smime dz_de = pic_info.dz_di * smime k1, k2 = 0.02, 0.5 nkbins = 100 idx = (np.abs(kx - k1)).argmin() idy = (np.abs(ky - k1)).argmin() idz = (np.abs(kz - k1)).argmin() fnorm = max(fkx[idx], fky[idy], fkz[idz]) * 2 kpower = np.logspace(math.log10(k1), math.log10(k2), 100) fpower1 = kpower**(-5 / 3) fpower1 *= fnorm / fpower1[0] fpower2 = kpower**-1.5 fpower2 *= fpower1[0] / fpower2[0] fpower3 = kpower**-2 fpower3 *= fpower1[0] / fpower3[0] fig = plt.figure(figsize=[7, 5]) rect = [0.15, 0.16, 0.8, 0.8] ax = fig.add_axes(rect) ax.set_prop_cycle('color', COLORS) ax.loglog(kx, fkx, linewidth=2, label=r'$k_x$') ax.loglog(ky, fky, linewidth=2, label=r'$k_y$') ax.loglog(kz, fkz, linewidth=2, label=r'$k_z$') ax.loglog(kpower, fpower1, linewidth=1, color='k', linestyle='--', label=r'$\sim k^{-5/3}$') ax.loglog(kpower, fpower2, linewidth=1, color='k', linestyle='-.', label=r'$\sim k^{-3/2}$') ax.loglog(kpower, fpower3, linewidth=1, color='k', linestyle=':', label=r'$\sim k^{-2}$') ax.legend(loc=1, prop={'size': 16}, ncol=1, shadow=False, fancybox=False, frameon=False) ax.tick_params(bottom=True, top=True, left=True, right=True) ax.tick_params(axis='x', which='minor', direction='in', top=True) ax.tick_params(axis='x', which='major', direction='in') ax.tick_params(axis='y', which='minor', direction='in', left=True) ax.tick_params(axis='y', which='major', direction='in') text1 = r'$' + var_label + '$' ax.text(0.02, 0.05, text1, color='k', fontsize=20, bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0), horizontalalignment='left', verticalalignment='center', transform=ax.transAxes) ax.set_xlim([1E-2, 1E1]) # ax.set_ylim([1E-7, 2E-1]) ax.set_xlabel(r'$kd_e$', fontsize=20) ax.set_ylabel(r'$E_{' + var_label + '}(k)$', fontsize=20) ax.tick_params(labelsize=16) fdir = '../img/power_spectrum/' + pic_run + '/' + var_name + '/' mkdir_p(fdir) fname = fdir + var_name + '_xyz_' + str(tframe) + '.pdf' fig.savefig(fname) fig = plt.figure(figsize=[7, 5]) rect = [0.15, 0.16, 0.8, 0.8] ax = fig.add_axes(rect) ax.set_prop_cycle('color', COLORS) ax.loglog(kpara, fkpara, linewidth=2, label=r'$k_\parallel$') ax.loglog(kperp, fkperp, linewidth=2, label=r'$k_\perp$') ax.loglog(kpower, fpower1, linewidth=1, color='k', linestyle='--', label=r'$\sim k^{-5/3}$') ax.loglog(kpower, fpower2, linewidth=1, color='k', linestyle='-.', label=r'$\sim k^{-3/2}$') ax.loglog(kpower, fpower3, linewidth=1, color='k', linestyle=':', label=r'$\sim k^{-2}$') ax.legend(loc=1, prop={'size': 16}, ncol=1, shadow=False, fancybox=False, frameon=False) ax.tick_params(bottom=True, top=True, left=True, right=True) ax.tick_params(axis='x', which='minor', direction='in', top=True) ax.tick_params(axis='x', which='major', direction='in') ax.tick_params(axis='y', which='minor', direction='in', left=True) ax.tick_params(axis='y', which='major', direction='in') text1 = r'$' + var_label + '$' ax.text(0.02, 0.05, text1, color='k', fontsize=20, bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0), horizontalalignment='left', verticalalignment='center', transform=ax.transAxes) ax.set_xlim([1E-2, 1E1]) # ax.set_ylim([1E-7, 2E-1]) ax.set_xlabel(r'$kd_e$', fontsize=20) ax.set_ylabel(r'$E_{' + var_label + '}(k)$', fontsize=20) ax.tick_params(labelsize=16) fname = fdir + var_name + '_para_perp_' + str(tframe) + '.pdf' fig.savefig(fname) if show_plot: plt.show() else: plt.close('all')
type=int, help='Time frame for fields') parser.add_argument('--multi_frames', action="store_true", default=False, help='whether analyzing multiple frames') return parser.parse_args() if __name__ == "__main__": args = get_cmd_args() run_name = args.run_name run_dir = args.run_dir species = args.species tframe_fields = args.tframe_fields multi_frames = args.multi_frames picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json' pic_info = read_data_from_json(picinfo_fname) tratio = pic_info.particle_interval / pic_info.fields_interval # plot_ne_jdote(pic_info, run_dir, run_name, 30) cts = range(pic_info.ntf) def processInput(job_id): print job_id ct = job_id plot_ne_jdote(pic_info, run_dir, run_name, ct) # ncores = multiprocessing.cpu_count() ncores = 8 Parallel(n_jobs=ncores)(delayed(processInput)(ct) for ct in cts)
def rho_bands_2d(plot_config, show_plot=True): """Plot densities for energetic particles in the 2D simulation """ pic_run = plot_config["pic_run"] species = plot_config["species"] tframe = plot_config["tframe"] picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) pic_run_dir = pic_info.run_dir if species == 'e': vth = pic_info.vthe else: vth = pic_info.vthi nbins = 1000 ndata = nbins + 3 # including magnetic field tindex = pic_info.particle_interval * tframe gama = 1.0 / math.sqrt(1.0 - 3 * vth**2) eth = gama - 1.0 ebins = np.logspace(-6, 4, nbins) ebins /= eth xmin, xmax = 0, pic_info.lx_di zmin, zmax = -pic_info.lz_di * 0.5, pic_info.lz_di * 0.5 nx, nz = pic_info.nx, pic_info.nz smime = math.sqrt(pic_info.mime) dx_de = pic_info.dx_di * smime dy_de = pic_info.dy_di * smime dz_de = pic_info.dz_di * smime kwargs = { "current_time": tframe, "xl": 0, "xr": pic_info.lx_di, "zb": -pic_info.lz_di, "zt": pic_info.lz_di } # fname = pic_run_dir + "data/Ay.gda" # x, z, Ay = read_2d_fields(pic_info, fname, **kwargs) fname = pic_run_dir + "data/bx.gda" x, z, bx = read_2d_fields(pic_info, fname, **kwargs) fname = pic_run_dir + "data/by.gda" x, z, by = read_2d_fields(pic_info, fname, **kwargs) fname = pic_run_dir + "data/bz.gda" x, z, bz = read_2d_fields(pic_info, fname, **kwargs) ib = 1.0 / np.sqrt(bx**2 + by**2 + bz**2) bx = bx * ib by = by * ib bz = bz * ib kappax = (bx * np.gradient(bx, axis=1) / dx_de + bz * np.gradient(bx, axis=0) / dz_de) kappay = (bx * np.gradient(by, axis=1) / dx_de + bz * np.gradient(by, axis=0) / dz_de) kappaz = (bx * np.gradient(bz, axis=1) / dx_de + bz * np.gradient(bz, axis=0) / dz_de) fname = pic_run_dir + "data/vex.gda" x, z, vex = read_2d_fields(pic_info, fname, **kwargs) fname = pic_run_dir + "data/vey.gda" x, z, vey = read_2d_fields(pic_info, fname, **kwargs) fname = pic_run_dir + "data/vez.gda" x, z, vez = read_2d_fields(pic_info, fname, **kwargs) fname = pic_run_dir + "data/vix.gda" x, z, vix = read_2d_fields(pic_info, fname, **kwargs) fname = pic_run_dir + "data/viy.gda" x, z, viy = read_2d_fields(pic_info, fname, **kwargs) fname = pic_run_dir + "data/viz.gda" x, z, viz = read_2d_fields(pic_info, fname, **kwargs) fname = pic_run_dir + "data/ne.gda" x, z, ne = read_2d_fields(pic_info, fname, **kwargs) fname = pic_run_dir + "data/ni.gda" x, z, ni = read_2d_fields(pic_info, fname, **kwargs) inrho = 1.0 / (ne + ni * pic_info.mime) vx = (ne * vex + ni * vix * pic_info.mime) * inrho vy = (ne * vey + ni * viy * pic_info.mime) * inrho vz = (ne * vez + ni * viz * pic_info.mime) * inrho vdot_kappa = vx * kappax + vy * kappay + vz * kappaz nbands = 7 nreduce = 16 nxr = pic_info.nx // nreduce nzr = pic_info.nz // nreduce ntot = np.zeros((nzr, nxr)) nhigh = np.zeros((nzr, nxr)) fig = plt.figure(figsize=[14, 7]) rect0 = [0.055, 0.75, 0.4, 0.20] hgap, vgap = 0.09, 0.025 if species == 'e': nmins = [1E-1, 1E-2, 5E-3, 1E-3, 6E-5, 2E-5, 6E-6] nmaxs = [5E0, 1E0, 5E-1, 1E-1, 6E-3, 2E-3, 6E-4] else: nmins = [1E-1, 2E-2, 1E-2, 5E-3, 5E-4, 5E-5, 1.2E-5] nmaxs = [5E0, 2E0, 1E0, 5E-1, 5E-2, 5E-3, 1.2E-3] nmins = np.asarray(nmins) / 10 nmaxs = np.asarray(nmaxs) / 10 axs = [] rects = [] nrows = (nbands + 1) // 2 for iband in range(nbands + 1): row = iband % nrows col = iband // nrows if row == 0: rect = np.copy(rect0) rect[0] += (rect[2] + hgap) * col ax = fig.add_axes(rect) ax.set_ylim([-20, 20]) ax.tick_params(bottom=True, top=True, left=True, right=True) ax.tick_params(axis='x', which='minor', direction='in') ax.tick_params(axis='x', which='major', direction='in') ax.tick_params(axis='y', which='minor', direction='in') ax.tick_params(axis='y', which='major', direction='in') if row < nrows - 1: ax.tick_params(axis='x', labelbottom=False) else: ax.set_xlabel(r'$x/d_i$', fontsize=16) if col == 0: ax.set_ylabel(r'$z/d_i$', fontsize=16) ax.tick_params(labelsize=12) axs.append(ax) rects.append(np.copy(rect)) rect[1] -= rect[3] + vgap band_break = 4 for iband in range(nbands): print("Energy band: %d" % iband) if iband < band_break: ax = axs[iband] rect = rects[iband] else: ax = axs[iband + 1] rect = rects[iband + 1] fname = (pic_run_dir + "data-smooth2/n" + species + "_" + str(iband) + "_" + str(tindex) + ".gda") nrho = np.fromfile(fname, dtype=np.float32) nrho = nrho.reshape((nzr, nxr)) if iband >= 5: nhigh += nrho ntot += nrho nmin, nmax = nmins[iband], nmaxs[iband] p1 = ax.imshow(nrho + 1E-10, extent=[xmin, xmax, zmin, zmax], norm=LogNorm(vmin=nmin, vmax=nmax), cmap=plt.cm.inferno, aspect='auto', origin='lower', interpolation='bicubic') # ax.contour(x, z, Ay, colors='w', linewidths=0.5) if iband == 0: label1 = r'$n(\varepsilon < 10\varepsilon_\text{th})$' elif iband > 0 and iband < nbands - 1: label1 = (r'$n(' + str(2**(iband - 1) * 10) + r'\varepsilon_\text{th} < ' + r'\varepsilon < ' + str(2**iband * 10) + r'\varepsilon_\text{th})$') else: label1 = (r'$n(\varepsilon > ' + str(2**(nbands - 2) * 10) + r'\varepsilon_\text{th})$') ax.text(0.98, 0.87, label1, color='k', fontsize=16, bbox=dict(facecolor='w', alpha=0.75, edgecolor='none', boxstyle="round,pad=0.1"), horizontalalignment='right', verticalalignment='center', transform=ax.transAxes) twci = math.ceil((tframe * pic_info.dt_fields) / 0.1) * 0.1 text1 = r'$t\Omega_{ci}=' + ("{%0.0f}" % twci) + '$' if iband == 0: # ax.set_title(text1, fontsize=16) xpos = (rect[2] + hgap * 0.5) / rect[2] ax.text(xpos, 1.1, text1, color='k', fontsize=16, bbox=dict(facecolor='w', alpha=0.75, edgecolor='none', boxstyle="round,pad=0.1"), horizontalalignment='center', verticalalignment='center', transform=ax.transAxes) rect_cbar = np.copy(rect) rect_cbar[0] += rect[2] + 0.01 rect_cbar[2] = 0.007 cbar_ax = fig.add_axes(rect_cbar) cbar = fig.colorbar(p1, cax=cbar_ax, extend='both') cbar.ax.tick_params(labelsize=12) ax = axs[band_break] rect = rects[band_break] vmin, vmax = -1.0, 1.0 knorm = 100 p1 = ax.imshow(vdot_kappa * knorm, extent=[xmin, xmax, zmin, zmax], vmin=vmin, vmax=vmax, cmap=plt.cm.seismic, aspect='auto', origin='lower', interpolation='bicubic') # ax.contour(x, z, Ay, colors='k', linewidths=0.5) ax.tick_params(labelsize=12) label1 = r'$' + str(knorm) + r'\boldsymbol{v}\cdot\boldsymbol{\kappa}$' ax.text(0.98, 0.87, label1, color='w', fontsize=16, bbox=dict(facecolor='k', alpha=0.5, edgecolor='none', boxstyle="round,pad=0.1"), horizontalalignment='right', verticalalignment='center', transform=ax.transAxes) rect_cbar = np.copy(rect) rect_cbar[0] += rect[2] + 0.01 rect_cbar[2] = 0.007 cbar_ax = fig.add_axes(rect_cbar) cbar = fig.colorbar(p1, cax=cbar_ax, extend='both') cbar.set_ticks(np.linspace(-1, 1, num=5)) cbar.ax.tick_params(labelsize=12) fdir = '../img/open_bc/rho_bands_2d/' + pic_run + '/' mkdir_p(fdir) fname = (fdir + 'nrho_bands_' + species + '_' + str(tframe) + ".jpg") fig.savefig(fname, dpi=200) if show_plot: plt.show() else: plt.close()
def transfer_pic_to_mhd(run_dir, run_name, tframe): """Transfer the required fields Args: run_dir: simulation directory run_name: name of the simulation run tframe: time frame boundary_x: boundary condition along x-direction 0 for periodic; 1 for others boundary_z: boundary condition along z-direction """ print("Time frame: %d" % tframe) picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json' pic_info = read_data_from_json(picinfo_fname) lx_di = pic_info.lx_di lz_di = pic_info.lz_di kwargs = {"current_time": tframe, "xl": 0, "xr": lx_di, "zb": -0.5 * lz_di, "zt": 0.5 * lz_di} fname = run_dir + "data/bx.gda" x, z, bx = read_2d_fields(pic_info, fname, **kwargs) fname = run_dir + "data/by.gda" x, z, by = read_2d_fields(pic_info, fname, **kwargs) fname = run_dir + "data/bz.gda" x, z, bz = read_2d_fields(pic_info, fname, **kwargs) nx, = x.shape nz, = z.shape mhd_data = np.zeros((nz+4, nx+4, 8), dtype=np.float32) # We need to switch y and z directions absB = np.sqrt(bx**2 + by**2 + bz**2) mhd_data[2:nz+2, 2:nx+2, 4] = bx mhd_data[2:nz+2, 2:nx+2, 5] = bz mhd_data[2:nz+2, 2:nx+2, 6] = -by mhd_data[2:nz+2, 2:nx+2, 7] = absB del bx, by, bz, absB mime = pic_info.mime # Electron fname = run_dir + "data/ne.gda" x, z, ne = read_2d_fields(pic_info, fname, **kwargs) fname = run_dir + "data/vex.gda" x, z, vex = read_2d_fields(pic_info, fname, **kwargs) fname = run_dir + "data/vey.gda" x, z, vey = read_2d_fields(pic_info, fname, **kwargs) fname = run_dir + "data/vez.gda" x, z, vez = read_2d_fields(pic_info, fname, **kwargs) vx = ne * vex vy = ne * vey vz = ne * vez del vex, vey, vez # Ion fname = run_dir + "data/ni.gda" x, z, ni = read_2d_fields(pic_info, fname, **kwargs) fname = run_dir + "data/vix.gda" x, z, vix = read_2d_fields(pic_info, fname, **kwargs) fname = run_dir + "data/viy.gda" x, z, viy = read_2d_fields(pic_info, fname, **kwargs) fname = run_dir + "data/viz.gda" x, z, viz = read_2d_fields(pic_info, fname, **kwargs) imass = 1.0 / (ne + ni * mime) vx = (vx + ni * mime * vix) * imass vy = (vy + ni * mime * viy) * imass vz = (vz + ni * mime * viz) * imass del vix, viy, viz, ne, ni, imass absV = np.sqrt(vx**2 + vy**2 + vz**2) mhd_data[2:nz+2, 2:nx+2, 0] = vx mhd_data[2:nz+2, 2:nx+2, 1] = vz mhd_data[2:nz+2, 2:nx+2, 2] = -vy mhd_data[2:nz+2, 2:nx+2, 3] = absV del vx, vy, vz, absV # Assuming periodic boundary along x for fields and particles # Assuming conducting boundary along z for fields and reflective for particles mhd_data[:, 0:2, :] = mhd_data[:, nx-1:nx+1, :] mhd_data[:, nx+2:, :] = mhd_data[:, 3:5, :] mhd_data[0:2, :, :] = mhd_data[3:1:-1, :, :] mhd_data[nz+2:, :, :] = mhd_data[nz+1:nz-1:-1, :, :] fpath = run_dir + 'bin_data/' mkdir_p(fpath) fname = fpath + 'mhd_data_' + str(tframe).zfill(4) print(mhd_data.shape) print(np.isfortran(mhd_data)) mhd_data.tofile(fname)
def compare_spectrum(plot_config): """Compare 2D and 3D spectra Args: plot_config: plotting configuration """ species = plot_config["species"] bg = plot_config["bg"] root_dir = "/net/scratch3/xiaocanli/reconnection/Cori_runs/" pic_runs = ["2D-sigmae100-Lx125-bg0.0-100ppc-15gr"] pic_runs.append("3D-sigmae100-Lx125-bg0.0-100ppc-1024KNL") tframes = np.asarray([0, 20, 40, 52]) fig = plt.figure(figsize=[7, 5]) rect = [0.14, 0.14, 0.8, 0.8] ax = fig.add_axes(rect) # colors = np.copy(COLORS) # colors[5] = colors[6] colors = palettable.tableau.Tableau_10.mpl_colors for irun, pic_run in enumerate(pic_runs): pic_run_dir = root_dir + pic_run + "/" picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) if species == 'e': vth = pic_info.vthe else: vth = pic_info.vthi ebins = np.logspace(-4, 6, 1000) if species in ['i', 'ion', 'proton']: ebins *= pic_info.mime if irun == 0: fnorm = 1 lstyle = '--' else: fnorm = pic_info.ny lstyle = '-' tinterval = pic_info.eparticle_interval dtf = math.ceil(pic_info.dt_fields / 0.1) * 0.1 pdim = "2D" if "2D" in pic_run else "3D" for iframe, tframe in enumerate(tframes): tindex = tinterval * tframe fname = (pic_run_dir + "spectrum_combined/spectrum_" + species + "_" + str(tindex) + ".dat") spect = np.fromfile(fname, dtype=np.float32) ndata, = spect.shape spect[3:] /= np.gradient(ebins) * fnorm if iframe == len(tframes) - 1: eindex_20, ene = find_nearest(ebins, 20) spect[spect == 0] = np.nan if iframe > 0: ax.loglog(ebins, spect[3:], linewidth=1, linestyle=lstyle, color=colors[iframe - 1]) else: if irun == 1: ax.loglog(ebins, spect[3:], linewidth=1, linestyle='--', color='k') if species == 'e': fpower = 1E10 * ebins**-2.5 power_index = "{%0.1f}" % -2.5 pname = r'$\sim \varepsilon^{' + power_index + '}$' ax.loglog(ebins[548:648], fpower[548:648], linewidth=1, color='k') else: fpower = 2E12 * ebins**-3.5 power_index = "{%0.1f}" % -3.5 pname = r'$\sim \varepsilon^{' + power_index + '}$' ax.loglog(ebins[368:468], fpower[368:468], linewidth=1, color='k') ax.text(0.95, 0.7, pname, color='k', fontsize=20, bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0), horizontalalignment='right', verticalalignment='center', transform=ax.transAxes) ax.plot([0, 10], [0, 0], linestyle="--", color='k', linewidth=1, label='2D') ax.plot([0, 10], [0, 0], linestyle="-", color='k', linewidth=1, label='3D') ax.legend(loc=3, prop={'size': 20}, ncol=1, shadow=False, fancybox=False, frameon=False) ax.tick_params(bottom=True, top=True, left=True, right=True) ax.tick_params(axis='x', which='minor', direction='in', top=True) ax.tick_params(axis='x', which='major', direction='in') ax.tick_params(axis='y', which='minor', direction='in') ax.tick_params(axis='y', which='major', direction='in') if species in ['e', 'electron']: ax.set_xlim([1E-1, 2E3]) else: ax.set_xlim([1E-1, 2E3]) ax.set_ylim([1E-5, 1E9]) text1 = r'$(\gamma - 1)m_' + species + r'c^2$' ax.set_xlabel(text1, fontsize=20) ax.set_ylabel(r'$f(\gamma - 1)$', fontsize=20) ax.tick_params(labelsize=16) if species == 'e': xpos = [0.4, 0.7, 0.87, 0.94] else: xpos = [0.4, 0.67, 0.86, 0.93] text1 = r'$t\Omega_{ci}=0$' ax.text(xpos[0], 0.10, text1, color='k', fontsize=16, bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0), horizontalalignment='center', verticalalignment='bottom', transform=ax.transAxes) text2 = r'$' + str(int(tframes[1] * 10)) + '$' ax.text(xpos[1], 0.10, text2, color=colors[0], fontsize=16, bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0), horizontalalignment='center', verticalalignment='bottom', transform=ax.transAxes) text3 = r'$' + str(int(tframes[2] * 10)) + '$' ax.text(xpos[2], 0.10, text3, color=colors[1], fontsize=16, bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0), horizontalalignment='center', verticalalignment='bottom', transform=ax.transAxes) text4 = r'$' + str(int(tframes[3] * 10)) + '$' ax.text(xpos[3], 0.10, text4, color=colors[2], fontsize=16, bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0), horizontalalignment='left', verticalalignment='bottom', transform=ax.transAxes) fdir = '../img/cori_sigma/spectrum/' mkdir_p(fdir) fname = fdir + species + 'spect_32.pdf' fig.savefig(fname) plt.show()
def plot_temp_dist(plot_config, show_plot=True): """ Plot temperature distribution """ pic_run = plot_config["pic_run"] pic_run_dir = plot_config["pic_run_dir"] species = plot_config["species"] tframe = plot_config["tframe"] picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) tinit = pic_info.vthe**2 fdir = '../data/temperature_anisotropy/' + pic_run + '/' fname = fdir + 'ftpara_' + species + '_' + str(tframe) + '.gda' fdata = np.fromfile(fname, dtype=np.float32) nbins_temp = int(fdata[0]) temp_bins_edge = fdata[1:nbins_temp + 2] temp_bins_mid = 0.5 * (temp_bins_edge[1:] + temp_bins_edge[:-1]) temp_bins_mid /= tinit dtemp = np.diff(temp_bins_edge) ftpara = fdata[nbins_temp + 2:] / dtemp fname = fdir + 'ftperp_' + species + '_' + str(tframe) + '.gda' fdata = np.fromfile(fname, dtype=np.float32) ftperp = fdata[nbins_temp + 2:] / dtemp fig = plt.figure(figsize=[3.25, 2.5]) rect = [0.16, 0.16, 0.79, 0.8] ax = fig.add_axes(rect) ax.set_prop_cycle('color', COLORS) ax.tick_params(bottom=True, top=True, left=True, right=True) ax.tick_params(axis='x', which='minor', direction='in', bottom=True, top=True) ax.tick_params(axis='x', which='major', direction='in', bottom=True, top=True) ax.tick_params(axis='y', which='minor', direction='in') ax.tick_params(axis='y', which='major', direction='in') ax.loglog(temp_bins_mid, ftpara, linewidth=1, label=r'$T_\parallel$') ax.loglog(temp_bins_mid, ftperp, linewidth=1, label=r'$T_\perp$') ax.legend(loc=1, prop={'size': 10}, ncol=1, shadow=False, fancybox=False, frameon=False) ax.set_xlim([1E-1, 1E2]) ax.tick_params(labelsize=8) ax.set_xlabel(r'$T/T_0$', fontsize=10) ax.set_ylabel(r'$f(T)$', fontsize=10) fdir = '../img/temp_dist/' + pic_run + '/' mkdir_p(fdir) fname = fdir + 'temp_dist_' + species + '_' + str(tframe) + '.pdf' fig.savefig(fname) if show_plot: plt.show() else: plt.close()
help='particle species') parser.add_argument('--run_dir', action="store", default=default_run_dir, help='run directory') parser.add_argument('--run_name', action="store", default=default_run_name, help='run name') parser.add_argument('--tframe_fields', action="store", default='30', type=int, help='Time frame for fields') parser.add_argument('--multi_frames', action="store_true", default=False, help='whether analyzing multiple frames') return parser.parse_args() if __name__ == "__main__": args = get_cmd_args() run_name = args.run_name run_dir = args.run_dir species = args.species tframe_fields = args.tframe_fields multi_frames = args.multi_frames picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json' pic_info = read_data_from_json(picinfo_fname) save_mhd_config(run_name) # transfer_pic_to_mhd(run_dir, run_name, 0) ncores = multiprocessing.cpu_count() ncores = 10 cts = range(pic_info.ntf) def processInput(job_id): time_frame = job_id transfer_pic_to_mhd(run_dir, run_name, time_frame) Parallel(n_jobs=ncores)(delayed(processInput)(ct) for ct in cts)
def save_mhd_config(run_name): """Save MHD configuration Need to switch y and z directions Args: run_name: simulation run name """ picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json' pic_info = read_data_from_json(picinfo_fname) double_data = np.zeros(13) int_data = np.zeros(14, dtype=np.int32) smime = math.sqrt(pic_info.mime) lx = pic_info.lx_di * smime ly = pic_info.lz_di * smime lz = 0.0 nx = pic_info.nx ny = pic_info.nz nz = pic_info.ny if nx > 1: double_data[0] = lx / nx else: double_data[0] = 0.0 if ny > 1: double_data[1] = ly / ny else: double_data[1] = 0.0 if nz > 1: double_data[2] = lz / nz else: double_data[2] = 0.0 double_data[3] = 0.0 double_data[4] = -0.5 * ly double_data[5] = 0.0 double_data[6] = lx double_data[7] = 0.5 * ly double_data[8] = 0.0 double_data[9] = lx double_data[10] = ly double_data[11] = lz double_data[12] = pic_info.dtwpe * pic_info.fields_interval int_data[0] = pic_info.nx int_data[1] = pic_info.nz int_data[2] = pic_info.ny int_data[3] = pic_info.nx / pic_info.topology_x int_data[4] = pic_info.nz / pic_info.topology_z int_data[5] = pic_info.ny / pic_info.topology_y int_data[6] = pic_info.topology_x int_data[7] = pic_info.topology_z int_data[8] = pic_info.topology_y int_data[9] = 9 int_data[10] = 0 # Periodic boundary condition as default int_data[11] = 0 int_data[12] = 0 int_data[13] = 0 fpath = run_dir + 'bin_data/' mkdir_p(fpath) fname = fpath + 'mhd_config.dat' double_data.tofile(fname) f = open(fname, 'a') int_data.tofile(f) f.close()
def contour_tratio_beta(plot_config, show_plot=True): """ Plot contour of temperature ratio and parallel plasma beta """ pic_run = plot_config["pic_run"] pic_run_dir = plot_config["pic_run_dir"] species = plot_config["species"] tframe = plot_config["tframe"] picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) fdir = '../data/temperature_anisotropy/' + pic_run + '/' fname = fdir + 'ftratio_bpara_' + species + '_' + str(tframe) + '.gda' fdata = np.fromfile(fname, dtype=np.float32) nbins_tratio = int(fdata[0]) nbins_beta = int(fdata[1]) tratio_bins_edge = fdata[2:nbins_tratio+3] beta_bins_edge = fdata[nbins_tratio+3:nbins_beta+nbins_tratio+4] tratio_bins_mid = 0.5 * (tratio_bins_edge[1:] + tratio_bins_edge[:-1]) dtratio = np.diff(tratio_bins_edge) beta_bins_mid = 0.5 * (beta_bins_edge[1:] + beta_bins_edge[:-1]) dbeta = np.diff(beta_bins_edge) ftratio_beta = fdata[nbins_beta+nbins_tratio+4:] ftratio_beta = ftratio_beta.reshape([nbins_beta, nbins_tratio]).T delta = np.dot(dtratio[:, None], dbeta[None, :]) ftratio_beta /= delta # ftratio_beta[ftratio_beta <= 0] = np.nan tratio_min = tratio_bins_mid[0] tratio_max = tratio_bins_mid[-1] beta_min = beta_bins_mid[0] beta_max = beta_bins_mid[-1] # According to Bale et al. 2009, # T_\perp / T_\parallel = 1 + a/(\beta_\parallel - \beta_0)^b. # For mirror instability threshold, (a, b, \beta_0) = (0.77, 0.76, -0.016) # For oblique firehose instability threshold, (a, b, \beta_0) = (-1.4, 1.0, -0.11) tratio_firhose = 1 - 1.4 / (beta_bins_mid + 0.11) tratio_mirror = 1 + 0.77 / (beta_bins_mid + 0.016)**0.76 tratio_firhose[tratio_firhose < 0] = np.nan fig = plt.figure(figsize=[3.25, 2.5]) rect = [0.18, 0.16, 0.67, 0.8] ax = fig.add_axes(rect) ax.tick_params(bottom=True, top=True, left=True, right=True) ax.tick_params(axis='x', which='minor', direction='in', bottom=True, top=True) ax.tick_params(axis='x', which='major', direction='in', bottom=True, top=True) ax.tick_params(axis='y', which='minor', direction='in') ax.tick_params(axis='y', which='major', direction='in') im = ax.pcolormesh(beta_bins_mid, tratio_bins_mid, ftratio_beta, cmap=plt.cm.jet, norm=LogNorm(vmin=1E0, vmax=1E12)) ax.set_xscale('log') ax.set_yscale('log') ax.plot(beta_bins_mid, tratio_firhose, color='k', linestyle='--') ax.plot(beta_bins_mid, tratio_mirror, color='k', linestyle='--') ax.set_xlim([1E-3, 1E3]) ax.set_ylim([1E-2, 1E2]) ax.tick_params(labelsize=8) ax.set_xlabel(r'$\beta_\parallel$', fontsize=10) ax.set_ylabel(r'$T_\perp/T_\parallel$', fontsize=10) rect_cbar = np.copy(rect) rect_cbar[0] += rect[2] + 0.02 rect_cbar[2] = 0.02 cbar_ax = fig.add_axes(rect_cbar) cbar = fig.colorbar(im, cax=cbar_ax) cbar.ax.tick_params(labelsize=8) fdir = '../img/brazil_plot/' + pic_run + '/' mkdir_p(fdir) fname = fdir + 'tratio_bpara_' + species + '_' + str(tframe) + '.jpg' fig.savefig(fname, dpi=300) if show_plot: plt.show() else: plt.close()
def energy_conversion(plot_config): """Plot energy conversion Args: plot_config: plotting configuration """ pic_run = plot_config["pic_run"] pic_run_dir = plot_config["pic_run_dir"] fig = plt.figure(figsize=[3.25, 2.5]) w1, h1 = 0.78, 0.78 xs, ys = 0.96 - w1, 0.96 - h1 ax = fig.add_axes([xs, ys, w1, h1]) picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) tenergy = pic_info.tenergy enorm = pic_info.ene_magnetic[0] ene_bx = pic_info.ene_bx ene_by = pic_info.ene_by ene_bz = pic_info.ene_bz ene_magnetic = pic_info.ene_magnetic ene_electric = pic_info.ene_electric kene_e = pic_info.kene_e kene_i = pic_info.kene_i etot = ene_magnetic + ene_electric + kene_e + kene_i print("Energy conservation: %e" % ((etot[-1] - etot[0]) / etot[0])) print("Energy conversion: %e" % ((ene_magnetic[-1] - ene_magnetic[0]) / ene_magnetic[0])) ene_bx /= enorm ene_by /= enorm ene_bz /= enorm ene_magnetic /= enorm kene_e /= enorm kene_i /= enorm ax.plot(tenergy, ene_magnetic, linewidth=1, linestyle='-', label='magnetic') ax.plot(tenergy, kene_e, linewidth=1, linestyle='-', label='electron') ax.plot(tenergy, kene_i, linewidth=1, linestyle='-', label='ion') ax.legend(loc=6, prop={'size': 12}, ncol=1, shadow=False, fancybox=False, frameon=False) ax.tick_params(bottom=True, top=False, left=True, right=True) ax.set_xlim([0, 400]) ax.set_ylim([0, 1.05]) ax.set_xlabel(r'$t\Omega_{ci}$', fontsize=12) ax.set_ylabel(r'$\text{Energy}/\varepsilon_{B0}$', fontsize=12) ax.tick_params(labelsize=10) fdir = '../img/' + pic_run + '/' mkdir_p(fdir) fname = fdir + 'econv.pdf' fig.savefig(fname) plt.show()
def particle_energization(plot_config, show_plot=True): """Particle-based energization Args: plot_config: plotting configuration """ species = plot_config["species"] tframe = plot_config["tframe"] pic_run = plot_config["pic_run"] pic_run_dir = plot_config["pic_run_dir"] ylims, data_indices = get_plot_setup(plot_config["plot_type"], species) tstarts = [6, 10, 20, 30] tends = [10, 20, 30, 40] nplots = len(tstarts) fnorm = 1E-3 for iplot in range(nplots): tstart = tstarts[iplot] tend = tends[iplot] ylim = np.asarray(ylims[iplot]) / fnorm fig1 = plt.figure(figsize=[4.8, 2.0]) box1 = [0.14, 0.2, 0.8, 0.75] axs1 = [] nframes = tend - tstart fpath = "../data/particle_interp/" + pic_run + "/" picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) dtp = math.ceil(pic_info.dt_particles / 0.1) * 0.1 ax = fig1.add_axes(box1) for tframe in range(tstart, tend + 1): tstep = tframe * pic_info.particle_interval tframe_fluid = tstep // pic_info.fields_interval fname = fpath + "particle_energization_" + species + "_" + str( tstep) + ".gda" fdata = np.fromfile(fname, dtype=np.float32) nbins = int(fdata[0]) nbinx = int(fdata[1]) nvar = int(fdata[2]) ebins = fdata[3:nbins + 3] fbins = np.sum(fdata[nbins + 3:].reshape((nvar, nbinx, nbins)), axis=1) if species == 'i': ebins *= pic_info.mime # ebins are actually gamma fbins[1:, :] = div0(fbins[1:, :], fbins[0, :]) # normalized with thermal energy if species == 'e': vth = pic_info.vthe else: vth = pic_info.vthi gama = 1.0 / math.sqrt(1.0 - 3 * vth**2) eth = gama - 1.0 if species == 'i': eth *= pic_info.mime ebins /= eth color = plt.cm.Spectral_r((tframe - tstart) / float(nframes), 1) fdata = np.zeros(nbins) for idata in data_indices: fdata += fbins[idata, :] ax.semilogx(ebins, fdata / fnorm, linewidth=1, color=color) if species == 'e': if "2D" in pic_run: ax.set_xlim([1E0, 200]) else: ax.set_xlim([1E0, 200]) else: if "2D" in pic_run: ax.set_xlim([1E0, 500]) else: ax.set_xlim([1E0, 1000]) ax.set_ylim(ylim) box1[0] += box1[2] + 0.02 ax.set_ylabel(r'$\left<\nu^\text{I}_\text{COM}\right>/10^{-3}$', fontsize=10) ax.set_xlabel(r'$\varepsilon/\varepsilon_\text{th}$', fontsize=10) ax.tick_params(labelsize=8) ax.plot(ax.get_xlim(), [0, 0], linestyle='--', color='k') ax.tick_params(bottom=True, top=False, left=True, right=False) ax.tick_params(axis='x', which='minor', direction='in') ax.tick_params(axis='x', which='major', direction='in') ax.tick_params(axis='y', which='minor', direction='in') ax.tick_params(axis='y', which='major', direction='in') box1[0] -= box1[2] + 0.02 rect_cbar = np.copy(box1) rect_cbar[0] += box1[2] + 0.01 rect_cbar[2] = 0.015 cax = fig1.add_axes(rect_cbar) cax.tick_params(axis='y', which='major', direction='in') sm = plt.cm.ScalarMappable(cmap=plt.cm.Spectral_r, norm=plt.Normalize(vmin=tstart * dtp, vmax=tend * dtp)) # fake up the array of the scalar mappable. Urgh... sm._A = [] cbar = fig1.colorbar(sm, cax=cax) cbar.set_label(r'$t\Omega_{ci}$', fontsize=12) cbar.set_ticks((np.linspace(tstart, tend, tend - tstart + 1) * dtp)) cbar.ax.tick_params(labelsize=10) # bg_str = str(int(bg * 10)).zfill(2) # fdir = '../img/cori_3d/particle_energization/bg' + bg_str + '/' # mkdir_p(fdir) # fname = (fdir + 'particle_' + plot_config["plot_type"] + '_' + # species + '_' + str(iplot) + '.pdf') # fig1.savefig(fname) if show_plot: plt.show() else: plt.close('all')
def fluid_energization(plot_config, show_plot=True): """Plot fluid energization Args: plot_config: plotting configuration """ species = plot_config["species"] pic_run = plot_config["pic_run"] pic_run_dir = plot_config["pic_run_dir"] if species == 'e': ylim = [-0.2, 1.0] else: ylim = [-0.6, 1.7] fig1 = plt.figure(figsize=[7, 2.5]) box1 = [0.09, 0.18, 0.85, 0.68] axs1 = [] fig2 = plt.figure(figsize=[7, 2.5]) box2 = [0.09, 0.18, 0.85, 0.68] axs2 = [] fig3 = plt.figure(figsize=[7, 2.5]) box3 = [0.09, 0.18, 0.85, 0.68] axs3 = [] picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) if "3D" in pic_run: enorm = pic_info.ny else: enorm = 1.0 tfields = pic_info.tfields tenergy = pic_info.tenergy fname = "../data/fluid_energization/" + pic_run + "/" fname += "emf_ptensor_" + species + '.gda' fluid_ene = np.fromfile(fname, dtype=np.float32) nvar = int(fluid_ene[0]) nframes = int(fluid_ene[1]) fluid_ene[2:] /= enorm curv_drift_dote = fluid_ene[2:nframes + 2] bulk_curv_dote = fluid_ene[nframes + 2:2 * nframes + 2] grad_drift_dote = fluid_ene[2 * nframes + 2:3 * nframes + 2] magnetization_dote = fluid_ene[3 * nframes + 2:4 * nframes + 2] comp_ene = fluid_ene[4 * nframes + 2:5 * nframes + 2] shear_ene = fluid_ene[5 * nframes + 2:6 * nframes + 2] ptensor_ene = fluid_ene[6 * nframes + 2:7 * nframes + 2] pgyro_ene = fluid_ene[7 * nframes + 2:8 * nframes + 2] fname = "../data/fluid_energization/" + pic_run + "/" fname += "para_perp_acc_" + species + '.gda' fluid_ene = np.fromfile(fname, dtype=np.float32) nvar = int(fluid_ene[0]) nframes = int(fluid_ene[1]) fluid_ene[2:] /= enorm acc_drift_dote_t = fluid_ene[2:nframes + 2] acc_drift_dote_s = fluid_ene[nframes + 2:2 * nframes + 2] acc_drift_dote = acc_drift_dote_t + acc_drift_dote_s epara_ene = fluid_ene[4 * nframes + 2:5 * nframes + 2] eperp_ene = fluid_ene[5 * nframes + 2:6 * nframes + 2] acc_drift_dote[-1] = acc_drift_dote[-2] jperp_dote = curv_drift_dote + grad_drift_dote + magnetization_dote jagy_dote = ptensor_ene - jperp_dote if species == 'e': dkene = pic_info.dkene_e else: dkene = pic_info.dkene_i dkene /= enorm ax = fig1.add_axes(box1) axs1.append(ax) COLORS = palettable.tableau.Tableau_10.mpl_colors ax.set_prop_cycle('color', COLORS) label2 = (r'$\boldsymbol{j}_{' + species + '\perp}' + r'\cdot\boldsymbol{E}_\perp$') ax.plot(tfields, eperp_ene, linewidth=1, label=label2) label1 = (r'$\boldsymbol{j}_{' + species + '\parallel}' + r'\cdot\boldsymbol{E}_\parallel$') ax.plot(tfields, epara_ene, linewidth=1, label=label1) label6 = r'$dK_' + species + '/dt$' ax.plot(tenergy, dkene, linewidth=1, label=label6) label3 = r'$(\nabla\cdot\tensorsym{P}_' + species + r')\cdot\boldsymbol{v}_E$' ax.plot(tfields, ptensor_ene, linewidth=1, label=label3) ax.plot([0, tenergy.max()], [0, 0], color='k', linestyle='--') ax.set_xlim([0, np.max(tfields)]) # ax.set_ylim(ylim) ax.tick_params(labelsize=10) ax.set_ylabel('Energization', fontsize=12) pdim = "2D" if "2D" in pic_run else "3D" ax.text(0.02, 0.9, pdim, color='k', fontsize=12, bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0), horizontalalignment='left', verticalalignment='center', transform=ax.transAxes) ax.set_xlabel(r'$t\Omega_{ci}$', fontsize=12) ax = fig2.add_axes(box1) axs2.append(ax) # COLORS = palettable.colorbrewer.qualitative.Set1_9.mpl_colors ax.set_prop_cycle('color', COLORS) label2 = (r'$\boldsymbol{j}_{' + species + '\perp}' + r'\cdot\boldsymbol{E}_\perp$') ax.plot(tfields, eperp_ene, linewidth=1, label=label2) ax.plot(tfields, curv_drift_dote, linewidth=1, label='Curvature') # ax.plot(tfields, bulk_curv_dote, linewidth=1, label='Bulk Curvature') ax.plot(tfields, grad_drift_dote, linewidth=1, label='Gradient') ax.plot(tfields, magnetization_dote, linewidth=1, label='Magnetization') # ax.plot(tfields, acc_drift_dote, linewidth=1, label='Polarization') jdote_sum = (curv_drift_dote + grad_drift_dote + magnetization_dote + jagy_dote + acc_drift_dote) # ax.plot(tfields, jdote_sum, linewidth=1) ax.plot([0, tenergy.max()], [0, 0], color='k', linestyle='--') ax.set_xlim([0, np.max(tfields)]) # ax.set_ylim(ylim) ax.tick_params(labelsize=10) ax.set_ylabel('Energization', fontsize=12) pdim = "2D" if "2D" in pic_run else "3D" ax.text(0.02, 0.9, pdim, color='k', fontsize=12, bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0), horizontalalignment='left', verticalalignment='center', transform=ax.transAxes) ax.set_xlabel(r'$t\Omega_{ci}$', fontsize=12) ax = fig3.add_axes(box1) axs3.append(ax) # COLORS = palettable.colorbrewer.qualitative.Set1_9.mpl_colors ax.set_prop_cycle('color', COLORS) label2 = (r'$\boldsymbol{j}_{' + species + '\perp}' + r'\cdot\boldsymbol{E}_\perp' + '$') ax.plot(tfields, eperp_ene, linewidth=1, label=label2) ax.plot(tfields, comp_ene, linewidth=1, label='Compression') ax.plot(tfields, shear_ene, linewidth=1, label='Shear') # label2 = (r'$\boldsymbol{j}_{' + species + '\perp}' + # r'\cdot\boldsymbol{E}_\perp -' + 'n_' + species + # 'm_' + species + r'(d\boldsymbol{u}_' + species + # r'/dt)\cdot\boldsymbol{v}_E$') # ax.plot(tfields, eperp_ene - acc_drift_dote, linewidth=1, label=label2) label4 = (r'$\boldsymbol{j}_{' + species + r'-\text{agy}}' + r'\cdot\boldsymbol{E}_\perp$') ax.plot(tfields, jagy_dote, linewidth=1, label=label4) # jdote_sum = comp_ene + shear_ene + jagy_dote # ax.plot(tfields, jdote_sum, linewidth=1) ax.plot([0, tenergy.max()], [0, 0], color='k', linestyle='--') ax.set_xlim([0, np.max(tfields)]) # ax.set_ylim(ylim) ax.tick_params(labelsize=10) ax.set_ylabel('Energization', fontsize=12) pdim = "2D" if "2D" in pic_run else "3D" ax.text(0.02, 0.9, pdim, color='k', fontsize=12, bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0), horizontalalignment='left', verticalalignment='center', transform=ax.transAxes) ax.set_xlabel(r'$t\Omega_{ci}$', fontsize=12) box1[0] += box1[2] + 0.07 axs1[0].legend(loc='upper left', prop={'size': 12}, ncol=4, bbox_to_anchor=(0, 1.22), shadow=False, fancybox=False, frameon=False) axs2[0].legend(loc='upper left', prop={'size': 12}, ncol=4, bbox_to_anchor=(0, 1.22), shadow=False, fancybox=False, frameon=False) axs3[0].legend(loc='upper left', prop={'size': 12}, ncol=4, bbox_to_anchor=(0, 1.22), shadow=False, fancybox=False, frameon=False) fdir = '../img/cori_3d/fluid_energization/' mkdir_p(fdir) fname = fdir + 'fluid_ene_' + species + '.pdf' # fig1.savefig(fname) fdir = '../img/cori_3d/fluid_energization/' mkdir_p(fdir) fname = fdir + 'fluid_drift_' + species + '.pdf' # fig2.savefig(fname) fdir = '../img/cori_3d/fluid_energization/' mkdir_p(fdir) fname = fdir + 'fluid_comp_shear_' + species + '.pdf' # fig3.savefig(fname) if show_plot: plt.show() else: plt.close('all')
def energy_conversion(plot_config): """Plot energy conversion Args: plot_config: plotting configuration """ pic_run = plot_config["pic_run"] root_dir = "/net/scratch3/xiaocanli/reconnection/Cori_runs/" pic_run_dir = root_dir + pic_run + '/' picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) fig = plt.figure(figsize=[3.25, 2.5]) w1, h1 = 0.78, 0.78 xs, ys = 0.96 - w1, 0.96 - h1 ax = fig.add_axes([xs, ys, w1, h1]) COLORS = palettable.tableau.Tableau_10.mpl_colors ax.set_prop_cycle('color', COLORS) tenergy = pic_info.tenergy enorm = pic_info.ene_magnetic[0] ene_bx = pic_info.ene_bx ene_by = pic_info.ene_by ene_bz = pic_info.ene_bz ene_magnetic = pic_info.ene_magnetic ene_electric = pic_info.ene_electric kene_e = pic_info.kene_e kene_i = pic_info.kene_i etot = ene_magnetic + ene_electric + kene_e + kene_i dene_mag = ene_magnetic[-1] - ene_magnetic[0] dene_ele = ene_electric[-1] - ene_electric[0] print("Energy conservation: %e" % ((etot[-1] - etot[0]) / etot[0])) print("Energy conversion: %e" % (dene_mag / ene_magnetic[0])) print("Electron gain: %e" % ((kene_e[-1] - kene_e[0]) / abs(dene_mag))) print("Ion gain: %e" % ((kene_i[-1] - kene_i[0]) / abs(dene_mag))) print("Electric: %e" % (dene_ele / abs(dene_mag))) ene_bx /= enorm ene_by /= enorm ene_bz /= enorm ene_magnetic /= enorm kene_e /= enorm kene_i /= enorm ax.plot(tenergy, ene_magnetic, linewidth=1, linestyle='-') ax.plot(tenergy, kene_e, linewidth=1, linestyle='-') ax.plot(tenergy, kene_i, linewidth=1, linestyle='-') ax.text(0.03, 0.6, "magnetic", color=COLORS[0], fontsize=12, bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0), horizontalalignment='left', verticalalignment='center', transform=ax.transAxes) ax.text(0.03, 0.5, "electron", color=COLORS[1], fontsize=12, bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0), horizontalalignment='left', verticalalignment='center', transform=ax.transAxes) ax.text(0.03, 0.4, "ion", color=COLORS[2], fontsize=12, bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0), horizontalalignment='left', verticalalignment='center', transform=ax.transAxes) ax.tick_params(bottom=True, top=True, left=True, right=True) ax.tick_params(axis='x', which='minor', direction='in', top=False) ax.tick_params(axis='x', which='major', direction='in') ax.tick_params(axis='y', which='minor', direction='in', left=False) ax.tick_params(axis='y', which='major', direction='in') ax.set_xlim([0, 260]) ax.set_ylim([0, 1.05]) ax.set_xlabel(r'$t\Omega_{ci}$', fontsize=12) ax.set_ylabel(r'$\text{Energy}/\varepsilon_{B0}$', fontsize=12) ax.tick_params(labelsize=10) fdir = '../img/cori_3d/' + pic_run + '/' mkdir_p(fdir) fname = fdir + 'econv.pdf' fig.savefig(fname) plt.show()
def energy_spectrum_multi(bg, spect_info, species='e'): """Plot energy spectra for runs with different guide field """ if species == 'h': species = 'H' bg_str = str(int(bg * 10)).zfill(2) mimes = np.asarray([25, 100, 400]) tmaxs = np.asarray([114, 114, 102]) fig = plt.figure(figsize=[7, 5]) ax = fig.add_axes([0.15, 0.15, 0.8, 0.8]) COLORS = palettable.tableau.Tableau_10.mpl_colors ax.set_prop_cycle('color', COLORS) for mime, tmax in zip(mimes, tmaxs): run_name = "mime" + str(mime) + "_beta002_bg" + bg_str picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json' pic_info = read_data_from_json(picinfo_fname) if species == 'e': vth = pic_info.vthe else: vth = pic_info.vthi gama = 1.0 / math.sqrt(1.0 - 3 * vth**2) eth = gama - 1.0 fdir = '../data/spectra/' + run_name + '/' fname = fdir + 'spectrum-' + species.lower() + '.' + str(tmax) flog = np.fromfile(fname) emin_log = math.log10(spect_info["emin"]) emax_log = math.log10(spect_info["emax"]) elog = 10**(np.linspace(emin_log, emax_log, spect_info["nbins"])) flog *= np.gradient(elog) elog /= eth flog /= np.gradient(elog) nptot = pic_info.nx * pic_info.ny * pic_info.nz * pic_info.nppc flog /= nptot ltext = r"$m_i/m_e=" + str(mime) + "$" ax.loglog(elog, flog, linewidth=3, label=ltext) ax.legend(loc=3, prop={'size': 16}, ncol=1, shadow=False, fancybox=False, frameon=False) if species == 'e': ax.set_xlim([3E-1, 5E2]) else: ax.set_xlim([3E-1, 1E3]) ax.set_ylim([1E-11, 1E0]) ax.set_yticks(np.logspace(-10, 0, num=6)) ax.set_xlabel(r'$\varepsilon/\varepsilon_\text{th}$', fontdict=FONT, fontsize=20) ax.set_ylabel(r'$f(\varepsilon)$', fontdict=FONT, fontsize=20) ax.tick_params(labelsize=16) fpath = "../img/img_high_mime/spectra/" mkdir_p(fpath) fname = fpath + "spect_bg" + bg_str + "_" + species + ".pdf" fig.savefig(fname) plt.show()
def plot_spectrum(plot_config): """Plot spectrum for all time frames for a single run Args: plot_config: plotting configuration """ species = plot_config["species"] tstart = plot_config["tstart"] tend = plot_config["tend"] pic_run = plot_config["pic_run"] root_dir = "/net/scratch3/xiaocanli/reconnection/Cori_runs/" pic_run_dir = root_dir + pic_run + "/" species = plot_config["species"] picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) if species == 'e': vth = pic_info.vthe sname = 'e' else: vth = pic_info.vthi sname = 'i' ebins = np.logspace(-6, 4, 1000) gama = 1.0 / math.sqrt(1.0 - 3 * vth**2) eth = gama - 1.0 emin, emax = 1E-6, 1E4 nband = 1000 dloge = (math.log10(emax) - math.log10(emin)) / (nband - 1) emin0 = 10**(math.log10(emin) - dloge) ebins = np.logspace(math.log10(emin0), math.log10(emax), nband + 1) pbins = np.sqrt((ebins + 1)**2 - 1) pbins /= np.sqrt((eth + 1)**2 - 1) pbins_mid = (pbins[:-1] + pbins[1:]) * 0.5 dpbins = np.diff(pbins) ebins /= eth ebins_mid = (ebins[:-1] + ebins[1:]) * 0.5 debins = np.diff(ebins) dt_particles = pic_info.dt_particles # in 1/wci nframes = tend - tstart + 1 dtf = pic_info.fields_interval * pic_info.dtwci fig = plt.figure(figsize=[7, 5]) rect = [0.13, 0.16, 0.7, 0.8] ax = fig.add_axes(rect) for tframe in range(tstart, tend + 1): print("Time frame: %d" % tframe) tindex = pic_info.fields_interval * tframe fname = (pic_run_dir + "spectrum_combined/spectrum_" + species + "_" + str(tindex) + ".dat") spect = np.fromfile(fname, dtype=np.float32) ndata, = spect.shape spect[3:] /= np.diff(ebins) spect[spect == 0] = np.nan ax.loglog(ebins_mid, spect[3:], linewidth=1, color=plt.cm.Spectral_r((tframe - tstart) / float(nframes), 1)) if species == 'e': pindex = -5.5 power_index = "{%0.1f}" % pindex pname = r'$\sim \varepsilon^{' + power_index + '}$' fpower = 1E18 * ebins_mid**pindex ax.loglog(ebins_mid, fpower, linewidth=1, color='k', linestyle='--') else: pindex = -3.5 power_index = "{%0.1f}" % pindex pname = r'$\sim \varepsilon^{' + power_index + '}$' fpower = 1E15 * ebins_mid**pindex ax.loglog(ebins_mid, fpower, linewidth=1, color='k', linestyle='--') ax.text(0.94, 0.85, pname, color='k', fontsize=20, bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0), horizontalalignment='right', verticalalignment='center', transform=ax.transAxes) ax.tick_params(bottom=True, top=True, left=True, right=True) ax.tick_params(axis='x', which='minor', direction='in', top=True) ax.tick_params(axis='x', which='major', direction='in') ax.tick_params(axis='y', which='minor', direction='in', left=True) ax.tick_params(axis='y', which='major', direction='in') if species in ['e', 'electron']: ax.set_xlim([1E-1, 1E3]) else: ax.set_xlim([1E-1, 5E3]) if '3D' in pic_run: ax.set_ylim([1E0, 1E12]) ax.set_yticks(np.logspace(0, 10, num=6)) else: ax.set_ylim([1E-1, 1E12]) ax.set_yticks(np.logspace(-1, 9, num=6)) ax.set_xlabel(r'$\varepsilon/\varepsilon_\text{th}$', fontsize=20) ax.set_ylabel(r'$f(\varepsilon)$', fontsize=20) ax.tick_params(labelsize=16) rect_cbar = np.copy(rect) rect_cbar[0] += rect[2] + 0.02 rect_cbar[2] = 0.03 cax = fig.add_axes(rect_cbar) colormap = plt.cm.get_cmap('jet', tend - tstart + 1) sm = plt.cm.ScalarMappable(cmap=plt.cm.Spectral_r, norm=plt.Normalize(vmin=tstart * dtf, vmax=tend * dtf)) cax.tick_params(axis='x', which='major', direction='in') # fake up the array of the scalar mappable. Urgh... sm._A = [] cbar = fig.colorbar(sm, cax=cax) cbar.set_label(r'$t\Omega_{ci}$', fontsize=16) cbar.ax.tick_params(labelsize=12) fdir = '../img/cori_3d/spectrum/' + pic_run + '/' mkdir_p(fdir) fname = fdir + 'spectrum_' + species + '_2.pdf' fig.savefig(fname) plt.show()
def contour_tratio_beta(plot_config, show_plot=True): """ Plot contour of temperature ratio and parallel plasma beta """ pic_run = plot_config["pic_run"] pic_run_dir = plot_config["pic_run_dir"] species = plot_config["species"] tframe = plot_config["tframe"] picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) fdir = '../data/temperature_anisotropy/' + pic_run + '/' fname = fdir + 'ftratio_bpara_' + species + '_' + str(tframe) + '.gda' fdata = np.fromfile(fname, dtype=np.float32) nbins_tratio = int(fdata[0]) nbins_beta = int(fdata[1]) tratio_bins_edge = fdata[2:nbins_tratio + 3] beta_bins_edge = fdata[nbins_tratio + 3:nbins_beta + nbins_tratio + 4] tratio_bins_mid = 0.5 * (tratio_bins_edge[1:] + tratio_bins_edge[:-1]) dtratio = np.diff(tratio_bins_edge) beta_bins_mid = 0.5 * (beta_bins_edge[1:] + beta_bins_edge[:-1]) dbeta = np.diff(beta_bins_edge) ftratio_beta = fdata[nbins_beta + nbins_tratio + 4:] ftratio_beta = ftratio_beta.reshape([nbins_beta, nbins_tratio]).T delta = np.dot(dtratio[:, None], dbeta[None, :]) ftratio_beta /= delta # ftratio_beta[ftratio_beta <= 0] = np.nan tratio_min = tratio_bins_mid[0] tratio_max = tratio_bins_mid[-1] beta_min = beta_bins_mid[0] beta_max = beta_bins_mid[-1] # According to Bale et al. 2009, # T_\perp / T_\parallel = 1 + a/(\beta_\parallel - \beta_0)^b. # For mirror instability threshold, (a, b, \beta_0) = (0.77, 0.76, -0.016) # For oblique firehose instability threshold, (a, b, \beta_0) = (-1.4, 1.0, -0.11) tratio_firhose = 1 - 1.4 / (beta_bins_mid + 0.11) tratio_mirror = 1 + 0.77 / (beta_bins_mid + 0.016)**0.76 tratio_firhose[tratio_firhose < 0] = np.nan fig = plt.figure(figsize=[3.25, 2.5]) rect = [0.18, 0.16, 0.67, 0.8] ax = fig.add_axes(rect) ax.tick_params(bottom=True, top=True, left=True, right=True) ax.tick_params(axis='x', which='minor', direction='in', bottom=True, top=True) ax.tick_params(axis='x', which='major', direction='in', bottom=True, top=True) ax.tick_params(axis='y', which='minor', direction='in') ax.tick_params(axis='y', which='major', direction='in') im = ax.pcolormesh(beta_bins_mid, tratio_bins_mid, ftratio_beta, cmap=plt.cm.jet, norm=LogNorm(vmin=1E0, vmax=1E12)) ax.set_xscale('log') ax.set_yscale('log') ax.plot(beta_bins_mid, tratio_firhose, color='k', linestyle='--') ax.plot(beta_bins_mid, tratio_mirror, color='k', linestyle='--') ax.set_xlim([1E-3, 1E3]) ax.set_ylim([1E-2, 1E2]) ax.tick_params(labelsize=8) ax.set_xlabel(r'$\beta_\parallel$', fontsize=10) ax.set_ylabel(r'$T_\perp/T_\parallel$', fontsize=10) rect_cbar = np.copy(rect) rect_cbar[0] += rect[2] + 0.02 rect_cbar[2] = 0.02 cbar_ax = fig.add_axes(rect_cbar) cbar = fig.colorbar(im, cax=cbar_ax) cbar.ax.tick_params(labelsize=8) fdir = '../img/brazil_plot/' + pic_run + '/' mkdir_p(fdir) fname = fdir + 'tratio_bpara_' + species + '_' + str(tframe) + '.jpg' fig.savefig(fname, dpi=300) if show_plot: plt.show() else: plt.close()
def save_mhd_config(run_name): """Save MHD configuration Need to switch y and z directions Args: run_name: simulation run name """ picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json' pic_info = read_data_from_json(picinfo_fname) double_data = np.zeros(13) int_data = np.zeros(14, dtype=np.int32) smime = math.sqrt(pic_info.mime) lx = pic_info.lx_di * smime ly = pic_info.lz_di * smime lz = 0.0 nx = pic_info.nx ny = pic_info.nz nz = pic_info.ny if nx > 1: double_data[0] = lx / nx else: double_data[0] = 0.0 if ny > 1: double_data[1] = ly / ny else: double_data[1] = 0.0 if nz > 1: double_data[2] = lz / nz else: double_data[2] = 0.0 double_data[3] = 0.0 double_data[4] = -0.5 * ly double_data[5] = 0.0 double_data[6] = lx double_data[7] = 0.5 * ly double_data[8] = 0.0 double_data[9] = lx double_data[10] = ly double_data[11] = lz double_data[12] = pic_info.dtwpe * pic_info.fields_interval int_data[0] = pic_info.nx int_data[1] = pic_info.nz int_data[2] = pic_info.ny int_data[3] = pic_info.nx / pic_info.topology_x int_data[4] = pic_info.nz / pic_info.topology_z int_data[5] = pic_info.ny / pic_info.topology_y int_data[6] = pic_info.topology_x int_data[7] = pic_info.topology_z int_data[8] = pic_info.topology_y int_data[9] = 9 int_data[10] = 0 # Periodic boundary condition as default int_data[11] = 0 int_data[12] = 0 int_data[13] = 0 fpath = run_dir + 'bin_data/' mkdir_p(fpath) fname = fpath + 'mhd_config.dat' double_data.tofile(fname) f = open(fname, 'a') int_data.tofile(f) f.close()
def transfer_to_h5part(plot_config): """Transfer current HDF5 file to H5Part format All particles at the same time step are stored in the same time step """ pic_run = plot_config["pic_run"] pic_run_dir = plot_config["pic_run_dir"] traj_dir = plot_config["traj_dir"] if plot_config["species"] == 'e': species = 'electron' else: species = 'H' picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) fpath_traj = pic_run_dir + traj_dir + '/' fname = fpath_traj + species + 's.h5p' fh_in = h5py.File(fname, 'r') particle_tags = list(fh_in.keys()) nptl = len(particle_tags) ptl, ntf = read_particle_data(0, particle_tags, pic_info, fh_in) Ux = np.zeros(ntf * nptl, dtype=ptl['Ux'].dtype) Uy = np.zeros(ntf * nptl, dtype=ptl['Uy'].dtype) Uz = np.zeros(ntf * nptl, dtype=ptl['Uz'].dtype) dX = np.zeros(ntf * nptl, dtype=ptl['dX'].dtype) dY = np.zeros(ntf * nptl, dtype=ptl['dY'].dtype) dZ = np.zeros(ntf * nptl, dtype=ptl['dZ'].dtype) i = np.zeros(ntf * nptl, dtype=ptl['i'].dtype) q = np.zeros(ntf * nptl, dtype=ptl['q'].dtype) gamma = np.zeros(ntf * nptl, dtype=ptl['gamma'].dtype) t = np.zeros(ntf * nptl, dtype=ptl['t'].dtype) if 'Bx' in ptl: Bx = np.zeros(ntf * nptl, dtype=ptl['Bx'].dtype) By = np.zeros(ntf * nptl, dtype=ptl['By'].dtype) Bz = np.zeros(ntf * nptl, dtype=ptl['Bz'].dtype) Ex = np.zeros(ntf * nptl, dtype=ptl['Ex'].dtype) Ey = np.zeros(ntf * nptl, dtype=ptl['Ey'].dtype) Ez = np.zeros(ntf * nptl, dtype=ptl['Ez'].dtype) if 'Vx' in ptl: Vx = np.zeros(ntf * nptl, dtype=ptl['Vx'].dtype) Vy = np.zeros(ntf * nptl, dtype=ptl['Vy'].dtype) Vz = np.zeros(ntf * nptl, dtype=ptl['Vz'].dtype) ne = np.zeros(ntf * nptl, dtype=ptl['ne'].dtype) ni = np.zeros(ntf * nptl, dtype=ptl['ni'].dtype) # Read all particle data for iptl in range(nptl): ptl, ntf = read_particle_data(iptl, particle_tags, pic_info, fh_in) Ux[iptl::nptl] = ptl['Ux'] Uy[iptl::nptl] = ptl['Uy'] Uz[iptl::nptl] = ptl['Uz'] dX[iptl::nptl] = ptl['dX'] dY[iptl::nptl] = ptl['dY'] dZ[iptl::nptl] = ptl['dZ'] i[iptl::nptl] = ptl['i'] q[iptl::nptl] = ptl['q'] gamma[iptl::nptl] = ptl['gamma'] t[iptl::nptl] = ptl['t'] if 'Bx' in ptl: Bx[iptl::nptl] = ptl['Bx'] By[iptl::nptl] = ptl['By'] Bz[iptl::nptl] = ptl['Bz'] Ex[iptl::nptl] = ptl['Ex'] Ey[iptl::nptl] = ptl['Ey'] Ez[iptl::nptl] = ptl['Ez'] if 'Vx' in ptl: Vx[iptl::nptl] = ptl['Vx'] Vy[iptl::nptl] = ptl['Vy'] Vz[iptl::nptl] = ptl['Vz'] ne[iptl::nptl] = ptl['ne'] ni[iptl::nptl] = ptl['ni'] fh_in.close() fname_out = fpath_traj + species + 's.h5part' fh_out = h5py.File(fname_out, 'w') for tindex in range(0, ntf): grp = fh_out.create_group('Step#' + str(tindex)) es, ee = tindex * nptl, (tindex + 1) * nptl grp.create_dataset('Ux', (nptl, ), data=Ux[es:ee]) grp.create_dataset('Uy', (nptl, ), data=Uy[es:ee]) grp.create_dataset('Uz', (nptl, ), data=Uz[es:ee]) grp.create_dataset('dX', (nptl, ), data=dX[es:ee]) grp.create_dataset('dY', (nptl, ), data=dY[es:ee]) grp.create_dataset('dZ', (nptl, ), data=dZ[es:ee]) grp.create_dataset('i', (nptl, ), data=i[es:ee]) grp.create_dataset('q', (nptl, ), data=q[es:ee]) grp.create_dataset('gamma', (nptl, ), data=gamma[es:ee]) grp.create_dataset('t', (nptl, ), data=t[es:ee]) if 'Bx' in ptl: grp.create_dataset('Bx', (nptl, ), data=Bx[es:ee]) grp.create_dataset('By', (nptl, ), data=By[es:ee]) grp.create_dataset('Bz', (nptl, ), data=Bz[es:ee]) grp.create_dataset('Ex', (nptl, ), data=Ex[es:ee]) grp.create_dataset('Ey', (nptl, ), data=Ey[es:ee]) grp.create_dataset('Ez', (nptl, ), data=Ez[es:ee]) if 'Vx' in ptl: grp.create_dataset('Vx', (nptl, ), data=Vx[es:ee]) grp.create_dataset('Vy', (nptl, ), data=Vy[es:ee]) grp.create_dataset('Vz', (nptl, ), data=Vz[es:ee]) grp.create_dataset('ne', (nptl, ), data=ne[es:ee]) grp.create_dataset('ni', (nptl, ), data=ni[es:ee]) fh_out.close()
def plot_spectrum_both(plot_config, show_plot=True): """Plot spectrum both species Args: plot_config: plotting configuration """ species = plot_config["species"] tstart = plot_config["tstart"] tend = plot_config["tend"] tframe = plot_config["tframe"] pic_run = plot_config["pic_run"] pic_run_dir = plot_config["pic_run_dir"] species = plot_config["species"] picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) vthe = pic_info.vthe gama = 1.0 / math.sqrt(1.0 - 3 * vthe**2) ethe = gama - 1.0 vthi = pic_info.vthi gama = 1.0 / math.sqrt(1.0 - 3 * vthi**2) ethi = gama - 1.0 ebins = np.logspace(-6, 4, 1000) ebins_e = ebins / ethe ebins_i = ebins / ethi dt_particles = pic_info.dt_particles # in 1/wci nframes = tend - tstart + 1 dtf = math.ceil(pic_info.dt_particles / 0.1) * 0.1 fig = plt.figure(figsize=[3.5, 2.5]) rect = [0.16, 0.16, 0.8, 0.8] ax = fig.add_axes(rect) ax.set_prop_cycle('color', COLORS) # for tframe in range(tstart_plot, tend_plot + 1): print("Time frame: %d" % tframe) tindex = pic_info.particle_interval * tframe fname = (pic_run_dir + "spectrum_combined/spectrum_e_" + str(tindex) + ".dat") spect_e = np.fromfile(fname, dtype=np.float32) fname = (pic_run_dir + "spectrum_combined/spectrum_i_" + str(tindex) + ".dat") spect_i = np.fromfile(fname, dtype=np.float32) spect_e[3:] /= np.gradient(ebins_e) spect_i[3:] /= np.gradient(ebins_i) # initial thermal distribution fname = (pic_run_dir + "spectrum_combined/spectrum_e_0.dat") spect_init = np.fromfile(fname, dtype=np.float32) ndata, = spect_init.shape spect_init[3:] /= np.gradient(ebins_e) ax.loglog(ebins_e, spect_init[3:], linewidth=1, color='k', linestyle='--', label='initial') ax.loglog(ebins_e, spect_e[3:], linewidth=1, label='electron') ax.loglog(ebins_i, spect_i[3:], linewidth=1, label='ion') ax.legend(loc=3, prop={'size': 10}, ncol=1, shadow=False, fancybox=False, frameon=False) ax.tick_params(bottom=True, top=True, left=True, right=True) ax.tick_params(axis='x', which='minor', direction='in', top='on') ax.tick_params(axis='x', which='major', direction='in') ax.tick_params(axis='y', which='minor', direction='in', left='on') ax.tick_params(axis='y', which='major', direction='in') ax.set_xlim([1E-1, 2E3]) ax.set_ylim([1E-1, 2E12]) ax.set_yticks(np.logspace(-1, 11, num=7)) ax.set_xlabel(r'$\varepsilon/\varepsilon_\text{th}$', fontsize=10) ax.set_ylabel(r'$f(\varepsilon)$', fontsize=10) ax.tick_params(labelsize=8) fdir = '../img/cori_3d/spectrum/' + pic_run + '/both_species/' mkdir_p(fdir) fname = fdir + 'spectrum_both_' + str(tframe) + '.pdf' fig.savefig(fname) if show_plot: plt.show() else: plt.close()
def test_fluid_energization(): """Test fluid-based energization """ run_name = "mime25_beta002_guide00_frequent_dump" species = "e" jdote_name = '../data/jdote_data/jdote_' + run_name + '_' + species + '.json' jdote = read_data_from_json(jdote_name) jcurv_dote = jdote.jcpara_dote jgrad_dote = jdote.jgrad_dote jmag_dote = jdote.jmag_dote jpara_dote = jdote.jqnupara_dote jperp_dote = jdote.jqnuperp_dote jdote_name = '../data/jpolar_dote/jpolar_dote_' + run_name + '_' + species + '.dat' jpolar_dote = np.fromfile(jdote_name, np.float32) fname = "../data/fluid_energization/" fname += "emf_ptensor_" + species + '.gda' fluid_ene = np.fromfile(fname, dtype=np.float32) nvar = int(fluid_ene[0]) nframes = int(fluid_ene[1]) curv_drift_dote = fluid_ene[2:nframes+2] grad_drift_dote = fluid_ene[nframes+2:2*nframes+2] magnetization_dote = fluid_ene[2*nframes+2:3*nframes+2] comp_ene = fluid_ene[3*nframes+2:4*nframes+2] shear_ene = fluid_ene[4*nframes+2:5*nframes+2] ptensor_ene = fluid_ene[5*nframes+2:6*nframes+2] fname = "../data/fluid_energization/" fname += "para_perp_acc_" + species + '.gda' fluid_ene = np.fromfile(fname, dtype=np.float32) nvar = int(fluid_ene[0]) nframes = int(fluid_ene[1]) acc_drift_dote = fluid_ene[2:nframes+2] para_ene = fluid_ene[2*nframes+2:3*nframes+2] perp_ene = fluid_ene[3*nframes+2:4*nframes+2] acc_drift_dote = fluid_ene[2:nframes+2] acc_drift_dote[-1] = acc_drift_dote[-2] fname = "../data/fluid_energization/" fname += "para_perp_acc_" + species + '.gda' fluid_ene = np.fromfile(fname, dtype=np.float32) nvar = int(fluid_ene[0]) nframes = int(fluid_ene[1]) acc_drift_dote = fluid_ene[2:nframes+2] para_ene = fluid_ene[nframes+2:2*nframes+2] perp_ene = fluid_ene[2*nframes+2:3*nframes+2] acc_drift_dote[-1] = acc_drift_dote[-2] # plt.plot(jcurv_dote, linewidth=2) # plt.plot(jgrad_dote, linewidth=2) # plt.plot(jmag_dote, linewidth=2) # plt.plot(curv_drift_dote) # plt.plot(grad_drift_dote) # plt.plot(-magnetization_dote) jperp_dote_n = curv_drift_dote + grad_drift_dote + magnetization_dote jperp_dote_n += acc_drift_dote plt.plot(jpara_dote + jperp_dote, linewidth=2) # plt.plot(jperp_dote, linewidth=2) # plt.plot(jpara_dote, linewidth=2) # plt.plot(jdote.jpolar_dote, linewidth=2) # plt.plot(jperp_dote_n) plt.plot(para_ene + perp_ene) # plt.plot(para_ene) # plt.plot(perp_ene) # plt.plot(ptensor_ene + acc_drift_dote) # plt.plot(comp_ene + shear_ene) # plt.plot(acc_drift_dote) plt.show()
def plot_spectrum(plot_config): """Plot spectrum for all time frames for a single run Args: plot_config: plotting configuration """ species = plot_config["species"] tstart = plot_config["tstart"] tend = plot_config["tend"] pic_run = plot_config["pic_run"] root_dir = "/net/scratch3/xiaocanli/reconnection/Cori_runs/" pic_run_dir = root_dir + pic_run + "/" species = plot_config["species"] picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) if species == 'e': vth = pic_info.vthe sname = 'e' else: vth = pic_info.vthi sname = 'i' ebins = np.logspace(-4, 6, 1000) if species in ['i', 'ion', 'proton']: ebins *= pic_info.mime dt_particles = pic_info.dt_particles # in 1/wci nframes = tend - tstart + 1 dtf = math.ceil(pic_info.dt_particles / 0.1) * 0.1 fig = plt.figure(figsize=[7, 5]) rect = [0.13, 0.16, 0.7, 0.8] ax = fig.add_axes(rect) for tframe in range(tstart, tend + 1): print("Time frame: %d" % tframe) tindex = pic_info.eparticle_interval * tframe fname = (pic_run_dir + "spectrum_combined/spectrum_" + species + "_" + str(tindex) + ".dat") spect = np.fromfile(fname, dtype=np.float32) ndata, = spect.shape spect[3:] /= np.gradient(ebins) spect[spect == 0] = np.nan ax.loglog(ebins, spect[3:], linewidth=1, color=plt.cm.Spectral_r((tframe - tstart) / float(nframes), 1)) if species == 'e': pindex = -2.5 power_index = "{%0.1f}" % pindex pname = r'$\propto (\gamma - 1)^{' + power_index + '}$' fpower = 1E13 * ebins**pindex ax.loglog(ebins, fpower, linewidth=1, color='k', linestyle='--') else: pindex = -3.5 power_index = "{%0.1f}" % pindex pname = r'$\propto (\gamma - 1)^{' + power_index + '}$' fpower = 1E15 * ebins**pindex ax.loglog(ebins, fpower, linewidth=1, color='k', linestyle='--') ax.text(0.94, 0.85, pname, color='k', fontsize=20, bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0), horizontalalignment='right', verticalalignment='center', transform=ax.transAxes) ax.tick_params(bottom=True, top=True, left=True, right=True) ax.tick_params(axis='x', which='minor', direction='in', top=True) ax.tick_params(axis='x', which='major', direction='in') ax.tick_params(axis='y', which='minor', direction='in', left=True) ax.tick_params(axis='y', which='major', direction='in') if species in ['e', 'electron']: ax.set_xlim([1E-1, 1E3]) else: ax.set_xlim([1E-1, 1E3]) if '3D' in pic_run: ax.set_ylim([1E0, 1E12]) ax.set_yticks(np.logspace(0, 10, num=6)) else: ax.set_ylim([1E-1, 1E9]) ax.set_yticks(np.logspace(-1, 9, num=6)) text1 = r'$(\gamma - 1)m_' + species + r'c^2$' ax.set_xlabel(text1, fontsize=20) ax.set_ylabel(r'$f(\gamma - 1)$', fontsize=20) ax.tick_params(labelsize=16) rect_cbar = np.copy(rect) rect_cbar[0] += rect[2] + 0.02 rect_cbar[2] = 0.03 cax = fig.add_axes(rect_cbar) colormap = plt.cm.get_cmap('jet', tend - tstart + 1) sm = plt.cm.ScalarMappable(cmap=plt.cm.Spectral_r, norm=plt.Normalize(vmin=tstart * dtf, vmax=tend * dtf)) cax.tick_params(axis='x', which='major', direction='in') # fake up the array of the scalar mappable. Urgh... sm._A = [] cbar = fig.colorbar(sm, cax=cax) cbar.set_label(r'$t\Omega_{ci}$', fontsize=16) cbar.ax.tick_params(labelsize=12) fdir = '../img/cori_3d/spectrum/' + pic_run + '/' mkdir_p(fdir) fname = fdir + 'spectrum_' + species + '_2.pdf' fig.savefig(fname) plt.show()
def magnetic_power_spectrum(plot_config, show_plot=True): """Plot power spectrum of magnetic field Args: plot_config: plot configuration """ tframe = plot_config["tframe"] bg = plot_config["bg"] pic_runs = ["2D-Lx150-bg" + str(bg) + "-150ppc-16KNL"] pic_runs.append("3D-Lx150-bg" + str(bg) + "-150ppc-2048KNL") pic_run = pic_runs[1] root_dir = "/net/scratch3/xiaocanli/reconnection/Cori_runs/" pic_run_dir = root_dir + pic_run + "/" picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) k1, k2 = 0.03, 1.0 nkbins = 100 pindex = -2.7 kpower = np.logspace(math.log10(k1), math.log10(k2), 100) fpower3 = kpower**pindex / 1E4 fig = plt.figure(figsize=[3.5, 2.5]) rect = [0.17, 0.16, 0.78, 0.8] ax = fig.add_axes(rect) COLORS = palettable.tableau.Tableau_10.mpl_colors ax.set_prop_cycle('color', COLORS) tframes = range(10, 36, 5) for tframe in tframes: tindex = tframe * pic_info.fields_interval for ivar, var in enumerate(["bx", "by", "bz"]): fdir = ('../data/power_spectrum/' + pic_run + '/power_spectrum_' + var + '/') fname = fdir + var + str(tindex) + '.para' kpara, fdata = read_power_spectrum(fname) if ivar > 0: fkpara += fdata else: fkpara = fdata fname = fdir + var + str(tindex) + '.perp' kperp, fdata = read_power_spectrum(fname) if ivar > 0: fkperp += fdata else: fkperp = fdata ax.loglog(kperp, fkperp, linewidth=1, label=r'$k_\perp$') label1 = r'$\propto k_\perp^{' + str(pindex) + '}$' ax.loglog(kpower, fpower3, linewidth=0.5, color='k', linestyle='--', label=label1) ax.tick_params(bottom=True, top=True, left=True, right=True) ax.tick_params(axis='x', which='minor', direction='in', top=False) ax.tick_params(axis='x', which='major', direction='in') ax.tick_params(axis='y', which='minor', direction='in', left=False) ax.tick_params(axis='y', which='major', direction='in') twci = math.ceil((tframe * pic_info.dt_fields) / 0.1) * 0.1 # text1 = r'$t\Omega_{ci}=' + ("{%0.0f}" % twci) + '$' ax.text(0.7, 0.47, label1, color='k', fontsize=10, bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0), horizontalalignment='left', verticalalignment='center', transform=ax.transAxes) ax.set_xlim([1E-2, 5E0]) # ax.set_ylim([1E-7, 2E-1]) ax.set_yticks((np.logspace(-7, -1, 4))) ax.set_xlabel(r'$k_\perp d_e$', fontsize=10) ax.set_ylabel(r'$E_B(k_\perp)$', fontsize=10) ax.tick_params(labelsize=8) # Embedded plot for energy evolution rect1 = [0.29, 0.29, 0.30, 0.28] ax1 = fig.add_axes(rect1) ax1.tick_params(bottom=True, top=True, left=True, right=True) ax1.tick_params(axis='x', which='minor', direction='in', top=False) ax1.tick_params(axis='x', which='major', direction='in') ax1.tick_params(axis='y', which='minor', direction='in') ax1.tick_params(axis='y', which='major', direction='in') for irun, pic_run in enumerate(pic_runs): picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) enorm = pic_info.ene_magnetic[0] ene_bx = pic_info.ene_bx ene_by = pic_info.ene_by ene_bz = pic_info.ene_bz ene_magnetic = pic_info.ene_magnetic ene_electric = pic_info.ene_electric kene_e = pic_info.kene_e kene_i = pic_info.kene_i ene_bx /= enorm ene_by /= enorm ene_bz /= enorm ene_magnetic /= enorm kene_e /= enorm kene_i /= enorm tenergy = pic_info.tenergy lstyle = '-' if '3D' in pic_run else '--' ax1.plot(tenergy, ene_magnetic, linewidth=1, linestyle=lstyle, color='k') ax1.set_ylim([0.66, 1.02]) # for iframe, tframe in enumerate(tframes): # twci = tframe * pic_info.dt_fields # ax1.plot([twci, twci], ax1.get_ylim(), linewidth=0.5, # linestyle=':', color=COLORS[iframe]) tframes = np.asarray(tframes) * pic_info.dt_fields nframe, = tframes.shape ax1.scatter(tframes, [0.7] * nframe, c=COLORS[:nframe], marker='x', s=10, linewidth=0.5) ax1.text(0.6, 0.28, "2D", color='k', fontsize=6, bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0), horizontalalignment='center', verticalalignment='center', transform=ax1.transAxes) ax1.text(0.6, 0.52, "3D", color='k', fontsize=6, bbox=dict(facecolor='none', alpha=1.0, edgecolor='none', pad=10.0), horizontalalignment='center', verticalalignment='center', transform=ax1.transAxes) ax1.tick_params(labelsize=6) ax1.set_xlabel(r'$t\Omega_{ci}$', fontsize=6) ax1.set_ylabel(r'$\varepsilon_B/\varepsilon_{B0}$', fontsize=6) ax1.set_xlim([0, 400]) fdir = '../img/cori_3d/power_spectrum_pub/' + pic_run + '/' mkdir_p(fdir) fname = fdir + 'mag_perp.pdf' fig.savefig(fname) if show_plot: plt.show() else: plt.close('all')
def transfer_to_h5part(plot_config): """Transfer current HDF5 file to H5Part format All particles at the same time step are stored in the same time step """ pic_run = plot_config["pic_run"] pic_run_dir = plot_config["pic_run_dir"] traj_dir = plot_config["traj_dir"] if plot_config["species"] == 'e': species = 'electron' else: species = 'H' picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) fpath_traj = pic_run_dir + traj_dir + '/' fname = fpath_traj + species + 's.h5p' fh_in = h5py.File(fname, 'r') particle_tags = list(fh_in.keys()) nptl = len(particle_tags) ptl, ntf = read_particle_data(0, particle_tags, pic_info, fh_in) Ux = np.zeros(ntf * nptl, dtype=ptl['Ux'].dtype) Uy = np.zeros(ntf * nptl, dtype=ptl['Uy'].dtype) Uz = np.zeros(ntf * nptl, dtype=ptl['Uz'].dtype) dX = np.zeros(ntf * nptl, dtype=ptl['dX'].dtype) dY = np.zeros(ntf * nptl, dtype=ptl['dY'].dtype) dZ = np.zeros(ntf * nptl, dtype=ptl['dZ'].dtype) i = np.zeros(ntf * nptl, dtype=ptl['i'].dtype) q = np.zeros(ntf * nptl, dtype=ptl['q'].dtype) gamma = np.zeros(ntf * nptl, dtype=ptl['gamma'].dtype) t = np.zeros(ntf * nptl, dtype=ptl['t'].dtype) if 'Bx' in ptl: Bx = np.zeros(ntf * nptl, dtype=ptl['Bx'].dtype) By = np.zeros(ntf * nptl, dtype=ptl['By'].dtype) Bz = np.zeros(ntf * nptl, dtype=ptl['Bz'].dtype) Ex = np.zeros(ntf * nptl, dtype=ptl['Ex'].dtype) Ey = np.zeros(ntf * nptl, dtype=ptl['Ey'].dtype) Ez = np.zeros(ntf * nptl, dtype=ptl['Ez'].dtype) if 'Vx' in ptl: Vx = np.zeros(ntf * nptl, dtype=ptl['Vx'].dtype) Vy = np.zeros(ntf * nptl, dtype=ptl['Vy'].dtype) Vz = np.zeros(ntf * nptl, dtype=ptl['Vz'].dtype) ne = np.zeros(ntf * nptl, dtype=ptl['ne'].dtype) ni = np.zeros(ntf * nptl, dtype=ptl['ni'].dtype) # Read all particle data for iptl in range(nptl): ptl, ntf = read_particle_data(iptl, particle_tags, pic_info, fh_in) Ux[iptl::nptl] = ptl['Ux'] Uy[iptl::nptl] = ptl['Uy'] Uz[iptl::nptl] = ptl['Uz'] dX[iptl::nptl] = ptl['dX'] dY[iptl::nptl] = ptl['dY'] dZ[iptl::nptl] = ptl['dZ'] i[iptl::nptl] = ptl['i'] q[iptl::nptl] = ptl['q'] gamma[iptl::nptl] = ptl['gamma'] t[iptl::nptl] = ptl['t'] if 'Bx' in ptl: Bx[iptl::nptl] = ptl['Bx'] By[iptl::nptl] = ptl['By'] Bz[iptl::nptl] = ptl['Bz'] Ex[iptl::nptl] = ptl['Ex'] Ey[iptl::nptl] = ptl['Ey'] Ez[iptl::nptl] = ptl['Ez'] if 'Vx' in ptl: Vx[iptl::nptl] = ptl['Vx'] Vy[iptl::nptl] = ptl['Vy'] Vz[iptl::nptl] = ptl['Vz'] ne[iptl::nptl] = ptl['ne'] ni[iptl::nptl] = ptl['ni'] fh_in.close() fname_out = fpath_traj + species + 's.h5part' fh_out = h5py.File(fname_out, 'w') for tindex in range(0, ntf): grp = fh_out.create_group('Step#' + str(tindex)) es, ee = tindex * nptl, (tindex + 1) * nptl grp.create_dataset('Ux', (nptl, ), data=Ux[es:ee]) grp.create_dataset('Uy', (nptl, ), data=Uy[es:ee]) grp.create_dataset('Uz', (nptl, ), data=Uz[es:ee]) grp.create_dataset('dX', (nptl, ), data=dX[es:ee]) grp.create_dataset('dY', (nptl, ), data=dY[es:ee]) grp.create_dataset('dZ', (nptl, ), data=dZ[es:ee]) grp.create_dataset('i', (nptl, ), data=i[es:ee]) grp.create_dataset('q', (nptl, ), data=q[es:ee]) grp.create_dataset('gamma', (nptl, ), data=gamma[es:ee]) grp.create_dataset('t', (nptl, ), data=t[es:ee]) if 'Bx' in ptl: grp.create_dataset('Bx', (nptl, ), data=Bx[es:ee]) grp.create_dataset('By', (nptl, ), data=By[es:ee]) grp.create_dataset('Bz', (nptl, ), data=Bz[es:ee]) grp.create_dataset('Ex', (nptl, ), data=Ex[es:ee]) grp.create_dataset('Ey', (nptl, ), data=Ey[es:ee]) grp.create_dataset('Ez', (nptl, ), data=Ez[es:ee]) if 'Vx' in ptl: grp.create_dataset('Vx', (nptl, ), data=Vx[es:ee]) grp.create_dataset('Vy', (nptl, ), data=Vy[es:ee]) grp.create_dataset('Vz', (nptl, ), data=Vz[es:ee]) grp.create_dataset('ne', (nptl, ), data=ne[es:ee]) grp.create_dataset('ni', (nptl, ), data=ni[es:ee]) fh_out.close()
def pspect_mag_vel(plot_config, show_plot=True): """Plot power spectrum for magnetic field and velocity field Args: plot_config: plot configuration """ pic_run = plot_config["pic_run"] pic_run_dir = plot_config["pic_run_dir"] tframe = plot_config["tframe"] component = plot_config["component"] picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json' pic_info = read_data_from_json(picinfo_fname) tindex = tframe * pic_info.fields_interval var_name = 'vi' + component fdir = '../data/power_spectrum/' + pic_run + '/power_spectrum_' + var_name + '/' fname = fdir + var_name + str(tindex) + '.para' kpara, fkpara_v = read_power_spectrum(fname) fname = fdir + var_name + str(tindex) + '.perp' kperp, fkperp_v = read_power_spectrum(fname) # fkpara_v *= pic_info.mime * 0.5 # fkperp_v *= pic_info.mime * 0.5 var_name = 'b' + component fdir = '../data/power_spectrum/' + pic_run + '/power_spectrum_' + var_name + '/' fname = fdir + var_name + str(tindex) + '.para' kpara, fkpara_b = read_power_spectrum(fname) fname = fdir + var_name + str(tindex) + '.perp' kperp, fkperp_b = read_power_spectrum(fname) k1, k2 = 0.05, 0.5 nkbins = 100 id_para = (np.abs(kpara - k1)).argmin() id_perp = (np.abs(kperp - k1)).argmin() fnorm1 = max(fkpara_b[id_para], fkperp_b[id_perp]) * 2 fnorm2 = max(fkpara_v[id_para], fkperp_v[id_perp]) * 4 kpower = np.logspace(math.log10(k1), math.log10(k2), 100) fpower1 = kpower**(-5 / 3) fpower1 /= fpower1[0] fpower2 = kpower**-1.5 fpower2 *= fpower1[0] / fpower2[0] fpower3 = kpower**-2 fpower3 *= fpower1[0] / fpower3[0] fig = plt.figure(figsize=[7, 5]) rect = [0.15, 0.16, 0.8, 0.8] ax = fig.add_axes(rect) ax.set_prop_cycle('color', COLORS) p1, = ax.loglog(kpara, fkpara_b, linewidth=2, label=r'$E_B(k_\parallel)$') p2, = ax.loglog(kperp, fkperp_b, linewidth=2, label=r'$E_B(k_\perp)$') p3, = ax.loglog(kpara, fkpara_v, linewidth=2, linestyle='--', color=p1.get_color(), label=r'$E_V(k_\parallel)$') p4, = ax.loglog(kperp, fkperp_v, linewidth=2, linestyle='--', color=p2.get_color(), label=r'$E_V(k_\perp)$') ax.loglog(kpower, fpower1 * fnorm1, linewidth=1, color='k', linestyle='--', label=r'$\sim k^{-5/3}$') ax.loglog(kpower, fpower2 * fnorm1, linewidth=1, color='k', linestyle='-.', label=r'$\sim k^{-3/2}$') ax.loglog(kpower, fpower3 * fnorm1, linewidth=1, color='k', linestyle=':', label=r'$\sim k^{-2}$') ax.loglog(kpower, fpower1 * fnorm2, linewidth=1, color='k', linestyle='--') ax.loglog(kpower, fpower2 * fnorm2, linewidth=1, color='k', linestyle='-.') ax.loglog(kpower, fpower3 * fnorm2, linewidth=1, color='k', linestyle=':') ax.legend(loc=1, prop={'size': 16}, ncol=1, shadow=False, fancybox=False, frameon=False) ax.tick_params(bottom=True, top=True, left=True, right=True) ax.tick_params(axis='x', which='minor', direction='in', top='on') ax.tick_params(axis='x', which='major', direction='in') ax.tick_params(axis='y', which='minor', direction='in', left='on') ax.tick_params(axis='y', which='major', direction='in') ax.set_xlim([1E-2, 1E1]) ax.set_ylim([5E-9, 2E-1]) ax.set_xlabel(r'$kd_e$', fontsize=20) ax.set_ylabel(r'$E(k)$', fontsize=20) ax.tick_params(labelsize=16) fdir = '../img/power_spectrum/' + pic_run + '/mag_vel/' mkdir_p(fdir) fname = fdir + 'bvel_' + component + '_para_perp_' + str(tframe) + '.pdf' fig.savefig(fname) if show_plot: plt.show() else: plt.close('all')
def plot_energy_spectrum(run_name, spect_info, species='e', show_plot=True): """Plot particle energy spectrum Args: run_name: PIC simulation run name species: 'e' for electrons, 'H' for ions spect_info: dictionary for spectra information """ picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json' pic_info = read_data_from_json(picinfo_fname) if species == 'h': species = 'H' # ntf = spect_info["tmax"] ntf = pic_info.ntf if species == 'e': vth = pic_info.vthe else: vth = pic_info.vthi gama = 1.0 / math.sqrt(1.0 - 3 * vth**2) eth = gama - 1.0 emin_log = math.log10(spect_info["emin"]) emax_log = math.log10(spect_info["emax"]) nbins = spect_info["nbins"] elog = 10**(np.linspace(emin_log, emax_log, nbins)) elog /= eth nptot = pic_info.nx * pic_info.ny * pic_info.nz * pic_info.nppc tframes = range(0, ntf - 1) nframes = len(tframes) flogs = np.zeros((nframes, nbins)) fig = plt.figure(figsize=[7, 5]) rect = [0.14, 0.16, 0.82, 0.8] ax = fig.add_axes(rect) for iframe, tframe in enumerate(tframes): print("Time frame: %d" % tframe) fdir = '../data/spectra/' + run_name + '/' fname = fdir + 'spectrum-' + species.lower() + '.' + str(tframe) flog = np.fromfile(fname) flog /= nptot color = plt.cm.jet(tframe / float(ntf), 1) flogs[iframe, :] = flog # ax.loglog(elog, flog, linewidth=2, color=color) # fmin = np.min(flogs[np.nonzero(flogs)]) fmin = 1E-9 flogs += fmin fdata = np.diff(np.log10(flogs[:, 400:600]), axis=0).T ng = 3 kernel = np.ones((ng, ng)) / float(ng * ng) fdata = signal.convolve2d(fdata, kernel, mode='same') ax.imshow(fdata, vmin=-1E-1, vmax=1E-1, cmap=plt.cm.seismic, origin='lower', interpolation='bicubic') # if species == 'e': # ax.set_xlim([1E0, 5E2]) # ax.set_ylim([1E-9, 1E2]) # else: # ax.set_xlim([1E0, 2E3]) # ax.set_ylim([1E-7, 1E4]) ax.tick_params(bottom=True, top=True, left=True, right=False) ax.tick_params(axis='x', which='minor', direction='in') ax.tick_params(axis='x', which='major', direction='in') ax.tick_params(axis='y', which='minor', direction='in') ax.tick_params(axis='y', which='major', direction='in') ax.set_xlabel(r'$\varepsilon/\varepsilon_\text{th}$', fontdict=FONT, fontsize=20) ax.set_ylabel(r'$f(\varepsilon)$', fontdict=FONT, fontsize=20) ax.tick_params(labelsize=16) ename = 'electron' if species == 'e' else 'ion' fpath = "../img/img_high_mime/spectra/" + ename + "/" mkdir_p(fpath) fname = fpath + "spect_time_" + run_name + "_" + species + ".pdf" fig.savefig(fname) if show_plot: plt.show() else: plt.close()
def transfer_pic_to_mhd(run_dir, run_name, tframe): """Transfer the required fields Args: run_dir: simulation directory run_name: name of the simulation run tframe: time frame boundary_x: boundary condition along x-direction 0 for periodic; 1 for others boundary_z: boundary condition along z-direction """ print("Time frame: %d" % tframe) picinfo_fname = '../data/pic_info/pic_info_' + run_name + '.json' pic_info = read_data_from_json(picinfo_fname) lx_di = pic_info.lx_di lz_di = pic_info.lz_di kwargs = { "current_time": tframe, "xl": 0, "xr": lx_di, "zb": -0.5 * lz_di, "zt": 0.5 * lz_di } fname = run_dir + "data/bx.gda" x, z, bx = read_2d_fields(pic_info, fname, **kwargs) fname = run_dir + "data/by.gda" x, z, by = read_2d_fields(pic_info, fname, **kwargs) fname = run_dir + "data/bz.gda" x, z, bz = read_2d_fields(pic_info, fname, **kwargs) nx, = x.shape nz, = z.shape mhd_data = np.zeros((nz + 4, nx + 4, 8), dtype=np.float32) # We need to switch y and z directions absB = np.sqrt(bx**2 + by**2 + bz**2) mhd_data[2:nz + 2, 2:nx + 2, 4] = bx mhd_data[2:nz + 2, 2:nx + 2, 5] = bz mhd_data[2:nz + 2, 2:nx + 2, 6] = -by mhd_data[2:nz + 2, 2:nx + 2, 7] = absB del bx, by, bz, absB mime = pic_info.mime # Electron fname = run_dir + "data/ne.gda" x, z, ne = read_2d_fields(pic_info, fname, **kwargs) fname = run_dir + "data/vex.gda" x, z, vex = read_2d_fields(pic_info, fname, **kwargs) fname = run_dir + "data/vey.gda" x, z, vey = read_2d_fields(pic_info, fname, **kwargs) fname = run_dir + "data/vez.gda" x, z, vez = read_2d_fields(pic_info, fname, **kwargs) vx = ne * vex vy = ne * vey vz = ne * vez del vex, vey, vez # Ion fname = run_dir + "data/ni.gda" x, z, ni = read_2d_fields(pic_info, fname, **kwargs) fname = run_dir + "data/vix.gda" x, z, vix = read_2d_fields(pic_info, fname, **kwargs) fname = run_dir + "data/viy.gda" x, z, viy = read_2d_fields(pic_info, fname, **kwargs) fname = run_dir + "data/viz.gda" x, z, viz = read_2d_fields(pic_info, fname, **kwargs) imass = 1.0 / (ne + ni * mime) vx = (vx + ni * mime * vix) * imass vy = (vy + ni * mime * viy) * imass vz = (vz + ni * mime * viz) * imass del vix, viy, viz, ne, ni, imass absV = np.sqrt(vx**2 + vy**2 + vz**2) mhd_data[2:nz + 2, 2:nx + 2, 0] = vx mhd_data[2:nz + 2, 2:nx + 2, 1] = vz mhd_data[2:nz + 2, 2:nx + 2, 2] = -vy mhd_data[2:nz + 2, 2:nx + 2, 3] = absV del vx, vy, vz, absV # Assuming periodic boundary along x for fields and particles # Assuming conducting boundary along z for fields and reflective for particles mhd_data[:, 0:2, :] = mhd_data[:, nx - 1:nx + 1, :] mhd_data[:, nx + 2:, :] = mhd_data[:, 3:5, :] mhd_data[0:2, :, :] = mhd_data[3:1:-1, :, :] mhd_data[nz + 2:, :, :] = mhd_data[nz + 1:nz - 1:-1, :, :] fpath = run_dir + 'bin_data/' mkdir_p(fpath) fname = fpath + 'mhd_data_' + str(tframe).zfill(4) print(mhd_data.shape) print(np.isfortran(mhd_data)) mhd_data.tofile(fname)