def map(self, L, x, y): dd = 1.0 / (2.0**(int(L))) relx = int(x) * dd rely = int(y) * dd DW = (self.ds.domain_right_edge - self.ds.domain_left_edge) xl = self.ds.domain_left_edge[0] + relx * DW[0] yl = self.ds.domain_left_edge[1] + rely * DW[1] xr = xl + dd * DW[0] yr = yl + dd * DW[1] frb = FixedResolutionBuffer(self.data, (xl, xr, yl, yr), (256, 256)) cmi, cma = get_color_bounds( self.data['px'], self.data['py'], self.data['pdx'], self.data['pdy'], self.data[self.field], self.ds.domain_left_edge[0], self.ds.domain_right_edge[0], self.ds.domain_left_edge[1], self.ds.domain_right_edge[1], dd * DW[0] / (64 * 256), dd * DW[0]) if self.ds._get_field_info(self.field).take_log: cmi = np.log10(cmi) cma = np.log10(cma) to_plot = apply_colormap(np.log10(frb[self.field]), color_bounds=(cmi, cma)) else: to_plot = apply_colormap(frb[self.field], color_bounds=(cmi, cma)) rv = write_png_to_string(to_plot) return rv
def get_halo_map(self, ds, filename=None): """Get halo map and locate peaks Parameter --------- ds: yt.frontends.gadget.data_structures.GadgetHDF5Dataset Return ------ peaklist: np.ndarray In which contains location of halo peaks. """ # Get projected halo density halo_proj = ds.proj(self.halo_field, self.axis) # Get fiexed resolution buffer bounds = self.get_window_parameters(ds) halo_frb = FixedResolutionBuffer(halo_proj, bounds, self.imgsize) # YTarray to np.ndarray halo_map = np.array(halo_frb[self.halo_field], dtype=float) # Normalization halo_min = halo_map.min() halo_max = halo_map.max() halo_map_norm = (halo_map - halo_min) / (halo_max - halo_min) # Detect peaks # peaklist = self.locate_peak(halo_map_norm) if self.save == True: pz = yt.ProjectionPlot(ds, self.axis, self.halo_field, width=self.width) # pz.set_buff_size(self.buff_size) filepath = os.path.join(self.output_dir, filename) pz.save(filepath) return halo_map_norm
def to_frb(self, width, resolution, height=None, periodic=False): r"""This function returns a FixedResolutionBuffer generated from this object. An ObliqueFixedResolutionBuffer is an object that accepts a variable-resolution 2D object and transforms it into an NxM bitmap that can be plotted, examined or processed. This is a convenience function to return an FRB directly from an existing 2D data object. Unlike the corresponding to_frb function for other YTSelectionContainer2D objects, this does not accept a 'center' parameter as it is assumed to be centered at the center of the cutting plane. Parameters ---------- width : width specifier This can either be a floating point value, in the native domain units of the simulation, or a tuple of the (value, unit) style. This will be the width of the FRB. height : height specifier, optional This will be the height of the FRB, by default it is equal to width. resolution : int or tuple of ints The number of pixels on a side of the final FRB. periodic : boolean This can be true or false, and governs whether the pixelization will span the domain boundaries. Returns ------- frb : :class:`~yt.visualization.fixed_resolution.ObliqueFixedResolutionBuffer` A fixed resolution buffer, which can be queried for fields. Examples -------- >>> v, c = ds.find_max("density") >>> sp = ds.sphere(c, (100.0, 'au')) >>> L = sp.quantities.angular_momentum_vector() >>> cutting = ds.cutting(L, c) >>> frb = cutting.to_frb( (1.0, 'pc'), 1024) >>> write_image(np.log10(frb["Density"]), 'density_1pc.png') """ if is_sequence(width): validate_width_tuple(width) width = self.ds.quan(width[0], width[1]) if height is None: height = width elif is_sequence(height): validate_width_tuple(height) height = self.ds.quan(height[0], height[1]) if not is_sequence(resolution): resolution = (resolution, resolution) from yt.visualization.fixed_resolution import FixedResolutionBuffer bounds = (-width / 2.0, width / 2.0, -height / 2.0, height / 2.0) frb = FixedResolutionBuffer(self, bounds, resolution, periodic=periodic) return frb
def _regenerate_buffer(self): dx = (self.xlim[1] - self.xlim[0])/self.size[0] dy = (self.ylim[1] - self.ylim[0])/self.size[1] my_lim = (self.xlim[0] + dx*self.start_indices[0], self.xlim[0] + dx*(self.start_indices[0] + self.my_size[0]), self.ylim[0] + dy*self.start_indices[1], self.ylim[0] + dy*(self.start_indices[1] + self.my_size[1])) new_buffer = FixedResolutionBuffer(self.source, my_lim, self.my_size) self._buffer = new_buffer
def compute_fixed_resolution_buffer(self, bounds, target_data=None, target_cid=None, subset_state=None, broadcast=True, cache_id=None): print(str(subset_state) + ' in CFRB') # Return data FRB slice if subset is None, else return mask of subset if target_cid is None and subset_state is None: raise ValueError( "Either target_cid or subset_state should be specified") for bound in bounds: if isinstance(bound, tuple) and bound[2] < 1: raise ValueError("Number of steps in bounds should be >=1") field = cid_to_field(target_cid) print('Calling GSR in compute_statistic in compute_FRB') reg = self._get_subset_region(subset_state) nd = len([b for b in bounds if isinstance(b, tuple)]) if nd == 2: axis, coord = self._slice_args(bounds) sl = self.ds.slice(axis, coord, data_source=reg) frb = FixedResolutionBuffer(sl, *self._frb_args(bounds, axis)) if subset_state is None: return frb[field].d.T elif nd == 3: bds = np.array(bounds) le = self._get_loc(bds[:, 0]) re = self._get_loc(bds[:, 1]) shape = bds[:, 2].astype("int") if np.any(le < self._left_edge) | np.any(re > self._right_edge): ret = np.empty(shape) ret[:] = np.nan return ret ag = self.ds.arbitrary_grid(le, re, shape) if subset_state is None: return ag[field].d try: att_field = sub('"', '', subset_state.att.label).split(',')[1] cgatt = frb[att_field].d.T frb_mask = frb['zeros'].d.T # Possibly change to yt function include_inside in the future # Use other yt data.containers.include... fcns for other sets of logic wr = np.where( np.logical_and(cgatt >= subset_state.lo, cgatt <= subset_state.hi)) frb_mask[wr[0], wr[1]] = 1 return frb_mask except AttributeError: # Should never get here. print("Returning Nothing in cfrb") return
def display_yt(data_object, field): # Note what we are doing here: we are taking *views* of these, # as the logic in the ndarray traittype doesn't check for subclasses. frb = FRBViewer(px = data_object["px"].d, py = data_object["py"].d, pdx = data_object["pdx"].d, pdy = data_object["pdy"].d, val = data_object[field].d) controls = frb.setup_controls() return ipywidgets.HBox([controls, frb])
def map(self, field, L, x, y): if "," in field: field = tuple(field.split(",")) cmap = self.cmap dd = 1.0 / (2.0**(int(L))) relx = int(x) * dd rely = int(y) * dd DW = self.ds.domain_right_edge - self.ds.domain_left_edge xl = self.ds.domain_left_edge[0] + relx * DW[0] yl = self.ds.domain_left_edge[1] + rely * DW[1] xr = xl + dd * DW[0] yr = yl + dd * DW[1] try: self.lock() w = 256 # pixels data = self.data[field] frb = FixedResolutionBuffer(self.data, (xl, xr, yl, yr), (w, w)) cmi, cma = get_color_bounds( self.data["px"], self.data["py"], self.data["pdx"], self.data["pdy"], data, self.ds.domain_left_edge[0], self.ds.domain_right_edge[0], self.ds.domain_left_edge[1], self.ds.domain_right_edge[1], dd * DW[0] / (64 * 256), dd * DW[0], ) finally: self.unlock() if self.takelog: cmi = np.log10(cmi) cma = np.log10(cma) to_plot = apply_colormap(np.log10(frb[field]), color_bounds=(cmi, cma), cmap_name=cmap) else: to_plot = apply_colormap(frb[field], color_bounds=(cmi, cma), cmap_name=cmap) rv = write_png_to_string(to_plot) return rv
def get_data(self, cid, view=None): if view is None: nd = self.ndim else: nd = len([v for v in view if isinstance(v, slice)]) field = tuple(cid.label.split()) if nd == 2: axis, coord = self._slice_args(view) sl = self.ds.slice(axis, coord) frb = FixedResolutionBuffer(sl, *self._frb_args(view, axis)) return frb[field].d.T elif nd == 3: le = [] re = [] shape = [] for i, v in enumerate(view): le.append(self._get_loc(v.start, i)) re.append(self._get_loc(v.stop, i)) shape.append((v.stop - v.start) // v.step) ag = self.ds.arbitrary_grid(le, re, shape) return ag[field].d
def map(self, field, L, x, y): if ',' in field: field = tuple(field.split(',')) dd = 1.0 / (2.0**(int(L))) relx = int(x) * dd rely = int(y) * dd DW = (self.ds.domain_right_edge - self.ds.domain_left_edge) xl = self.ds.domain_left_edge[0] + relx * DW[0] yl = self.ds.domain_left_edge[1] + rely * DW[1] xr = xl + dd*DW[0] yr = yl + dd*DW[1] try: self.lock() data = self.data[field] frb = FixedResolutionBuffer(self.data, (xl, xr, yl, yr), (256, 256)) cmi, cma = get_color_bounds(self.data['px'], self.data['py'], self.data['pdx'], self.data['pdy'], data, self.ds.domain_left_edge[0], self.ds.domain_right_edge[0], self.ds.domain_left_edge[1], self.ds.domain_right_edge[1], dd*DW[0] / (64*256), dd*DW[0]) finally: self.unlock() if self.takelog: cmi = np.log10(cmi) cma = np.log10(cma) to_plot = apply_colormap(np.log10(frb[field]), color_bounds = (cmi, cma)) else: to_plot = apply_colormap(frb[field], color_bounds = (cmi, cma)) rv = write_png_to_string(to_plot) return rv
def _light_cone_projection(my_slice, field, pixels, weight_field=None, save_image=False, field_cuts=None): "Create a single projection to be added into the light cone stack." # We are just saving the projection object, so only the projection axis # needs to be considered since the lateral shifting and tiling occurs after # the projection object is made. # Likewise, only the box_depth_fraction needs to be considered. mylog.info("Making projection at z = %f from %s." % \ (my_slice["redshift"], my_slice["filename"])) region_center = [0.5 * (my_slice["object"].domain_right_edge[q] + my_slice["object"].domain_left_edge[q]) \ for q in range(my_slice["object"].dimensionality)] # 1. The Depth Problem # Use coordinate field cut in line of sight to cut projection to proper depth. if field_cuts is None: these_field_cuts = [] else: these_field_cuts = field_cuts.copy() if (my_slice["box_depth_fraction"] < 1): axis = ("x", "y", "z")[my_slice["projection_axis"]] depthLeft = \ my_slice["projection_center"][my_slice["projection_axis"]] \ - 0.5 * my_slice["box_depth_fraction"] depthRight = \ my_slice["projection_center"][my_slice["projection_axis"]] \ + 0.5 * my_slice["box_depth_fraction"] if (depthLeft < 0): cut_mask = ( "((obj['index', '%s'] + 0.5*obj['index', 'd%s'] >= 0) & " " (obj['index', '%s'] - 0.5*obj['index', 'd%s'] <= %f)) | " "((obj['index', '%s'] + 0.5*obj['index', 'd%s'] >= %f) & " " (obj['index', '%s'] - 0.5*obj['index', 'd%s'] <= 1))") % \ (axis, axis, axis, axis, depthRight, axis, axis, (depthLeft+1), axis, axis) elif (depthRight > 1): cut_mask = ( "((obj['index', '%s'] + 0.5*obj['index', 'd%s'] >= 0) & " "(obj['index', '%s'] - 0.5*obj['index', 'd%s'] <= %f)) | " "((obj['index', '%s'] + 0.5*obj['index', 'd%s'] >= %f) & " "(obj['index', '%s'] - 0.5*obj['index', 'd%s'] <= 1))") % \ (axis, axis, axis, axis, (depthRight-1), axis, axis, depthLeft, axis, axis) else: cut_mask = ( "(obj['index', '%s'] + 0.5*obj['index', 'd%s'] >= %f) & " "(obj['index', '%s'] - 0.5*obj['index', '%s'] <= %f)") % \ (axis, axis, depthLeft, axis, axis, depthRight) these_field_cuts.append(cut_mask) data_source = my_slice["object"].all_data() cut_region = data_source.cut_region(these_field_cuts) # Make projection. proj = my_slice["object"].proj(field, my_slice["projection_axis"], weight_field, center=region_center, data_source=cut_region) proj_field = proj.field[0] del data_source, cut_region # 2. The Tile Problem # Tile projection to specified width. # Original projection data. original_px = proj.field_data["px"].in_units("code_length").copy() original_py = proj.field_data["py"].in_units("code_length").copy() original_pdx = proj.field_data["pdx"].in_units("code_length").copy() original_pdy = proj.field_data["pdy"].in_units("code_length").copy() original_field = proj.field_data[proj_field].copy() original_weight_field = proj.field_data["weight_field"].copy() for my_field in ["px", "py", "pdx", "pdy", proj_field, "weight_field"]: proj.field_data[my_field] = [proj.field_data[my_field]] # Copy original into offset positions to make tiles. for x in range(int(np.ceil(my_slice["box_width_fraction"]))): x = my_slice["object"].quan(x, "code_length") for y in range(int(np.ceil(my_slice["box_width_fraction"]))): y = my_slice["object"].quan(y, "code_length") if ((x + y) > 0): proj.field_data["px"] += [original_px + x] proj.field_data["py"] += [original_py + y] proj.field_data["pdx"] += [original_pdx] proj.field_data["pdy"] += [original_pdy] proj.field_data["weight_field"] += [original_weight_field] proj.field_data[proj_field] += [original_field] for my_field in ["px", "py", "pdx", "pdy", proj_field, "weight_field"]: proj.field_data[my_field] = \ my_slice["object"].arr(proj.field_data[my_field]).flatten() # Delete originals. del original_px del original_py del original_pdx del original_pdy del original_field del original_weight_field # 3. The Shift Problem # Shift projection by random x and y offsets. image_axes = np.roll(np.arange(3), -my_slice["projection_axis"])[1:] di_left_x = my_slice["object"].domain_left_edge[image_axes[0]] di_right_x = my_slice["object"].domain_right_edge[image_axes[0]] di_left_y = my_slice["object"].domain_left_edge[image_axes[1]] di_right_y = my_slice["object"].domain_right_edge[image_axes[1]] offset = my_slice["projection_center"].copy() * \ my_slice["object"].domain_width offset = np.roll(offset, -my_slice["projection_axis"])[1:] # Shift x and y positions. proj.field_data["px"] -= offset[0] proj.field_data["py"] -= offset[1] # Wrap off-edge cells back around to other side (periodic boundary conditions). proj.field_data["px"][proj.field_data["px"] < di_left_x] += \ np.ceil(my_slice["box_width_fraction"]) * di_right_x proj.field_data["py"][proj.field_data["py"] < di_left_y] += \ np.ceil(my_slice["box_width_fraction"]) * di_right_y # After shifting, some cells have fractional coverage on both sides of the box. # Find those cells and make copies to be placed on the other side. # Cells hanging off the right edge. add_x_right = proj.field_data["px"] + 0.5 * proj.field_data["pdx"] > \ np.ceil(my_slice["box_width_fraction"]) * di_right_x add_x_px = proj.field_data["px"][add_x_right] add_x_px -= np.ceil(my_slice["box_width_fraction"]) * di_right_x add_x_py = proj.field_data["py"][add_x_right] add_x_pdx = proj.field_data["pdx"][add_x_right] add_x_pdy = proj.field_data["pdy"][add_x_right] add_x_field = proj.field_data[proj_field][add_x_right] add_x_weight_field = proj.field_data["weight_field"][add_x_right] del add_x_right # Cells hanging off the left edge. add_x_left = proj.field_data[ "px"] - 0.5 * proj.field_data["pdx"] < di_left_x add2_x_px = proj.field_data["px"][add_x_left] add2_x_px += np.ceil(my_slice["box_width_fraction"]) * di_right_x add2_x_py = proj.field_data["py"][add_x_left] add2_x_pdx = proj.field_data["pdx"][add_x_left] add2_x_pdy = proj.field_data["pdy"][add_x_left] add2_x_field = proj.field_data[proj_field][add_x_left] add2_x_weight_field = proj.field_data["weight_field"][add_x_left] del add_x_left # Cells hanging off the top edge. add_y_right = proj.field_data["py"] + 0.5 * proj.field_data["pdy"] > \ np.ceil(my_slice["box_width_fraction"]) * di_right_y add_y_px = proj.field_data["px"][add_y_right] add_y_py = proj.field_data["py"][add_y_right] add_y_py -= np.ceil(my_slice["box_width_fraction"]) * di_right_y add_y_pdx = proj.field_data["pdx"][add_y_right] add_y_pdy = proj.field_data["pdy"][add_y_right] add_y_field = proj.field_data[proj_field][add_y_right] add_y_weight_field = proj.field_data["weight_field"][add_y_right] del add_y_right # Cells hanging off the bottom edge. add_y_left = proj.field_data[ "py"] - 0.5 * proj.field_data["pdy"] < di_left_y add2_y_px = proj.field_data["px"][add_y_left] add2_y_py = proj.field_data["py"][add_y_left] add2_y_py += np.ceil(my_slice["box_width_fraction"]) * di_right_y add2_y_pdx = proj.field_data["pdx"][add_y_left] add2_y_pdy = proj.field_data["pdy"][add_y_left] add2_y_field = proj.field_data[proj_field][add_y_left] add2_y_weight_field = proj.field_data["weight_field"][add_y_left] del add_y_left # Add the hanging cells back to the projection data. proj.field_data["px"] = uconcatenate( [proj.field_data["px"], add_x_px, add_y_px, add2_x_px, add2_y_px]) proj.field_data["py"] = uconcatenate( [proj.field_data["py"], add_x_py, add_y_py, add2_x_py, add2_y_py]) proj.field_data["pdx"] = uconcatenate( [proj.field_data["pdx"], add_x_pdx, add_y_pdx, add2_x_pdx, add2_y_pdx]) proj.field_data["pdy"] = uconcatenate( [proj.field_data["pdy"], add_x_pdy, add_y_pdy, add2_x_pdy, add2_y_pdy]) proj.field_data[proj_field] = uconcatenate([ proj.field_data[proj_field], add_x_field, add_y_field, add2_x_field, add2_y_field ]) proj.field_data["weight_field"] = uconcatenate([ proj.field_data["weight_field"], add_x_weight_field, add_y_weight_field, add2_x_weight_field, add2_y_weight_field ]) # Delete original copies of hanging cells. del add_x_px, add_y_px, add2_x_px, add2_y_px del add_x_py, add_y_py, add2_x_py, add2_y_py del add_x_pdx, add_y_pdx, add2_x_pdx, add2_y_pdx del add_x_pdy, add_y_pdy, add2_x_pdy, add2_y_pdy del add_x_field, add_y_field, add2_x_field, add2_y_field del add_x_weight_field, add_y_weight_field, add2_x_weight_field, add2_y_weight_field # Tiles were made rounding up the width to the nearest integer. # Cut off the edges to get the specified width. # Cut in the x direction. cut_x = proj.field_data["px"] - 0.5 * proj.field_data["pdx"] < \ di_right_x * my_slice["box_width_fraction"] proj.field_data["px"] = proj.field_data["px"][cut_x] proj.field_data["py"] = proj.field_data["py"][cut_x] proj.field_data["pdx"] = proj.field_data["pdx"][cut_x] proj.field_data["pdy"] = proj.field_data["pdy"][cut_x] proj.field_data[proj_field] = proj.field_data[proj_field][cut_x] proj.field_data["weight_field"] = proj.field_data["weight_field"][cut_x] del cut_x # Cut in the y direction. cut_y = proj.field_data["py"] - 0.5 * proj.field_data["pdy"] < \ di_right_y * my_slice["box_width_fraction"] proj.field_data["px"] = proj.field_data["px"][cut_y] proj.field_data["py"] = proj.field_data["py"][cut_y] proj.field_data["pdx"] = proj.field_data["pdx"][cut_y] proj.field_data["pdy"] = proj.field_data["pdy"][cut_y] proj.field_data[proj_field] = proj.field_data[proj_field][cut_y] proj.field_data["weight_field"] = proj.field_data["weight_field"][cut_y] del cut_y # Create fixed resolution buffer to return back to the light cone object. # These buffers will be stacked together to make the light cone. frb = FixedResolutionBuffer( proj, (di_left_x, di_right_x * my_slice["box_width_fraction"], di_left_y, di_right_y * my_slice["box_width_fraction"]), (pixels, pixels), antialias=False) return frb
# Load data by calling yt #--------------------------------------------------------------------- for i in dumps: # get simulation directory mySim = AI.AthenaSimulation(Sim2DRun1) file = mySim.getFilepath(i, ext='.vtk') # now call yt ds = yt.load(file) # load dataset gs = ds.index.select_grids(ds.index.max_level) # load all grids grid = gs[0] # main grid # create a frb: antialias must be True if you don't want your data altered prj = ds.proj('density', 2) prj_frb = FixedResolutionBuffer(prj, (xo, xf, yo, yf), (ypix, xpix), antialias=True, periodic=True) # load all specified variables for var in vars: new_prj = prj_frb[var] img = np.array(new_prj) if PNG_IMAGES: img_name = var + "%03d" % (i, ) write_image(img, imagefolder + img_name + '.png', cmap_name='Spectral') else: img_name = var + ` i ` varfile = open(imagefolder + img_name, 'w') np.save(varfile, img)
def _regenerate_buffer(self): new_buffer = FixedResolutionBuffer( self.source, self.xlim + self.ylim, self.size) self._buffer = new_buffer
# make a derived field, call h2density (for yt Clump() to work) def _h2density(field, data): try: return data["density"] * data["H2"] except: return data[("stream", "density")] * data[("stream", "H2")] from yt.units import dimensions ds.add_field(("stream", "h2density"), function=_h2density, units="code_mass/code_length**3") print dd['h2density'].max() assert (dd['H2'] * dd['density']).max() == dd['h2density'].max() # prj = yt.ProjectionPlot(ds, # 0, # "h2density", # center='c') prj = ds.proj("h2density", 0) # prj.annotate_clumps(leaf_clumps) frb = FixedResolutionBuffer(prj, (-1,1,-1,1), (800,800)) my_image = frb["h2density"] fits.writeto("my_images.fits", my_image)
def display_yt(data_object, field): # Note what we are doing here: we are taking *views* of these, # as the logic in the ndarray traittype doesn't check for subclasses. frb = WidgytsCanvasViewer.from_obj(data_object, field) controls = frb.setup_controls() return ipywidgets.HBox([controls, frb])
def sim_frame_varAnimation(frame_args): def _amr_grid(all): if not int(frame_args.amrGrid): return None g = [] for b, _ in all.blocks: g.append([ [float(b.LeftEdge[0] / 100), float(b.RightEdge[0] / 100)], [float(b.LeftEdge[1] / 100), float(b.RightEdge[1] / 100)], ]) return g _init_yt() from yt.visualization import plot_window from yt.visualization.fixed_resolution import FixedResolutionBuffer f = frame_args.var ds = yt.load(str(_h5_file_list(frame_args.run_dir)[frame_args.frameIndex])) axis = ['x', 'y', 'z'].index(frame_args.axis) (bounds, center, display_center) = plot_window.get_window_parameters(axis, 'c', None, ds) slc = ds.slice(axis, center[axis], center=center) all = ds.all_data() dim = ds.domain_dimensions scale = 2 ** all.max_level if axis == 0: buff_size = (dim[1] * scale, dim[2] * scale) elif axis == 1: buff_size = (dim[0] * scale, dim[2] * scale) else: buff_size = (dim[0] * scale, dim[1] * scale) #TODO(pjm): antialis=True is important to get grid aligned? d = FixedResolutionBuffer(slc, bounds, buff_size, True)[f] l = PKDict( cartesian=PKDict( x=PKDict(x='y', y='z'), y=PKDict(x='z', y='x'), z=PKDict(x='x', y='y'), ), cylindrical=PKDict( r=PKDict(x='theta', y='z'), z=PKDict(x='r', y='theta'), theta=PKDict(x='r', y='z'), ), polar=PKDict( r=PKDict(x='phi', y='z'), phi=PKDict(x='r', y='z'), z=PKDict(x='r', y='phi'), ), spherical=PKDict( r=PKDict(x='theta', y='phi'), theta=PKDict(x='r', y='phi'), phi=PKDict(x='r', y='theta'), ), ) g = frame_args.sim_in.models.Grid_GridMain.geometry aspect_ratio = buff_size[1] / buff_size[0] return PKDict( global_max=float(frame_args.vmax) if frame_args.vmax else None, global_min=float(frame_args.vmin) if frame_args.vmin else None, subtitle='Time: {}, Plot {}'.format( _time_and_units(ds.parameters['time']), frame_args.frameIndex + 1, ), title='{}'.format(f), x_label=f'{l[g][frame_args.axis].x} [m]', x_range=[ds.parameters['xmin'] / 100, ds.parameters['xmax'] / 100, d.shape[1]], y_label=f'{l[g][frame_args.axis].y} [m]', y_range=[ds.parameters['ymin'] / 100, ds.parameters['ymax'] / 100, d.shape[0]], z_matrix=d.tolist(), amr_grid=_amr_grid(all), aspectRatio=aspect_ratio, summaryData=PKDict( aspectRatio=aspect_ratio, ), )
def plotselecthalos(axis, sim, halos, select, output): """ Function that plots a projection of the cube with selected halos """ import matplotlib as mpl import yt from yt.visualization.fixed_resolution import FixedResolutionBuffer import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np #define axis and permutation ax = {'x': 0, 'y': 1, 'z': 2} ax1 = {'x': 'y', 'y': 'z', 'z': 'x'} ax2 = {'x': 'z', 'y': 'x', 'z': 'y'} #make a projection by hand along one axis global resol resol = 512 global boxsize boxsize = (sim.domain_width.in_units('Mpccm/h'))[0].v #comoving Mpc/h projx = sim.proj(("deposit", "all_density"), ax[axis]) image2d = FixedResolutionBuffer(projx, (0.0, 0.999, 0.0, 0.999), (resol, resol)) #some display stuff fig = plt.figure(1, figsize=(8, 8), dpi=300) imgplot = plt.imshow(np.log10(image2d["deposit", "all_density"].v), origin='lower') imgplot.set_clim(-3, -1) #cbar=plt.colorbar() #cbar.set_label('log Density'+' (g cm$^{-2}$)', rotation=90) #loop over the halos and plot them print "Looping over selected ", select.size for hh in range(select.size): radius = 10 * halos['rvir'][select[hh]] * 1e-3 #cMpc/h circle = plt.Circle((halos[ax1[axis]][select[hh]] * resol / boxsize, halos[ax2[axis]][select[hh]] * resol / boxsize), radius=radius, fc='None', ec='black', linewidth=1) plt.gca().add_patch(circle) plt.gca().text(halos[ax1[axis]][select[hh]] * resol / boxsize - 10, halos[ax2[axis]][select[hh]] * resol / boxsize - 10, str(halos['id'][select[hh]]), fontsize=8, color='black') #map the axis to box size plt.xlabel(ax1[axis] + ' (cMpc h$^{-1}$)') plt.ylabel(ax2[axis] + ' (cMpc h$^{-1}$)') axe1 = plt.gca() axe1.xaxis.set_major_formatter(mpl.ticker.FuncFormatter(mjrFormatter)) axe1.yaxis.set_major_formatter(mpl.ticker.FuncFormatter(mjrFormatter)) plt.savefig(output + "_" + axis + "_proj.ps") fig.clf()