def create_profile(infile): ds = yt.load(infile) ad = ds.all_data() profile = yt.create_profile(ad, args.axis, fields=[args.field], weight_field=None, n_bins=args.nbins, logs={args.axis: args.axis_log, args.field: args.field_log}) return profile
def profile_plot(center_of_mass, filename): sp = ds.sphere(center_of_mass, (30, 'kpc')) profiles = yt.create_profile(sp, 'radius', fields.values()) for fieldname, field in fields.iteritems(): plt.loglog(profiles.x, profiles[field], label=fieldname) plt.xlim([profiles.x.min(), profiles.x.max()]) plt.xlabel('Radius $[kpc]$') plt.ylabel('$\\rho [M_{\odot} kpc^{-3}]$') plt.legend(loc='best') plt.savefig(filename) plt.clf()
def doit(filename): ds = yt.load(filename) ad = ds.all_data() profile = yt.create_profile(ad, args.binfields, args.fields, n_bins=tuple(args.nbins), weight_field=None) print(profile.keys()) print(profile["enucdot"].shape) print(profile["y"].shape) for y, e in zip(profile["y"], profile["enucdot"]): print('({}, {})'.format(y, e)) exit() return ds.time, emax, elocmax, efwhm
def det_fil_profile(start,end,var,weight,radius,ds): #Function to return a list of the weighted average of a variable for a list of concentric disks #Get the disk object cyl = gen_cyl(start,end,radius,ds) #Create a profile if weight == "": weight = None profile = yt.create_profile(cyl,"cylindrical_radius", var, weight_field=weight,n_bins=10,units={"cylindrical_radius":'Mpc'},extrema={"cylindrical_radius":(0.1,2.0)}) return profile
def compute_histogram(self, cids, range=None, bins=None, log=None, subset_state=None): fields = [tuple(cid.label.split()) for cid in cids] profile = yt.create_profile(self.region, fields, ['ones'], n_bins=bins[0], extrema={fields[0]: range[0]}, logs={fields[0]: log[0]}, weight_field=None) return profile['ones']
def make_prof_cut(Object, cut, fields): cr = ds.cut_region(Object, [cut]) prof = yt.create_profile( data_source=cr, bin_fields=["radius"], fields=fields, n_bins=60., units=dict(radius="kpc", rv="km/s"), logs=dict(radius=False), weight_field='cell_volume', extrema=dict(radius=(0,2.2*Rvir.value)), ) return prof
def DM_dens_prof(ds,sph,simtype,curr_sim,curr_halo): print datetime.now().strftime('%H:%M:%S'),'Making DM Density Profile Plot of halo #%d'%(curr_halo) field_type = 'deposit' field = 'io_density' weight= None rp = yt.create_profile(sph, 'radius', (field_type,field),weight_field=weight) output = yt.ProfilePlot(sph, "radius", (field_type,field),x_log=None,y_log=None) output.set_unit('radius', 'Mpccm/h') output.set_unit(field, 'Msun/kpc**3') output.set_log('radius',False) output.save('%s_%s_%d_prof_%s.png'%(simtype,curr_sim,curr_halo,field)) return rp
def ratio_pair(field, ad_pre=None, ad_cores=None, extrema={}, zlim=[1e-2, 1e4]): pdf_pre = yt.create_profile(ad_pre, [field[0], field[1]], field[2], weight_field=None, fractional=False, extrema=extrema) fig, ax = plt.subplots() norm = colors.LogNorm(vmin=zlim[0], vmax=zlim[1]) # vmin=1e-4, vmax=1 norm = None z_pre = pdf_pre[field[2]] pre_plot = ax.pcolormesh(z_pre, norm=norm) ##changed plt to ax #pre_plot.set_norm(norm) #locator = LogLocator() #formatter = LogFormatter() #cbar = fig.colorbar(pre_plot,ax=ax,norm=norm) ## can add ticks=[] #Set color to be used for low out-of-range values: #cbar.cmap.set_under('w') #cbar.locator = locator #cbar.formatter = formatter #cbar.update_normal(pre_plot) #cbar.set_cmap('arbre') #cbar.set_clim(vmin=1e-2,vmax=1e4) #cbar.ax.set_ylabel(r'density ($g/cm^3$)') #(r'cell_volume ($cm^3$)') ax.set_xlabel(r'%s' % (field[0])) ax.set_ylabel(r'%s' % (field[1])) xticks = ax.get_xticks().astype('int') these_xbins = pdf_pre.x_bins new_labels = tick_fixer(xticks, these_xbins) ax.set_xticklabels(new_labels) yticks = ax.get_yticks().astype('int') these_ybins = pdf_pre.y_bins new_labels = tick_fixer(yticks, these_ybins) ax.set_yticklabels(new_labels, rotation='45') outname = '/home/dcollins4096/PigPen/plot_test_%s_%s_%s.png' % tuple(field) plt.savefig(outname) print(outname) return {'pdf_pre': pdf_pre, 'ax': ax}
def prof_temp_halo(ds,sph,simtype,curr_sim,curr_halo): "This function makes a profile of the halo chosen, saves it, and returns the profile as an object for future use" print datetime.now().strftime('%H:%M:%S'),'Making gas temperature Profile Plot of halo #%d'%(curr_halo) fieldtype = 'gas' field = 'temperature' weight= None rp = yt.create_profile(sph,'radius',(fieldtype,field),weight_field=weight) plot = yt.ProfilePlot(sph,'radius',(fieldtype,field),weight_field=weight) plot.set_unit('radius', 'Mpccm/h') plot.set_unit(field, 'K') plot.set_log('radius',False) plot.save('%s_%s_%d_prof_%s.png'%(simtype,curr_sim,curr_halo,field)) #Return the profile object for future use. return rp
def main(**kwargs): dir = kwargs['base_directory'] + kwargs['directory'] fname = glob.glob(dir + 'id0/' + kwargs['id'] + '.????.vtk') fname.sort() ngrids = len(glob.glob(dir + 'id*/' + kwargs['id'] + fname[-9:])) comm = yt.communication_system.communicators[-1] nprocs = comm.size print ngrids, nprocs if yt.is_root(): if not os.path.isdir(dir + 'phase/'): os.mkdir(dir + 'phase/') for f in fname: phfname = dir + 'phase/' + kwargs['id'] + f[-9:-4] + '.phase.p' if os.path.isfile(phfname): print '%s is already there' % phfname else: if ngrids > nprocs: ds = yt.load(f, units_override=unit_base) else: ds = yt.load(f, units_override=unit_base, nprocs=nprocs * 8) le = np.array(ds.domain_left_edge) re = np.array(ds.domain_right_edge) sq = ds.box(le, re) pdfs = my_pdf(sq) for bf in bin_fields: n_bins = (aux[bf[0]]['n_bins'], aux[bf[1]]['n_bins']) logs = {} unit = {} extrema = {} for b in bf: logs[b] = aux[b]['log'] if aux[b].has_key('unit'): unit[b] = aux[b]['unit'] if aux[b].has_key('limits'): extrema[b] = aux[b]['limits'] pdf = yt.create_profile(sq, bf, fields=fields, n_bins=n_bins, logs=logs, extrema=extrema, units=unit, weight_field=None, fractional=True) pdfs.add_pdf(pdf, bf) if yt.is_root(): pickle.dump(pdfs, open(phfname, 'wb'), pickle.HIGHEST_PROTOCOL)
def test_profile_zero_weight(): def DMparticles(pfilter, data): filter = data[(pfilter.filtered_type, "particle_type")] == 1 return filter def DM_in_cell_mass(field, data): return data["deposit", "DM_density"] * data["index", "cell_volume"] add_particle_filter("DM", function=DMparticles, filtered_type="io", requires=["particle_type"]) _fields = ( "particle_position_x", "particle_position_y", "particle_position_z", "particle_mass", "particle_velocity_x", "particle_velocity_y", "particle_velocity_z", "particle_type", ) _units = ("cm", "cm", "cm", "g", "cm/s", "cm/s", "cm/s", "dimensionless") ds = fake_random_ds(32, particle_fields=_fields, particle_field_units=_units, particles=16) ds.add_particle_filter("DM") ds.add_field( ("gas", "DM_cell_mass"), units="g", function=DM_in_cell_mass, sampling_type="cell", ) sp = ds.sphere(ds.domain_center, (10, "kpc")) profile = yt.create_profile( sp, [("gas", "density")], [("gas", "radial_velocity")], weight_field=("gas", "DM_cell_mass"), ) assert not np.any(np.isnan(profile["gas", "radial_velocity"]))
def get_3d_profile(self, ds, variables): """ get radial profiles from 3d data """ source = ds.sphere([0, 0, 0], (self.rmax, "cm")) yt_profile = yt.create_profile( source, "radius", variables, n_bins=self.nbins, extrema={'radius': (self.dr / 2, self.rmax + self.dr / 2)}, logs={'radius': False}, weight_field='cell_mass', accumulation=False) for var in variables: self.profiles[var] = yt_profile[var].v return
def make_profile(ds): slice = ds.r[:, :, z_position] L = ds.domain_width.v[0] print(L) center = [0.5 * L, 0.5 * L, 0] slice.set_field_parameter("center", center) rp = yt.create_profile(slice, "cylindrical_radius", fields=["rho", "S_azimuth"], n_bins=N_bins, weight_field="weighting_field", extrema={"cylindrical_radius": (r_min, r_max)}) rho = rp["rho"].value rho_J = rp["S_azimuth"].value J = rho_J / rho R = rp.x.value print("made profile") return (R, rho, J)
def plot_entropy_profile_evolution(basename, RDnums, fileout): n = len(RDnums) colors = pl.cm.viridis(np.linspace(0, 1, n)) #fig,ax = plt.subplots(2,1) for i in range(len(RDnums)): ds = yt.load(basename + ('/RD00' + str(RDnums[i])) * 2) center_guess = initial_center_guess(ds, track_name) halo_center, halo_velocity = get_halo_center(ds, center_guess) rb = sym_refine_box(ds, halo_center) rp = yt.create_profile(rb, 'radius', ['entropy', 'total_energy'], units={'radius': 'kpc'}, logs={'radius': False}) zhere = "%.2f" % ds.current_redshift plt.figure(1) plt.plot(rp.x.value, rp['entropy'].value, color=colors[i], lw=2.0, label=zhere) plt.xlim(0, 200) plt.figure(2) plt.plot(rp.x.value, np.log10(rp['total_energy'].value), color=colors[i], lw=2.0, label=zhere) plt.figure(1) plt.legend() plt.xlabel('Radius [kpc]') plt.ylabel('Entropy') plt.savefig(fileout + '_entropy.pdf') plt.figure(2) plt.legend() plt.xlabel('Radius [kpc]') plt.ylabel('Energy') plt.savefig(fileout + '_energy.pdf') plt.close() return
def generate_profiles(ds, field_list, R = 2000, n_bins = 100, center_method = 'gpot'): start = time.time() # Find the gravitational potential minimum center = find_center(ds, center_method) # Make a sphere at this point sp = ds.sphere(center, ds.quan(R, 'kpc')) print('Creating profiles') profile = yt.create_profile(sp, 'radius', field_list, n_bins=n_bins) end = time.time() print('Finished creating profiles -- %f s' % (end-start)) return profile, center
def phase(filename,out_dir='',write_file=True,write_figure=True): ds=yt.load(filename,units_override=ya.unit_base,unit_system=tigress_unit_system) ya.add_yt_fields(ds,cooling=True,mhd=True,rotation=False) sp=ds.sphere(ds.domain_center,ds.domain_right_edge[0]) total_mass=sp.sum('cell_mass') print total_mass.in_units('Msun') for bf in bin_fields: xbin,ybin=bf pdf=yt.create_profile(sp,bf,field,extrema=extrema,logs=logs, n_bins=128,weight_field=None) outhead1='{}{}_{}_{}_{}'.format(out_dir,ds,xbin,ybin,field) if write_file: pdf.save_as_dataset(outhead1) if write_figure: p=pdf.plot() outhead2='{}.png'.format(outhead1) p.save(outhead2)
def _plot_ds_field(ds, field): disk = ds.disk(c, normal, radius, height) radial_profile = yt.create_profile( data_source=disk, bin_fields=["radius"], fields=field, n_bins=256, units=dict(radius="kpc"), logs=dict(radius=False), weight_field='cell_mass', extrema={'radius': (0, 300)}, ) p = yt.ProfilePlot.from_profiles(radial_profile) if (field != 'angular_momentum_magnitude'): p.set_ylim(field, -2e70, 2e70) else: p.set_ylim(field, 0, 1e70) p.set_log('%s' % field, False) p.save('radius_300/cell_mass/%s/%s' % (field, ds))
def createNormalProfile(Param_Dict): """Create a Profile plot for the selected x-and y-field. Return an array containing the data and a label. Parameters: Param_Dict: For the fields and DataSets to be plotted. Returns: arr: list containing two YTArrays having the x-field as the first and the y-field as second entry. """ # Create a data container to hold the whole dataset. ds = Param_Dict["CurrentDataSet"] ad = ds.all_data() # Create a 1d profile of density vs. temperature. prof = yt.create_profile(ad, Param_Dict["XAxis"], fields=[Param_Dict["YAxis"]], weight_field=Param_Dict["WeightField"]) labels = [Param_Dict["YAxis"]] arr = [prof.x, prof[Param_Dict["YAxis"]]] return arr, labels
def phase_part(ds, region, out_dir, params, overwrite=False): ''' calculate 2D joint PDFs using yt Inputs ------ ds: YTDataSet region: YTRegion out_dir: string directory name for output hdf files to be saved will be created if doesn't exist params: class (phase_parameters) Parameters ---------- overwrite: bool if false, skip it if file exists ''' logs = params.logs extrema = params.extrema bin_fields = params.bin_fields nbins = params.nbins if not os.path.isdir(out_dir): os.mkdir(out_dir) for bf in bin_fields: xbin, ybin = bf outhead1 = '{}{}-{}-{}'.format(out_dir, ds, xbin, ybin) if not os.path.isfile(outhead1 + '.h5') or overwrite: pdf = yt.create_profile(region, bf, ['cell_mass', 'cell_volume'], extrema=extrema, logs=logs, n_bins=nbins, weight_field=None) pdf.save_as_dataset(outhead1)
def do_phase(ds, fields=['density', 'pressure', 'cell_volume'], phase_args={}, weight_field=None, n_bins=[64, 64], prefix='RUN'): phase_args['bin_fields'] = [fields[0], fields[1]] phase_args['fields'] = [fields[2]] phase_args['weight_field'] = weight_field #phase_args['extrema']=local_extrema phase_args['n_bins'] = n_bins reg = ds.all_data() phase = yt.create_profile(reg, **phase_args) #self.phase = weakref.proxy(phase) pp = yt.PhasePlot.from_profile(phase) pp.set_xlabel(fields[0]) pp.set_ylabel(fields[1]) callback = equillibrium_callback() callback(pp) pp.save(prefix)
def phase(sq,phfname,bin_fields,aux={}): pdfs=my_pdf(sq) for bf in bin_fields: nbin1, nbin2=(128, 128) if bf[0] in aux: nbin1=aux[bf[0]]['n_bins'] if bf[1] in aux: nbin2=aux[bf[1]]['n_bins'] n_bins=(nbin1, nbin2) logs={} unit={} extrema={} for b in bf: logs[b]=False if b in aux: if 'log' in aux[b]: logs[b]=aux[b]['log'] if 'unit' in aux[b]: unit[b]=aux[b]['unit'] if 'limints' in aux[b]: extrema[b]=aux[b]['limits'] pdf=yt.create_profile(sq,bf,fields=fields, n_bins=n_bins,logs=logs,extrema=extrema,units=unit, weight_field=None,fractional=True) pdfs.add_pdf(pdf,bf) if yt.is_root(): pickle.dump(pdfs,open(phfname,'wb'),pickle.HIGHEST_PROTOCOL)
def get_data(data_sub_dir, number, R_min, R_max): dsi = yt.load(data_root_path + "/" + data_sub_dir + "/KerrSFp_{:06d}.3d.hdf5".format(number)) print("loaded dataset number " + str(number) + " for " + data_sub_dir) slice = dsi.r[:, :, z_position] slice.set_field_parameter("center", center) # weighting field = (cell_volume)^(2/3) / (2*pi * r * dr) @derived_field(name="weighting_field", units="", force_override=True) def _weighting_field(field, data): return pow(data["cell_volume"].in_base("cgs"), 2.0 / 3) * N_bins / (2 * math.pi * data["cylindrical_radius"] * (R_max - R_min) * cm) rp = yt.create_profile(slice, "cylindrical_radius", fields=["phi"], n_bins=128, weight_field="weighting_field", extrema={"cylindrical_radius": (R_min, R_max)}) phi = rp["phi"].value R = rp.x.value print("made profile") return (R, phi)
print ds.print_stats() # In[10]: sp = ds.sphere("c", (100.0, "kpc")) ## Radius vs. Ionizing Species Abundances # In[11]: rmin = 1.0 rmax = 100.0 prof_h = yt.create_profile(sp, 'radius', ('flash', 'h '), units = {'radius': 'kpc'}, extrema = {'radius': ((rmin,'kpc'),(rmax,'kpc'))}) prof_hel = yt.create_profile(sp, 'radius', ('flash', 'hel '), units = {'radius': 'kpc'}, extrema = {'radius': ((rmin,'kpc'),(rmax,'kpc'))}) prof_hplu = yt.create_profile(sp, 'radius', ('flash', 'hplu'), units = {'radius': 'kpc'}, extrema = {'radius': ((rmin,'kpc'),(rmax,'kpc'))}) prof_hep = yt.create_profile(sp, 'radius', ('flash', 'hep '), units = {'radius': 'kpc'}, extrema = {'radius': ((rmin,'kpc'),(rmax,'kpc'))}) prof_hepp = yt.create_profile(sp, 'radius', ('flash', 'hepp'), units = {'radius': 'kpc'}, extrema = {'radius': ((rmin,'kpc'),(rmax,'kpc'))})
time = [] radius = [] for i in range(first, last + 1): amrfile = "DD%4.4d/data%4.4d" % (i, i) pf = yt.load(amrfile) x_bins_1d = 32 r_min = pf.index.get_smallest_dx() r_max = pf.quan(1.0 - 1.0 / 64, 'code_length') sphere = pf.h.sphere(center, r_max) prof1d = yt.create_profile(sphere, 'radius', fields=["Neutral_Fraction", "HI_kph"], n_bins=x_bins_1d, units={'radius': 'code_length'}) # Find the radius of the I-front (f_HI=0.5) res = np.abs(prof1d["Neutral_Fraction"] - 0.5) ir = np.where(res == res.min())[0] r = np.interp(0.5, prof1d["Neutral_Fraction"], prof1d.x.value) r = pf.quan(r, 'code_length') time.append(pf.current_time.to('s')) radius.append(r.to('cm')) del pf del prof1d time = np.array(time)
def test_particle_profile_negative_field(): # see Issue #1340 n_particles = int(1e4) ppx, ppy, ppz = np.random.normal(size=[3, n_particles]) pvx, pvy, pvz = -np.ones((3, n_particles)) data = { 'particle_position_x': ppx, 'particle_position_y': ppy, 'particle_position_z': ppz, 'particle_velocity_x': pvx, 'particle_velocity_y': pvy, 'particle_velocity_z': pvz } bbox = 1.1 * np.array([[min(ppx), max(ppx)], [min(ppy), max(ppy)], [min(ppz), max(ppz)]]) ds = yt.load_particles(data, bbox=bbox) ad = ds.all_data() profile = yt.create_profile(ad, ["particle_position_x", "particle_position_y"], "particle_velocity_x", logs={ 'particle_position_x': True, 'particle_position_y': True, 'particle_position_z': True }, weight_field=None) assert profile['particle_velocity_x'].min() < 0 assert profile.x_bins.min() > 0 assert profile.y_bins.min() > 0 profile = yt.create_profile(ad, ["particle_position_x", "particle_position_y"], "particle_velocity_x", weight_field=None) assert profile['particle_velocity_x'].min() < 0 assert profile.x_bins.min() < 0 assert profile.y_bins.min() < 0 # can't use CIC deposition with log-scaled bin fields with assert_raises(RuntimeError): yt.create_profile(ad, ["particle_position_x", "particle_position_y"], "particle_velocity_x", logs={ 'particle_position_x': True, 'particle_position_y': False, 'particle_position_z': False }, weight_field=None, deposition='cic') # can't use CIC deposition with accumulation or fractional with assert_raises(RuntimeError): yt.create_profile(ad, ["particle_position_x", "particle_position_y"], "particle_velocity_x", logs={ 'particle_position_x': False, 'particle_position_y': False, 'particle_position_z': False }, weight_field=None, deposition='cic', accumulation=True, fractional=True)
field_bins = np.logspace(np.log10(field_min), np.log10(field_max), Nbins) bins = { 'thetaz': theta_bins, 'magnetic_field_strength': field_bins, 'magnetic_field_z': field_bins } # # Produce joint and marginalized distributions. # Formally these are not PDFs since we don't explicityly normalize, # BUT since the total volume is 1, they are in fact PDFs. # bin_fields = ['magnetic_field_strength', 'thetaz'] joint = yt.create_profile(region, bin_fields=bin_fields, fields=['cell_volume'], weight_field=None, override_bins=bins) prof_mag = yt.create_profile(region, bin_fields=['magnetic_field_strength'], fields=['cell_volume'], weight_field=None, override_bins=bins) prof_theta = yt.create_profile(region, bin_fields=['thetaz'], fields=['cell_volume'], weight_field=None, override_bins=bins) prof_bz = yt.create_profile(region, bin_fields=['magnetic_field_z'], fields=['cell_volume'],
# Load the dataset. ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") # Create a sphere of radius 1 Mpc centered on the max density location. sp = ds.sphere("max", (1, "Mpc")) # Calculate and store the bulk velocity for the sphere. bulk_velocity = sp.quantities.bulk_velocity() sp.set_field_parameter("bulk_velocity", bulk_velocity) # Create a 1D profile object for profiles over radius # and add a velocity profile. prof = yt.create_profile( sp, "radius", ("gas", "velocity_magnitude"), units={"radius": "kpc"}, extrema={"radius": ((0.1, "kpc"), (1000.0, "kpc"))}, weight_field="cell_mass", ) # Create arrays to plot. radius = prof.x mean = prof["gas", "velocity_magnitude"] std = prof.standard_deviation["gas", "velocity_magnitude"] # Plot the average velocity magnitude. plt.loglog(radius, mean, label="Mean") # Plot the variance of the velocity magnitude. plt.loglog(radius, std, label="Standard Deviation") plt.xlabel("r [kpc]") plt.ylabel("v [cm/s]")
import yt import matplotlib.pyplot as plt ds = yt.load("GasSloshing/sloshing_nomag2_hdf5_plt_cnt_0150") # Get a sphere object sp = ds.sphere(ds.domain_center, (500., "kpc")) # Bin up the data from the sphere into a radial profile rp = yt.create_profile(sp, 'radius', ['density', 'temperature'], units = {'radius': 'kpc'}, logs = {'radius': False}) # Make plots using matplotlib fig = plt.figure() ax = fig.add_subplot(111) # Plot the density as a log-log plot using the default settings dens_plot = ax.loglog(rp.x.value, rp["density"].value) # Here we set the labels of the plot axes ax.set_xlabel(r"$\mathrm{r\ (kpc)}$") ax.set_ylabel(r"$\mathrm{\rho\ (g\ cm^{-3})}$") # Save the default plot fig.savefig("density_profile_default.png" % ds)
@derived_field(name="slice_weighting_field", units="") def _slice_weighting_field(field, data): return pow(data["cell_volume"].in_base("cgs"), 2.0 / 3) * N_bins / (2 * math.pi * (data["cylindrical_radius"]) * (r_max - r_min) * cm) sphere = ds.sphere(center, r_max) slice = ds.r[:, :, z_position] slice.set_field_parameter("center", center) # make profile rp_sphere = yt.create_profile(sphere, "spherical_radius", fields=["phi"], n_bins=N_bins, weight_field="sphere_weighting_field", extrema={"spherical_radius": (r_min, r_max)}) rp_slice = yt.create_profile(slice, "spherical_radius", fields=["phi"], n_bins=N_bins, weight_field="slice_weighting_field", extrema={"spherical_radius": (r_min, r_max)}) ### plot profile r_plus = 1 + math.sqrt(1 - a**2) R_1 = rp_sphere.x.value phi_1 = rp_sphere["phi"].value r_BL_1 = R_1 * (1 + r_plus / (4 * R_1))**2
import yt # Load the dataset. ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") # Create a sphere of radius 1 Mpc centered on the max density location. sp = ds.sphere("max", (1, "Mpc")) # Calculate and store the bulk velocity for the sphere. bulk_velocity = sp.quantities.bulk_velocity() sp.set_field_parameter('bulk_velocity', bulk_velocity) # Create a 1D profile object for profiles over radius # and add a velocity profile. prof = yt.create_profile(sp, 'radius', ('gas', 'velocity_magnitude'), units = {'radius': 'kpc'}, extrema = {'radius': ((0.1, 'kpc'), (1000.0, 'kpc'))}, weight_field='cell_mass') # Create arrays to plot. radius = prof.x mean = prof['gas', 'velocity_magnitude'] std = prof.standard_deviation['gas', 'velocity_magnitude'] # Plot the average velocity magnitude. plt.loglog(radius, mean, label='Mean') # Plot the variance of the velocity magnitude. plt.loglog(radius, std, label='Standard Deviation') plt.xlabel('r [kpc]') plt.ylabel('v [cm/s]') plt.legend()
import yt import yt.units as u ds = yt.load("HiresIsolatedGalaxy/DD0044/DD0044") center = [0.53, 0.53, 0.53] normal = [0, 0, 1] radius = 40 * u.kpc height = 5 * u.kpc disk = ds.disk(center, [0, 0, 1], radius, height) profile = yt.create_profile( data_source=disk, bin_fields=[("index", "radius")], fields=[("gas", "velocity_cylindrical_theta")], n_bins=256, units=dict(radius="kpc", velocity_cylindrical_theta="km/s"), logs=dict(radius=False), weight_field=("gas", "mass"), extrema=dict(radius=(0, 40)), ) plot = yt.ProfilePlot.from_profiles(profile) plot.set_log(("gas", "velocity_cylindrical_theta"), False) plot.set_ylim(("gas", "velocity_cylindrical_theta"), 60, 160) plot.save()
import yt import matplotlib.pyplot as plt ds = yt.load("GasSloshing/sloshing_nomag2_hdf5_plt_cnt_0150") # Get a sphere object sp = ds.sphere(ds.domain_center, (500., "kpc")) # Bin up the data from the sphere into a radial profile rp = yt.create_profile(sp, 'radius', ['density', 'temperature'], units={'radius': 'kpc'}, logs={'radius': False}) # Make plots using matplotlib fig = plt.figure() ax = fig.add_subplot(111) # Plot the density as a log-log plot using the default settings dens_plot = ax.loglog(rp.x.value, rp["density"].value) # Here we set the labels of the plot axes ax.set_xlabel(r"$\mathrm{r\ (kpc)}$") ax.set_ylabel(r"$\mathrm{\rho\ (g\ cm^{-3})}$") # Save the default plot
import yt.units as u ds = yt.load('HiresIsolatedGalaxy/DD0044/DD0044') center = [0.53, 0.53, 0.53] normal = [0,0,1] radius = 40*u.kpc height = 2*u.kpc disk = ds.disk(center, [0,0,1], radius, height) profile = yt.create_profile( data_source=disk, bin_fields=["radius", "cylindrical_tangential_velocity"], fields=["cell_mass"], n_bins=256, units=dict(radius="kpc", cylindrical_tangential_velocity="km/s", cell_mass="Msun"), logs=dict(radius=False, cylindrical_tangential_velocity=False), weight_field=None, extrema=dict(radius=(0,40), cylindrical_tangential_velocity=(-250, 250)), ) plot = yt.PhasePlot.from_profile(profile) plot.set_cmap("cell_mass", "YlOrRd") plot.save()
# Load the dataset. ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") # Create a sphere of radius 1 Mpc centered on the max density location. sp = ds.sphere("max", (1, "Mpc")) # Calculate and store the bulk velocity for the sphere. bulk_velocity = sp.quantities.bulk_velocity() sp.set_field_parameter("bulk_velocity", bulk_velocity) # Create a 1D profile object for profiles over radius # and add a velocity profile. prof = yt.create_profile( sp, "radius", ("gas", "velocity_magnitude"), units={"radius": "kpc"}, extrema={"radius": ((0.1, "kpc"), (1000.0, "kpc"))}, weight_field="cell_mass", ) # Create arrays to plot. radius = prof.x.value mean = prof["gas", "velocity_magnitude"].value variance = prof.variance["gas", "velocity_magnitude"].value # Plot the average velocity magnitude. plt.loglog(radius, mean, label="Mean") # Plot the variance of the velocity magnitude. plt.loglog(radius, variance, label="Standard Deviation") plt.xlabel("r [kpc]") plt.ylabel("v [cm/s]")
import yt from yt.units import kpc import matplotlib.pyplot as plt dirprefix = "/scratch/cerberus/d4/mepa/" #dirname = "/scratch/01707/mepa/Rad_1Mpc/RadCosmoLW_res128/" dirname = dirprefix + "data/RadCosmo_res128/stampede/" filename = "radCosmoLW_hdf5_chk_0381" fn = dirname + filename ds = yt.load(fn) sp = ds.sphere("max", (100.0, "kpc")) prof1 = yt.create_profile(sp, 'radius', ('flash', 'h '), units = {'radius': 'kpc'}, extrema = {'radius': ((0.1, 'kpc'), (100.0, 'kpc'))}) prof2 = yt.create_profile(sp, 'radius', ('flash', 'hplu'), units = {'radius': 'kpc'}, extrema = {'radius': ((0.1, 'kpc'), (100.0, 'kpc'))}) prof3 = yt.create_profile(sp, 'radius', ('flash', 'hel '), units = {'radius': 'kpc'}, extrema = {'radius': ((0.1, 'kpc'), (100.0, 'kpc'))}) prof4 = yt.create_profile(sp, 'radius', ('flash', 'hep '), units = {'radius': 'kpc'}, extrema = {'radius': ((0.1, 'kpc'), (100.0, 'kpc'))}) prof5 = yt.create_profile(sp, 'radius', ('flash', 'hepp'), units = {'radius': 'kpc'}, extrema = {'radius': ((0.1, 'kpc'), (100.0, 'kpc'))}) radius = prof1.x.value h = prof1['flash', 'h '].value hplu = prof2['flash', 'hplu'].value
import yt import pylab ds = yt.load("plt164582") dd = ds.all_data() p = yt.create_profile(dd, "z", "temperature", n_bins=ds.domain_dimensions[2], weight_field="cell_volume", logs={"z": False}) #pylab.plot(p.x, p[("gas","temperature")]) pylab.plot(p.x, p.variance[("gas", "temperature")] / p[("gas", "temperature")]) ax = pylab.gca() ax.set_yscale("log") pylab.savefig("average.png")
hc = HaloCatalog(data_ds=ds, halos_ds=halos_ds) hc.load() halos = hc.halo_list fieldname = 'gas' fieldvalue = fields[fieldname] index = 0 halo = halos[index] # PROJECTION PLOT com = [halo.quantities['particle_position_x'], halo.quantities['particle_position_y'], halo.quantities['particle_position_z']] sp = ds.sphere(com, (30, 'kpc')) amv = sp.quantities.angular_momentum_vector() amv = amv / np.sqrt((amv**2).sum()) center = sp.quantities.center_of_mass() res = 1024 width = [0.01, 0.01, 0.01] image = yt.off_axis_projection(ds, center, amv, width, res, fieldvalue) yt.write_image(np.log10(image), '%s_%d_%s_offaxis_projection.png' % (ds, index, fieldname)) # PROFILE PLOT com = [halo.quantities['particle_position_x'], halo.quantities['particle_position_y'], halo.quantities['particle_position_z']] sp = ds.sphere(com, (30, 'kpc')) profiles = yt.create_profile(sp, 'radius', fields.values()) for fieldname, field in fields.iteritems(): plt.loglog(profiles.x, profiles[field], label=fieldname) plt.xlim([profiles.x.min(), profiles.x.max()]) plt.xlabel('Radius $[kpc]$') plt.ylabel('$\\rho [M_{\odot} kpc^{-3}]$') plt.legend(loc='best') plt.savefig('%s_%d_profile.png' % (ds, index))
sp0 = ds.sphere(ds.domain_center, (500., "kpc")) # Compute the bulk velocity from the cells in this sphere bulk_vel = sp0.quantities.bulk_velocity() # Get the second sphere sp1 = ds.sphere(ds.domain_center, (500., "kpc")) # Set the bulk velocity field parameter sp1.set_field_parameter("bulk_velocity", bulk_vel) # Radial profile without correction rp0 = yt.create_profile(sp0, 'radius', 'radial_velocity', units = {'radius': 'kpc'}, logs = {'radius': False}) # Radial profile with correction for bulk velocity rp1 = yt.create_profile(sp1, 'radius', 'radial_velocity', units = {'radius': 'kpc'}, logs = {'radius': False}) # Make a plot using matplotlib fig = plt.figure() ax = fig.add_subplot(111) ax.plot(rp0.x.value, rp0["radial_velocity"].in_units("km/s").value, rp1.x.value, rp1["radial_velocity"].in_units("km/s").value)
"time_unit":(UnitTime.value, UnitTime.units), "mass_unit":(UnitMass.value, UnitMass.units)}) masses = {} times = {} radii = {} i = rank while i < len(ts[:]): ds = ts[i] sphere = ds.sphere([0.,0.,0.], (2.2*Rvir.value, "kpc")) profile = yt.create_profile( data_source=sphere, bin_fields=["radius"], fields=["cell_mass"], n_bins=60., units=dict(radius="kpc", cell_mass="Msun"), logs=dict(radius=False), weight_field=None, extrema=dict(radius=(0,2.2*Rvir.value)), accumulation=True ) masses[i] = 1.*profile['cell_mass'].value times[i] = 1.*ds.current_time.in_units('yr').value radii[i] = 1.*profile.x.value i += size masses = comm.gather(masses, root=0) if rank == 0: all_masses = {} for d in masses: for k, v in d.iteritems():
return data["rho"]*pow(data["chi"],-3) @derived_field(name = "rho_J_eff", units = "") def _rho_J_eff(field, data): return data["S_azimuth"]*pow(data["chi"],-3) @derived_field(name = "rho_J_prime_eff", units = "") def _rho_J_prime_eff(field, data): return data["S_azimuth_prime"]*pow(data["chi"],-3)""" # make slice slice = ds.r[:,:,z_position] slice.set_field_parameter("center", center) # make profile rp_1 = yt.create_profile(slice, "spherical_radius", fields=["phi"], n_bins=128, weight_field="weighting_field", extrema={"spherical_radius" : (r_min, r_max)}) ### plot profile fig, ax1 = plt.subplots() colours = ['r', 'b'] """# plot phi R = rp_1.x.value r_plus = 1 + math.sqrt(1 - 0.99**2) r_BL = R*(1 + r_plus/(4*R))**2 r_star = r_BL + np.log(r_BL) r_3_4 = r_BL**(3.0/4) ax1.plot(np.log(r_BL), rp_1["phi"].value, colours[0] + '-') ax1.set_xlabel("$\\ln(r_{BL})$") ax1.set_ylabel("$\\phi$")
import yt import yt.units as u ds = yt.load('HiresIsolatedGalaxy/DD0044/DD0044') center = [0.53, 0.53, 0.53] normal = [0,0,1] radius = 40*u.kpc height = 5*u.kpc disk = ds.disk(center, [0,0,1], radius, height) profile = yt.create_profile( data_source=disk, bin_fields=["radius"], fields=["cylindrical_tangential_velocity_absolute"], n_bins=256, units=dict(radius="kpc", cylindrical_tangential_velocity_absolute="km/s"), logs=dict(radius=False), weight_field='cell_mass', extrema=dict(radius=(0,40)), ) plot = yt.ProfilePlot.from_profiles(profile) plot.set_log('cylindrical_tangential_velocity_absolute', False) plot.set_ylim('cylindrical_tangential_velocity_absolute', 60, 160) plot.save()
file_names.append("../../DD" + `i`.zfill(4) + "/" + "cloud_collision_" + `i`.zfill(4)) labels = [] for file in file_names: ds = yt.load(file) sphere = ds.sphere('max', (75, 'pc')) # calculate and stor the bulk velocity of the sphere bulk_velocity = sphere.quantities.bulk_velocity() sphere.set_field_parameter('bulk_velocity', bulk_velocity) # create 1d profile object for profiles over radius # and add a velocity profile. prof = yt.create_profile(sphere, 'radius', ('gas', 'velocity_magnitude'), units = {'radius': 'pc'}, extrema = {'radius': ((0.1, 'pc'), (75, 'pc'))}, weight_field ='cell_mass') # create arrays to plot radius = prof.x.value mean = prof['gas', 'velocity_magnitude'].value variance = prof.variance['gas', 'velocity_magnitude'].value # plot the variance of the velocity magnitude plt.loglog(radius, variance*1.0E-5, label="Standarad Deviation") labels.append(r"%0.2f Myr" % ds.current_time.value) plt.xlabel(r"Radius $(\mathrm{pc})$") plt.ylabel('v [km/s]') plt.xlim(1,75) plt.legend(labels, loc="lower left", frameon=False)
import yt # Create a time-series object. sim = yt.load_simulation("enzo_tiny_cosmology/32Mpc_32.enzo", "Enzo") sim.get_time_series(redshifts=[5, 4, 3, 2, 1, 0]) # Lists to hold profiles, labels, and plot specifications. profiles = [] labels = [] plot_specs = [] # Loop over each dataset in the time-series. for ds in sim: # Create a data container to hold the whole dataset. ad = ds.all_data() # Create a 1d profile of density vs. temperature. profiles.append( yt.create_profile(ad, [("gas", "density")], fields=[("gas", "temperature")])) # Add labels and linestyles. labels.append(f"z = {ds.current_redshift:.2f}") plot_specs.append(dict(linewidth=2, alpha=0.7)) # Create the profile plot from the list of profiles. plot = yt.ProfilePlot.from_profiles(profiles, labels=labels, plot_specs=plot_specs) # Save the image. plot.save()
sp = ds.sphere(center, (float(rvir.in_units('kpc')) * 2.25, 'kpc')) radius_bins = ds.arr( np.linspace(0, float(rvir.in_units('kpc')) * 2.25, num=100), 'kpc') print(rockstar_id) #print(radius_bins) #add set varialbles to none so if they do not get set, we see that when the get written rp_gas = yt.create_profile(sp, 'radius', [('gas', 'cell_mass')], accumulation=True, units={ 'radius': 'kpc', 'cell_mass': 'Msun' }, weight_field=None, override_bins={'radius': radius_bins}) rp_stars = yt.create_profile(sp, ('stars', 'particle_radius'), [('stars', 'particle_mass')], accumulation=True, units={ ('stars', 'particle_radius'): 'kpc', ('stars', 'particle_mass'): 'Msun' }, weight_field=None, override_bins={
ts = yt.load("id0/galaxyhalo.*.vtk", parameters= {"length_unit":(UnitLength.value, UnitLength.units), "time_unit":(UnitTime.value, UnitTime.units), "mass_unit":(UnitMass.value, UnitMass.units)}) i = rank while i < len(ts): ds = ts[i] sphere = ds.sphere([0.,0.,0.], (2.2*Rvir.value, "kpc")) profile = yt.create_profile( data_source=sphere, bin_fields=["radius"], fields=["density", "pressure", "temperature", "rv", "entropy", "tcool"], n_bins=60., units=dict(radius="kpc", rv="km/s"), logs=dict(radius=False), weight_field='cell_volume', extrema=dict(radius=(0,2.2*Rvir.value)), ) plt.loglog(profile.x, profile['density']) plt.xlabel('R[kpc]') plt.ylabel('Density [g/cm**3]') plt.savefig('Density_'+str(i).zfill(4)+'.png') plt.clf() plt.plot(profile.x, profile['rv']) plt.xlabel('R[kpc]') plt.ylabel('rv [km/s]') plt.savefig('rv_'+str(i).zfill(4)+'.png')