def container_setup(density=mass_hydrogen_cgs, current_redshift=0): # Set solver parameters my_chemistry = chemistry_data() my_chemistry.use_grackle = 1 my_chemistry.with_radiative_cooling = 0 my_chemistry.primordial_chemistry = 1 my_chemistry.metal_cooling = 0 my_chemistry.UVbackground = 0 my_chemistry.use_volumetric_heating_rate = 1 # Set units my_chemistry.comoving_coordinates = 1 my_chemistry.a_units = 1.0 my_chemistry.a_value = 1.0 / (1.0 + current_redshift) / \ my_chemistry.a_units my_chemistry.density_units = mass_hydrogen_cgs * \ (1 + current_redshift)**3 my_chemistry.length_units = cm_per_mpc # 1 Mpc in cm my_chemistry.time_units = sec_per_Myr # 1 Gyr in s my_chemistry.velocity_units = my_chemistry.a_units * \ (my_chemistry.length_units / my_chemistry.a_value) / \ my_chemistry.time_units # Call convenience function for setting up a fluid container. # This container holds the solver parameters, units, and fields. temperature = np.logspace(1, 6, 51) fc = setup_fluid_container(my_chemistry, density=density, temperature=temperature, converge=True) fc["volumetric_heating_rate"][:] = 1.e-24 # erg/s/cm^3 return fc
def test_tabulated_mmw_metal_dependence(): """ Make sure that increasing the metal mass fraction of a gas increases the mean molecular weight, when run in tabulated mode. """ grackle_dir = os.path.dirname( os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) data_file_path = bytearray( os.sep.join([grackle_dir, "input", "CloudyData_UVB=HM2012.h5"]), 'utf-8') my_random_state = np.random.RandomState(723466) density_units = random_logscale(-28, -26, random_state=my_random_state) length_units = random_logscale(0, 2, random_state=my_random_state) time_units = random_logscale(0, 2, random_state=my_random_state) velocity_units = length_units / time_units current_redshift = 0. mmw_vals = [] for metal_mass_frac in [0., 0.02041]: # proper units my_chem = chemistry_data() my_chem.use_grackle = 1 my_chem.with_radiative_cooling = 0 my_chem.primordial_chemistry = 0 my_chem.metal_cooling = 1 my_chem.UVbackground = 1 my_chem.grackle_data_file = data_file_path my_chem.comoving_coordinates = 0 my_chem.a_units = 1.0 my_chem.a_value = 1.0 / (1.0 + current_redshift) / my_chem.a_units my_chem.density_units = density_units my_chem.length_units = length_units my_chem.time_units = time_units my_chem.velocity_units = velocity_units fc = setup_fluid_container(my_chem, converge=False, metal_mass_fraction=metal_mass_frac) fc.calculate_mean_molecular_weight() mmw_vals.append(fc['mu']) mmw_no_metals, mmw_with_metals = mmw_vals assert_array_less( mmw_no_metals, mmw_with_metals, ("The mmw didn't increase when the metal fraction of the gas was " "increased (for primordial_chemisty=0)"))
def get_defChem(): #* Initialise chemistry_data instance my_chemistry = chemistry_data() #* Set parameters my_chemistry.use_grackle = 1 my_chemistry.with_radiative_cooling = 0 my_chemistry.primordial_chemistry = 1 my_chemistry.metal_cooling = 0 my_chemistry.UVbackground = 0 my_chemistry.comoving_coordinates = 0 my_chemistry.a_units = 1.0 my_chemistry.a_value = 1.0 my_chemistry.density_units = mass_hydrogen_cgs my_chemistry.length_units = 1.0 my_chemistry.time_units = 1.0 my_chemistry.velocity_units = my_chemistry.length_units / my_chemistry.time_units return my_chemistry
def make_chem(grackle_data_file, with_radiative_cooling=0, primordial_chemistry=3, metal_cooling=1, UVbackground=1, self_shielding_method=0, H2_self_shielding=0, comoving_coordinates=0, a_units=1.0, a_value=1.0, current_redshift=0.): print("making chem.") # Set solver parameters my_chemistry = chemistry_data() my_chemistry.use_grackle = 1 my_chemistry.with_radiative_cooling = with_radiative_cooling my_chemistry.primordial_chemistry = primordial_chemistry my_chemistry.metal_cooling = metal_cooling my_chemistry.UVbackground = UVbackground my_chemistry.self_shielding_method = self_shielding_method my_chemistry.H2_self_shielding = H2_self_shielding #grackle_dir = os.path.dirname(os.path.dirname(os.path.dirname( # os.path.dirname(os.path.abspath(__file__))))) #my_chemistry.grackle_data_file = os.sep.join( # [grackle_dir, "input", "CloudyData_UVB=HM2012.h5"]) my_chemistry.grackle_data_file = grackle_data_file # Set units #current_redshift = 0. my_chemistry.comoving_coordinates = comoving_coordinates # proper units my_chemistry.a_units = a_units my_chemistry.a_value = a_value / (1.0 + current_redshift) / \ my_chemistry.a_units my_chemistry.density_units = mass_hydrogen_cgs # rho = 1.0 is 1.67e-24 g my_chemistry.length_units = cm_per_mpc # 1 Mpc in cm my_chemistry.time_units = sec_per_Myr # 1 Gyr in s my_chemistry.velocity_units = my_chemistry.a_units * \ (my_chemistry.length_units / my_chemistry.a_value) / \ my_chemistry.time_units print(my_chemistry.grackle_data_file) return my_chemistry
def prepare_grackle_data(ds, parameters=None): sim_type = type(ds) par_map = _parameter_map.get(sim_type) if par_map is None: raise RuntimeError("Simulation type not supported: %s." % sim_type) all_parameters = \ dict([(gpar, ds.parameters[dpar]) for gpar, dpar in par_map.items() if dpar in ds.parameters]) all_parameters['use_grackle'] = 1 if parameters is None: parameters = {} all_parameters.update(parameters) my_chemistry = chemistry_data() for gpar, val in all_parameters.items(): if val is None: continue if isinstance(val, str): sval = bytes(val, 'utf-8') setattr(my_chemistry, gpar, sval) else: setattr(my_chemistry, gpar, val) my_chemistry.comoving_coordinates = ds.cosmological_simulation my_chemistry.density_units = (ds.mass_unit / ds.length_unit**3).in_cgs().d my_chemistry.length_units = ds.length_unit.in_cgs().d my_chemistry.time_units = ds.time_unit.in_cgs().d my_chemistry.a_units = 1 / ( 1 + ds.parameters.get('CosmologyInitialRedshift', 0)) my_chemistry.a_value = 1 / (1 + ds.current_redshift) / my_chemistry.a_units my_chemistry.velocity_units = ds.velocity_unit.in_cgs().d my_chemistry.initialize() ds.grackle_data = my_chemistry
def wrapped_initializer(mass_unit_cgs, length_unit_cgs, time_unit_cgs, verbose=False): """ Create a `grackle.chemistry_data` object Inputs ------ mass_units_cgs : float length_unit_cgs : float time_unit_cgs : float verbose : Optional(bool) Returns ------- rval : int return value from Grackle. Returns 1 for success, 0 for failure. my_chemistry : `grackle.chemistry_data` object """ if verbose: print( """`grackle_helpers.wrapped_initializer` is setting up grackle assuming code units: mass : {:.3} M_solar length : {:.3} pc time : {:.3} Myr """.format( mass_unit_cgs / M_solar, length_unit_cgs / pc, time_unit_cgs / Myr, )) current_redshift = 0. # Set solver parameters my_chemistry = chemistry_data() my_chemistry.use_grackle = 1 my_chemistry.with_radiative_cooling = 1 my_chemistry.primordial_chemistry = 0 my_chemistry.metal_cooling = 1 my_chemistry.UVbackground = 1 my_chemistry.self_shielding_method = 0 my_chemistry.H2_self_shielding = 0 grackle_dir = "/pfs/home/egentry/local/grackle" my_chemistry.grackle_data_file = os.path.join(grackle_dir, "input", "CloudyData_UVB=HM2012.h5") print("grackle cooling file: ", my_chemistry.grackle_data_file) # Set units my_chemistry.comoving_coordinates = 0 # proper units my_chemistry.a_units = 1.0 my_chemistry.a_value = 1. / (1. + current_redshift) / \ my_chemistry.a_units my_chemistry.density_units = mass_unit_cgs / length_unit_cgs**3 my_chemistry.length_units = length_unit_cgs my_chemistry.time_units = time_unit_cgs my_chemistry.velocity_units = my_chemistry.a_units * \ (my_chemistry.length_units / my_chemistry.a_value) / \ my_chemistry.time_units rval = my_chemistry.initialize() return rval, my_chemistry
chemistry_data, \ grid_to_grackle from pygrackle.fluid_container import \ _yt_to_grackle DS_NAME = "IsolatedGalaxy/galaxy0030/galaxy0030" if 'YT_DATA_DIR' in os.environ: ds_path = os.sep.join([os.environ['YT_DATA_DIR'], DS_NAME]) else: ds_path = DS_NAME ds = yt.load(ds_path) my_chemistry = chemistry_data() my_chemistry.use_grackle = 1 my_chemistry.primordial_chemistry = 1 my_chemistry.metal_cooling = 1 my_chemistry.self_shielding_method = 0 my_chemistry.H2_self_shielding = 0 my_dir = os.path.dirname(os.path.abspath(__file__)) grackle_data_file = bytearray( os.path.join(my_dir, "..", "..", "..", "input", "CloudyData_UVB=HM2012.h5"), 'utf-8') my_chemistry.grackle_data_file = grackle_data_file my_chemistry.comoving_coordinates = 0 my_chemistry.density_units = 1.67e-24 my_chemistry.length_units = 1.0 my_chemistry.time_units = 1.0e12
def test_proper_comoving_units_tabular(): """ Make sure proper and comoving units systems give the same answer with tabular cooling. """ grackle_dir = os.path.dirname( os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) data_file_path = bytearray( os.sep.join([grackle_dir, "input", "CloudyData_UVB=HM2012.h5"]), 'utf-8') my_random_state = np.random.RandomState(19650909) for current_redshift in [0., 1., 3., 6., 9.]: # comoving units chem_c = chemistry_data() chem_c.use_grackle = 1 chem_c.with_radiative_cooling = 0 chem_c.primordial_chemistry = 0 chem_c.metal_cooling = 1 chem_c.UVbackground = 1 chem_c.grackle_data_file = data_file_path set_cosmology_units(chem_c, current_redshift=current_redshift, initial_redshift=99.) fc_c = setup_fluid_container(chem_c, converge=False) fc_c.calculate_temperature() fc_c.calculate_cooling_time() t_sort_c = np.argsort(fc_c["temperature"]) t_cool_c = fc_c["cooling_time"][t_sort_c] * chem_c.time_units # proper units chem_p = chemistry_data() chem_p.use_grackle = 1 chem_p.with_radiative_cooling = 0 chem_p.primordial_chemistry = 0 chem_p.metal_cooling = 1 chem_p.UVbackground = 1 chem_p.grackle_data_file = data_file_path chem_p.comoving_coordinates = 0 chem_p.a_units = 1.0 chem_p.a_value = 1.0 / (1.0 + current_redshift) / chem_p.a_units # Set the proper units to be of similar magnitude to the # comoving system to help the solver be more efficient. chem_p.density_units = random_logscale(-2, 2, random_state=my_random_state) * \ chem_c.density_units / (1 + current_redshift)**3 chem_p.length_units = random_logscale(-2, 2, random_state=my_random_state) * \ chem_c.length_units * (1 + current_redshift) chem_p.time_units = random_logscale(-2, 2, random_state=my_random_state) * \ chem_c.time_units chem_p.velocity_units = chem_p.length_units / chem_p.time_units fc_p = setup_fluid_container(chem_p, converge=False) fc_p.calculate_temperature() fc_p.calculate_cooling_time() t_sort_p = np.argsort(fc_p["temperature"]) t_cool_p = fc_p["cooling_time"][t_sort_p] * chem_p.time_units comp = "\nDU1: %e, LU1: %e, TU1: %e - DU2: %e, LU2: %e, TU2L %e." % \ (chem_p.density_units, chem_p.length_units, chem_p.time_units, chem_c.density_units, chem_c.length_units, chem_c.time_units) assert_rel_equal( t_cool_p, t_cool_c, 4, (("Proper and comoving tabular cooling times disagree for " + "z = %f with min/max = %f/%f.\n") % (current_redshift, (t_cool_p / t_cool_c).min(), (t_cool_p / t_cool_c).max()) + comp))
def test_proper_units(): """ Make sure two different proper units systems give the same answer. """ grackle_dir = os.path.dirname( os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) data_file_path = bytearray( os.sep.join([grackle_dir, "input", "CloudyData_UVB=HM2012.h5"]), 'utf-8') my_random_state = np.random.RandomState(20150725) for current_redshift in [0., 1., 3.]: # proper units chem_1 = chemistry_data() chem_1.use_grackle = 1 chem_1.with_radiative_cooling = 0 chem_1.primordial_chemistry = 1 chem_1.metal_cooling = 1 chem_1.UVbackground = 1 chem_1.grackle_data_file = data_file_path chem_1.comoving_coordinates = 0 chem_1.a_units = 1.0 chem_1.a_value = 1.0 / (1.0 + current_redshift) / chem_1.a_units chem_1.density_units = random_logscale(-1, 1, random_state=my_random_state) chem_1.length_units = random_logscale(0, 2, random_state=my_random_state) chem_1.time_units = random_logscale(0, 2, random_state=my_random_state) chem_1.velocity_units = chem_1.length_units / chem_1.time_units fc_1 = setup_fluid_container(chem_1, converge=False) fc_1.calculate_temperature() fc_1.calculate_cooling_time() t_sort_1 = np.argsort(fc_1["temperature"]) t_cool_1 = fc_1["cooling_time"][t_sort_1] * chem_1.time_units # proper units chem_2 = chemistry_data() chem_2.use_grackle = 1 chem_2.with_radiative_cooling = 0 chem_2.primordial_chemistry = 1 chem_2.metal_cooling = 1 chem_2.UVbackground = 1 chem_2.grackle_data_file = data_file_path chem_2.comoving_coordinates = 0 chem_2.a_units = 1.0 chem_2.a_value = 1.0 / (1.0 + current_redshift) / chem_2.a_units chem_2.density_units = random_logscale(-28, -26, random_state=my_random_state) chem_2.length_units = random_logscale(0, 2, random_state=my_random_state) chem_2.time_units = random_logscale(0, 2, random_state=my_random_state) chem_2.velocity_units = chem_2.length_units / chem_2.time_units fc_2 = setup_fluid_container(chem_2, converge=False) fc_2.calculate_temperature() fc_2.calculate_cooling_time() t_sort_2 = np.argsort(fc_2["temperature"]) t_cool_2 = fc_2["cooling_time"][t_sort_2] * chem_2.time_units comp = "\nDU1: %e, LU1: %e, TU1: %e - DU2: %e, LU2: %e, TU2L %e." % \ (chem_1.density_units, chem_1.length_units, chem_1.time_units, chem_2.density_units, chem_2.length_units, chem_2.time_units) assert_rel_equal( t_cool_1, t_cool_2, 4, (("Different proper unit system cooling times disagree for " + "z = %f with min/max = %f/%f.") % (current_redshift, (t_cool_1 / t_cool_2).min(), (t_cool_1 / t_cool_2).max()) + comp))
def run_grackle(initial_temperature, density, final_time, safety_factor=1e-2): current_redshift = 0. tiny_number = 1.0e-20 pygrackle.evolve_constant_density = _new_evolve_constant_density # Set solver parameters my_chemistry = chemistry_data() my_chemistry.three_body_rate = 4 my_chemistry.use_grackle = 1 my_chemistry.with_radiative_cooling = 0 my_chemistry.primordial_chemistry = 2 my_chemistry.metal_cooling = 0 my_chemistry.UVbackground = 0 my_chemistry.self_shielding_method = 0 my_chemistry.H2_self_shielding = 0 grackle_dir = os.path.dirname( os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) my_chemistry.grackle_data_file = os.sep.join( [grackle_dir, "input", "CloudyData_UVB=HM2012.h5"]) # Set units my_chemistry.comoving_coordinates = 0 # proper units my_chemistry.a_units = 1.0 my_chemistry.three_body_rate = 4 my_chemistry.a_value = 1. / (1. + current_redshift) / \ my_chemistry.a_units my_chemistry.density_units = 1.66053904e-24 # 1u: amu # rho = 1.0 is 1.67e-24 g my_chemistry.length_units = 1.0 # cm my_chemistry.time_units = 1.0 # s my_chemistry.velocity_units = my_chemistry.a_units * \ (my_chemistry.length_units / my_chemistry.a_value) / \ my_chemistry.time_units rval = my_chemistry.initialize() fc = FluidContainer(my_chemistry, 1) fc["density"][:] = density tiny_number = 1.0e-20 if my_chemistry.primordial_chemistry > 0: # these are in mass_density fc["HI"][:] = 0.76 * fc["density"] / 3. fc["HII"][:] = 0.76 * fc["density"] / 3. fc["HeI"][:] = (1 - 0.76) * fc["density"] / 2. fc["HeII"][:] = (1 - 0.76) * fc["density"] / 2. fc["HeIII"][:] = tiny_number if my_chemistry.primordial_chemistry > 1: fc["H2I"][:] = 0.76 * fc["density"] / 3. fc["H2II"][:] = tiny_number #0.76 * fc["density"] /4. fc["HM"][:] = tiny_number #0.76 * fc["density"] /4. if my_chemistry.primordial_chemistry > 2: fc["DI"][:] = 2.0 * 3.4e-5 * fc["density"] fc["DII"][:] = tiny_number * fc["density"] fc["HDI"][:] = tiny_number * fc["density"] if my_chemistry.metal_cooling == 1: fc["metal"][:] = 0.1 * fc["density"] * \ my_chemistry.SolarMetalFractionByMass fc["x-velocity"][:] = 0.0 fc["y-velocity"][:] = 0.0 fc["z-velocity"][:] = 0.0 fc["energy"][:] = initial_temperature / \ fc.chemistry_data.temperature_units fc.calculate_temperature() fc["energy"][:] *= initial_temperature / fc["temperature"] # let gas cool at constant density data = pygrackle.evolve_constant_density(fc, final_time=final_time, safety_factor=safety_factor) return data
def test_equilibrium(): """ Test ionization equilibrium for a primordial gas against the analytical solution using the same rates. This test takes a long time because the iteration to convergence near T = 1e4 K is slow. """ my_chem = chemistry_data() my_chem.use_grackle = 1 my_chem.with_radiative_cooling = 0 my_chem.primordial_chemistry = 1 my_chem.metal_cooling = 0 my_chem.UVbackground = 0 my_chem.comoving_coordinates = 0 my_chem.a_units = 1.0 my_chem.a_value = 1.0 my_chem.density_units = mass_hydrogen_cgs my_chem.length_units = 1.0 my_chem.time_units = 1.0 my_chem.velocity_units = my_chem.length_units / my_chem.time_units fc = setup_fluid_container(my_chem, temperature=np.logspace(4.5, 9, 200), converge=True, tolerance=1e-6, max_iterations=np.inf) fc.calculate_temperature() fc.calculate_cooling_time() t_sort = np.argsort(fc["temperature"]) t_cool = fc["cooling_time"][t_sort] * my_chem.time_units my_T = fc["temperature"][t_sort] my_nH = fc.calculate_hydrogen_number_density().mean() cooling_rate_eq = -1 * total_cooling(my_T, my_nH) / my_nH**2 cooling_rate_g = fc["energy"][t_sort] / t_cool * fc["density"] * \ my_chem.density_units / my_nH**2 # Make a cooling rate figure fontsize = 14 axes = pyplot.axes() axes.loglog(my_T, -1 * cooling_rate_eq, color='black', alpha=0.7, linestyle="--", linewidth=1.5) axes.loglog(my_T, -1 * cooling_rate_g, color='black', alpha=0.7, linestyle="-", linewidth=1) axes.xaxis.set_label_text('T [K]', fontsize=fontsize) axes.yaxis.set_label_text( r'$-\Lambda$ / n${_{\rm H}}^{2}$ [erg s$^{-1}$ cm$^{3}$]', fontsize=fontsize) axes.set_xlim(1e4, 1e9) axes.set_ylim(1e-26, 2e-22) tick_labels = axes.xaxis.get_ticklabels() + \ axes.yaxis.get_ticklabels() for tick_label in tick_labels: tick_label.set_size(fontsize) pyplot.savefig('cooling.png') pyplot.clf() # Make an ionization balance figure nH_eq = nHI(my_T, my_nH) + nHII(my_T, my_nH) nH_g = fc["HI"] + fc["HII"] fHI_eq = nHI(my_T, my_nH) / nH_eq fHI_g = fc["HI"] / nH_g fHII_eq = nHII(my_T, my_nH) / nH_eq fHII_g = fc["HII"] / nH_g nHe_eq = nHeI(my_T, my_nH) + nHeII(my_T, my_nH) + nHeIII(my_T, my_nH) nHe_g = fc["HeI"] + fc["HeII"] + fc["HeIII"] fHeI_eq = nHeI(my_T, my_nH) / nHe_eq fHeI_g = fc["HeI"] / nHe_g fHeII_eq = nHeII(my_T, my_nH) / nHe_eq fHeII_g = fc["HeII"] / nHe_g fHeIII_eq = nHeIII(my_T, my_nH) / nHe_eq fHeIII_g = fc["HeIII"] / nHe_g # Plot H ions axes = pyplot.axes() axes.loglog(my_T, fHI_eq, color="#B82E00", alpha=0.7, linestyle="--", linewidth=1.5) axes.loglog(my_T, fHII_eq, color="#B88A00", alpha=0.7, linestyle="--", linewidth=1.5) axes.loglog(my_T, fHI_g, label="HI", color="#B82E00", alpha=0.7, linestyle="-", linewidth=1.) axes.loglog(my_T, fHII_g, label="HII", color="#B88A00", alpha=0.7, linestyle="-", linewidth=1.) # Plot He ions axes.loglog(my_T, fHeI_eq, color="#002EB8", alpha=0.7, linestyle="--", linewidth=1.5) axes.loglog(my_T, fHeII_eq, color="#008AB8", alpha=0.7, linestyle="--", linewidth=1.5) axes.loglog(my_T, fHeIII_eq, color="#00B88A", alpha=0.7, linestyle="--", linewidth=1.5) axes.loglog(my_T, fHeI_g, label="HeI", color="#002EB8", alpha=0.7, linestyle="-", linewidth=1.) axes.loglog(my_T, fHeII_g, label="HeII", color="#008AB8", alpha=0.7, linestyle="-", linewidth=1.) axes.loglog(my_T, fHeIII_g, label="HeIII", color="#00B88A", alpha=0.7, linestyle="-", linewidth=1.) axes.xaxis.set_label_text('T [K]', fontsize=fontsize) axes.yaxis.set_label_text('fraction', fontsize=fontsize) axes.set_xlim(1e4, 1e9) axes.set_ylim(1e-10, 1) tick_labels = axes.xaxis.get_ticklabels() + \ axes.yaxis.get_ticklabels() for tick_label in tick_labels: tick_label.set_size(fontsize) axes.legend(loc='best', prop=dict(size=fontsize)) pyplot.savefig('fractions.png') test_precision = 1 # test the cooling rates cool_ratio = cooling_rate_eq / cooling_rate_g assert_rel_equal( cooling_rate_eq, cooling_rate_g, test_precision, "Equilibrium cooling rates disagree with min/max = %f/%f." % (cool_ratio.min(), cool_ratio.max())) # test the ionization balance assert_rel_equal( fHI_eq, fHI_g, test_precision, "HI fractions disagree with min/max = %f/%f." % ((fHI_eq / fHI_g).min(), (fHI_eq / fHI_g).max())) assert_rel_equal( fHII_eq, fHII_g, test_precision, "HII fractions disagree with min/max = %f/%f." % ((fHII_eq / fHII_g).min(), (fHII_eq / fHII_g).max())) assert_rel_equal( fHeI_eq, fHeI_g, test_precision, "HeI fractions disagree with min/max = %f/%f." % ((fHeI_eq / fHeI_g).min(), (fHeI_eq / fHeI_g).max())) assert_rel_equal( fHeII_eq, fHeII_g, test_precision, "HeII fractions disagree with min/max = %f/%f." % ((fHeII_eq / fHeII_g).min(), (fHeII_eq / fHeII_g).max())) assert_rel_equal( fHeIII_eq, fHeIII_g, test_precision, "HeIII fractions disagree with min/max = %f/%f." % ((fHeIII_eq / fHeIII_g).min(), (fHeIII_eq / fHeIII_g).max()))
def run_grackle(density = 1e10, initial_temperature = 1e3, final_time = 1e5, safety_factor=1e-2): current_redshift = 0. tiny_number = 1.0e-20 pygrackle.evolve_constant_density = _new_evolve_constant_density # Set solver parameters my_chemistry = chemistry_data() my_chemistry.three_body_rate = 4 my_chemistry.use_grackle = 1 my_chemistry.with_radiative_cooling = 1 my_chemistry.primordial_chemistry = 2 my_chemistry.metal_cooling = 0 my_chemistry.UVbackground = 0 my_chemistry.self_shielding_method = 0 my_chemistry.H2_self_shielding = 0 my_chemistry.cie_cooling = 0 grackle_dir = "/home/kwoksun2/grackle" my_chemistry.grackle_data_file = os.sep.join( [grackle_dir, "input", "CloudyData_UVB=HM2012.h5"]) # Set units my_chemistry.comoving_coordinates = 0 # proper units my_chemistry.a_units = 1.0 my_chemistry.three_body_rate = 4 my_chemistry.a_value = 1. / (1. + current_redshift) / \ my_chemistry.a_units my_chemistry.density_units = 1.66053904e-24 # 1u: amu # rho = 1.0 is 1.67e-24 g my_chemistry.length_units = 1.0 # cm my_chemistry.time_units = 1.0 # s my_chemistry.velocity_units = my_chemistry.a_units * \ (my_chemistry.length_units / my_chemistry.a_value) / \ my_chemistry.time_units rval = my_chemistry.initialize() fc = FluidContainer(my_chemistry, 1) fc["density"][:] = density tiny_number = 1.0e-20 if my_chemistry.primordial_chemistry > 0: # these are in mass_density fc["HI"][:] = 0.76 * fc["density"] /3. fc["HII"][:] = 0.76 * fc["density"] /3. fc["HeI"][:] = (1 - 0.76) * fc["density"] /2. fc["HeII"][:] = (1 - 0.76) * fc["density"] /2. fc["HeIII"][:] = tiny_number if my_chemistry.primordial_chemistry > 1: fc["H2I"][:] = 0.76 * fc["density"] /3. fc["H2II"][:] = tiny_number fc["HM"][:] = tiny_number fc["de"][:] = fc["HII"][:] + fc["HeII"][:]/4. + fc["HeIII"][:]/4.*2.0 if my_chemistry.primordial_chemistry > 2: fc["DI"][:] = 2.0 * 3.4e-5 * fc["density"] fc["DII"][:] = tiny_number * fc["density"] fc["HDI"][:] = tiny_number * fc["density"] if my_chemistry.metal_cooling == 1: fc["metal"][:] = 0.1 * fc["density"] * \ my_chemistry.SolarMetalFractionByMass fc["x-velocity"][:] = 0.0 fc["y-velocity"][:] = 0.0 fc["z-velocity"][:] = 0.0 fc["energy"][:] = initial_temperature / \ fc.chemistry_data.temperature_units fc.calculate_temperature() fc["energy"][:] *= initial_temperature / fc["temperature"] tic = timeit.default_timer() # let gas cool at constant density data = pygrackle.evolve_constant_density( fc, final_time=final_time, safety_factor=safety_factor) toc = timeit.default_timer() run_time = toc - tic print("time lapsed", run_time) # convert grackle language to dengo language name_map_dict = { 'HI':'H_1', 'HII':'H_2', 'HeI':'He_1', 'HeII':'He_2', 'HeIII':'He_3', 'H2I' : 'H2_1', 'H2II': 'H2_2', 'HM' : 'H_m0', 'de':'de', 'temperature':'T', 'time': 't', 'energy':'ge'} weight_map_dict = { 'HI':1.00794, 'HII':1.00794, 'HeI':4.002602, 'HeII':4.002602, 'HeIII':4.002602, 'H2II': 2.01588, 'H2I' : 2.01588, 'HM' : 1.00794, 'de':1.00794, 'time': 1.0, 'temperature': 1.0, 'energy': 1.0} data_grackle = {} for key in name_map_dict.keys(): key_dengo = name_map_dict[key] if key_dengo in ["t","T","ge"]: data_grackle[key_dengo] = data[key].value else: data_grackle[key_dengo] = data[key].value / weight_map_dict[key] / u.amu_cgs.value save_obj(data_grackle, 'grackle_data') return data_grackle, run_time
eq_pressure = np.zeros(npoints) file = open(outname, "w") file.write("#n rho T P\n") for n in densities: # initial values (loop over this) density = n * 1.0 initial_temperature = 4000.0 final_time = 1000.0 # Myr # chemistry my_chemistry = chemistry_data() my_chemistry.use_grackle = 1 my_chemistry.with_radiative_cooling = 1 my_chemistry.primordial_chemistry = 1 my_chemistry.metal_cooling = 1 my_chemistry.self_shielding_method = 3 my_chemistry.UVbackground = 1 grackle_dir = '/home/emerick/code/grackle' my_chemistry.grackle_data_file = grackle_dir + '/input/' + cloudy_file # Set units my_chemistry.comoving_coordinates = 0 # proper units my_chemistry.a_units = 1.0 my_chemistry.a_value = 1. / (1. + current_redshift) / \ my_chemistry.a_units
def cooling_cell(density=12.2, initial_temperature=2.0E4, final_time=30.0, metal_fraction=4.0E-4, make_plot=False, save_output=False, primordial_chemistry=2, outname=None, save_H2_fraction=False, return_result=False, verbose=False, H2_converge=None, *args, **kwargs): current_redshift = 0. # Set solver parameters my_chemistry = chemistry_data() my_chemistry.use_grackle = 1 my_chemistry.with_radiative_cooling = 1 my_chemistry.primordial_chemistry = primordial_chemistry my_chemistry.metal_cooling = 1 my_chemistry.UVbackground = 1 my_chemistry.self_shielding_method = 3 if primordial_chemistry > 1: my_chemistry.H2_self_shielding = 2 my_chemistry.h2_on_dust = 1 my_chemistry.three_body_rate = 4 grackle_dir = "/home/aemerick/code/grackle-emerick/" my_chemistry.grackle_data_file = os.sep.join( #['/home/aemerick/code/grackle-emerick/input/CloudyData_UVB=HM2012.h5']) [grackle_dir, "input", "CloudyData_UVB=HM2012_shielded.h5"]) # set the factors my_chemistry.LW_factor = kwargs.get("LW_factor", 1.0) my_chemistry.k27_factor = kwargs.get("k27_factor", 1.0) #if 'LW_factor' in kwargs.keys(): # my_chemistry.LW_factor = kwargs['LW_factor'] #else: # my_chemistry.LW_factor = 1.0 #if 'k27_factor' in kwargs.keys(): # my_chemistry.k27_factor = kwargs['k27_factor'] #else: # my_chemistry.k27_factor = 1.0 # Set units my_chemistry.comoving_coordinates = 0 # proper units my_chemistry.a_units = 1.0 my_chemistry.a_value = 1. / (1. + current_redshift) / \ my_chemistry.a_units my_chemistry.density_units = mass_hydrogen_cgs # rho = 1.0 is 1.67e-24 g my_chemistry.length_units = cm_per_mpc # 1 Mpc in cm my_chemistry.time_units = sec_per_Myr # 1 Myr in s my_chemistry.velocity_units = my_chemistry.a_units * \ (my_chemistry.length_units / my_chemistry.a_value) / \ my_chemistry.time_units rval = my_chemistry.initialize() fc = FluidContainer(my_chemistry, 1) fc["density"][:] = density if my_chemistry.primordial_chemistry > 0: fc["HI"][:] = 0.76 * fc["density"] fc["HII"][:] = tiny_number * fc["density"] fc["HeI"][:] = (1.0 - 0.76) * fc["density"] fc["HeII"][:] = tiny_number * fc["density"] fc["HeIII"][:] = tiny_number * fc["density"] if my_chemistry.primordial_chemistry > 1: fc["H2I"][:] = tiny_number * fc["density"] fc["H2II"][:] = tiny_number * fc["density"] fc["HM"][:] = tiny_number * fc["density"] fc["de"][:] = tiny_number * fc["density"] fc['H2_self_shielding_length'][:] = 1.8E-6 if my_chemistry.primordial_chemistry > 2: fc["DI"][:] = 2.0 * 3.4e-5 * fc["density"] fc["DII"][:] = tiny_number * fc["density"] fc["HDI"][:] = tiny_number * fc["density"] if my_chemistry.metal_cooling == 1: fc["metal"][:] = metal_fraction * fc["density"] * \ my_chemistry.SolarMetalFractionByMass fc["x-velocity"][:] = 0.0 fc["y-velocity"][:] = 0.0 fc["z-velocity"][:] = 0.0 fc["energy"][:] = initial_temperature / \ fc.chemistry_data.temperature_units fc.calculate_temperature() fc["energy"][:] *= initial_temperature / fc["temperature"] # timestepping safety factor safety_factor = 0.001 # let gas cool at constant density #if verbose: print("Beginning Run") data = evolve_constant_density(fc, final_time=final_time, H2_converge=H2_converge, safety_factor=safety_factor, verbose=verbose) #else: # print "Beginning Run" # with NoStdStreams(): # data = evolve_constant_density( # fc, final_time=final_time, H2_converge = 1.0E-6, # safety_factor=safety_factor) # print "Ending Run" if make_plot: p1, = plt.loglog(data["time"].to("Myr"), data["temperature"], color="black", label="T") plt.xlabel("Time [Myr]") plt.ylabel("T [K]") data["mu"] = data["temperature"] / \ (data["energy"] * (my_chemistry.Gamma - 1.) * fc.chemistry_data.temperature_units) plt.twinx() p2, = plt.semilogx(data["time"].to("Myr"), data["mu"], color="red", label="$\\mu$") plt.ylabel("$\\mu$") plt.legend([p1, p2], ["T", "$\\mu$"], fancybox=True, loc="center left") plt.savefig("cooling_cell.png") # save data arrays as a yt dataset if outname is None: outname = 'cooling_cell_%.2f_%.2f' % (my_chemistry.k27_factor, my_chemistry.LW_factor) if save_output: yt.save_as_dataset({}, outname + '.h5', data) if my_chemistry.primordial_chemistry > 1: H2_fraction = (data['H2I'] + data['H2II']) / data['density'] else: H2_fraction = np.zeros(np.size(data['density'])) if save_H2_fraction: #np.savetxt(outname + ".dat", [data['time'], H2_fraction]) f = open("all_runs_d_%.2f.dat" % (density), "a") # f.write("# k27 LW f_H2 T time\n") f.write("%8.8E %8.8E %8.8E %8.8E %8.8E \n" % (my_chemistry.k27_factor, my_chemistry.LW_factor, H2_fraction[-1], data['temperature'][-1], data['time'][-1])) f.close() if return_result: return data else: return