def get_interpolated_ratios(bnd, alpha_val, n_val, interpolation_error, **kwargs): verbose = kwargs.get("verbose", "False") loc1 = [1, 1] loc2 = [2, 2] pf_ratio = [1.0, 1.0] if bnd == "up": p_p = p_ratios_up p_f = f_ratios_up p_a = alpha_tab_up p_n = n_tab_up elif bnd == "lo": p_p = p_ratios_lo p_f = f_ratios_lo p_a = alpha_tab_lo p_n = n_tab_lo else: die("Provided bnd not supported: %s" % bnd) loc1[0] = inverse_f_to_ind(n_val, p_n[0], p_n[size - 1], size - 1) loc1[1] = inverse_f_to_ind(alpha_val, p_a[0], p_a[size - 1], size - 1) if min(loc1[:]) > 0 and max(loc1[:]) <= size - 1: loc2[0] = loc1[0] + 1 loc2[1] = loc1[1] + 1 else: if (verbose): prtwarn("(ERROR) Obtained indices (%s): [%i, %i] -> [%f, %f]" % (bnd, loc1[0], loc1[1], pf_ratio[0], pf_ratio[1])) interpolation_error = True return pf_ratio, interpolation_error pf_ratio[0] = bilin_interpol( p_p[loc1[0]][loc1[1]], p_p[loc2[0]][loc1[1]], p_p[loc1[0]][loc2[1]], p_p[loc2[0]][loc2[1]], bl_in_tu(p_a[loc1[1]], alpha_val, p_a[loc2[1]]), bl_in_tu(p_n[loc1[0]], n_val, p_n[loc2[0]])) pf_ratio[1] = bilin_interpol( p_f[loc1[0]][loc1[1]], p_f[loc2[0]][loc1[1]], p_f[loc1[0]][loc2[1]], p_f[loc2[0]][loc2[1]], bl_in_tu(p_a[loc1[1]], alpha_val, p_a[loc2[1]]), bl_in_tu(p_n[loc1[0]], n_val, p_n[loc2[0]])) if min(pf_ratio[:]) <= 0.0: if (verbose): prtwarn("(ERROR) Obtained p & f (%s) ratios: [%f, %f]" % (bnd, pf_ratio[0], pf_ratio[1])) return pf_ratio, interpolation_error else: if (verbose): prtinfo(" Obtained indices (%s): [%i, %i] -> [%f, %f]" % (bnd, loc1[0], loc1[1], pf_ratio[0], pf_ratio[1])) interpolation_error = False return pf_ratio, interpolation_error
def crs_plot_main_fpq(parameter_names, parameter_values, plot_var, fcrs, qcrs, pcrs, field_max, time, location, **kwargs): global first_run, got_q_tabs, e_small, p_min_fix, p_max_fix, ncre, cre_eff, i_plot, marker, par_plotted_src marker = kwargs.get("marker", "x") i_plot = kwargs.get("i_plot", 0) try: for i in range(len(parameter_names)): exec("%s = %s" % (parameter_names[i], parameter_values[i]), globals()) except: die(" len(names) not equal len(values) at input.") # TODO -------- do it under *args TODO fixed_width = True # ------------------- global plot_ymax, p_fix_ratio, p_fix plot_ymax = field_max * cre_eff if first_run: dummyCRSfile = open("crs.dat", "w+") dummyCRSfile.close() p_fix = [] edges = [] edges[0:ncre] = range(0, ncre + 1, 1) p_fix[0:ncre] = zeros(ncre + 1) log_width = (log10(p_max_fix / p_min_fix)) / (ncre - 2.0) for i in range(0, ncre - 1): # organize p_fix p_fix[i + 1] = p_min_fix * 10.0**(log_width * edges[i]) p_fix_ratio = 10.0**log_width p_fix[0] = (sqrt(p_fix[1] * p_fix[2])) / p_fix_ratio p_fix[ncre] = (sqrt( p_fix[ncre - 2] * p_fix[ncre - 1])) * p_fix_ratio p_fix = asfarray(p_fix) i_lo = 0 i_up = ncre empty_cell = True for i in range(ncre): if fcrs[i] > 0.0: i_lo = i - 2 empty_cell = False break for i in range(ncre, 1, -1): if fcrs[i] > 0.0: i_up = max(0, i + 1) break i_cor = 0 if (fcrs[i_lo] == 0.0): i_cor = 1 fln = array(fcrs[i_lo + i_cor:i_up]) q = array(qcrs[i_lo + i_cor:i_up]) pln = p_fix[i_lo + i_cor:i_up] prn = p_fix[i_lo + 1 + i_cor:i_up + 1] pln[0] = pcrs[0] prn[-1] = pcrs[-1] plot = False # dummy variable until plot is made prtinfo( "\033[44mTime = %6.2f | i_lo = %2d, i_up = %2d %s" % (time, i_lo + i_cor if not empty_cell else 0, i_up if not empty_cell else 0, '(empty cell)' if empty_cell else ' ')) if (i_lo == ncre or i_up == 0): empty_cell = True return plot, empty_cell frn = fln * (prn / pln)**(-q) prtinfo( "Cutoff indices obtained (lo, up): %i, %i || momenta (lo, up): %f, %f " % (i_lo + i_cor, i_up, pcrs[0], pcrs[1])) if (verbosity_1): fcrs1e3 = [] for item in fcrs: fcrs1e3.append(float('%1.3e' % item)) # : print ("n = %1.3e" %item) prtinfo("f = " + str(fcrs1e3)) prtinfo("q = " + str(around(qcrs, 3))) if (empty_cell is False): plot = plot_data(plot_var, pln, prn, fln, frn, q, time, location, i_lo, i_up) i_plot = i_plot + 1 return plot, empty_cell
def crs_plot_main(plot_var, ncrs, ecrs, time, location, **kwargs): global first_run, got_q_tabs, e_small, p_min_fix, p_max_fix, ncre, cre_eff, i_plot, marker, clean_plot, hide_axes marker = kwargs.get("marker", "x") clean_plot = kwargs.get("clean_plot", "True") hide_axes = kwargs.get("hide_axes", False) i_lo = 0 i_up = ncre active_bins = [] empty_cell = True active_bins, i_lo, i_up = detect_active_bins_new(ncrs, ecrs) if (num_active_bins > 1): empty_cell = False # i_lo = max(i_lo,1) # temporarily do not display the leftmost bin # FIXME prtinfo( "\033[44mTime = %6.2f | i_lo = %2d, i_up = %2d %s" % (time, i_lo if not empty_cell else 0, i_up if not empty_cell else 0, '(empty cell)' if empty_cell else ' ')) if (empty_cell): return plt.subplot(122), empty_cell exit_code = False if interpolate_cutoffs: exit_code_lo = True pf_ratio_lo = [0., 0.] pf_ratio_lo, exit_code_lo = crs_pf.get_interpolated_ratios( "lo", ecrs[i_lo] / (ncrs[i_lo] * c * p_fix[i_lo + 1]), ncrs[i_lo], exit_code_lo, verbose=verbosity_2) exit_code_up = True pf_ratio_up = [0., 0.] if (i_up == ncre): i_up = i_up - 1 pf_ratio_up, exit_code_up = crs_pf.get_interpolated_ratios( "up", ecrs[i_up - 1] / (ncrs[i_up - 1] * c * p_fix[i_up - 1]), ncrs[i_up - 1], exit_code_up, verbose=verbosity_2) pln = p_fix[i_lo:i_up] prn = p_fix[i_lo + 1:i_up + 1] pln = array(pln) prn = array(prn) if interpolate_cutoffs: if exit_code_lo is True: if (verbosity_1): prtwarn( "Failed to extract boundary (lo) p and f from e, n: pf_ratio_lo = %.6f. Assuming p_fix value." % pf_ratio_lo[0]) # p_fix assumed else: pln[0] = p_fix[i_lo + 1] / pf_ratio_lo[0] fl_lo = crs_pf.e_small_2_f(e_small, pln[0]) fr_lo = fl_lo * pf_ratio_lo[1] if exit_code_up is True: if (verbosity_1): prtwarn( "Failed to extract boundary (up) p and f from e, n: pf_ratio_up = %.6f. Assuming p_fix value." % pf_ratio_up[0]) # p_fix assumed else: prn[-1] = p_fix[i_up - 1] * pf_ratio_up[0] fr_up = crs_pf.e_small_2_f(e_small, prn[-1]) fl_up = fr_up / pf_ratio_up[1] if (not q_explicit): if (verbosity_2): prtinfo("Spectral indices q will be interpolated") if (not got_q_tabs): prepare_q_tabs() got_q_tabs = True else: if (verbosity_2): prtinfo("Spectral indices q will be obtained explicitly") q_nr = [] fln = [] frn = [] for i in range(0, i_up - i_lo): if (q_explicit is True): q_tmp = 3.5 exit_code = False q_tmp, exit_code = nr_get_q( q_tmp, ecrs[i + i_lo] / (ncrs[i + i_lo] * c * pln[i]), prn[i] / pln[i], exit_code ) # this instruction is duplicated, TODO return it via detect_active_bins_new() else: q_tmp = interpolate_q( ecrs[i + i_lo] / (ncrs[i + i_lo] * c * pln[i]) ) # this instruction is duplicated, TODO return it via detect_active_bins_new() q_nr.append(q_tmp) fln.append(nq2f(ncrs[i + i_lo], q_nr[-1], pln[i], prn[i])) q_nr = array(q_nr) fln = array(fln) frn = array(fln) frn = frn * (prn / pln)**(-q_nr) plot = False # retrieve slopes and f values for cutoffs fln[0] = fl_lo frn[0] = fr_lo fln[-1] = fl_up frn[-1] = fr_up q_nr[0] = -log10(frn[0] / fln[0]) / log10(prn[0] / pln[0]) q_nr[0] = sign(q_nr[0]) * min(abs(q_nr[0]), q_big) q_nr[-1] = -log10(frn[-1] / fln[-1]) / log10(prn[-1] / pln[-1]) q_nr[-1] = sign(q_nr[-1]) * min(abs(q_nr[-1]), q_big) if (verbosity_1): ncrs1e3 = [] for item in ncrs: ncrs1e3.append(float('%1.3e' % item)) prtinfo("n = " + str(ncrs1e3)) ecrs1e3 = [] for item in ecrs: ecrs1e3.append(float('%1.3e' % item)) prtinfo("e = " + str(ecrs1e3)) prtinfo("q = " + str(around(q_nr, 3))) fln1e3 = [] for item in fln: fln1e3.append(float('%1.3e' % item)) prtinfo("f = " + str(fln1e3)) if (verbosity_1): prtinfo( "Cutoff indices obtained (lo, up): %i, %i || momenta (lo, up): %f, %f " % (i_lo, i_up, pln[0], prn[-1])) if (verbosity_2): dummyCRSfile = open("crs.dat", "a") p_all = list(p_fix) # fixes list binding problem - appending p_fix p_all[i_lo] = pln[0] p_all[i_up] = prn[-1] q_all = zeros(ncre) q_all[i_lo:i_up] = q_nr f_all = zeros(ncre + 1) f_all[i_lo:i_up] = fln string = "%15.3e %4.2f %2d %2d %2d" % (time, 0.0, ncre, i_lo, i_up) string = string + " " + str(p_all).strip("[").strip("]") + " " + str( f_all).strip("[").strip("]") + " " + str(q_all).strip("[").strip( "]") dummyCRSfile.write("%s " % string.replace("\n", "").replace("nan", "0.0") + "\n") dummyCRSfile.close() if empty_cell is not True: plot = plot_data(plot_var, pln, prn, fln, frn, q_nr, time, location, i_lo, i_up) i_plot = i_plot + 1 return plot, empty_cell
def detect_active_bins_new(n_in, e_in): global num_active_bins num_active_bins = 0 ne_gt_zero = [] f_gt_zero = [] q_gt_zero = [] e_ampl_l = [] e_ampl_r = [] active_bins_new = [] pln = [] prn = [] i_lo_tmp = 0 i_up_tmp = ncre for i in range(0, ncre): if ( n_in[i] > 0.0 and e_in[i] > 0.0 ): # returns nonzero bin numbers reduced by one compared to CRESP fortran ne_gt_zero.append(i) num_active_bins = num_active_bins + 1 if num_active_bins == 0: return active_bins_new, ncre, 0 i_lo_tmp = max(ne_gt_zero[0] - 2, 0) # edge number i_up_tmp = ne_gt_zero[num_active_bins - 1] # edge number pln = p_fix[i_lo_tmp:i_up_tmp] prn = p_fix[i_lo_tmp + 1:i_up_tmp + 1] num_active_bins = 0 for i in range(1, i_up_tmp - i_lo_tmp - 1): # range(HI-1) q_tmp = 3.5 exit_code = False if (q_explicit is True): q_tmp, exit_code = nr_get_q( q_tmp, e_in[i + i_lo_tmp] / (n_in[i + i_lo_tmp] * c * pln[i]), prn[i] / pln[i], exit_code) else: q_tmp = interpolate_q( e_in[i + i_lo_tmp] / (n_in[i + i_lo_tmp] * c * pln[i]) ) # this instruction is duplicated, TODO return it via detect_active_bins_new() q_tmp, exit_code = nr_get_q( q_tmp, e_in[i + i_lo_tmp] / (n_in[i + i_lo_tmp] * c * pln[i]), prn[i] / pln[i], exit_code) q_gt_zero.append(q_tmp) f_gt_zero.append( nq2f(n_in[i + i_lo_tmp], q_gt_zero[-1], pln[i], prn[i])) e_ampl_l.append(4 * pi * c**2 * f_gt_zero[-1] * pln[i]**3) e_ampl_r.append(4 * pi * c**2 * f_gt_zero[-1] * ((prn[i] / pln[i])**(q_tmp))**3) if (e_ampl_l[-1] > e_small or e_ampl_r[-1] > e_small): if not (abs(q_gt_zero[-1]) >= q_big): # outermost bins usually exceed q_big if inactive active_bins_new.append(ne_gt_zero[i - 1] + 1) num_active_bins = num_active_bins + 1 if num_active_bins == 0: return active_bins_new, i_lo_tmp, i_up_tmp i_lo_tmp = max(active_bins_new[0] - 1, 0) i_up_tmp = min(active_bins_new[-1] + 2, ncre) # temporary fix FIXME prtinfo("Active_bins: " + str(active_bins_new)) return active_bins_new, i_lo_tmp, i_up_tmp
def mark_plot_save(coords): global click_coords, image_number, f_run, marker_index # ------------ preparing data and passing ------------------------- position = h5ds.r[coords:coords] if (plot_field[0:-2] != "en_ratio"): prtinfo( ">>>>>>>>>>>>>>>>>>> Value of %s at point [%f, %f, %f] = %f " % (plot_field, coords[0], coords[1], coords[2], position[plot_field])) else: prtinfo("Value of %s at point [%f, %f, %f] = %f " % (plot_field, coords[0], coords[1], coords[2], position["cree" + str(plot_field[-2:])] / position["cren" + str(plot_field[-2:])])) plot_max = h5ds.find_max("cre" + plot_var + str(plot_field[-2:]))[ 0] # once again appended - needed as ylimit for the plot btot = (position["mag_field_x"].v**2 + position["mag_field_y"].v**2 + position["mag_field_z"].v**2)**0.5 btot_uG = 2.85 * btot # WARNING magic number @btot - conversion factor prtinfo("B_tot = %f = %f (uG)" % (btot, btot_uG)) if (True): # TODO DEPRECATED save_fqp ecrs = [] ncrs = [] if (plot_ovlp is not True): # overwrites position if (plot_layer is True): prtinfo("Plotting layer...") position = h5ds.r[ [coords[0], dom_l[avail_dim[0]], coords[2] ]:[coords[0], dom_r[avail_dim[0]], coords[2]]] elif (options.annotate_rect): # define borders of the selected region (plane) usr_w = float(options.usr_width) usr_h = float(options.usr_height) usr_c = [0, 0] usr_c[:] = [ float(options.usr_center[0]), float(options.usr_center[1]) ] lb = [0, 0, 0] lb[avail_dim[0]] = usr_c[0] - usr_w * 0.5 lb[avail_dim[1]] = usr_c[1] - usr_h * 0.5 lb[dim_map[slice_ax]] = slice_coord - ( dom_r[avail_dim[0]] - dom_l[avail_dim[0]]) / int( h5ds.domain_dimensions[avail_dim[0]]) rb = [0, 0, 0] rb[avail_dim[0]] = usr_c[0] + usr_w * 0.5 rb[avail_dim[1]] = usr_c[1] - usr_h * 0.5 rb[dim_map[slice_ax]] = slice_coord lt = [0, 0, 0] lt[avail_dim[0]] = usr_c[0] - usr_w * 0.5 lt[avail_dim[1]] = usr_c[1] + usr_h * 0.5 lt[dim_map[slice_ax]] = slice_coord rt = [0, 0, 0] rt[avail_dim[0]] = usr_c[0] + usr_w * 0.5 rt[avail_dim[1]] = usr_c[1] + usr_h * 0.5 rt[dim_map[slice_ax]] = slice_coord + ( dom_r[avail_dim[0]] - dom_l[avail_dim[0]]) / int( h5ds.domain_dimensions[avail_dim[0]]) # select region as plane spreading between lb and rt corners position = yt.data_objects.selection_data_containers.YTRegion( left_edge=lb, right_edge=rt, center=usr_c, ds=h5ds) # (center, left_edge, right_edge coords[avail_dim[0]:avail_dim[1]] = usr_c[:] coords[dim_map[slice_ax]] = slice_coord for ind in range(1, ncre + 1): ecrs.append( float(mean(position['cree' + str(ind).zfill(2)][0].v))) ncrs.append( float(mean(position['cren' + str(ind).zfill(2)][0].v))) fig2, exit_code = crs_plot_main(plot_var, ncrs, ecrs, time, coords, marker=marker_l[marker_index], clean_plot=options.clean_plot, hide_axes=options.no_axes) elif (plot_ovlp is True): # for overlap_layer prtinfo("Plotting layer with overlap...") dnum = int(h5ds.domain_dimensions[avail_dim[0]]) dl = (dom_r[avail_dim[0]] - dom_l[avail_dim[0]]) / float(dnum) for j in range(dnum): position = position = h5ds.r[ [coords[0], dom_l[avail_dim[0]] + dl * j, coords[2]]: [coords[0], dom_l[avail_dim[0]] + dl * j, coords[2]]] for ind in range(1, ncre + 1): ecrs.append(position['cree' + str(ind).zfill(2)][0].v) ncrs.append(position['cren' + str(ind).zfill(2)][0].v) fig2, exit_code_tmp = crs_plot_main( plot_var, ncrs, ecrs, time, coords, marker=marker_l[marker_index], i_plot=image_number, clean_plot=options.clean_plot, hide_axes=options.no_axes) if (exit_code_tmp is False): exit_code = exit_code_tmp # Just one plot is allright ecrs = [] ncrs = [] else: # for fqp, DEPRECATED probably fcrs = [] qcrs = [] pcut = [0., 0.] ecrs = [] ncrs = [] for ind in range(1, ncre + 1): ecrs.append(float(position['cree' + str(ind).zfill(2)][0].v)) ncrs.append(float(position['cren' + str(ind).zfill(2)][0].v)) for ind in range(1, ncre + 2): fcrs.append(float(position['cref' + str(ind).zfill(2)][0].v)) for ind in range(1, ncre + 1): qcrs.append(float(position['creq' + str(ind).zfill(2)][0].v)) pcut[:] = [position['crep01'][0].v, position['crep02'][0].v] fig2, exit_code = crs_plot_main_fpq(var_names, var_array, plot_var, fcrs, qcrs, pcut, field_max, time, coords, marker=marker_l[marker_index], clean_plot=options.clean_plot) if (exit_code is not True): if ((plot_layer is True) or (plot_ovlp is True)): line = s1.plot( [dom_l[avail_dim[0]], dom_r[avail_dim[0]]], [coords[2], coords[2]], color="white" ) # plot line (layer) if cell not empty WARNING - for now only works with mcrwind else: point = s1.plot(coords[avail_dim[0]], coords[avail_dim[1]], marker=marker_l[marker_index], color="red") # plot point if cell not empty s.savefig('results/' + filename_nam + '_' + plot_var + '_%04d.png' % image_number, transparent='True') # prtinfo(" ---> Saved plot to: %s " %str('results/'+filename_nam+'_'+plot_var+'_%04d.png' %image_number)) if (plot_layer is True): # Mark averaged level yt_data_plot.annotate_line( [coords[0], dom_l[avail_dim[0]], coords[2]], [coords[0], dom_r[avail_dim[0]], coords[2]], plot_args={ 'color': 'white', "lw": 10.0 }) else: if (not options.annotate_rect and marker_index > 0): yt_data_plot.annotate_marker( coords, marker=marker_l[marker_index - 1], plot_args={ 'color': 'red', 's': m_size_l[marker_index - 1], "lw": 4.5 }) # cumulatively annotate all clicked coordinates if (options.annotate_rect): yt_data_plot.annotate_line(lb, lt, plot_args={ 'color': 'white', "lw": 2.0 }) yt_data_plot.annotate_line(lt, rt, plot_args={ 'color': 'white', "lw": 2.0 }) yt_data_plot.annotate_line(rt, rb, plot_args={ 'color': 'white', "lw": 2.0 }) yt_data_plot.annotate_line(rb, lb, plot_args={ 'color': 'white', "lw": 2.0 }) marker_index = marker_index + 1 image_number = image_number + 1 # ------------- saving just the spectrum if (save_spectrum): extent = fig2.get_window_extent().transformed( s.dpi_scale_trans.inverted()) s.savefig('results/' + filename_nam + '_' + 'slice_' + slice_ax + '_' + plot_var + '_spec_%03d.pdf' % image_number, transparent='True', bbox_inches="tight", dpi=150) # bbox not working in py27 FIXME prtinfo( " ---> Saved plot to: %s.\n\033[44mPress 'q' to quit and save yt.SlicePlot with marked coordinates." % str('results/' + filename_nam + '_' + 'slice_' + slice_ax + '_' + plot_var + '_spectrum_%04d.pdf' % image_number)) else: prtwarn("Empty cell - not saving.") if (f_run): f_run = False
# ---------- reading parameters if (options.filename != "None"): filename = options.filename else: filename = argv[1] filename_trimmed = filename.split("/")[-1] filename_ext = filename_trimmed.split('.')[-1] filename_nam = filename_trimmed.split('.')[0].split('/')[-1] if (filename_ext != 'h5'): die("Script requires a (list of) hdf5 file(s) on input") if f_run: if not path.exists('results'): makedirs('results') prtinfo("Output directory created: %s" % (getcwd() + '/results')) var_array = [] if f_run is True: var_names = [] var_names = [ "ncre", "p_min_fix", "p_max_fix", "e_small", "cre_eff", "q_big" ] var_def = [ 20, 10., 1.e5, 1.e-6, 0.01, 30., ]
#!/usr/bin/python # -*- coding: utf-8 -*- import os import sys import h5py from colored_io import die, prtinfo, prtwarn # This script reads problem.par field from provided # h5/res file, extracts it and saves it in CWD, # so it can be used in new run. if (len(sys.argv) > 1): hdf5_filename = sys.argv[1] prtinfo("File to process is %s" % hdf5_filename) else: die("No file provided, exiting.") try: fh5 = h5py.File(hdf5_filename, 'r') parfile_out = open( "problem.par.%s" % hdf5_filename.strip(".res").strip(".h5"), 'w') except: die("Problem opening %s file. " % hdf5_filename) parameter_object = fh5["problem.par"] for line in parameter_object: # print(line.decode("utf-8")) parfile_out.write(line.decode("utf-8") + "\n") prtinfo( "Successfully read parameters from %s file, list of parameters saved to %s"