def make_energy_over_time(ds_paths, field_list, hdf5_directory, hdf5_filename, hdf5_groupname, region = 'sphere', r500_multiplier = 0.15, r200 = 1550, center_method = 'most_bound'): # try creating directory if it doesn't exist try: os.makedirs(hdf5_directory) except OSError as e: if e.errno != errno.EEXIST: raise ts = yt.DatasetSeries(ds_paths) ts_data = generate_energy_over_time(ts, field_list, region = region, r500_multiplier = r500_multiplier, r200 = r200, center_method = center_method) write_energy_over_time_to_hdf5(hdf5_directory + '/' + hdf5_filename, hdf5_groupname, ts_data, field_list)
def make_images(input_prefix,output_prefix,z_slice,min_dens,max_dens): ds_pattern = f"{input_prefix}_????/{input_prefix}_????.block_list" center = [0.0,0.0,z_slice] for ds in yt.DatasetSeries(ds_pattern): slc = yt.SlicePlot(ds,"z",("gas","density"), center = center, width = ds.domain_width[0]) box = ds.box(left_edge = -ds.domain_width/2.0, right_edge = ds.domain_width/2.0) sink_positions = [s for s in zip(box["sink","x"], box["sink","y"], box["sink","z"])] for s in sink_positions: slc.annotate_marker(s, coord_system = "data", plot_args = {'color':"k"}) slc.annotate_grids(linewidth = 0.5,alpha = 1.0) slc.set_zlim(("gas","density"),min_dens,max_dens) current_cycle = ds.parameters["current_cycle"] filename = f"{output_prefix}_{current_cycle:03}.png" slc.save(filename)
def test_tree_farm_descendents(self): ts = yt.DatasetSeries( os.path.join(test_data_dir, "fof_subfind/groups_02*/*.0.hdf5")) my_tree = TreeFarm(ts, setup_function=setup_ds) my_tree.set_selector("all") my_tree.trace_descendents("Group", filename="my_descendents/", fields=["virial_radius"]) a = ytree.load("my_descendents/fof_subhalo_tab_020.0.h5") assert isinstance(a, TreeFarmArbor) save_and_compare(a)
def yt_plot_mins(): initialize() tseries_toplot = yt.DatasetSeries(toplot, parallel=True) logging.getLogger().setLevel(logging.INFO) for ds in tseries_toplot.piter(): min, loc_min = ds.h.find_min('eint') print 'Plotting %s' % ds.basename plotSlices(ds, zoom_fac=4, center=loc_min, drawnozzle=False,\ markcenter=True, proj_axes=['x', 'y', 'z'],\ fields=['eint', 'pressure']) if yt.is_root(): t2 = time.time() print 'Total time: %.2f s\n--\ninitialization: %.2f s\nploting: %.2f'\ % (t2-t0, t1-t0, t2-t1)
def vol_renders(): """Volume render the simulations.""" import os import yt yt.enable_parallelism() results_base = 'results/approximate/' plots_base = 'plots/' for mass_P in ['0.90']: for mass_S in ['0.60', '0.90']: for roche in ['0.90', '1.00']: for rot in ['0', '1']: for hybrid in ['0', '1']: for ncell in ['256', '512', '1024']: mass_string = "_m_P_" + mass_P + "_m_S_" + mass_S results_dir = 'mass_P_' + mass_P + '/mass_S_' + mass_S + '/roche' + roche + '/rot' + rot + '/hybrid' + hybrid + '/n' + ncell + '/' output_dir = results_base + results_dir + '/output/' if not os.path.exists(output_dir): continue plot_list = wdmerger.get_plotfiles(output_dir, prefix='smallplt') plot_list = [output_dir + plot for plot in plot_list] plot_dir = plots_base + results_dir if not os.path.exists(plot_dir) and is_root(): os.makedirs(plot_dir) ts = yt.DatasetSeries(plot_list) for ds in ts.piter(): pltname = ds.basename outfile_name = plot_dir + 'approximate' + mass_string + '_roche_' + roche + '_rot_' + rot + '_hybrid_' + hybrid + '_n_' + ncell + '_' + pltname + '.png' if os.path.isfile(outfile_name): continue wdmerger.vol_render_density(outfile_name, ds)
def make_images(input_prefix, output_prefix): ds_pattern = f"{input_prefix}_????/{input_prefix}_????.block_list" for ds in yt.DatasetSeries(ds_pattern): box = ds.box(left_edge=-ds.domain_width / 2.0, right_edge=ds.domain_width / 2.0) x = box["sink", "x"] y = box["sink", "y"] z = box["sink", "z"] fig, ax = plt.subplots() ax.plot(x, y, marker="x", linestyle="None") ax.set_xlim(-ds.domain_width[0] / 2.0, ds.domain_width[0] / 2.0) ax.set_ylim(-ds.domain_width[0] / 2.0, ds.domain_width[0] / 2.0) ax.set_xlabel("x") ax.set_ylabel("y") current_cycle = ds.parameters["current_cycle"] filename = f"{output_prefix}_{current_cycle:03}.png" fig.savefig(filename) plt.close(fig)
def get_particles(haloname, simname, snapname): snaps = np.sort( np.asarray( glob.glob("/nobackupp2/mpeeples/%s/%s/%s/%s" % (haloname, simname, snapname, snapname)))) #abssnap = os.path.abspath(snaps[0]) assert os.path.lexists(snaps[0]) out_dir = '/u/rcsimons/' assert os.path.lexists(out_dir) new_snapfiles = np.asarray(snaps) ts = yt.DatasetSeries(new_snapfiles) def _stars(pfilter, data): return data[(pfilter.filtered_type, "particle_type")] == 2 def _darkmatter(pfilter, data): return data[(pfilter.filtered_type, "particle_type")] == 4 yt.add_particle_filter("stars", function=_stars, filtered_type='all', requires=["particle_type"]) yt.add_particle_filter("darkmatter", function=_darkmatter, filtered_type='all', requires=["particle_type"]) for ds, snapfile in zip(reversed(ts), np.flipud(new_snapfiles)): ad = ds.all_data() ds.add_particle_filter('stars') ds.add_particle_filter('darkmatter') dark_pos_x = ad['darkmatter', 'particle_position_x'].in_units('kpc') stars_pos_x = ad['stars', 'particle_position_x'].in_units('kpc') print shape(dark_pos_x), shape(stars_pos_x)
def test_tree_farm_ancestors(self): ts = yt.DatasetSeries( os.path.join(test_data_dir, "fof_subfind/groups_04*/*.0.hdf5")) ds = yt.load(ts.outputs[-1]) ad = ds.all_data() mw = ad["Group", "particle_mass"] > ds.quan(1e14, "Msun") mw_ids = ad["Group", "particle_identifier"][mw].d.astype(np.int64) my_tree = TreeFarm(ts, setup_function=setup_ds) my_tree.set_ancestry_filter("most_massive") my_tree.set_ancestry_short("above_mass_fraction", 0.5) my_tree.set_selector("all") my_tree.trace_ancestors("Group", mw_ids, filename="my_ancestors/", fields=["virial_radius"]) tfn = os.path.join("my_ancestors/%s.0.h5" % str(ds)) a = ytree.load(tfn) assert isinstance(a, TreeFarmArbor) save_and_compare(a)
#!/usr/bin/env python import matplotlib matplotlib.use('Agg') import os import sys import numpy as np import yt yt.enable_parallelism() #dir = '/home/ychen/data/0only_0529_h1/' dir = '/d/d11/ychen/MHD_jet/0517_L45_M10_b1_h1_20Myr' try: ind = int(sys.argv[1]) ts = yt.DatasetSeries(os.path.join(dir, '*_hdf5_plt_cnt_%02d?0' % ind), parallel=10) except IndexError: ts = yt.DatasetSeries(os.path.join(dir, '*_hdf5_plt_cnt_???0'), parallel=10) figuredir = os.path.join(dir, 'volume_rendering_temperature_clip4') annotateddir = os.path.join(figuredir, 'annotated') tfdir = os.path.join(figuredir, 'transfer_function') if yt.is_root(): for subdir in [figuredir, tfdir, annotateddir]: if not os.path.exists(subdir): os.mkdir(subdir) #fname = '/home/ychen/d9/FLASH4/stampede/0529_L45_M10_b1_h1/MHD_Jet_hdf5_plt_cnt_0620' #ds = yt.load(fname)
nskip = 1 # reduce number of images by factor finest = None # finest AMR level, either specify level or None for auto # region of slice: xlo, xhi, ylo, yhi, zlo, zhi region = np.array([-0.5, 0.5, -0.25, 0.25, 0.0, 1.0]) # if 2D plane, do NOT choose exact edge # region = np.array([-1.0, 1.0, -1.0, 1.0, 0.0, 2.0]) # if 2D plane, do NOT choose exact edge variables = ['z_velocity'] # variables for extraction yt.funcs.mylog.setLevel(30) # eliminate output from yt load # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # Find index of the start and end times # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # Create the array of plt directories and time of plt file all_plt_files = glob.glob("plt?????") all_ts = yt.DatasetSeries(all_plt_files, parallel=True) # Initialize storage array for all times and plt files time_storage = {} # Iterate through plt's to find time indices # this method leaves None's and index numbers for plt's not in time range for sto, ds in all_ts.piter(storage=time_storage): if ds.current_time >= starttime and ds.current_time <= endtime: sto.result = float(ds.current_time) sto.result_id = str(ds) # Convert the storage dictionary values to time and plt file names time1 = np.array(list(time_storage.values())) time = [x for x in time1 if x is not None] numplt1 = np.array(list(time_storage.keys()))
import yt try: from mpi4py import MPI except: MPI = None yt.enable_parallelism() import logging logging.getLogger('yt').setLevel(logging.ERROR) import pickle t1 = time.time() # Scan for files fregex = 'MHD_Jet_hdf5_plt_cnt_0*' tseries = yt.DatasetSeries(fregex, parallel=True) storage = {} for sto, ds in tseries.piter(storage=storage): if MPI: print 'Loading %s ... (%3i/%3i)' % (ds.basename, MPI.COMM_WORLD.rank+1, MPI.COMM_WORLD.size) else: print 'Loading %s ...' % (ds.basename) alldata = ds.all_data() tempmin, tempmax = alldata.quantities.extrema('temp') presmin, presmax = alldata.quantities.extrema('pressure') densmin, densmax = alldata.quantities.extrema('density') sto.result = (ds.basename, ds.current_time, tempmin, tempmax, presmin, presmax, densmin, densmax) t2 = time.time()
def CRPres(field, data): return 0.33333 * (data['cray'] * data['density']) def GasPres(field, data): return data['pressure'] - 0.33333 * (data['cray'] * data['density'] * pUnit) yt.add_field(("gas", "GasPres"), function=GasPres, units="g/cm/s**2") yt.add_field(("gas", "CRPres"), function=CRPres, units="g/cm**3") # Load the dataset. ts = yt.DatasetSeries("Plot Files/More Plot Files/parkerCRs_hdf5_plt_cnt_0*") counter = 0 for ds in ts: print(ds.derived_field_list) # Create a sphere of radius 1 Mpc centered on the max density location. sp = ds.sphere("max", (1, "Mpc")) time = str(ds.current_time.in_units('Myr')) time = (time[:4]) if len(time) > 4 else time t = "{} Myrs".format(str(time)) # Calculate and store the bulk velocity for the sphere. bulk_velocity = sp.quantities.bulk_velocity() sp.set_field_parameter('bulk_velocity', bulk_velocity)
#!/usr/bin/env python import os import numpy as np import yt from yt_cluster_ratio_fields import * yt.enable_parallelism() dir = './' ts = yt.DatasetSeries(os.path.join(dir, 'data/*_hdf5_plt_cnt_1364'), parallel=1) figuredir = os.path.join(dir, 'volume_rendering_entropy_ratio_300Myr_perspective') tfdir = os.path.join(figuredir, 'transfer_function') if yt.is_root(): for subdir in [figuredir, tfdir]: if not os.path.exists(subdir): os.mkdir(subdir) #fname = '/home/ychen/d9/FLASH4/stampede/0529_L45_M10_b1_h1/MHD_Jet_hdf5_plt_cnt_0620' bounds = (0.4, 2) # Since this rendering is done in log space, the transfer function needs # to be specified in log space. tf = yt.ColorTransferFunction(np.log10(bounds)) tf.sample_colormap(-0.35, 0.001, alpha=0.9, colormap="arbre") tf.sample_colormap(-0.2, 0.001, alpha=0.3, colormap="arbre") tf.sample_colormap(-0.1, 0.001, alpha=0.2, colormap="arbre")
'1to1_b0', '1to1_b0.5', '1to1_b1', '1to3_b0', '1to3_b0.5', '1to3_b1', '1to10_b0', '1to10_b0.5', '1to10_b1' ] center_methods = ['gpot', 'particle_gpot', 'most_bound', 'gpot_final'] # do all time series for sim_name in sim_names: ds_header = 'fiducial_%s_mag_hdf5_plt_cnt_' % sim_name ds_full_paths = glob.glob(data_dir + 'fid_mag/' + sim_name + '/' + ds_header + '0[0-9][0-9][05]') ds_full_paths.sort() # Get a collection of datasets to iterate over ts = yt.DatasetSeries(ds_full_paths) axis = 'z' ds_final = yt.load(ds_full_paths[-1]) c_final = magnolia.find_center(ds_final, center_method='gpot') for center_method in center_methods: try: os.makedirs(img_dir + '/' + sim_name + '/magnetic_field_strength_4Mpc/' + center_method) except OSError as e: if e.errno != errno.EEXIST: raise for ds in ts:
yt.add_field(("gas", "unbound_mass"), display_name=r'$M_{\rm ej}$', function=_unbound_mass, take_log=False, units=None, force_override=True) if args.chkplt == 'chk': LOAD_FILES = clusterdir + args.run + '/multitidal_hdf5_chk_' + args.files elif args.chkplt == 'plt': LOAD_FILES = clusterdir + args.run + '/multitidal_hdf5_plt_cnt_' + args.files yt.enable_parallelism() ts = yt.DatasetSeries(LOAD_FILES) t_array = [] unbound_m_array = [] bound_m_array = [] for ds in ts.piter(): t_array.append(float(ds.current_time.d)) #s = yt.SlicePlot(ds, 'z', 'unbound_mass') #s.save(savepath + args.run + '/unbound_mass/') ad = ds.all_data() pos_ad = ad.cut_region(['obj["unbound_mass"] >= 0.'])
# # This script is written for yt3.0 # import yt from yt.utilities.linear_interpolators import * import numpy as na import matplotlib.pyplot as plt delta_grid = [] grid_vol = [] time = [] grid_le_x = [] grid_re_x = [] part_x = [] ts = yt.DatasetSeries("*/*.hierarchy") for ds in ts: if ds.index.num_grids != ds.index.max_level + 1: print('Something is wrong, there is not one grid per level', ds.index.num_grids, ds.index.max_level + 1) break ad = ds.all_data() # particle position xp = ad['particle_position_x'][1] yp = ad['particle_position_y'][1] zp = ad['particle_position_z'][1] xv = ad['particle_velocity_x'][1]
print haloname, simname, snapname, run_parallel snaps = np.sort( np.asarray( glob.glob("/nobackupp2/mpeeples/%s/%s/%s/%s" % (haloname, simname, snapname, snapname)))) #abssnap = os.path.abspath(snaps[0]) assert os.path.lexists(snaps[0]) out_dir = '/u/rcsimons/' assert os.path.lexists(out_dir) new_snapfiles = np.asarray(snaps) ts = yt.DatasetSeries(new_snapfiles) def _stars(pfilter, data): return data[(pfilter.filtered_type, "particle_type")] == 2 #this gets dark matter particles in zoom region only def _darkmatter(pfilter, data): return data[(pfilter.filtered_type, "particle_type")] == 4 yt.add_particle_filter("stars", function=_stars, filtered_type='all', requires=["particle_type"]) yt.add_particle_filter("darkmatter", function=_darkmatter, filtered_type='all',
def test_mmc(tolerance, input_prefix, output): ds_pattern = f"{input_prefix}_????/{input_prefix}_????.block_list" cycle = [] mass = [] px = [] py = [] pz = [] n_p = [] # Can't test conservation of quantities if there are less than 2 snapshots # If this has happened, something has probably gone wrong in any case, so # return False if (len(yt.DatasetSeries(ds_pattern)) < 2): return False for ds in yt.DatasetSeries(ds_pattern): box = ds.box(left_edge=-ds.domain_width / 2.0, right_edge=ds.domain_width / 2.0) mass.append(box["sink", "mass"].sum()) px.append((box["sink", "mass"] * box["sink", "vx"]).sum()) py.append((box["sink", "mass"] * box["sink", "vy"]).sum()) pz.append((box["sink", "mass"] * box["sink", "vz"]).sum()) n_p.append(len(box["sink", "mass"])) cycle.append(ds["current_cycle"]) mass_error, mass_error_pass = test_error(mass, tolerance) px_error, px_error_pass = test_error(px, tolerance) py_error, py_error_pass = test_error(py, tolerance) pz_error, pz_error_pass = test_error(pz, tolerance) # matplotlib params params = { 'axes.labelsize': 16, 'axes.titlesize': 16, 'font.size': 16, 'legend.fontsize': 16, 'xtick.labelsize': 16, 'ytick.labelsize': 16, 'figure.figsize': (7, 12), 'figure.subplot.left': 0.15, 'figure.subplot.right': 0.95, 'figure.subplot.bottom': 0.25, 'figure.subplot.top': 0.95, 'figure.subplot.wspace': 0.10, 'figure.subplot.hspace': 0.05, 'lines.markersize': 3.0, 'lines.linewidth': 2.0 } plt.rcParams.update(params) plt.rc('font', **{'family': 'sans-serif', 'sans-serif': ['Times']}) fig, ax = plt.subplots(nrows=3, sharex=True) ax[0].plot(cycle, mass_error) grid_line_positions = np.linspace(-0.1, 0.1, 11, endpoint=True) for y in grid_line_positions: ax[0].axhline(y=y, ls="--", color="k", linewidth=0.5, alpha=0.7) ax[1].axhline(y=y, ls="--", color="k", linewidth=0.5, alpha=0.7) ax[0].set_ylim(-0.1, 0.1) ax[0].set_ylabel("Total Mass Error") ax[1].plot(cycle, px_error, label="x-momentum") ax[1].plot(cycle, py_error, label="y-momentum", ls="--") ax[1].plot(cycle, pz_error, label="z-momentum", ls=":") ax[1].set_ylim(-0.1, 0.1) ax[1].set_ylabel(r"Total Momentum Error") ax[1].legend(loc=0) ax[2].plot(cycle, n_p) ax[2].set_ylabel("Number of Particles") ax[2].set_xlabel("Cycle number") fig.savefig(output) plt.close(fig) print(f"Saved plot to {output}") return mass_error_pass and px_error_pass and py_error_pass and pz_error_pass
end_time=5000., start_time=-500) usable_files = mym.find_files(m_times, files) sink_form_time = mym.find_sink_formation_time(files) del files if os.path.isfile(save_dir + output) == False: f = open(save_dir + output, 'a+') f.close() f = open(save_dir + output, 'w') f.write('Time, Particles, Gas\n') f.close() storage = {} ts = yt.DatasetSeries(usable_files, parallel=True) for sto, ds in ts.piter(storage=storage): time = ds.current_time.in_units('yr').value - sink_form_time dd = ds.all_data() center_pos = dd['Center_Position'] center_vel = dd['Center_Velocity'] part_pos = dd['All_Particle_Positions'] part_mass = dd['All_Particle_Masses'] part_vel = dd['All_Particle_Velocities'] print("part_mass =", myf.get_part_mass()) print("part_vel =", myf.get_part_vel()) print("center_vel =", myf.get_center_vel()) print("part_pos =", myf.get_part_pos()) print("center_pos =", myf.get_center_pos()) if ('io', 'particle_mass') in ds.derived_field_list: '''
def test_mc(tolerance,input_prefix,output): ds_pattern = f"{input_prefix}_????/{input_prefix}_????.block_list" time = [] gas_mass = [] sink_mass = [] # Can't test conservation of quantities if there are less than 2 snapshots # If this has happened, something has probably gone wrong in any case, so # return False if (len(yt.DatasetSeries(ds_pattern)) < 2): return False for ds in yt.DatasetSeries(ds_pattern): box = ds.box(left_edge = -ds.domain_width/2.0, right_edge = ds.domain_width/2.0) data = ds.all_data() gas_mass.append(data["gas","mass"].sum()) sink_mass.append(box["sink","mass"].sum()) time.append(ds.current_time) total_mass = [gm + sm for (gm,sm) in zip(gas_mass,sink_mass)] mass_error, mass_error_pass = test_error(total_mass,tolerance) print(f"Maximum mass error = {np.max(np.abs(mass_error))}") # replace zeros with a small number. Helpful for plotting purposes mass_error[mass_error == 0] = 1.0e-100 ### make the figure # set matplotlib params params = {'axes.labelsize': 16, 'axes.titlesize': 16, 'font.size': 16, 'legend.fontsize': 16, 'xtick.labelsize': 16, 'ytick.labelsize': 16, 'figure.figsize' : (8,6), 'figure.subplot.left' : 0.15, 'figure.subplot.right' : 0.95 , 'figure.subplot.bottom' : 0.25 , 'figure.subplot.top' : 0.95 , 'figure.subplot.wspace' : 0.10 , 'figure.subplot.hspace' : 0.05 , 'lines.markersize' : 3.0, 'lines.linewidth' : 2.0 } plt.rcParams.update(params) fig,ax = plt.subplots() ax.plot(time,gas_mass/total_mass[0],label = "Gas mass") ax.plot(time,sink_mass/total_mass[0],label = "Sink mass") ax.plot(time,total_mass/total_mass[0],label = "Total mass") grid_line_positions = np.linspace(0.0,1.0,11,endpoint = True) for y in grid_line_positions: ax.axhline(y = y,ls = "--",color = "k",linewidth = 0.5,alpha = 0.7) ax.set_ylim(0.0,1.05) ax.set_ylabel("Mass fraction") ax.set_xlabel("Time (years)") ax.legend(loc = 0) fig.savefig(output) print(f"Saved plot to {output}") return mass_error_pass
import numpy as np import matplotlib.pyplot as plt import yt # If you want to run in parallel this *must* be the first # thing after importing yt! yt.enable_parallelism() # We first create a time series object of the data files, using a # "wildcard" syntax ts = yt.DatasetSeries("../data/WindTunnel/windtunnel_4lev_hdf5_plt_cnt_*") # This is a dictionary object which we'll use to store the results in my_storage = {} # Now we loop over the time series, calculating the average x-velocity and # storing the result. We also make slice plots of every snapshot, # annotating the grid lines on top. for sto, ds in ts.piter(storage=my_storage): dd = ds.all_data() # This is an object giving us all the data # This line computes the average x-velocity weighted by the # density vx = dd.quantities.weighted_average_quantity("velocity_x", "density") # We now store both the filename and # the result in the storage. sto.result_id = str(ds) # Taking str() of ds gives us the filename sto.result = (ds.current_time, vx) # Make a slice plot, setting the z-lim of the density field,
# Get the MMPB properties mmpb_files = glob(mmpb_file) if len(mmpb_files) > 1: print 'More than one file matches %s, '\ 'the supplied file name for the MMPB properties. '\ 'Set which file you want to use with --mmpb_file'\ % (mmpb_file) sys.exit() else: mmpb_file = mmpb_files[0] mmpb_props = np.load(mmpb_file)[()] # Generate data series snaps = glob(sim_dir + '/' + snap_base + '*') ts = yt.DatasetSeries(snaps) # Initialize galaxy properties dictionary galaxy_props = {} fields = [ 'scale', 'stars_total_mass', 'stars_com', 'stars_maxdens', 'stars_hist_center', 'stars_rhalf', 'stars_mass_profile', 'stars_c_to_a', 'stars_b_to_a', 'stars_shape_axes', 'dm_c_to_a', 'dm_b_to_a', 'dm_shape_axes', 'stars_L', 'gas_total_mass', 'gas_maxdens', 'gas_L' ] for field in fields: if field in [ 'scale', 'stars_total_mass', 'stars_rhalf', 'gas_total_mass' ]:
dir = './' ls = { (0, 10): ['solid', 2], (10, 20): ['dotted', 2], (20, 30): ['dashed', 1], (30, 60): ['solid', 1], (60, 100): ['dotted', 1] } rmin, rmax = -10, 100 try: ind = int(sys.argv[1]) ts = yt.DatasetSeries(os.path.join(dir, 'data/*_hdf5_part_%04d' % ind), parallel=1) except IndexError: ts = yt.DatasetSeries(os.path.join(dir, 'data/*_hdf5_part_???0'), parallel=0) maindir = os.path.join(dir, 'particles_dr_histogram/') if yt.is_root(): for subdir in [maindir]: if not os.path.exists(subdir): os.mkdir(subdir) f0 = '/d/d8/ychen/2016_production_runs/1212_L45_M10_b1_h0_10Myr/data/MHD_Jet_10Myr_hdf5_part_0000' ds0 = yt.load(f0) ds0.add_particle_filter("metal") ad0 = ds0.all_data()
#!/usr/bin/env python import os import numpy as np import yt yt.enable_parallelism() dir = '/home/ychen/data/0605_L45_M10_b1_h0/' ts = yt.DatasetSeries(os.path.join(dir, '*_hdf5_plt_cnt_??[0,5]0'), parallel=22) figuredir = os.path.join(dir, 'volume_rendering_plane_parallel') tfdir = os.path.join(figuredir, 'transfer_function') if yt.is_root(): for subdir in [figuredir, tfdir]: if not os.path.exists(subdir): os.mkdir(subdir) #fname = '/home/ychen/d9/FLASH4/stampede/0529_L45_M10_b1_h1/MHD_Jet_hdf5_plt_cnt_0620' #ds = yt.load(fname) bounds = (1e-28, 1e-25) # Since this rendering is done in log space, the transfer function needs # to be specified in log space. tf = yt.ColorTransferFunction(np.log10(bounds)) tf.sample_colormap(np.log10(1E-25), 0.005, alpha=0.03, colormap="arbre") #tf.sample_colormap(np.log10(2E-26), 0.005, alpha=0.05, colormap="arbre") tf.sample_colormap(np.log10(1E-26), 0.005, alpha=0.2, colormap="arbre")
import yt import yt.units as u import os yt.enable_parallelism() lower_limit = 599 upper_limit = 600 dataset_series = [] #d_path = '/mnt/research/galaxies-REU/sims/isolated-galaxies/MW_1638kpcBox_800pcCGM_200pcDisk_lowres/ d_path = '/mnt/c/scratch/sciteam/dsilvia/simulations/galaxy_simulation/reu_sims/MW_1638kpcBox_800pcCGM_200pcDisk/thermalFB/' for x in range(lower_limit, upper_limit): dataset_series.append(d_path + 'DD%04d/DD%04d' % (x, x)) ts = yt.DatasetSeries(dataset_series) fields = ['baroclinic_vorticity_magnitude'] for ds in ts.piter(): for field in fields: p = yt.ProjectionPlot(ds, 'z', field, width=(100, 'kpc')) p.set_cmap(field=field, cmap='RdYlGn_r') p.annotate_timestamp(draw_inset_box=True, text_args={ 'size': 30, 'color': 'w' }) #p.annotate_quiver('velocity_x', 'velocity_y', 10) # Note: if increasing buffer size, change quiver density accordingly # e.g. if buff_size = 3200 => change 10 to 40
FITSProjection,\ FITSOffAxisProjection from astropy.wcs import WCS from synchrotron.yt_synchrotron_emissivity import\ setup_part_file,\ write_synchrotron_hdf5,\ synchrotron_filename,\ synchrotron_fits_filename,\ StokesFieldName from tools import setup_cl dir = './' try: ind = int(sys.argv[1]) ts = yt.DatasetSeries(os.path.join(dir, 'data/*_hdf5_plt_cnt_%04d' % ind), parallel=1, setup_function=setup_part_file) except IndexError: ts = yt.DatasetSeries(os.path.join(dir, 'data/*_hdf5_plt_cnt_????'), parallel=8, setup_function=setup_part_file) mock_observation = True #nus = [(nu, 'MHz') for nu in [100,300,600,1400,8000]] nus = [(nu, 'MHz') for nu in [100, 1400, 8000]] zoom_fac = 4 #proj_axis = [1,0,2] proj_axis = 'x' ptype = 'lobe'
import yt from yt.utilities.parallel_tools.parallel_analysis_interface \ import communication_system import h5py import time import numpy as np @yt.derived_field(name="IonizedHydrogen", units="", display_name=r"\frac{\rho_{HII}}{\rho_H}") def IonizedHydrogen(field, data): return data["HII_Density"]/(data["HI_Density"]+data["HII_Density"]) ts = yt.DatasetSeries("SED800/DD*/*.index", parallel=8) ionized_z = np.zeros(ts[0].domain_dimensions, dtype="float32") t1 = time.time() for ds in ts.piter(): z = ds.current_redshift for g in parallel_objects(ds.index.grids, njobs = 16): i1, j1, k1 = g.get_global_startindex() # Index into our domain i2, j2, k2 = g.get_global_startindex() + g.ActiveDimensions # Look for the newly ionized gas newly_ion = ((g["IonizedHydrogen"] > 0.999) & (ionized_z[i1:i2,j1:j2,k1:k2] < z)) ionized_z[i1:i2,j1:j2,k1:k2][newly_ion] = z g.clear_data() print("Iteration completed %0.3e" % (time.time()-t1)) comm = communication_system.communicators[-1]
yt.mylog.setLevel("INFO") import synchrotron.yt_synchrotron_emissivity as sync from itertools import chain yt.enable_parallelism(suppress_logging=True) dir = './data/' ptype = 'lobe' proj_axis = 'x' #proj_axis = [1,0,2] extend_cells = 8 try: ind = int(sys.argv[1]) #ts = yt.DatasetSeries(os.path.join(dir,'*_hdf5_plt_cnt_%04d' % ind), parallel=1, setup_function=sync.setup_part_file) ts = yt.DatasetSeries(os.path.join(dir, '*_hdf5_plt_cnt_%04d' % ind), parallel=1) except IndexError: ts = yt.DatasetSeries(os.path.join(dir, '*_hdf5_plt_cnt_????'), parallel=1) for ds in ts.piter(): #if '0000' in ds.basename: continue #sync.write_synchrotron_hdf5(ds, 'jetp', (150, 'MHz'), 'x', extend_cells=0) #sync.write_synchrotron_hdf5(ds, 'lobe', (150, 'MHz'), 'x', extend_cells=32) #sync.write_synchrotron_hdf5(ds, 'lobe', (1.4, 'GHz'), 'x', extend_cells=32) #nus = chain(range(100,200,25), range(200,900,50), range(900,1500,100)) nus = [100, 300, 600, 1400, 8000] #nus = [100, 1400] for nu in [(nu, 'MHz') for nu in nus]: #for nu in [(150, 'MHz'), (1400, 'MHz')]: # The two projection axes cannot be completed at the same time # Remember to comment out one of the following lines
f = open(save_dir + output_file, 'a+') f.close() f = open(save_dir + output_file, 'w') if args.measure_disks != "False": f.write('Time, Lz_1, Lz_2 \n') elif args.measure_all != "False": f.write('Time, Particles, Disk, Infalling, Outflowing \n') else: f.write( 'Time, Mass, Momentum, Angular Momentum, Max speed, Unbound Mass, CoM dist, Mean speed, F_rad, F_tan \n' ) f.close() storage = {} ts = yt.DatasetSeries(usable_files, parallel=True, units_override=units_override) for sto, ds in ts.piter(storage=storage): dd = ds.all_data() if args.measure_disks != "False": if args.disk_center == 'CoM': center_1 = [ dd['CoM'][0].in_units('cm'), dd['CoM'][1].in_units('cm'), dd['CoM'][2].in_units('cm') ] center_2 = None else: center_1 = [ dd['particle_posx'][0].in_units('cm'), dd['particle_posy'][0].in_units('cm'), dd['particle_posz'][0].in_units('cm')
@author: brend """ import numpy as np from matplotlib import pyplot as plt import os from mpl_toolkits.mplot3d import Axes3D import glob import yt from yt.config import ytcfg #======================================================================================================================== """ Question 5 Plot Accelerations """ #======================================================================================================================== path = ("HW4_vertTraj.txt") my_fns = glob.glob(path + "/Orbit/orbit_hdf5_chk_00[0-9][0-9]") my_fns.sort() fields = [" t[s]", "z(t) [m]"] indices = dd["particle_index"].astype("int") print(indices) ts = yt.DatasetSeries(my_fns) # suppress_logging=True cuts down on a lot of noise trajs = ts.particle_trajectories(indices, fields=fields, suppress_logging=True) print(trajs["particle_position_x"]) print(trajs["particle_position_x"].shape)