def plot_faraday(data): """ Plot the faraday rotation strength along a given line of sight. :param data: Reduced data object. """ if settings.include_lambda: cbtitle=r"Faraday Rotation $\beta$ [rad]" +"\n$\lambda$ = {} cm".format(settings.faraday_lambda) else: cbtitle=r"Faraday RM [rad m$^{-2}$]" if data._ndim == 3: # Check on line of sight if settings.line_of_sight == "all": line_of_sight = ["x", "y", "z"] elif settings.line_of_sight == "x" or settings.line_of_sight == "y" or settings.line_of_sight == "z": line_of_sight = [settings.line_of_sight] else: sys.exit("Line of sight parameter is not known. Should be 'x', 'y', 'z' or 'all'." "\nCurrent value: '{}'".format(settings.line_of_sight)) for los in line_of_sight: faraday = get_faraday_strength(data, los) print("Plotting Faraday effect along {}".format(los)) title = "Faraday - {}\n{}".format(los, print_tools.trim_filename(settings.filename)) plotting.plot_surface(data=data, matrix_2d=faraday, line_of_sight=los, title=title, cmap=settings.cmap_faraday, logscale=settings.logscale_faraday, cblabel=cbtitle, cbformat=settings.cbar_format_faraday) else: faraday = get_faraday_strength(data, "x") print("Plotting Faraday effect for 2D dataset.") plotting.plot_surface(data=data, matrix_2d=faraday, line_of_sight="x", title="Faraday\n{}".format(print_tools.trim_filename(settings.filename)), cmap=settings.cmap_faraday, logscale=settings.logscale_faraday, cblabel=cbtitle, cbformat=settings.cbar_format_faraday) return
def check_to_remove_interpolated(): """ Checks and asks again if interpolated .npy files must be deleted. This can not be undone. Assumes that files have default naming convention defined in physics/ionization.py, eg. ion_ and f_ """ anim_seq = get_animation_sequence() f_npy_files = [] ion_npy_files = [] for filename in anim_seq: ion_npy_files.append("interpolated_files/ion_{}.npy".format( filename[:-4])) f_npy_files.append("interpolated_files/f_param_{}.npy".format( filename[:-4])) if settings.remove_npyfiles: print("Files >>{}.npy<< through >>{}.npy<< will be removed.".format( print_tools.trim_filename(ion_npy_files[0]), print_tools.trim_filename(ion_npy_files[-1]))) print("Files >>{}.npy<< through >>{}.npy<< will be removed.".format( print_tools.trim_filename(f_npy_files[0]), print_tools.trim_filename(f_npy_files[-1]))) usr_input = input("Continue? Y/N: ") if usr_input == "yes" or usr_input == "Y" or usr_input == "y": for npy_file in ion_npy_files: os.remove(npy_file) for npy_file in f_npy_files: os.remove(npy_file) print("Files removed.\n") else: print("Files not removed.\n") return
def check_to_remove_png(pngfiles): """ Checks and asks again if png files must be deleted. This can not be undone. :param pngfiles: (List) List containing the paths to the .png files. """ if settings.remove_pngfiles: print("Files >>{}.png<< through >>{}.png<< will be removed.".format( print_tools.trim_filename(pngfiles[0]), print_tools.trim_filename(pngfiles[-1]))) usr_input = input("Continue? Y/N: ") if usr_input == "yes" or usr_input == "Y" or usr_input == "y": for png_file in pngfiles: os.remove(png_file) print("Files removed.\n") else: print("Files not removed.\n") return
def plot_h_alpha(data): """ Plot the h-alpha line intensity over a given line of sight. :param data: Reduced data object """ cb_title = "H-alpha intensity [cgs]" if data._ndim == 3: # Check on line of sight if settings.line_of_sight == "all": line_of_sight = ["x", "y", "z"] elif settings.line_of_sight == "x" or settings.line_of_sight == "y" or settings.line_of_sight == "z": line_of_sight = [settings.line_of_sight] else: sys.exit( "Line of sight parameter is not known. Should be 'x', 'y', 'z' or 'all'." "\nCurrent value: '{}'".format(settings.line_of_sight)) for los in line_of_sight: intensity = get_intensity(data, los) print("Plotting H-alpha intensity along {}".format(los)) title = "H-alpha - {}\n{}".format( los, print_tools.trim_filename(settings.filename)) plotting.plot_surface(data=data, matrix_2d=intensity, line_of_sight=los, title=title, cmap=settings.cmap_halpha, logscale=settings.logscale_halpha, cblabel=cb_title, cbformat=settings.cbar_format_halpha) else: intensity = get_intensity(data, "x") print("Plotting H-alpha intensity for 2D dataset.") plotting.plot_surface(data=data, matrix_2d=intensity, line_of_sight="x", title="H-alpha\n{}".format( print_tools.trim_filename( settings.filename)), cmap=settings.cmap_halpha, logscale=settings.logscale_halpha, cblabel=cb_title, cbformat=settings.cbar_format_halpha) return
def save_regridded_data(regrid_data): """ Saves the regridded data as a Numpy file. :param regrid_data: The regridded data, output from get_amr_data(). """ if settings.saveFiles: if not os.path.isdir("dat_files"): os.mkdir("dat_files") fn = 'dat_files/' + print_tools.trim_filename( settings.filename) + "_regridded_dat" np.save(fn, regrid_data) print("Regridded data saved to %s.npy" % fn) return
def create_gif(images, duration=None): """ Creates a .gif file from a given list of image paths. :param images: Sorted list containing the filepaths to the desired images. :param duration: Duration of each frame, in seconds. """ if duration is None: duration = settings.frame_duration imageArray = [] print("\nGENERATING GIF FILE...") counter = 0 for im in images: imageArray.append(imageio.imread(im)) counter += 1 print("Iterated over {} images".format(counter)) gifname = "animations/gif_files/{}.gif".format( print_tools.trim_filename(images[0])[:-5]) imageio.mimsave(gifname, imageArray, duration=duration) print(".gif file saved to {}".format(gifname)) return
def get_i_f(data, altitude=20000): """ Returns the degree of ionization for each datapoint in the given input. :param data: Reduced data object. :param altitude: Altitude at which to evaluate (in km). Default is 20000, otherwise rounded to nearest base 1e4 integer. Type is double or integer :return: i | Degree of ionization at each data point of the input matrix. Type is np.ndarray of dimension ndim. f | f-value at each data point of the input matrix, multiplied by 1e16 (see table in paper). Type is np.ndarray of dimension ndim. """ #Perform altitude check if not altitude == 20000: altitude = _round_to_base(altitude, 10000) #Select ionization table if int(altitude) == 10000: i_table = ionization_10k elif int(altitude) == 20000: i_table = ionization_20k else: i_table = ionization_30k #Select f table if int(altitude) == 10000: f_table = f_10k elif int(altitude) == 20000: f_table = f_20k else: f_table = f_30k #Create bivariate spline approximation over rectangular mesh #Has to be done only once, then use it to evaluate (T, p) point spline_ion = RectBivariateSpline(T_table, pg_table, i_table) spline_f = RectBivariateSpline(T_table, pg_table, f_table) #Re-dimensionalize temperature and pressure temp = data.T * units.unit_temperature pg = data.p * units.unit_pressure # Prevent double loading during the same run if data.ion is not None and data.f_param is not None: return data.ion, data.f_param else: #See if data is already stored to disk: filen = print_tools.trim_filename(settings.filename) if os.path.isfile("interpolated_files/ion_" + filen + ".npy") and os.path.isfile( "interpolated_files/f_param_" + filen + ".npy"): print("Interpolated data already exists -- loading files.") print(" Loading Numpy files...") ion = np.load("interpolated_files/ion_" + filen + ".npy") f = np.load("interpolated_files/f_param_" + filen + ".npy") print(" Done.") data.ion = ion data.f_param = f * 1e16 return ion, f * 1e16 #Create matrix of same size of input ion = np.zeros_like(temp) f = np.zeros_like(temp) #Fast iteration over array elements (calls the C array operator API) it = np.nditer(temp, flags=['multi_index']) print("Interpolating matrix for ionization and f.") if data._ndim == 2: tot_points = len(data.T[0, :]) else: tot_points = len(data.T[0, 0, :]) ctr = 0 while not it.finished: #Get current index of iterator, Type = Tuple idx = it.multi_index #Get temperature and pressure at current index t_i = temp[idx] p_i = pg[idx] #Interpolate ionization degree, save to current index ion[idx] = spline_ion.ev(t_i, p_i) #Interpolate f, save to current index f[idx] = spline_f.ev(t_i, p_i) #Advance iterator ctr += 1 #Print out progress if ctr % 250 == 0: print_tools.progress(idx[-1], tot_points, '-- interpolating...') it.iternext() print_tools.progress(tot_points, tot_points, '-- completed.') print("\n") # save Numpy arrays for easy acces later on if settings.saveFiles: np.save("interpolated_files/ion_" + filen, ion) np.save("interpolated_files/f_param_" + filen, f) print("Interpolated arrays saved to") print(" interpolated_files/ion_" + filen + ".npy") print(" interpolated_files/f_param_" + filen + ".npy") data.ion = ion data.f_param = f * 1e16 # Parameter f is tabulated in units of 10^16 cm-3 return ion, f * 1e16
def __init__(self, file): """ Initializes Class instance. @param file: .dat file, opened in binary mode. """ print("Reading %s" % settings.filename) hdr = dat_reader.get_header(file) # Obtain raw data try: # Mesh is uniformely refined raw_data = dat_reader.get_uniform_data(file) except IOError: print( " Data is not uniformely refined, performing regridding to finest level" ) # Check if data already regridded and saved: fn = "dat_files/" + print_tools.trim_filename( settings.filename) + "_regridded_dat.npy" if os.path.isfile(fn): print(" Regridded data already exists -- loading files.") raw_data = np.load(fn) else: # Data not found, initiate regridding if settings.multiple_procs: print( " Regridding data using parallelization, number of procs = %s" % settings.nb_of_procs) raw_data = dat_reader.get_amr_data_multiprocessing(file) else: raw_data = dat_reader.get_amr_data(file) print(" Regridding done.") print("Processing data...") self._version = hdr["version"] self._nw = hdr["nw"] self._ndir = hdr["ndir"] self._ndim = hdr["ndim"] self._levmax = hdr["levmax"] self._nleafs = hdr["nleafs"] self._it = hdr["it"] self._time = hdr["time"] self._xmin = hdr["xmin"][0] self._xmax = hdr["xmax"][0] if self._ndim >= 2: self._ymin = hdr["xmin"][1] self._ymax = hdr["xmax"][1] if self._ndim == 3: self._zmin = hdr["xmin"][2] self._zmax = hdr["xmax"][2] self._wnames = hdr["w_names"] self._physics_type = hdr["physics_type"] if self._physics_type == "hd": settings.plot_Blines = False self._gamma = hdr["gamma"] #Initialize primitive and conservative variables. #In essence not needed, but done to flag usage before initialization. self.rho = None self.momx = None self.momy = None self.momz = None self.e = None self.b1 = None self.b2 = None self.b3 = None self.p = None self.v1 = None self.v2 = None self.v3 = None self.T = None #Ionization degree etc, prevent double loading. self.ion = None self.fparam = None #Define conservative variables self._setConservativeVariables(raw_data) #Calculate primitive variables self._setPrimitiveVariables() #Calculate box sizes self._setupUniformGrid() print(" Processing done.\n")
def plot_surface(data, matrix_2d, line_of_sight, title=None, xlabel=None, ylabel=None, cblabel=None): """ Creates a surface plot of the integrated data. @param data: Reduced data object. @param matrix_2d: Integrated matrix along the line of sight. Type is np.ndarray of dimension 2 @param line_of_sight: (String) Line of sight corresponding to matrix_2d. Can be 'x', 'y' or 'z', default = 'x'. @param title: (Optional, String) Title for the figure. @param xlabel: (Optional, String) Label for horizontal axis. @param ylabel: (Optional, String) Label for vertical axis. @param cblabel: (Optional, String) Label for the color bar. @note: - X integration: visual is from outside axis to origin, z is upwards, y is to the right - Y integration: visual is from origin to outside axis, z is upwards, x is to the right - Z integration: visual is from outside axis to origin, y is upwards, x is to the right """ hori_ax, vert_ax = get_arrays(data, line_of_sight) bounds = [ np.min(hori_ax), np.max(hori_ax), np.min(vert_ax), np.max(vert_ax) ] # Create figure fig, ax = plt.subplots(1) if settings.logscale: im = plt.imshow(matrix_2d, norm=mpl.colors.LogNorm(), cmap=settings.cmap, extent=bounds) else: im = plt.imshow(matrix_2d, cmap=settings.cmap, extent=bounds) im.set_interpolation("bilinear") colorb = fig.colorbar(im) #Labels if cblabel is not None: colorb.set_label(cblabel) else: colorb.set_label("Intensity [cgs]") if xlabel is not None: ax.set_xlabel(xlabel) else: ax.set_xlabel("[%.0e cm]" % units.unit_length) if ylabel is not None: ax.set_ylabel(ylabel) else: ax.set_ylabel("[%.0e cm]" % units.unit_length) filename = print_tools.trim_filename(settings.filename) if title is not None: ax.set_title(title + "\n" + filename) else: ax.set_title(filename) #Bounds ax.set_xlim([bounds[0], bounds[1]]) ax.set_ylim([bounds[2], bounds[3]]) #Magnetic field lines if settings.plot_Blines: impose_fieldlines(data, line_of_sight, ax) return