index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
46,677
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/tests/_python_reference/network.py
import numba import numpy as np from numba.experimental import jitclass from pynucastro.rates import TableIndex, TableInterpolator, TabularRate, Tfactors from pynucastro.screening import PlasmaState, ScreenFactors jn = 0 jp = 1 jhe4 = 2 jc12 = 3 jo16 = 4 jne20 = 5 jne23 = 6 jna23 = 7 jmg23 = 8 nnuc = 9 A = np.zeros((nnuc), dtype=np.int32) A[jn] = 1 A[jp] = 1 A[jhe4] = 4 A[jc12] = 12 A[jo16] = 16 A[jne20] = 20 A[jne23] = 23 A[jna23] = 23 A[jmg23] = 23 Z = np.zeros((nnuc), dtype=np.int32) Z[jn] = 0 Z[jp] = 1 Z[jhe4] = 2 Z[jc12] = 6 Z[jo16] = 8 Z[jne20] = 10 Z[jne23] = 10 Z[jna23] = 11 Z[jmg23] = 12 names = [] names.append("n") names.append("h1") names.append("he4") names.append("c12") names.append("o16") names.append("ne20") names.append("ne23") names.append("na23") names.append("mg23") def to_composition(Y): """Convert an array of molar fractions to a Composition object.""" from pynucastro import Composition, Nucleus nuclei = [Nucleus.from_cache(name) for name in names] comp = Composition(nuclei) for i, nuc in enumerate(nuclei): comp.X[nuc] = Y[i] * A[i] return comp @jitclass([ ("c12_c12__he4_ne20", numba.float64), ("c12_c12__n_mg23", numba.float64), ("c12_c12__p_na23", numba.float64), ("he4_c12__o16", numba.float64), ("n__p__weak__wc12", numba.float64), ("he4_he4_he4__c12", numba.float64), ("na23__ne23", numba.float64), ("ne23__na23", numba.float64), ]) class RateEval: def __init__(self): self.c12_c12__he4_ne20 = np.nan self.c12_c12__n_mg23 = np.nan self.c12_c12__p_na23 = np.nan self.he4_c12__o16 = np.nan self.n__p__weak__wc12 = np.nan self.he4_he4_he4__c12 = np.nan self.na23__ne23 = np.nan self.ne23__na23 = np.nan # note: we cannot make the TableInterpolator global, since numba doesn't like global jitclass # load data for na23 --> ne23 na23__ne23_rate = TabularRate(rfile='na23--ne23-toki') na23__ne23_info = (na23__ne23_rate.table_rhoy_lines, na23__ne23_rate.table_temp_lines, na23__ne23_rate.tabular_data_table) # load data for ne23 --> na23 ne23__na23_rate = TabularRate(rfile='ne23--na23-toki') ne23__na23_info = (ne23__na23_rate.table_rhoy_lines, ne23__na23_rate.table_temp_lines, ne23__na23_rate.tabular_data_table) @numba.njit() def ye(Y): return np.sum(Z * Y)/np.sum(A * Y) @numba.njit() def c12_c12__he4_ne20(rate_eval, tf): # c12 + c12 --> he4 + ne20 rate = 0.0 # cf88r rate += np.exp( 61.2863 + -84.165*tf.T913i + -1.56627*tf.T913 + -0.0736084*tf.T9 + -0.072797*tf.T953 + -0.666667*tf.lnT9) rate_eval.c12_c12__he4_ne20 = rate @numba.njit() def c12_c12__n_mg23(rate_eval, tf): # c12 + c12 --> n + mg23 rate = 0.0 # cf88r rate += np.exp( -12.8056 + -30.1485*tf.T9i + 11.4826*tf.T913 + 1.82849*tf.T9 + -0.34844*tf.T953) rate_eval.c12_c12__n_mg23 = rate @numba.njit() def c12_c12__p_na23(rate_eval, tf): # c12 + c12 --> p + na23 rate = 0.0 # cf88r rate += np.exp( 60.9649 + -84.165*tf.T913i + -1.4191*tf.T913 + -0.114619*tf.T9 + -0.070307*tf.T953 + -0.666667*tf.lnT9) rate_eval.c12_c12__p_na23 = rate @numba.njit() def he4_c12__o16(rate_eval, tf): # c12 + he4 --> o16 rate = 0.0 # nac2 rate += np.exp( 69.6526 + -1.39254*tf.T9i + 58.9128*tf.T913i + -148.273*tf.T913 + 9.08324*tf.T9 + -0.541041*tf.T953 + 70.3554*tf.lnT9) # nac2 rate += np.exp( 254.634 + -1.84097*tf.T9i + 103.411*tf.T913i + -420.567*tf.T913 + 64.0874*tf.T9 + -12.4624*tf.T953 + 137.303*tf.lnT9) rate_eval.he4_c12__o16 = rate @numba.njit() def n__p__weak__wc12(rate_eval, tf): # n --> p rate = 0.0 # wc12w rate += np.exp( -6.78161) rate_eval.n__p__weak__wc12 = rate @numba.njit() def he4_he4_he4__c12(rate_eval, tf): # he4 + he4 + he4 --> c12 rate = 0.0 # fy05n rate += np.exp( -0.971052 + -37.06*tf.T913i + 29.3493*tf.T913 + -115.507*tf.T9 + -10.0*tf.T953 + -1.33333*tf.lnT9) # fy05r rate += np.exp( -24.3505 + -4.12656*tf.T9i + -13.49*tf.T913i + 21.4259*tf.T913 + -1.34769*tf.T9 + 0.0879816*tf.T953 + -13.1653*tf.lnT9) # fy05r rate += np.exp( -11.7884 + -1.02446*tf.T9i + -23.57*tf.T913i + 20.4886*tf.T913 + -12.9882*tf.T9 + -20.0*tf.T953 + -2.16667*tf.lnT9) rate_eval.he4_he4_he4__c12 = rate @numba.njit() def na23__ne23(rate_eval, T, rhoY): # na23 --> ne23 na23__ne23_interpolator = TableInterpolator(*na23__ne23_info) r = na23__ne23_interpolator.interpolate(np.log10(rhoY), np.log10(T), TableIndex.RATE.value) rate_eval.na23__ne23 = 10.0**r @numba.njit() def ne23__na23(rate_eval, T, rhoY): # ne23 --> na23 ne23__na23_interpolator = TableInterpolator(*ne23__na23_info) r = ne23__na23_interpolator.interpolate(np.log10(rhoY), np.log10(T), TableIndex.RATE.value) rate_eval.ne23__na23 = 10.0**r def rhs(t, Y, rho, T, screen_func=None): return rhs_eq(t, Y, rho, T, screen_func) @numba.njit() def rhs_eq(t, Y, rho, T, screen_func): tf = Tfactors(T) rate_eval = RateEval() # reaclib rates c12_c12__he4_ne20(rate_eval, tf) c12_c12__n_mg23(rate_eval, tf) c12_c12__p_na23(rate_eval, tf) he4_c12__o16(rate_eval, tf) n__p__weak__wc12(rate_eval, tf) he4_he4_he4__c12(rate_eval, tf) # tabular rates na23__ne23(rate_eval, T, rho*ye(Y)) ne23__na23(rate_eval, T, rho*ye(Y)) if screen_func is not None: plasma_state = PlasmaState(T, rho, Y, Z) scn_fac = ScreenFactors(6, 12, 6, 12) scor = screen_func(plasma_state, scn_fac) rate_eval.c12_c12__he4_ne20 *= scor rate_eval.c12_c12__n_mg23 *= scor rate_eval.c12_c12__p_na23 *= scor scn_fac = ScreenFactors(2, 4, 6, 12) scor = screen_func(plasma_state, scn_fac) rate_eval.he4_c12__o16 *= scor scn_fac = ScreenFactors(2, 4, 2, 4) scor = screen_func(plasma_state, scn_fac) scn_fac2 = ScreenFactors(2, 4, 4, 8) scor2 = screen_func(plasma_state, scn_fac2) rate_eval.he4_he4_he4__c12 *= scor * scor2 dYdt = np.zeros((nnuc), dtype=np.float64) dYdt[jn] = ( -Y[jn]*rate_eval.n__p__weak__wc12 +5.00000000000000e-01*rho*Y[jc12]**2*rate_eval.c12_c12__n_mg23 ) dYdt[jp] = ( +5.00000000000000e-01*rho*Y[jc12]**2*rate_eval.c12_c12__p_na23 +Y[jn]*rate_eval.n__p__weak__wc12 ) dYdt[jhe4] = ( -rho*Y[jhe4]*Y[jc12]*rate_eval.he4_c12__o16 -3*1.66666666666667e-01*rho**2*Y[jhe4]**3*rate_eval.he4_he4_he4__c12 +5.00000000000000e-01*rho*Y[jc12]**2*rate_eval.c12_c12__he4_ne20 ) dYdt[jc12] = ( -2*5.00000000000000e-01*rho*Y[jc12]**2*rate_eval.c12_c12__he4_ne20 -2*5.00000000000000e-01*rho*Y[jc12]**2*rate_eval.c12_c12__n_mg23 -2*5.00000000000000e-01*rho*Y[jc12]**2*rate_eval.c12_c12__p_na23 -rho*Y[jhe4]*Y[jc12]*rate_eval.he4_c12__o16 +1.66666666666667e-01*rho**2*Y[jhe4]**3*rate_eval.he4_he4_he4__c12 ) dYdt[jo16] = ( +rho*Y[jhe4]*Y[jc12]*rate_eval.he4_c12__o16 ) dYdt[jne20] = ( +5.00000000000000e-01*rho*Y[jc12]**2*rate_eval.c12_c12__he4_ne20 ) dYdt[jne23] = ( -Y[jne23]*rate_eval.ne23__na23 +Y[jna23]*rate_eval.na23__ne23 ) dYdt[jna23] = ( -Y[jna23]*rate_eval.na23__ne23 +5.00000000000000e-01*rho*Y[jc12]**2*rate_eval.c12_c12__p_na23 +Y[jne23]*rate_eval.ne23__na23 ) dYdt[jmg23] = ( +5.00000000000000e-01*rho*Y[jc12]**2*rate_eval.c12_c12__n_mg23 ) return dYdt def jacobian(t, Y, rho, T, screen_func=None): return jacobian_eq(t, Y, rho, T, screen_func) @numba.njit() def jacobian_eq(t, Y, rho, T, screen_func): tf = Tfactors(T) rate_eval = RateEval() # reaclib rates c12_c12__he4_ne20(rate_eval, tf) c12_c12__n_mg23(rate_eval, tf) c12_c12__p_na23(rate_eval, tf) he4_c12__o16(rate_eval, tf) n__p__weak__wc12(rate_eval, tf) he4_he4_he4__c12(rate_eval, tf) # tabular rates na23__ne23(rate_eval, T, rho*ye(Y)) ne23__na23(rate_eval, T, rho*ye(Y)) if screen_func is not None: plasma_state = PlasmaState(T, rho, Y, Z) scn_fac = ScreenFactors(6, 12, 6, 12) scor = screen_func(plasma_state, scn_fac) rate_eval.c12_c12__he4_ne20 *= scor rate_eval.c12_c12__n_mg23 *= scor rate_eval.c12_c12__p_na23 *= scor scn_fac = ScreenFactors(2, 4, 6, 12) scor = screen_func(plasma_state, scn_fac) rate_eval.he4_c12__o16 *= scor scn_fac = ScreenFactors(2, 4, 2, 4) scor = screen_func(plasma_state, scn_fac) scn_fac2 = ScreenFactors(2, 4, 4, 8) scor2 = screen_func(plasma_state, scn_fac2) rate_eval.he4_he4_he4__c12 *= scor * scor2 jac = np.zeros((nnuc, nnuc), dtype=np.float64) jac[jn, jn] = ( -rate_eval.n__p__weak__wc12 ) jac[jn, jc12] = ( +5.00000000000000e-01*rho*2*Y[jc12]*rate_eval.c12_c12__n_mg23 ) jac[jp, jn] = ( +rate_eval.n__p__weak__wc12 ) jac[jp, jc12] = ( +5.00000000000000e-01*rho*2*Y[jc12]*rate_eval.c12_c12__p_na23 ) jac[jhe4, jhe4] = ( -rho*Y[jc12]*rate_eval.he4_c12__o16 -3*1.66666666666667e-01*rho**2*3*Y[jhe4]**2*rate_eval.he4_he4_he4__c12 ) jac[jhe4, jc12] = ( -rho*Y[jhe4]*rate_eval.he4_c12__o16 +5.00000000000000e-01*rho*2*Y[jc12]*rate_eval.c12_c12__he4_ne20 ) jac[jc12, jhe4] = ( -rho*Y[jc12]*rate_eval.he4_c12__o16 +1.66666666666667e-01*rho**2*3*Y[jhe4]**2*rate_eval.he4_he4_he4__c12 ) jac[jc12, jc12] = ( -2*5.00000000000000e-01*rho*2*Y[jc12]*rate_eval.c12_c12__he4_ne20 -2*5.00000000000000e-01*rho*2*Y[jc12]*rate_eval.c12_c12__n_mg23 -2*5.00000000000000e-01*rho*2*Y[jc12]*rate_eval.c12_c12__p_na23 -rho*Y[jhe4]*rate_eval.he4_c12__o16 ) jac[jo16, jhe4] = ( +rho*Y[jc12]*rate_eval.he4_c12__o16 ) jac[jo16, jc12] = ( +rho*Y[jhe4]*rate_eval.he4_c12__o16 ) jac[jne20, jc12] = ( +5.00000000000000e-01*rho*2*Y[jc12]*rate_eval.c12_c12__he4_ne20 ) jac[jne23, jne23] = ( -rate_eval.ne23__na23 ) jac[jne23, jna23] = ( +rate_eval.na23__ne23 ) jac[jna23, jc12] = ( +5.00000000000000e-01*rho*2*Y[jc12]*rate_eval.c12_c12__p_na23 ) jac[jna23, jne23] = ( +rate_eval.ne23__na23 ) jac[jna23, jna23] = ( -rate_eval.na23__ne23 ) jac[jmg23, jc12] = ( +5.00000000000000e-01*rho*2*Y[jc12]*rate_eval.c12_c12__n_mg23 ) return jac
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,678
pynucastro/pynucastro
refs/heads/main
/pynucastro/reduction/reduction_utils.py
class MPIImportError(Exception): pass class FailedMPIImport: """Class that can replace an mpi4py.MPI import and will throw an error if used.""" def __init__(self, error=None, msg=None): self.error_obj = error if msg is None: msg = ("Failed to import MPI from mpi4py. Check your mpi4py installation if you" " want to run with MPI.") self.msg = msg def __getattr__(self, attr): if self.error_obj is not None: raise MPIImportError(self.msg) from self.error_obj raise MPIImportError(self.msg) def mpi_importer(): """ Lazy MPI import, where we only throw an error if the import failed and then we attempt to use the object. """ try: from mpi4py import MPI # pylint: disable=import-outside-toplevel except (ModuleNotFoundError, ImportError) as e: MPI = FailedMPIImport(e) return MPI def mpi_numpy_decomp(MPI_N, MPI_rank, n): """ Decompose a set of conditions for *MPI_N* MPI processes, where the conditions are a sequence of 3 sequences with ordering (composition_sequence, density_sequence, temperature_sequence). This structure for the dataset is necessary for the vectorized reduction algorithms. """ if MPI_N <= n[0]: comp_idx = MPI_rank comp_step = MPI_N rho_idx = T_idx = 0 rho_step = T_step = 1 elif MPI_N <= n[0]*n[1]: m = MPI_N // n[0] if MPI_rank <= n[0]*m: comp_idx = MPI_rank % n[0] comp_step = n[0] rho_idx = MPI_rank // n[0] rho_step = m else: comp_idx = n[0] comp_step = 1 rho_idx = n[1] rho_step = 1 T_idx = 0 T_step = 1 elif MPI_N <= n[0]*n[1]*n[2]: m = MPI_N // (n[0] * n[1]) if MPI_rank <= n[0]*n[1]*m: comp_idx = MPI_rank % n[0] comp_step = n[0] rho_idx = (MPI_rank // n[0]) % n[1] rho_step = n[1] T_idx = MPI_rank // (n[0] * n[1]) T_step = m else: comp_idx = n[0] comp_step = 1 rho_idx = n[1] rho_step = 1 T_idx = n[2] T_step = 1 else: m = MPI_N // (n[0] * n[1]) if MPI_rank <= n[0]*n[1]*n[2]: comp_idx = MPI_rank % n[0] comp_step = n[0] rho_idx = (MPI_rank // n[0]) % n[1] rho_step = n[1] T_idx = MPI_rank // (n[0] * n[1]) T_step = n[2] else: comp_idx = n[0] comp_step = 1 rho_idx = n[1] rho_step = 1 T_idx = n[2] T_step = 1 return comp_idx, comp_step, rho_idx, rho_step, T_idx, T_step def to_list(x, n=1): """ Convert a sequence or non-iterable to a list. In the non-iterable case, the supplied object will be repeated *n* times (default 1). """ try: return list(x) except TypeError: return [x] * n
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,679
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/tests/test_screening.py
import pytest from pytest import approx from pynucastro import networks from pynucastro.screening import chugunov_2007, chugunov_2009 class TestScreening: @pytest.fixture(scope="class") def rc(self): files = ["c12-ag-o16-nac2", "c12-c12a-ne20-cf88", "c12-c12n-mg23-cf88", "c12-c12p-na23-cf88", "he4-aag-c12-fy05"] return networks.RateCollection(files) def test_screening_map(self, rc): screening_map = rc.get_screening_map() assert len(screening_map) == 4 assert len(screening_map[0].rates) == 1 assert len(screening_map[1].rates) == 3 assert len(screening_map[2].rates) == 1 assert len(screening_map[3].rates) == 1 # two triple-alpha screening steps assert screening_map[2].rates[0] == screening_map[3].rates[0] == rc.rates[4] def test_screening_chugunov_2007(self, rc): c = networks.Composition(rc.unique_nuclei) c.set_solar_like() rates = {"c12 + he4 --> o16 <nac2_reaclib__>": 5.794539791829924, "c12 + c12 --> he4 + ne20 <cf88_reaclib__>": 103.21274049093526, "c12 + c12 --> n + mg23 <cf88_reaclib__reverse>": 103.21274049093526, "c12 + c12 --> p + na23 <cf88_reaclib__>": 103.21274049093526, "he4 + he4 + he4 --> c12 <fy05_reaclib__>": 6.502599619793744} factors = rc.evaluate_screening(1.e6, 1.e8, c, screen_func=chugunov_2007) for r, factor in factors.items(): assert factor == approx(rates[r.get_rate_id()]) def test_screening_chugunov_2009(self, rc): c = networks.Composition(rc.unique_nuclei) c.set_solar_like() rates = {"c12 + he4 --> o16 <nac2_reaclib__>": 4.405674333522246, "c12 + c12 --> he4 + ne20 <cf88_reaclib__>": 89.6640543016441, "c12 + c12 --> n + mg23 <cf88_reaclib__reverse>": 89.6640543016441, "c12 + c12 --> p + na23 <cf88_reaclib__>": 89.6640543016441, "he4 + he4 + he4 --> c12 <fy05_reaclib__>": 4.380701422122169} factors = rc.evaluate_screening(1.e6, 1.e8, c, screen_func=chugunov_2009) for r, factor in factors.items(): assert factor == approx(rates[r.get_rate_id()])
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,680
pynucastro/pynucastro
refs/heads/main
/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py
#!/usr/bin/env python """ Reformat the partition function tables retrieved from https://download.nucastro.org/astro/fits/ into a standard format for pynucastro. The tables part_frdm.asc and part_etfsiq.asc corresponds to: Thomas Rauscher and Friedrich-Karl Thielemann, Atomic Data and Nuclear Data Tables, 75:1–351, 2000 """ import argparse from pynucastro.nucdata import PeriodicTable #Create a parser variable that demands for a table and creates an option to add a name to the formatted table parser = argparse.ArgumentParser() parser.add_argument('table', type=str, help='Name of the input table. "E.g. part_frdm.asc.txt"') parser.add_argument('-o', '--output', type=str, default='frdm_low', help='Name of the formatted table E.g. ') args = parser.parse_args() finput = open(args.table, 'r') temp = ['0.01', '0.15', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1.0', '1.5', '2.0', '2.5', '3.0', '3.5', '4.0', '4.5', '5.0', '6.0', '7.0', '8.0', '9.0', '10.0'] temperatures = ['{}E+9'.format(t) for t in temp] fout = open(args.output+'.txt', 'w') fout.write('# Partition function evaluation name: {}\n'.format(args.output)) fout.write('# Each entry is of the form:\n') fout.write('#\n') fout.write('# [nucleus name, e.g. ni56]\n') fout.write('# [List of partition function values]\n') fout.write('#\n') fout.write('# Partition functions all evaluated at these temperatures (K):\n') fout.write(' '.join(temperatures) + '\n\n') for _ in range(5): finput.readline() for line in finput: nucleus_stats = line.strip().split() Z = int(nucleus_stats.pop(0)) A = int(nucleus_stats.pop(0)) J = float(nucleus_stats.pop(0)) if Z == 0: assert A == 1 abbrev = 'n' else: element = PeriodicTable.lookup_Z(Z) abbrev = '{}{}'.format(element.abbreviation, A) part1 = finput.readline().strip().strip('\n') part2 = finput.readline().strip().strip('\n') part3 = finput.readline().strip().strip('\n') fout.write('{}\n'.format(abbrev)) fout.write('{}\n\n'.format(part1+' '+part2+' '+part3)) finput.readline() fout.close() finput.close()
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,681
pynucastro/pynucastro
refs/heads/main
/examples/CNO_cython/setup.py
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext import numpy ext = Extension("cno_rhs", ["cno_rhs.pyx"], include_dirs = [numpy.get_include()]) setup(ext_modules=[ext], cmdclass = {'build_ext': build_ext})
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,682
pynucastro/pynucastro
refs/heads/main
/pynucastro/nucdata/AtomicMassEvaluation/ame_nuclide.py
class AMENuclide(object): """Hold the information for a single nucleus from the AME database.""" def __init__(self, n=None, z=None, a=None, element=None, origin=None, mexcess=None, d_mexcess=None, nucbind=None, d_nucbind=None, decay_type=None, ebeta=None, d_ebeta=None, mass=None, d_mass=None): self.n = None self.z = None self.a = None self.element = None self.origin = None self.mexcess = None self.d_mexcess = None self.nucbind = None self.d_nucbind = None self.decay_type = None self.ebeta = None self.d_ebeta = None self.mass = None self.d_mass = None if n: self.n = int(n) if z: self.z = int(z) if a: self.a = int(a) self.element = element self.origin = origin if mexcess: self.mexcess = float(mexcess) if d_mexcess: self.d_mexcess = float(d_mexcess) if nucbind: self.nucbind = float(nucbind) if d_nucbind: self.d_nucbind = float(d_nucbind) self.decay_type = decay_type if ebeta: self.ebeta = float(ebeta) if d_ebeta: self.d_ebeta = float(d_ebeta) if mass: self.mass = float(mass) if d_mass: self.d_mass = float(d_mass) self.convert_MeV() self.convert_amu() def print_contents(self): """ Print Contents """ print('n = {}'.format(self.n)) print('z = {}'.format(self.z)) print('a = {}'.format(self.a)) print('element = {}'.format(self.element)) print('origin = {}'.format(self.origin)) print('mexcess = {}'.format(self.mexcess)) print('d_mexcess = {}'.format(self.d_mexcess)) print('nucbind = {}'.format(self.nucbind)) print('d_nucbind = {}'.format(self.d_nucbind)) print('decay_type = {}'.format(self.decay_type)) print('ebeta = {}'.format(self.ebeta)) print('d_ebeta = {}'.format(self.d_ebeta)) print('mass = {}'.format(self.mass)) print('d_mass = {}'.format(self.d_mass)) def convert_MeV(self): """ Convert keV to MeV """ if self.mexcess: self.mexcess = self.mexcess/1.0e3 if self.d_mexcess: self.d_mexcess = self.d_mexcess/1.0e3 if self.nucbind: self.nucbind = self.nucbind/1.0e3 if self.d_nucbind: self.d_nucbind = self.d_nucbind/1.0e3 if self.ebeta: self.ebeta = self.ebeta/1.0e3 if self.d_ebeta: self.d_ebeta = self.d_ebeta/1.0e3 def convert_amu(self): """ Convert micro-amu to amu """ if self.mass: self.mass = self.mass/1.0e6 if self.d_mass: self.d_mass = self.d_mass/1.0e6 def __str__(self): return "{}-{}".format(self.element, self.a)
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,683
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/tests/test_python_net2.py
# unit tests for rates import pytest import pynucastro as pyna class TestPythonNetwork2: @pytest.fixture(scope="class") def pynet(self, reaclib_library): mylib = reaclib_library.linking_nuclei(["he4", "c12", "o16"]) return pyna.PythonNetwork(libraries=[mylib], inert_nuclei=["ne20"]) def test_full_ydot_string(self, pynet): dyodt = \ """dYdt[jo16] = ( -Y[jo16]*rate_eval.o16__he4_c12 +rho*Y[jhe4]*Y[jc12]*rate_eval.he4_c12__o16 ) """ dynedt = \ """dYdt[jne20] = 0.0 """ assert pynet.full_ydot_string(pyna.Nucleus("o16")) == dyodt assert pynet.full_ydot_string(pyna.Nucleus("ne20")) == dynedt
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,684
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/tests/test_approx_screening.py
# unit tests for screening with approximate rates # we'll test both symmetric and "normal" screening import pytest import pynucastro as pyna class TestApproxScreening: @pytest.fixture(scope="class") def mynet(self, reaclib_library): return reaclib_library.linking_nuclei(["p", "he4", "mg24", "al27", "si28", "p31", "s32"]) @pytest.fixture(scope="class") def pynet_symmetric(self, mynet): pynet_symmetric = pyna.PythonNetwork(libraries=[mynet], symmetric_screening=True) pynet_symmetric.make_ap_pg_approx() pynet_symmetric.remove_nuclei(["al27", "p31"]) return pynet_symmetric @pytest.fixture(scope="class") def pynet(self, mynet): pynet = pyna.PythonNetwork(libraries=[mynet]) pynet.make_ap_pg_approx() pynet.remove_nuclei(["al27", "p31"]) return pynet def test_symmetric_screening(self, pynet_symmetric): screening_map = pynet_symmetric.get_screening_map() # all of the reaclib rates that are 2 body (and not "n") should have # be in the screening map for r in pynet_symmetric.reaclib_rates: if r.Q < 0: nucs = [q for q in r.products if q.Z != 0] if len(nucs) == 1: continue assert nucs[0] in r.symmetric_screen and nucs[1] in r.symmetric_screen r_scn = [q for q in screening_map if q.n1 in r.symmetric_screen and q.n2 in r.symmetric_screen] assert len(r_scn) == 1 else: nucs = [q for q in r.reactants if q.Z != 0] if len(nucs) == 1: continue assert nucs[0] in r.symmetric_screen and nucs[1] in r.symmetric_screen r_scn = [q for q in screening_map if q.n1 in r.symmetric_screen and q.n2 in r.symmetric_screen] assert len(r_scn) == 1 def test_screening(self, pynet): screening_map = pynet.get_screening_map() # all of the reaclib rates that are 2 body (and not "n") should have # be in the screening map for r in pynet.reaclib_rates: nucs = [q for q in r.reactants if q.Z != 0] if len(nucs) == 1: continue assert nucs[0] in r.ion_screen and nucs[1] in r.ion_screen r_scn = [q for q in screening_map if q.n1 in r.ion_screen and q.n2 in r.ion_screen] assert len(r_scn) == 1
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,685
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/python_network.py
"""Support modules to write a pure python reaction network ODE source""" import os import shutil import sys from pynucastro.networks.rate_collection import RateCollection from pynucastro.rates.rate import ApproximateRate class PythonNetwork(RateCollection): """A pure python reaction network.""" def full_ydot_string(self, nucleus, indent=""): """construct the python form of dY(nucleus)/dt""" ostr = "" if not self.nuclei_consumed[nucleus] + self.nuclei_produced[nucleus]: # this captures an inert nucleus ostr += f"{indent}dYdt[j{nucleus}] = 0.0\n\n" else: ostr += f"{indent}dYdt[j{nucleus}] = (\n" for r in self.nuclei_consumed[nucleus]: c = r.reactants.count(nucleus) if c == 1: ostr += f"{indent} -{r.ydot_string_py()}\n" else: ostr += f"{indent} -{c}*{r.ydot_string_py()}\n" for r in self.nuclei_produced[nucleus]: c = r.products.count(nucleus) if c == 1: ostr += f"{indent} +{r.ydot_string_py()}\n" else: ostr += f"{indent} +{c}*{r.ydot_string_py()}\n" ostr += f"{indent} )\n\n" return ostr def full_jacobian_element_string(self, ydot_i_nucleus, y_j_nucleus, indent=""): """return the Jacobian element dYdot(ydot_i_nucleus)/dY(y_j_nucleus)""" # this is the jac(i,j) string idx_str = f"jac[j{ydot_i_nucleus}, j{y_j_nucleus}]" ostr = "" if not self.nuclei_consumed[ydot_i_nucleus] + self.nuclei_produced[ydot_i_nucleus]: # this covers the case where a nucleus is not created or # destroyed in the entire network, but is just passive ostr += f"{indent}{idx_str} = 0.0\n\n" else: ostr += f"{indent}{idx_str} = (\n" rate_terms_str = "" for r in self.nuclei_consumed[ydot_i_nucleus]: c = r.reactants.count(ydot_i_nucleus) jac_str = r.jacobian_string_py(y_j_nucleus) if jac_str == "": continue if c == 1: rate_terms_str += f"{indent} -{jac_str}\n" else: rate_terms_str += f"{indent} -{c}*{jac_str}\n" for r in self.nuclei_produced[ydot_i_nucleus]: c = r.products.count(ydot_i_nucleus) jac_str = r.jacobian_string_py(y_j_nucleus) if jac_str == "": continue if c == 1: rate_terms_str += f"{indent} +{jac_str}\n" else: rate_terms_str += f"{indent} +{c}*{jac_str}\n" if rate_terms_str == "": return "" ostr += rate_terms_str ostr += f"{indent} )\n\n" return ostr def screening_string(self, indent=""): ostr = "" ostr += f"{indent}plasma_state = PlasmaState(T, rho, Y, Z)\n" screening_map = self.get_screening_map() for i, scr in enumerate(screening_map): if not (scr.n1.dummy or scr.n2.dummy): # calculate the screening factor ostr += f"\n{indent}scn_fac = ScreenFactors({scr.n1.Z}, {scr.n1.A}, {scr.n2.Z}, {scr.n2.A})\n" ostr += f"{indent}scor = screen_func(plasma_state, scn_fac)\n" if scr.name == "he4_he4_he4": # we don't need to do anything here, but we want to avoid immediately applying the screening pass elif scr.name == "he4_he4_he4_dummy": # make sure the previous iteration was the first part of 3-alpha assert screening_map[i - 1].name == "he4_he4_he4" # handle the second part of the screening for 3-alpha ostr += f"{indent}scn_fac2 = ScreenFactors({scr.n1.Z}, {scr.n1.A}, {scr.n2.Z}, {scr.n2.A})\n" ostr += f"{indent}scor2 = screen_func(plasma_state, scn_fac2)\n" # there might be both the forward and reverse 3-alpha # if we are doing symmetric screening for r in scr.rates: # use scor from the previous loop iteration ostr += f"{indent}rate_eval.{r.fname} *= scor * scor2\n" else: # there might be several rates that have the same # reactants and therefore the same screening applies # -- handle them all now for r in scr.rates: ostr += f"{indent}rate_eval.{r.fname} *= scor\n" return ostr def rates_string(self, indent=""): """section for evaluating the rates and storing them in rate_eval""" ostr = "" ostr += f"{indent}# reaclib rates\n" for r in self.reaclib_rates: ostr += f"{indent}{r.fname}(rate_eval, tf)\n" if self.derived_rates: ostr += f"\n{indent}# derived rates\n" for r in self.derived_rates: ostr += f"{indent}{r.fname}(rate_eval, tf)\n" if self.tabular_rates: ostr += f"\n{indent}# tabular rates\n" for r in self.tabular_rates: ostr += f"{indent}{r.fname}(rate_eval, T, rho*ye(Y))\n" ostr += "\n" # apply screening factors, if we're given a screening function ostr += f"{indent}if screen_func is not None:\n" ostr += self.screening_string(indent=indent + 4*" ") if self.approx_rates: ostr += f"\n{indent}# approximate rates\n" for r in self.approx_rates: ostr += f"{indent}{r.fname}(rate_eval, tf)\n" return ostr def _write_network(self, outfile=None): """ This is the actual RHS for the system of ODEs that this network describes. """ # pylint: disable=arguments-differ if outfile is None: of = sys.stdout else: of = open(outfile, "w") indent = 4*" " of.write("import numba\n") of.write("import numpy as np\n") of.write("from numba.experimental import jitclass\n\n") of.write("from pynucastro.rates import TableIndex, TableInterpolator, TabularRate, Tfactors\n") of.write("from pynucastro.screening import PlasmaState, ScreenFactors\n\n") # integer keys for i, n in enumerate(self.unique_nuclei): of.write(f"j{n} = {i}\n") of.write(f"nnuc = {len(self.unique_nuclei)}\n\n") # nuclei properties of.write("A = np.zeros((nnuc), dtype=np.int32)\n\n") for n in self.unique_nuclei: of.write(f"A[j{n}] = {n.A}\n") of.write("\n") of.write("Z = np.zeros((nnuc), dtype=np.int32)\n\n") for n in self.unique_nuclei: of.write(f"Z[j{n}] = {n.Z}\n") of.write("\n") of.write("names = []\n") for n in self.unique_nuclei: of.write(f"names.append(\"{n.short_spec_name}\")\n") of.write("\n") of.write("def to_composition(Y):\n") of.write(f'{indent}''"""Convert an array of molar fractions to a Composition object."""\n') of.write(f'{indent}'"from pynucastro import Composition, Nucleus\n") of.write(f'{indent}'"nuclei = [Nucleus.from_cache(name) for name in names]\n") of.write(f'{indent}'"comp = Composition(nuclei)\n") of.write(f'{indent}'"for i, nuc in enumerate(nuclei):\n") of.write(f'{indent*2}'"comp.X[nuc] = Y[i] * A[i]\n") of.write(f'{indent}'"return comp\n\n") # partition function data (if needed) nuclei_pfs = self.get_nuclei_needing_partition_functions() for n in nuclei_pfs: of.write(f"{n}_temp_array = np.array({list(n.partition_function.temperature/1.0e9)})\n") of.write(f"{n}_pf_array = np.array({list(n.partition_function.partition_function)})\n") of.write("\n") # rate_eval class of.write("@jitclass([\n") for r in self.all_rates: of.write(f'{indent}("{r.fname}", numba.float64),\n') of.write("])\n") of.write("class RateEval:\n") of.write(f"{indent}def __init__(self):\n") for r in self.all_rates: of.write(f"{indent*2}self.{r.fname} = np.nan\n") of.write("\n") # tabular rate data if self.tabular_rates: of.write("# note: we cannot make the TableInterpolator global, since numba doesn't like global jitclass\n") for r in self.tabular_rates: of.write(f"# load data for {r.rid}\n") of.write(f"{r.fname}_rate = TabularRate(rfile='{r.rfile}')\n") of.write(f"{r.fname}_info = ({r.fname}_rate.table_rhoy_lines,\n") of.write(f" {r.fname}_rate.table_temp_lines,\n") of.write(f" {r.fname}_rate.tabular_data_table)\n\n") of.write("@numba.njit()\n") of.write("def ye(Y):\n") of.write(f"{indent}return np.sum(Z * Y)/np.sum(A * Y)\n\n") # the functions to evaluate the temperature dependence of the rates _rate_func_written = [] for r in self.rates: if isinstance(r, ApproximateRate): # write out the function string for all of the rates we depend on for cr in r.get_child_rates(): if cr in _rate_func_written: continue of.write(cr.function_string_py()) _rate_func_written.append(cr) # now write out the function that computes the # approximate rate of.write(r.function_string_py()) else: if r in _rate_func_written: continue of.write(r.function_string_py()) _rate_func_written.append(r) # the rhs() function of.write("def rhs(t, Y, rho, T, screen_func=None):\n") of.write(f"{indent}return rhs_eq(t, Y, rho, T, screen_func)\n\n") of.write("@numba.njit()\n") of.write("def rhs_eq(t, Y, rho, T, screen_func):\n\n") # get the rates of.write(f"{indent}tf = Tfactors(T)\n") of.write(f"{indent}rate_eval = RateEval()\n\n") of.write(self.rates_string(indent=indent)) of.write("\n") of.write(f"{indent}dYdt = np.zeros((nnuc), dtype=np.float64)\n\n") # now make the RHSs for n in self.unique_nuclei: of.write(self.full_ydot_string(n, indent=indent)) of.write(f"{indent}return dYdt\n\n") # the jacobian() function of.write("def jacobian(t, Y, rho, T, screen_func=None):\n") of.write(f"{indent}return jacobian_eq(t, Y, rho, T, screen_func)\n\n") of.write("@numba.njit()\n") of.write("def jacobian_eq(t, Y, rho, T, screen_func):\n\n") # get the rates of.write(f"{indent}tf = Tfactors(T)\n") of.write(f"{indent}rate_eval = RateEval()\n\n") of.write(self.rates_string(indent=indent)) of.write("\n") of.write(f"{indent}jac = np.zeros((nnuc, nnuc), dtype=np.float64)\n\n") # now fill each Jacobian element for n_i in self.unique_nuclei: for n_j in self.unique_nuclei: of.write(self.full_jacobian_element_string(n_i, n_j, indent=indent)) of.write(f"{indent}return jac\n") # Copy any tables in the network to the current directory # if the table file cannot be found, print a warning and continue. try: odir = os.path.dirname(outfile) except TypeError: odir = None for tr in self.tabular_rates: tdir = os.path.dirname(tr.rfile_path) if tdir != os.getcwd(): tdat_file = os.path.join(tdir, tr.table_file) if os.path.isfile(tdat_file): shutil.copy(tdat_file, odir or os.getcwd()) else: print(f'WARNING: Table data file {tr.table_file} not found.') rtoki_file = os.path.join(tdir, tr.rfile) if os.path.isfile(rtoki_file): shutil.copy(rtoki_file, odir or os.getcwd()) else: print(f'WARNING: Table metadata file {tr.rfile} not found.')
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,686
pynucastro/pynucastro
refs/heads/main
/pynucastro/nucdata/mass_table.py
import os class MassTable: """ The purpose of this class is to: a) Create a dictionary mapping nuclides to their mass excess A_nuc - A measured in MeV from the table mass_excess2020.txt. b) Parse the information of the previously defined dictionary to the Nucleus class. The only required variable to construct an instance of this class is : var filename: that contains the .txt table file with the nuclei and their mass excess. If this variable is not provided, then mass_excess2020.txt is considered by default. """ def __init__(self, filename=None): self._mass_diff = {} if filename: self.filename = filename else: datafile_name = 'mass_excess2020.txt' nucdata_dir = os.path.dirname(os.path.realpath(__file__)) self.filename = os.path.join(os.path.join(nucdata_dir, 'AtomicMassEvaluation'), datafile_name) self._read_table() def _read_table(self): file = open(self.filename, 'r') for _ in range(4): file.readline() for line in file: data_list = line.strip().split() #print(data_list) A_str = data_list.pop(0) Z_str = data_list.pop(0) dm_str = data_list.pop(0) A = int(A_str) Z = int(Z_str) dm = float(dm_str) self._mass_diff[A, Z] = dm file.close() def get_mass_diff(self, a, z): if (a, z) in self._mass_diff: return self._mass_diff[a, z] raise NotImplementedError("Nuclear mass difference is not available")
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,687
pynucastro/pynucastro
refs/heads/main
/pynucastro/rates/tests/test_library_rates_by_name.py
# unit tests for rates class TestGetRatesByName: def test_reaclib_rates(self, reaclib_library): r1 = "c12(a,g)o16" r2 = "c12(c12,a)ne20" r3 = "a(aa,g)c12" r4 = "f20(e,nu)o20" # not found in ReacLib r5 = "f20(,e)ne20" assert reaclib_library.get_rate_by_name(r1).fname == "he4_c12__o16" assert reaclib_library.get_rate_by_name(r2).fname == "c12_c12__he4_ne20" assert reaclib_library.get_rate_by_name(r3).fname == "he4_he4_he4__c12" assert reaclib_library.get_rate_by_name(r4) is None assert reaclib_library.get_rate_by_name(r5).fname == "f20__ne20__weak__wc12" def test_tabular_rates(self, tabular_library): r4 = "f20(e,nu)o20" # note found in ReacLib r5 = "f20(,e)ne20" r6 = "ti45(e,nu)sc45" r7 = "ti45(,e)v45" assert tabular_library.get_rate_by_name(r4).fname == "f20__o20" assert tabular_library.get_rate_by_name(r5).fname == "f20__ne20" assert tabular_library.get_rate_by_name(r6).fname == "ti45__sc45" assert tabular_library.get_rate_by_name(r7).fname == "ti45__v45"
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,688
pynucastro/pynucastro
refs/heads/main
/pynucastro/rates/library.py
import collections import io import os import re from pynucastro.nucdata import Nucleus, UnsupportedNucleus from pynucastro.rates.rate import (DerivedRate, Rate, RateFileError, ReacLibRate, TabularRate, _find_rate_file, get_rates_dir, load_rate) def list_known_rates(): """ list the rates found in the library """ lib_path = f"{os.path.dirname(__file__)}/../library/" for _, _, filenames in os.walk(lib_path): for f in filenames: # skip over files that are not rate files if f.endswith(".md") or f.endswith(".dat") or f.endswith(".py") or f.endswith(".ipynb"): continue try: lib = Library(f) except (RateFileError, UnsupportedNucleus): continue print(f"{f:32} : ") for r in lib.get_rates(): print(f" : {r}") def _rate_name_to_nuc(name): # first try to interpret name as A(x,y)B rate_str = re.compile(r"([A-Za-z0-9]+)\(([A-Za-z0-9_]*),([A-Za-z0-9_]*)\)([A-Za-z0-9]+)", re.IGNORECASE) nucs = rate_str.search(name) try: _r = [nucs.group(1), nucs.group(2)] _p = [nucs.group(3), nucs.group(4)] except AttributeError: return None # now try to make nuclei objects. reactants = [] for nuc in _r: if nuc == "": continue try: n = Nucleus(nuc) reactants.append(n) except (ValueError, AssertionError): # we need to interpret some things specially if nuc.lower() in ["e", "nu", "_", "g", "gamma"]: # first electrons and neutrins, and nothing continue if nuc.lower() == "aa": reactants.append(Nucleus("he4")) reactants.append(Nucleus("he4")) else: raise products = [] for nuc in _p: if nuc == "": continue try: n = Nucleus(nuc) products.append(n) except (ValueError, AssertionError): # we need to interpret some things specially if nuc.lower() in ["e", "nu", "_", "g", "gamma"]: # first electrons and neutrinos, gammas, and nothing continue if nuc.lower() == "aa": products.append(Nucleus("he4")) products.append(Nucleus("he4")) else: raise return reactants, products class Library: """ A Library is a Rate container that reads a single file containing one or many Reaclib rates, possibly containing multiple sets per rate. The Library class also implements searching based on rules specified by RateFilter objects. """ def __init__(self, libfile=None, rates=None): self._library_file = libfile if rates: self._rates = None if isinstance(rates, Rate): rates = [rates] if isinstance(rates, dict): self._rates = rates elif isinstance(rates, (list, set)): self._add_from_rate_list(rates) else: raise TypeError("rates in Library constructor must be a Rate object, list of Rate objects, or dictionary of Rate objects keyed by Rate.get_rate_id()") else: self._rates = {} self._library_source_lines = collections.deque() if self._library_file: self._library_file = _find_rate_file(self._library_file) self._read_library_file() def heaviest(self): """ Return the heaviest nuclide in this library. """ nuc = None for _, r in self._rates.items(): rnuc = r.heaviest() if nuc: if rnuc.A > nuc.A or (rnuc.A == nuc.A and rnuc.Z < nuc.Z): nuc = rnuc else: nuc = rnuc return nuc def lightest(self): """ Return the lightest nuclide in this library. """ nuc = None for _, r in self._rates.items(): rnuc = r.lightest() if nuc: if rnuc.A < nuc.A or (rnuc.A == nuc.A and rnuc.Z > nuc.Z): nuc = rnuc else: nuc = rnuc return nuc def _add_from_rate_list(self, ratelist): """ Add to the rate dictionary from the supplied list of Rate objects. """ if not self._rates: self._rates = {} for r in ratelist: rid = r.get_rate_id() if rid in self._rates: raise ValueError(f"supplied a Rate object already in the Library: {r}") self._rates[rid] = r def _read_library_file(self): # loop through library file, read lines with open(self._library_file) as flib: for line in flib: ls = line.rstrip('\n') if ls.strip(): self._library_source_lines.append(ls) # identify distinct rates from library lines current_chapter = None while True: if len(self._library_source_lines) == 0: break # Check to see if there is a chapter ID, if not then use current_chapter # (for Reaclib v1 formatted library files) line = self._library_source_lines[0].strip() chapter = None if line in ('t', 'T'): chapter = 't' self._library_source_lines.popleft() else: try: chapter = int(line) except (TypeError, ValueError): # we can't interpret line as a chapter so use current_chapter assert current_chapter, f'malformed library file {self._library_file}, cannot identify chapter.' chapter = current_chapter else: self._library_source_lines.popleft() current_chapter = chapter rlines = None rate_type = None if chapter == 't': rlines = [self._library_source_lines.popleft() for i in range(5)] rate_type = "tabular" elif isinstance(chapter, int): rlines = [self._library_source_lines.popleft() for i in range(3)] rate_type = "reaclib" if rlines: sio = io.StringIO('\n'.join([f'{chapter}'] + rlines)) #print(sio.getvalue()) try: if rate_type == "reaclib": r = ReacLibRate(rfile=sio) elif rate_type == "tabular": r = TabularRate(rfile=sio) else: raise NotImplementedError("rate not implemented") except UnsupportedNucleus: pass else: rid = r.get_rate_id() if rid in self._rates: self._rates[rid] = self._rates[rid] + r else: self._rates[rid] = r def write_to_file(self, filename, prepend_rates_dir=False): """ Write the library out to a file of the given name in Reaclib format. Will be automatically written to the pynucastro rate file directory if True is passed in as the second argument. """ if prepend_rates_dir: filename = os.path.join(get_rates_dir(), filename) with open(filename, 'w') as f: for rate in self.get_rates(): rate.write_to_file(f) def __repr__(self): """ Return a string containing the rates IDs in this library. """ rstrings = [] tmp_rates = [v for k, v in self._rates.items()] for r in sorted(tmp_rates): if r.Q is not None and r.Q >= 0: rstrings.append(f'{r.__repr__():30} [Q = {float(r.Q):6.2f} MeV] ({r.get_rate_id()})') for r in sorted(tmp_rates): if r.Q is not None and r.Q < 0: rstrings.append(f'{r.__repr__():30} [Q = {float(r.Q):6.2f} MeV] ({r.get_rate_id()})') for r in sorted(tmp_rates): if r.Q is None: rstrings.append(f'{r.__repr__():30} ({r.get_rate_id()})') return '\n'.join(rstrings) def __add__(self, other): """ Add two libraries to get a library containing rates from both. """ new_rates = self._rates for rid, r in other._rates.items(): if rid in new_rates: if r != new_rates[rid]: raise ValueError(f'rate {r} defined differently in libraries {self._library_file} and {other._library_file}') else: new_rates[rid] = r new_library = Library(rates=new_rates) return new_library def __sub__(self, other): return self.diff(other) def get_num_rates(self): """Return the number of rates known to the library""" return len(self._rates) def get_rates(self): """ Return a list of the rates in this library. """ rlist = [r for _, r in self._rates.items()] return rlist def get_rate(self, rid): """ Return a rate matching the id provided. """ try: return self._rates[rid] except KeyError: pass # fallback to the rate fname try: r = [q for q in self.get_rates() if q.fname == rid][0] return r except IndexError: raise LookupError(f"rate identifier {rid!r} does not match a rate in this library.") from None def get_rate_by_nuclei(self, reactants, products): """given a list of reactants and products, return any matching rates""" _tmp = [r for r in self.get_rates() if sorted(r.reactants) == sorted(reactants) and sorted(r.products) == sorted(products)] if not _tmp: return None if len(_tmp) == 1: return _tmp[0] return _tmp def get_rate_by_name(self, name): """Given a string representing a rate in the form 'A(x,y)B' (or a list of strings for multiple rates) return the Rate objects that match from the Library. If there are multiple inputs, then a list of Rate objects is returned. """ if isinstance(name, str): rate_name_list = [name] else: rate_name_list = name rates_out = [] for rname in rate_name_list: reactants, products = _rate_name_to_nuc(rname) rf = RateFilter(reactants=reactants, products=products) _lib = self.filter(rf) if _lib is None: return None rates_out += _lib.get_rates() if (len(rates_out)) == 1: return rates_out[0] return rates_out def get_nuclei(self): """get the list of unique nuclei""" return {nuc for r in self.get_rates() for nuc in r.reactants + r.products} def diff(self, other_library): """Return a Library containing the rates in this library that are not contained in other_library""" diff_rates = set(self.get_rates()) - set(other_library.get_rates()) new_library = Library(rates=diff_rates) return new_library def remove_rate(self, rate): """Manually remove a rate from the library by supplying the short name "A(x,y)B, a Rate object, or the rate id""" if isinstance(rate, Rate): rid = rate.get_rate_id() self._rates.pop(rid) elif isinstance(rate, str): rid = self.get_rate_by_name(rate).get_rate_id() self._rates.pop(rid) else: # we assume that a rate id as provided self._rates.pop(rate) def add_rate(self, rate): """Manually add a rate by giving a Rate object""" if isinstance(rate, Rate): if rate not in self._rates: self._rates[rate.get_rate_id()] = rate else: raise TypeError("invalid Rate object") def linking_nuclei(self, nuclist, with_reverse=True, print_warning=True): """ Return a Library object containing the rates linking the nuclei provided in the list of Nucleus objects or nucleus abbreviations 'nuclist'. If with_reverse is True, then include reverse rates. Otherwise include only forward rates. If print_warning is True, then print out a warning if one of the input nuclei is not linked. """ if isinstance(nuclist, (Nucleus, str)): nuclist = [nuclist] nucleus_set = set() for nuc in nuclist: if isinstance(nuc, Nucleus): nucleus_set.add(nuc) else: anuc = Nucleus(nuc) nucleus_set.add(anuc) # Discard rates with nuclei that are not in nucleus_set filtered_rates = [] for r in self.get_rates(): include = True for nuc in r.reactants: if nuc not in nucleus_set: include = False break for nuc in r.products: if nuc not in nucleus_set: include = False break if not with_reverse and r.reverse: include = False if include: filtered_rates.append(r) # create a new library containing the filtered rates new_lib = Library(rates=filtered_rates) # print out a warning if one of the input nuclei is not linked if print_warning: lib_nuclei = new_lib.get_nuclei() for nuc in nucleus_set: if nuc not in lib_nuclei: print(f"warning: {nuc} was not able to be linked") return new_lib def filter(self, filter_spec): """ filter_specs should be an iterable of RateFilter objects or a single RateFilter object. Library.filter yields all rates matching any RateFilter in filter_specs. If RateFilter.exact, then return rates with exactly the reactants or products passed in as arguments. """ if isinstance(filter_spec, RateFilter): filter_specifications = [filter_spec] else: filter_specifications = list(filter_spec) matching_rates = {} for rid, r in self._rates.items(): for f in filter_specifications: if f.matches(r): matching_rates[rid] = r break if matching_rates: return Library(rates=matching_rates) return None def forward(self): """ Select only the forward rates, discarding the inverse rates obtained by detailed balance. """ only_fwd_filter = RateFilter(reverse=False) only_fwd = self.filter(only_fwd_filter) return only_fwd def backward(self): """ Select only the reverse rates, obtained by detailed balance. """ only_bwd_filter = RateFilter(reverse=True) only_bwd = self.filter(only_bwd_filter) return only_bwd def derived_forward(self): """ In this library, we exclude the weak and tabular rates from the .forward() library which includes all the ReacLib forward reactions. In a future PR, we will classify forward reactions as exothermic (Q>0), and reverse by endothermic (Q<0). However, ReacLib does not follow this path. If a reaction is measured experimentally (independent of Q), they use detailed balance to get the opposite direction. Eventually, I want to classify forward and reverse by positive Q and negative Q; however, for testing purposes, making this classification may eventually lead to computing the detailed balance twice. The idea of derived_forward is to eliminate the reverse and weak, and see if our job gives the same Reaclib predictions, checking the NSE convergence with the pf functions. In the future, I want to move this function in a unit test. """ collect_rates = [] onlyfwd = self.forward() for r in onlyfwd.get_rates(): try: DerivedRate(rate=r, compute_Q=False, use_pf=False) except ValueError: continue else: collect_rates.append(r) list1 = Library(rates=collect_rates) return list1 def derived_backward(self, compute_Q=False, use_pf=False): """ This library contains the detailed balance reverse reactions over the selected .derived_forward(), computed by hand. """ derived_rates = [] onlyfwd = self.derived_forward() for r in onlyfwd.get_rates(): try: i = DerivedRate(rate=r, compute_Q=compute_Q, use_pf=use_pf) except ValueError: continue else: derived_rates.append(i) onlybwd = Library(rates=derived_rates) return onlybwd class RateFilter: """RateFilter filters out a specified rate or set of rates A RateFilter stores selection rules specifying a rate or group of rates to assist in searching for rates stored in a Library. """ def __init__(self, reactants=None, products=None, exact=True, reverse=None, min_reactants=None, max_reactants=None, min_products=None, max_products=None, filter_function=None): """Create a new RateFilter with the given selection rules Keyword Arguments: reactants -- Description of the reactants as one of: 1. a list of Nucleus objects 2. a list of string descriptions of reactant nuclides these strings must be parsable by Nucleus 3. a single reactant Nucleus 4. a single string description of the reactant nuclide products -- Description of the products in same form as above exact -- boolean, if True, products or reactants must match exactly [default] if False, then all products or reactants must be found in a comparison rate, but the comparison may contain additional products or reactants reverse -- boolean, if True, only match reverse-derived rates if False, only match directly-derived rates if None, you don't care, match both [default] min_reactants -- int, match Rates that have at least this many reactants min_products -- int, match Rates that have at least this many products max_reactants -- int, match Rates that have no more than this many reactants max_products -- int, match Rates that have no more than this many products filter_function -- callable (Rate -> bool), a callable that can take a single rate as an argument may be used to specify additional criteria, returning True if the rate meets all of them, False otherwise Examples: Create a filter that finds all proton capture and proton-burning reactions in a Library instance my_library:: >>> pcap_filter = RateFilter(reactants='p', exact=False) >>> pcap_library = my_library.filter(pcap_filter) or you can use Nucleus:: >>> pcap_filter = RateFilter(reactants=Nucleus('p'), exact=False) >>> pcap_library = my_library.filter(pcap_filter) Create a filter that finds C12 (a,g) O16 Notes: + photons/gammas are not treated as nuclides, so they cannot be a reactant or product + this rate is in the ReacLib library used here as O16 --> He4 C12 -- you need to know how your library treats rates:: >>> cago_filter = RateFilter(reactants='o16', products=['c12', 'a']) >>> cago_library = my_library.filter(cago_filter) """ self.reactants = [] self.products = [] self.exact = exact self.reverse = reverse self.min_reactants = min_reactants self.min_products = min_products self.max_reactants = max_reactants self.max_products = max_products self.filter_function = filter_function if reactants: if isinstance(reactants, (Nucleus, str)): reactants = [reactants] self.reactants = [self._cast_nucleus(r) for r in reactants] if products: if isinstance(products, (Nucleus, str)): products = [products] self.products = [self._cast_nucleus(r) for r in products] @staticmethod def _cast_nucleus(r): """ Make sure r is of type Nucleus. """ if not isinstance(r, Nucleus): rnuc = Nucleus(r) return rnuc return r @staticmethod def _contents_equal(a, b): """ Return True if the contents of a and b exactly match, ignoring ordering. If either a or b is None, return True only if both a and b are None. """ if a and b: return len(a) == len(b) and sorted(a) == sorted(b) return (not a) and (not b) @staticmethod def _compare_nuclides(test, reference, exact=True): """ test and reference should be iterables of Nucleus objects. If an exact match is desired, test and reference should exactly match, ignoring ordering. Otherwise, return True only if every element of test appears at least one time in reference. """ matches = True if exact: matches = RateFilter._contents_equal(test, reference) else: for nuc in test: if nuc not in reference: matches = False break return matches def matches(self, r): """ Given a Rate r, see if it matches this RateFilter. """ # do cheaper checks first matches_reverse = True matches_min_reactants = True matches_min_products = True matches_max_reactants = True matches_max_products = True if isinstance(self.reverse, bool): matches_reverse = self.reverse == r.reverse if isinstance(self.min_reactants, int): matches_min_reactants = len(r.reactants) >= self.min_reactants if isinstance(self.min_products, int): matches_min_products = len(r.products) >= self.min_products if isinstance(self.max_reactants, int): matches_max_reactants = len(r.reactants) <= self.max_reactants if isinstance(self.max_products, int): matches_max_products = len(r.products) <= self.max_products # exit early if any of these checks failed if not (matches_reverse and matches_min_reactants and matches_min_products and matches_max_reactants and matches_max_products): return False # now do more expensive checks, and exit immediately if any fail if self.reactants: if not self._compare_nuclides(self.reactants, r.reactants, self.exact): return False if self.products: if not self._compare_nuclides(self.products, r.products, self.exact): return False if self.filter_function is not None: if not self.filter_function(r): return False return True def invert(self): """ Return a RateFilter matching the inverse rate. """ newfilter = RateFilter(reactants=self.products, products=self.reactants, exact=self.exact, reverse=self.reverse, min_reactants=self.min_products, max_reactants=self.max_products, min_products=self.min_reactants, max_products=self.max_reactants) return newfilter class ReacLibLibrary(Library): """Load the latest stored version of the ReacLib library and return a Library""" def __init__(self): libfile = 'reaclib_default2_20220329' Library.__init__(self, libfile=libfile) class TabularLibrary(Library): """Load all of the tabular rates known and return a Library""" def __init__(self): # find all of the tabular rates that pynucastro knows about # we'll assume that these are of the form *-toki lib_path = f"{os.path.dirname(__file__)}/../library/tabular" trates = [] for _, _, filenames in os.walk(lib_path): for f in filenames: if f.endswith("-toki"): trates.append(load_rate(f)) Library.__init__(self, rates=trates) class SuzukiLibrary(Library): """ Load all of the tabular rates inside /library/tabular/suzuki/ and return a Library. """ def __init__(self): # find all of the tabular rates that pynucastro knows about # we'll assume that these are of the form *-toki lib_path = f"{os.path.dirname(__file__)}/../library/tabular/suzuki" trates = [] for _, _, filenames in os.walk(lib_path): for f in filenames: if f.endswith("-toki"): trates.append(load_rate(f)) Library.__init__(self, rates=trates) class LangankeLibrary(Library): """ Load all of the tabular rates inside /library/tabular/langanke/ and return a Library. """ def __init__(self): # find all of the tabular rates that pynucastro knows about # we'll assume that these are of the form *-toki lib_path = f"{os.path.dirname(__file__)}/../library/tabular/langanke" trates = [] for _, _, filenames in os.walk(lib_path): for f in filenames: if f.endswith("-toki"): trates.append(load_rate(f)) Library.__init__(self, rates=trates)
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,689
pynucastro/pynucastro
refs/heads/main
/pynucastro/rates/tests/test_library.py
# unit tests for rates import pynucastro as pyna class TestLibrary: @classmethod def setup_class(cls): """ this is run once for each class before any tests """ @classmethod def teardown_class(cls): """ this is run once for each class after all tests """ def setup_method(self): """ this is run before each test """ trates = [] trates.append(pyna.load_rate("c12-pg-n13-ls09")) trates.append(pyna.load_rate("c13-pg-n14-nacr")) trates.append(pyna.load_rate("n13--c13-wc12")) trates.append(pyna.load_rate("n13-pg-o14-lg06")) trates.append(pyna.load_rate("n14-pg-o15-im05")) trates.append(pyna.load_rate("n15-pa-c12-nacr")) trates.append(pyna.load_rate("o14--n14-wc12")) trates.append(pyna.load_rate("o15--n15-wc12")) self.library = pyna.Library(rates=trates) self.removed_rates = [] self.removed_rates.append(trates.pop()) self.removed_rates.append(trates.pop()) self.smaller_lib = pyna.Library(rates=trates) def teardown_method(self): """ this is run after each test """ self.library = None self.smaller_lib = None self.removed_rates = None def test_heaviest(self): assert self.library.heaviest() == pyna.Nucleus("n15") def test_lightest(self): assert self.library.lightest() == pyna.Nucleus("p") def test_get_num_rates(self): assert self.library.get_num_rates() == 8 def test_get_rate(self): assert self.library.get_rate("c12 + p --> n13 <ls09_reaclib__>") == pyna.load_rate("c12-pg-n13-ls09") def test_diff(self): diff_lib = self.library - self.smaller_lib assert sorted(diff_lib.get_rates()) == sorted(self.removed_rates) def test_linking_nuclei(self): new_lib = self.library.linking_nuclei(["p", "c12", "n13", "c13"]) assert sorted(new_lib.get_rates()) == sorted([pyna.load_rate("c12-pg-n13-ls09"), pyna.load_rate("n13--c13-wc12")]) def test_forward_backward(self): assert self.library.backward() is None
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,690
pynucastro/pynucastro
refs/heads/main
/pynucastro/nucdata/__init__.py
"""Properties of nuclei needed in construction reaction rates (in particular, the binding energies) """ #__all__ = [binding_nuclide, binding_table, elements, partition_function] from .binding_table import BindingTable from .elements import Element, PeriodicTable, UnidentifiedElement from .mass_table import MassTable from .nucleus import Nucleus, UnsupportedNucleus, get_nuclei_in_range from .partition_function import (PartitionFunction, PartitionFunctionCollection, PartitionFunctionTable) from .spin_table import SpinTable
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,691
pynucastro/pynucastro
refs/heads/main
/pynucastro/library/tabular/suzuki/checktables.py
#!/usr/bin/env python3 import argparse parser = argparse.ArgumentParser() parser.add_argument("infile", type=str) parser.add_argument("-p", action="store_true", help="print stuff for checking which rate is which") args = parser.parse_args() table_file = None header_lines = None def nuc_A_first(nuc_A_last): snuc = "" for c in nuc_A_last: if c.isdigit(): snuc += c for c in nuc_A_last: if not c.isdigit(): snuc += c return snuc try: # get the nuclei from the name of the rate metadata file nucs_file = args.infile[:-5].split("--") f = open(args.infile, "r") chapter = f.readline().strip() # assert the chapter is "t" for a tabulated rate assert chapter == "t" # get the nuclei inside the rate metadata file nucs = f.readline().strip().split() # assert the nuclei in the rate metadata match the nuclei in the metadata filename assert nucs_file[0] == nucs[0] assert nucs_file[1] == nucs[1] # get the name of table file and number of header lines table_file = f.readline().strip() # get the nuclei from the table file and assert # those are the same nuclei involved in the rate table_file_nucs = table_file.split("_")[0].split("-") assert table_file_nucs[0].lower() == nuc_A_first(nucs[0]).lower() assert table_file_nucs[1].lower() == nuc_A_first(nucs[1]).lower() header_lines = int(f.readline().strip()) # assert table sizes are correct n = int(f.readline().strip()) assert n == 152 n = int(f.readline().strip()) assert n == 39 f.close() if args.p: print(args.infile) print(table_file) # checks to make sure valid data begins after the # number of header lines the rate metadata file says f = open(table_file, "r") for i, line in enumerate(f): if i > header_lines: break if i < header_lines: ls = line.strip() assert ls == "" or ls.startswith("!") if i == header_lines: lss = line.strip().split() rhoy = lss[0] temp = lss[1] assert rhoy == "1.000000e+07" assert temp == "1.000000e+07" if args.p: print("{}: {}".format(i, line.strip())) f.close() except: # noqa print("FAILED") else: print("OK")
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,692
pynucastro/pynucastro
refs/heads/main
/logo/logo_base.py
import pynucastro as pyna files = ["c12-pg-n13-ls09", "c13-pg-n14-nacr", "n13--c13-wc12", "n13-pg-o14-lg06", "n14-pg-o15-im05", "n15-pa-c12-nacr", "o14--n14-wc12", "o15--n15-wc12", "o14-ap-f17-Ha96c", "f17-pg-ne18-cb09", "ne18--f18-wc12", "f18-pa-o15-il10"] rc = pyna.RateCollection(files) comp = pyna.Composition(rc.get_nuclei()) comp.set_solar_like() rc.plot(rho=2.e6, T=3.e7, comp=comp, outfile="cno_flow.png")
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,693
pynucastro/pynucastro
refs/heads/main
/pynucastro/nucdata/binding_table.py
""" Reads tabular binding energy/nucleon data file and supplies table data. """ # Common Imports import os class BindingTable: """A simple class to manage reading and parsing the table of binding energy/nucleon.""" header_length = 2 def __init__(self, datfile=None): """ Initialize """ self.datfile = None if datfile: self.datfile = datfile else: thisdir = os.path.dirname(os.path.realpath(__file__)) fname = os.path.join(thisdir, 'binding_2016.txt') if os.path.isfile(fname): self.datfile = fname self.energies = {} if self.datfile: self.read() def read(self): """ Read the binding energy table """ try: f = open(self.datfile, 'r') except IOError: print('ERROR: data file not found!') raise # Get rid of the header for _ in range(self.header_length): f.readline() # Read nuclide mass data for line in f: ls = line.strip() n, z, ebind = ls.split() self.energies[int(n), int(z)] = float(ebind) f.close() def get_binding_energy(self, n, z): """ Returns the binding energy given n and z. """ if (n, z) in self.energies: return self.energies[n, z] raise NotImplementedError(f"nuclear data for Z={z} and N={n} not available")
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,694
pynucastro/pynucastro
refs/heads/main
/examples/triple-alpha/triple-alpha.py
# triple-alpha rate module generator from pynucastro.networks import PythonNetwork files = ["c12-gaa-he4-fy05", "he4-aag-c12-fy05"] triple_alpha_net = PythonNetwork(files) triple_alpha_net.write_network("triple-alpha_rhs.py")
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,695
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/tests/test_full_python_net.py
import os import shutil import numpy as np import pytest from numpy.testing import assert_allclose from pynucastro import networks class TestFullPythonNetwork: @pytest.fixture(scope="class") def fn(self): files = ["c12-c12a-ne20-cf88", "c12-c12n-mg23-cf88", "c12-c12p-na23-cf88", "c12-ag-o16-nac2", "na23--ne23-toki", "ne23--na23-toki", "n--p-wc12", "he4-aag-c12-fy05"] return networks.PythonNetwork(files) def test_write_network(self, fn): """test the write_network function""" test_path = "_test_python/" reference_path = "_python_reference/" base_path = os.path.relpath(os.path.dirname(__file__)) test_file = "network.py" os.makedirs(test_path, exist_ok=True) fn.write_network(outfile=os.path.join(test_path, test_file)) # compare contents of files with open(os.path.join(test_path, test_file), "r") as generated, \ open(os.path.join(base_path, reference_path, test_file), "r") as reference: assert generated.readlines() == reference.readlines() # clean up generated files if the test passed shutil.rmtree(test_path) def test_ydots(self, fn): test_path = "_test_python/" test_file = "network.py" os.makedirs(test_path, exist_ok=True) fn.write_network(outfile=os.path.join(test_path, test_file)) import _test_python.network as net X = np.zeros(net.nnuc) X[:] = 1.0 / net.nnuc Y = X * net.nnuc rho = 1.e8 T = 1.e9 ydot = net.rhs(0.0, Y, rho, T) ydot_benchmark = np.array([-1.129728e-03, 1.979093e-03, -1.702699e+06, 5.667057e+05, 6.454310e+02, 1.044892e-03, -1.745420e-02, 1.829885e-02, 4.718987e-06]) assert_allclose(ydot, ydot_benchmark, rtol=1.e-6)
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,696
pynucastro/pynucastro
refs/heads/main
/examples/rp-process/rp_process.py
#!/usr/bin/env python3 import sys import argparse from collections import deque from pynucastro.rates import Library, RateFilter from pynucastro.nucdata import Nucleus, BindingTable from pynucastro.networks import PythonNetwork, Composition ################################################# # Set up argument parser and process arguments # ################################################# description = """Script for generating a reaction network modeling the rp-process with a given nucleus as the endpoint.""" endpoint_help = """The nucleus at which the network terminates. Should be provided as the string abbreviation of the nuclide (e.g. Ni56, case insensitive).""" library_help = """The library file to draw the rates from. This is supplied directly to the Library constructor.""" write_network_help = """The name of the Python file to write the network to. No network will be written out if this is not supplied.""" write_lib_help = """The name of the file in the library directory to write the constructed library to. The library will not be written out if this is not supplied.""" parser = argparse.ArgumentParser(description=description) parser.add_argument('endpoint', help=endpoint_help) parser.add_argument('-l', '--library', default='reaclib_default2_20220329', help=library_help) parser.add_argument('-w', '--write_network', default='', help=write_network_help) parser.add_argument('--write_lib', default='', help=write_lib_help) args = parser.parse_args(sys.argv[1:]) endpoint = Nucleus(args.endpoint) ##################################### # Load library and generate network # ##################################### print("Loading library...") full_lib = Library(args.library) print("Building network...") core_nuclei = ["p", "d", "he3", "he4", "li7", "be7", "be8", "b8", "c12", "n13", "n14", "n15", "o14", "o15", "o16", "o17", "o18", "f17", "f18", "f19", "f20", "ne18", "ne19", "ne20", "ne21"] core_nuclei = list(map(Nucleus, core_nuclei)) core_lib = full_lib.linking_nuclei(core_nuclei) def is_beta_plus(rate): """ Filter for beta+ decays (and electron captures). """ if len(rate.products) != len(rate.reactants): return False if len(rate.reactants) != 1: return False react, = rate.reactants prod, = rate.products return prod.Z < react.Z # Restrict the library to these 7 reaction types # Forward rates p_gamma = RateFilter(reactants="p", max_products=1, exact=False) alpha_gamma = RateFilter(reactants="he4", max_products=1, exact=False) alpha_p = RateFilter(reactants="he4", products="p", exact=False) # Reverse and weak rates gamma_p = RateFilter(products="p", max_reactants=1, exact=False) gamma_alpha = RateFilter(products="he4", max_reactants=1, exact=False) p_alpha = RateFilter(reactants="p", products="he4", exact=False) beta_plus = RateFilter(filter_function=is_beta_plus) # Compute reduced library red_lib = full_lib.filter((p_gamma, alpha_gamma, alpha_p, gamma_p, gamma_alpha, p_alpha, beta_plus)) bintable = BindingTable() def flatten(iterable): """ Take iterable of iterables, and flatten it to one dimension. """ for col in iterable: for item in col: yield item def append_all(q, iterable): """ Append all items in the iterable to the queue. """ for item in iterable: q.append(item) def product_limiter(): """ This helps trim the library a bit by excluding rates with products with more protons than the endpoint, heavier than the endpoint, or with relatively high or low neutron percentages. """ # Proton number bounds Zlo, Zhi = 6, endpoint.Z # Nucleon number bounds Alo, Ahi = 12, endpoint.A # Bounds on A / Z ratio to drop peripheral nuclei Rlo, Rhi = 1.69, 2.2 def limit_products(r): meet_conds = \ ( (Zlo <= p.Z <= Zhi and Alo <= p.A <= Ahi and Rlo <= p.A / p.Z <= Rhi and (p.N, p.Z) in bintable.energies) or (p.Z, p.A) == (1, 1) or (p.Z, p.A) == (2, 4) for p in r.products ) return all(meet_conds) return limit_products limiter = product_limiter() final_lib = Library(rates=core_lib.get_rates()) seeds = [nuc for nuc in core_nuclei if nuc.A >= 12] encountered = set(seeds) | {Nucleus("p"), Nucleus("he4")} seeds = deque(seeds) while seeds: # Get the new rates with seed as a reactant seed = seeds.popleft() filt = RateFilter(reactants=seed, filter_function=limiter, exact=False) new_lib = red_lib.filter(filt) if new_lib is None: continue final_lib += new_lib # Append all unseen nuclei to the queue prod = (r.products for r in new_lib.get_rates()) prod = flatten(prod) prod = filter(lambda p: p not in encountered, prod) prod = sorted(set(prod)) append_all(seeds, prod) encountered.update(prod) encountered = sorted(encountered) rp_net = PythonNetwork(libraries=[final_lib], precedence=["wc17", "ths8"]) print("Network constructed.") print() print(f"Species Encountered:") print(encountered) print() print(f"Number of Species: {len(encountered)}") print(f"Number of Rates: {len(rp_net.rates)}") print() if args.write_lib: final_lib.write_to_file(args.write_lib, True) if args.write_network: print("Writing network...") rp_net.write_network(args.write_network) print("Task completed.")
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,697
pynucastro/pynucastro
refs/heads/main
/pynucastro/rates/tests/conftest.py
# reuse fixture from networks/tests # pylint: disable=unused-import from pynucastro.networks.tests.conftest import reaclib_library # noqa: F401 from pynucastro.networks.tests.conftest import tabular_library # noqa: F401
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,698
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/base_cxx_network.py
"""Support for a pure C++ reaction network. These functions will write the C++ code necessary to integrate a reaction network comprised of the rates that are passed in. """ import itertools import os import re import shutil import sys from abc import ABC, abstractmethod import numpy as np import sympy from pynucastro.networks.rate_collection import RateCollection from pynucastro.networks.sympy_network_support import SympyRates class BaseCxxNetwork(ABC, RateCollection): """Interpret the collection of rates and nuclei and produce the C++ code needed to integrate the network. """ def __init__(self, *args, **kwargs): """Initialize the C++ network. We take a single argument: a list of rate files that will make up the network """ super().__init__(*args, **kwargs) # Get the template files for writing this network code self.template_files = self._get_template_files() self.symbol_rates = SympyRates() self.ydot_out_result = None self.solved_ydot = False self.jac_out_result = None self.jac_null_entries = None self.solved_jacobian = False self.function_specifier = "inline" self.dtype = "double" # a dictionary of functions to call to handle specific parts # of the C++ template self.ftags = {} self.ftags['<nrat_reaclib>'] = self._nrat_reaclib self.ftags['<nrat_tabular>'] = self._nrat_tabular self.ftags['<nrxn>'] = self._nrxn self.ftags['<rate_names>'] = self._rate_names self.ftags['<ebind>'] = self._ebind self.ftags['<compute_screening_factors>'] = self._compute_screening_factors self.ftags['<table_num>'] = self._table_num self.ftags['<declare_tables>'] = self._declare_tables self.ftags['<table_declare_meta>'] = self._table_declare_meta self.ftags['<table_init_meta>'] = self._table_init_meta self.ftags['<compute_tabular_rates>'] = self._compute_tabular_rates self.ftags['<ydot>'] = self._ydot self.ftags['<enuc_add_energy_rate>'] = self._enuc_add_energy_rate self.ftags['<jacnuc>'] = self._jacnuc self.ftags['<initial_mass_fractions>'] = self._initial_mass_fractions self.ftags['<reaclib_rate_functions>'] = self._reaclib_rate_functions self.ftags['<rate_struct>'] = self._rate_struct self.ftags['<fill_reaclib_rates>'] = self._fill_reaclib_rates self.ftags['<approx_rate_functions>'] = self._approx_rate_functions self.ftags['<fill_approx_rates>'] = self._fill_approx_rates self.ftags['<part_fun_data>'] = self._fill_partition_function_data self.ftags['<part_fun_cases>'] = self._fill_partition_function_cases self.ftags['<spin_state_cases>'] = self._fill_spin_state_cases self.indent = ' ' self.num_screen_calls = None @abstractmethod def _get_template_files(self): # This method should be overridden by derived classes # to support specific output templates. # This method returns a list of strings that are file paths to template files. return [] def get_indent_amt(self, l, k): """determine the amount of spaces to indent a line""" rem = re.match(r'\A'+k+r'\(([0-9]*)\)\Z', l) return int(rem.group(1)) def _write_network(self, odir=None): """ This writes the RHS, jacobian and ancillary files for the system of ODEs that this network describes, using the template files. """ # pylint: disable=arguments-differ # Prepare RHS terms if not self.solved_ydot: self.compose_ydot() if not self.solved_jacobian: self.compose_jacobian() # Process template files for tfile in self.template_files: tfile_basename = os.path.basename(tfile) outfile = tfile_basename.replace('.template', '') if odir is not None: if not os.path.isdir(odir): try: os.mkdir(odir) except OSError: sys.exit(f"unable to create directory {odir}") outfile = os.path.normpath(odir + "/" + outfile) with open(tfile) as ifile, open(outfile, "w") as of: for l in ifile: ls = l.strip() foundkey = False for k, func in self.ftags.items(): if k in ls: foundkey = True n_indent = self.get_indent_amt(ls, k) func(n_indent, of) if not foundkey: of.write(l) # Copy any tables in the network to the current directory # if the table file cannot be found, print a warning and continue. for tr in self.tabular_rates: tdir = os.path.dirname(tr.rfile_path) if tdir != os.getcwd(): tdat_file = os.path.join(tdir, tr.table_file) if os.path.isfile(tdat_file): shutil.copy(tdat_file, odir or os.getcwd()) else: print(f'WARNING: Table data file {tr.table_file} not found.') def compose_ydot(self): """create the expressions for dYdt for the nuclei, where Y is the molar fraction. This will take the form of a dict, where the key is a nucleus, and the value is a list of tuples, with the forward-reverse pairs of a rate """ ydot = {} for n in self.unique_nuclei: if not self.nuclei_rate_pairs[n]: ydot[n] = None else: ydot_sym_terms = [] for rp in self.nuclei_rate_pairs[n]: if rp.forward is not None: fwd = self.symbol_rates.ydot_term_symbol(rp.forward, n) else: fwd = None if rp.reverse is not None: rvs = self.symbol_rates.ydot_term_symbol(rp.reverse, n) else: rvs = None ydot_sym_terms.append((fwd, rvs)) ydot[n] = ydot_sym_terms self.ydot_out_result = ydot self.solved_ydot = True def compose_jacobian(self): """Create the Jacobian matrix, df/dY""" jac_null = [] jac_sym = [] for nj in self.unique_nuclei: for ni in self.unique_nuclei: rsym_is_null = True rsym = float(sympy.sympify(0.0)) for r in self.nuclei_consumed[nj]: rsym_add, rsym_add_null = self.symbol_rates.jacobian_term_symbol(r, nj, ni) rsym = rsym + rsym_add rsym_is_null = rsym_is_null and rsym_add_null for r in self.nuclei_produced[nj]: rsym_add, rsym_add_null = self.symbol_rates.jacobian_term_symbol(r, nj, ni) rsym = rsym + rsym_add rsym_is_null = rsym_is_null and rsym_add_null jac_sym.append(rsym) jac_null.append(rsym_is_null) self.jac_out_result = jac_sym self.jac_null_entries = jac_null self.solved_jacobian = True def _compute_screening_factors(self, n_indent, of): screening_map = self.get_screening_map() for i, scr in enumerate(screening_map): nuc1_info = f'{float(scr.n1.Z)}_rt, {float(scr.n1.A)}_rt' nuc2_info = f'{float(scr.n2.Z)}_rt, {float(scr.n2.A)}_rt' if not (scr.n1.dummy or scr.n2.dummy): # Scope the screening calculation to avoid multiple definitions of scn_fac. of.write(f'\n{self.indent*n_indent}' + '{') of.write(f'\n{self.indent*(n_indent+1)}constexpr auto scn_fac = scrn::calculate_screen_factor({nuc1_info}, {nuc2_info});\n\n') # Insert a static assert (which will always pass) to require the # compiler to evaluate the screen factor at compile time. of.write(f'\n{self.indent*(n_indent+1)}static_assert(scn_fac.z1 == {float(scr.n1.Z)}_rt);\n\n') of.write(f'\n{self.indent*(n_indent+1)}actual_screen<do_T_derivatives>(pstate, scn_fac, scor, dscor_dt);\n') of.write(f'{self.indent*n_indent}' + '}\n\n') if scr.name == "he4_he4_he4": # we don't need to do anything here, but we want to avoid immediately applying the screening pass elif scr.name == "he4_he4_he4_dummy": # make sure the previous iteration was the first part of 3-alpha assert screening_map[i - 1].name == "he4_he4_he4" # handle the second part of the screening for 3-alpha of.write(f'\n{self.indent*n_indent}' + '{') of.write(f'\n{self.indent*(n_indent+1)}constexpr auto scn_fac2 = scrn::calculate_screen_factor({nuc1_info}, {nuc2_info});\n\n') of.write(f'\n{self.indent*(n_indent+1)}static_assert(scn_fac2.z1 == {float(scr.n1.Z)}_rt);\n\n') of.write(f'\n{self.indent*(n_indent+1)}actual_screen<do_T_derivatives>(pstate, scn_fac2, scor2, dscor2_dt);\n') of.write(f'\n{self.indent*n_indent}' + '}\n\n') # there might be both the forward and reverse 3-alpha # if we are doing symmetric screening for rr in scr.rates: of.write('\n') of.write(f'{self.indent*n_indent}ratraw = rate_eval.screened_rates(k_{rr.cname()});\n') of.write(f'{self.indent*n_indent}rate_eval.screened_rates(k_{rr.cname()}) *= scor * scor2;\n') of.write(f'{self.indent*n_indent}if constexpr (std::is_same<T, rate_derivs_t>::value) {{\n') of.write(f'{self.indent*n_indent} dratraw_dT = rate_eval.dscreened_rates_dT(k_{rr.cname()});\n') of.write(f'{self.indent*n_indent} rate_eval.dscreened_rates_dT(k_{rr.cname()}) = ratraw * (scor * dscor2_dt + dscor_dt * scor2) + dratraw_dT * scor * scor2;\n') of.write(f'{self.indent*n_indent}}}\n') else: # there might be several rates that have the same # reactants and therefore the same screening applies # -- handle them all now for rr in scr.rates: of.write('\n') of.write(f'{self.indent*n_indent}ratraw = rate_eval.screened_rates(k_{rr.cname()});\n') of.write(f'{self.indent*n_indent}rate_eval.screened_rates(k_{rr.cname()}) *= scor;\n') of.write(f'{self.indent*n_indent}if constexpr (std::is_same<T, rate_derivs_t>::value) {{\n') of.write(f'{self.indent*n_indent} dratraw_dT = rate_eval.dscreened_rates_dT(k_{rr.cname()});\n') of.write(f'{self.indent*n_indent} rate_eval.dscreened_rates_dT(k_{rr.cname()}) = ratraw * dscor_dt + dratraw_dT * scor;\n') of.write(f'{self.indent*n_indent}}}\n') of.write('\n') # the C++ screen.H code requires that there be at least 1 screening # factor because it statically allocates some arrays, so if we turned # off screening, just set num_screen_calls = 1 here. self.num_screen_calls = max(1, len(screening_map)) def _nrat_reaclib(self, n_indent, of): # Writes the number of Reaclib rates of.write(f'{self.indent*n_indent}const int NrateReaclib = {len(self.reaclib_rates + self.derived_rates)};\n') def _nrat_tabular(self, n_indent, of): # Writes the number of tabular rates of.write(f'{self.indent*n_indent}const int NrateTabular = {len(self.tabular_rates)};\n') def _nrxn(self, n_indent, of): for i, r in enumerate(self.all_rates): of.write(f'{self.indent*n_indent}k_{r.cname()} = {i+1},\n') of.write(f'{self.indent*n_indent}NumRates = k_{self.all_rates[-1].cname()}\n') def _rate_names(self, n_indent, of): for i, r in enumerate(self.all_rates): if i < len(self.all_rates)-1: cont = "," else: cont = "" of.write(f'{self.indent*n_indent}"{r.cname()}"{cont} // {i+1},\n') def _ebind(self, n_indent, of): for nuc in self.unique_nuclei: of.write(f'{self.indent*n_indent}ebind_per_nucleon({nuc.cindex()}) = {nuc.nucbind}_rt;\n') def _table_num(self, n_indent, of): of.write(f'{self.indent*n_indent}const int num_tables = {len(self.tabular_rates)};\n') def _declare_tables(self, n_indent, of): for r in self.tabular_rates: idnt = self.indent*n_indent of.write(f'{idnt}extern AMREX_GPU_MANAGED table_t {r.table_index_name}_meta;\n') of.write(f'{idnt}extern AMREX_GPU_MANAGED Array3D<Real, 1, {r.table_temp_lines}, 1, {r.table_rhoy_lines}, 1, {r.table_num_vars}> {r.table_index_name}_data;\n') of.write(f'{idnt}extern AMREX_GPU_MANAGED Array1D<Real, 1, {r.table_rhoy_lines}> {r.table_index_name}_rhoy;\n') of.write(f'{idnt}extern AMREX_GPU_MANAGED Array1D<Real, 1, {r.table_temp_lines}> {r.table_index_name}_temp;\n') of.write('\n') def _table_declare_meta(self, n_indent, of): for r in self.tabular_rates: idnt = self.indent*n_indent of.write(f"{idnt}AMREX_GPU_MANAGED table_t {r.table_index_name}_meta;\n") of.write(f'{idnt}AMREX_GPU_MANAGED Array3D<Real, 1, {r.table_temp_lines}, 1, {r.table_rhoy_lines}, 1, {r.table_num_vars}> {r.table_index_name}_data;\n') of.write(f'{idnt}AMREX_GPU_MANAGED Array1D<Real, 1, {r.table_rhoy_lines}> {r.table_index_name}_rhoy;\n') of.write(f'{idnt}AMREX_GPU_MANAGED Array1D<Real, 1, {r.table_temp_lines}> {r.table_index_name}_temp;\n\n') def _table_init_meta(self, n_indent, of): for r in self.tabular_rates: idnt = self.indent*n_indent of.write(f'{idnt}{r.table_index_name}_meta.ntemp = {r.table_temp_lines};\n') of.write(f'{idnt}{r.table_index_name}_meta.nrhoy = {r.table_rhoy_lines};\n') of.write(f'{idnt}{r.table_index_name}_meta.nvars = {r.table_num_vars};\n') of.write(f'{idnt}{r.table_index_name}_meta.nheader = {r.table_header_lines};\n\n') of.write(f'{idnt}init_tab_info({r.table_index_name}_meta, "{r.table_file}", {r.table_index_name}_rhoy, {r.table_index_name}_temp, {r.table_index_name}_data);\n\n') of.write('\n') def _compute_tabular_rates(self, n_indent, of): if len(self.tabular_rates) > 0: idnt = self.indent*n_indent for r in self.tabular_rates: of.write(f'{idnt}tabular_evaluate({r.table_index_name}_meta, {r.table_index_name}_rhoy, {r.table_index_name}_temp, {r.table_index_name}_data,\n') of.write(f'{idnt} rhoy, state.T, rate, drate_dt, edot_nu, edot_gamma);\n') of.write(f'{idnt}rate_eval.screened_rates(k_{r.cname()}) = rate;\n') of.write(f'{idnt}if constexpr (std::is_same<T, rate_derivs_t>::value) {{\n') of.write(f'{idnt} rate_eval.dscreened_rates_dT(k_{r.cname()}) = drate_dt;\n') of.write(f'{idnt}}}\n') of.write(f'{idnt}rate_eval.add_energy_rate(k_{r.cname()}) = edot_nu + edot_gamma;\n') of.write('\n') def _ydot(self, n_indent, of): # Write YDOT for n in self.unique_nuclei: if self.ydot_out_result[n] is None: of.write(f"{self.indent*n_indent}{self.symbol_rates.name_ydot_nuc}({n.cindex()}) = 0.0;\n\n") continue of.write(f"{self.indent*n_indent}{self.symbol_rates.name_ydot_nuc}({n.cindex()}) =\n") for j, pair in enumerate(self.ydot_out_result[n]): # pair here is the forward, reverse pair for a single rate as it affects # nucleus n if pair.count(None) == 0: num = 2 elif pair.count(None) == 1: num = 1 else: raise NotImplementedError("a rate pair must contain at least one rate") of.write(f"{2*self.indent*n_indent}") if num == 2: of.write("(") if pair[0] is not None: sol_value = self.symbol_rates.cxxify(sympy.cxxcode(pair[0], precision=15, standard="c++11")) of.write(f"{sol_value}") if num == 2: of.write(" + ") if pair[1] is not None: sol_value = self.symbol_rates.cxxify(sympy.cxxcode(pair[1], precision=15, standard="c++11")) of.write(f"{sol_value}") if num == 2: of.write(")") if j == len(self.ydot_out_result[n])-1: of.write(";\n\n") else: of.write(" +\n") def _enuc_add_energy_rate(self, n_indent, of): # Add tabular per-reaction neutrino energy generation rates to the energy generation rate # (not thermal neutrinos) idnt = self.indent * n_indent for r in self.tabular_rates: if len(r.reactants) != 1: sys.exit('ERROR: Unknown energy rate corrections for a reaction where the number of reactants is not 1.') else: reactant = r.reactants[0] of.write(f'{idnt}enuc += C::Legacy::n_A * {self.symbol_rates.name_y}({reactant.cindex()}) * rate_eval.add_energy_rate(k_{r.cname()});\n') def _jacnuc(self, n_indent, of): # now make the Jacobian n_unique_nuclei = len(self.unique_nuclei) for jnj, nj in enumerate(self.unique_nuclei): for ini, ni in enumerate(self.unique_nuclei): jac_idx = n_unique_nuclei*jnj + ini if not self.jac_null_entries[jac_idx]: jvalue = self.symbol_rates.cxxify(sympy.cxxcode(self.jac_out_result[jac_idx], precision=15, standard="c++11")) of.write(f"{self.indent*(n_indent)}scratch = {jvalue};\n") of.write(f"{self.indent*n_indent}jac.set({nj.cindex()}, {ni.cindex()}, scratch);\n\n") def _initial_mass_fractions(self, n_indent, of): for i, _ in enumerate(self.unique_nuclei): if i == 0: of.write(f"{self.indent*n_indent}unit_test.X{i+1} = 1.0\n") else: of.write(f"{self.indent*n_indent}unit_test.X{i+1} = 0.0\n") def _reaclib_rate_functions(self, n_indent, of): assert n_indent == 0, "function definitions must be at top level" for r in self.reaclib_rates + self.derived_rates: of.write(r.function_string_cxx(dtype=self.dtype, specifiers=self.function_specifier)) def _rate_struct(self, n_indent, of): assert n_indent == 0, "function definitions must be at top level" of.write("struct rate_t {\n") of.write(" Array1D<Real, 1, NumRates> screened_rates;\n") if len(self.tabular_rates) > 0: of.write(" Array1D<Real, NrateReaclib+1, NrateReaclib+NrateTabular> add_energy_rate;\n") of.write("};\n\n") of.write("struct rate_derivs_t {\n") of.write(" Array1D<Real, 1, NumRates> screened_rates;\n") of.write(" Array1D<Real, 1, NumRates> dscreened_rates_dT;\n") if len(self.tabular_rates) > 0: of.write(" Array1D<Real, NrateReaclib+1, NrateReaclib+NrateTabular> add_energy_rate;\n") of.write("};\n\n") def _approx_rate_functions(self, n_indent, of): assert n_indent == 0, "function definitions must be at top level" for r in self.approx_rates: of.write(r.function_string_cxx(dtype=self.dtype, specifiers=self.function_specifier)) def _fill_reaclib_rates(self, n_indent, of): for r in self.reaclib_rates + self.derived_rates: of.write(f"{self.indent*n_indent}rate_{r.cname()}<do_T_derivatives>(tfactors, rate, drate_dT);\n") of.write(f"{self.indent*n_indent}rate_eval.screened_rates(k_{r.cname()}) = rate;\n") of.write(f"{self.indent*n_indent}if constexpr (std::is_same<T, rate_derivs_t>::value) {{\n") of.write(f"{self.indent*n_indent} rate_eval.dscreened_rates_dT(k_{r.cname()}) = drate_dT;\n\n") of.write(f"{self.indent*n_indent}}}\n") def _fill_approx_rates(self, n_indent, of): for r in self.approx_rates: of.write(f"{self.indent*n_indent}rate_{r.cname()}<T>(rate_eval, rate, drate_dT);\n") of.write(f"{self.indent*n_indent}rate_eval.screened_rates(k_{r.cname()}) = rate;\n") of.write(f"{self.indent*n_indent}if constexpr (std::is_same<T, rate_derivs_t>::value) {{\n") of.write(f"{self.indent*n_indent} rate_eval.dscreened_rates_dT(k_{r.cname()}) = drate_dT;\n\n") of.write(f"{self.indent*n_indent}}}\n") def _fill_partition_function_data(self, n_indent, of): # itertools recipe def batched(iterable, n): "Batch data into tuples of length n. The last batch may be shorter." # batched('ABCDEFG', 3) --> ABC DEF G if n < 1: raise ValueError('n must be at least one') it = iter(iterable) while batch := tuple(itertools.islice(it, n)): yield batch temp_arrays, temp_indices = self.dedupe_partition_function_temperatures() decl = "MICROPHYSICS_UNUSED HIP_CONSTEXPR static AMREX_GPU_MANAGED amrex::Real" for i, temp in enumerate(temp_arrays): # number of points of.write(f"{self.indent*n_indent}constexpr int npts_{i+1} = {len(temp)};\n\n") # write the temperature out, but for readability, split it to 5 values per line of.write(f"{self.indent*n_indent}// this is T9\n\n") of.write(f"{self.indent*n_indent}{decl} temp_array_{i+1}[npts_{i+1}] = {{\n") for data in batched(temp / 1.0e9, 5): tmp = " ".join([f"{t}," for t in data]) of.write(f"{self.indent*(n_indent+1)}{tmp}\n") of.write(f"{self.indent*n_indent}}};\n\n") if i == len(temp_arrays) - 1: of.write("\n") for n, i in temp_indices.items(): # write the partition function data out, but for readability, split # it to 5 values per line of.write(f"{self.indent*n_indent}// this is log10(partition function)\n\n") of.write(f"{self.indent*n_indent}{decl} {n}_pf_array[npts_{i+1}] = {{\n") for data in batched(np.log10(n.partition_function.partition_function), 5): tmp = " ".join([f"{x}," for x in data]) of.write(f"{self.indent*(n_indent+1)}{tmp}\n") of.write(f"{self.indent*n_indent}}};\n\n") def _fill_partition_function_cases(self, n_indent, of): _, temp_indices = self.dedupe_partition_function_temperatures() for n, i in temp_indices.items(): of.write(f"{self.indent*n_indent}case {n.cindex()}:\n") of.write(f"{self.indent*(n_indent+1)}part_fun::interpolate_pf<part_fun::npts_{i+1}>(tfactors.T9, part_fun::temp_array_{i+1}, part_fun::{n}_pf_array, pf, dpf_dT);\n") of.write(f"{self.indent*(n_indent+1)}break;\n\n") def _fill_spin_state_cases(self, n_indent, of): def key_func(nuc): if nuc.spin_states is None: return -1 return nuc.spin_states # group identical cases together to satisfy clang-tidy nuclei = sorted(self.unique_nuclei + self.approx_nuclei, key=key_func) for spin_state, group in itertools.groupby(nuclei, key=key_func): if spin_state == -1: continue for n in group: of.write(f"{self.indent*n_indent}case {n.cindex()}:\n") of.write(f"{self.indent*(n_indent+1)}spin = {spin_state};\n") of.write(f"{self.indent*(n_indent+1)}break;\n\n")
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,699
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/tests/conftest.py
import pytest import pynucastro as pyna # enable assert rewriting for the helper functions in ./helpers.py pytest.register_assert_rewrite('pynucastro.networks.tests.helpers') @pytest.fixture(scope="package") def reaclib_library(): return pyna.ReacLibLibrary() @pytest.fixture(scope="package") def tabular_library(): return pyna.TabularLibrary()
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,700
pynucastro/pynucastro
refs/heads/main
/pynucastro/rates/tests/test_ratefilter.py
# unit tests for rates import pytest import pynucastro as pyna class TestRateFilter: @pytest.fixture(scope="class") def library(self): """ this is run before each test """ files = ["c12-pg-n13-ls09", "c13-pg-n14-nacr", "n13-pg-o14-lg06", "n14-pg-o15-im05", "n15-pa-c12-nacr", "o14--n14-wc12", "o15--n15-wc12", "o14-ap-f17-Ha96c", "f17--o17-wc12", "f17-pg-ne18-cb09", "ne18--f18-wc12", "f18--o18-wc12", "n15-pg-o16-li10", "o16-pg-f17-ia08", "o17-pg-f18-il10", "f18-pa-o15-il10"] rates = [] for f in files: rates.append(pyna.load_rate(f)) return pyna.Library(rates=rates) def test_inexact_filter(self, library): filt = pyna.RateFilter(reactants=['c12'], exact=False) newlib = library.filter(filt) rates = newlib.get_rates() assert len(rates) == 1 assert str(rates[0]) == "C12 + p ⟶ N13 + 𝛾" def test_custom(self, library): # filter out all the rates with fluorine filt = pyna.RateFilter(filter_function=lambda r: len([q for q in r.reactants + r.products if q.Z == 9])) newlib = library.filter(filt) assert len(newlib.get_rates()) == 8 def test_exact(self, library): filt = pyna.RateFilter(reactants=["n15", "p"]) newlib = library.filter(filt) rates = newlib.get_rates() assert len(rates) == 2 assert str(rates[0]) == "N15 + p ⟶ He4 + C12" assert str(rates[1]) == "N15 + p ⟶ O16 + 𝛾"
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,701
pynucastro/pynucastro
refs/heads/main
/pynucastro/screening/tests/test_screen.py
import pytest from pytest import approx import pynucastro as pyna from pynucastro.screening import (chugunov_2007, chugunov_2009, make_plasma_state, make_screen_factors, potekhin_1998) class TestScreen: @pytest.fixture(scope="class") def nuclei(self): return [pyna.Nucleus("h1"), pyna.Nucleus("he4"), pyna.Nucleus("c12"), pyna.Nucleus("o16"), pyna.Nucleus("n14"), pyna.Nucleus("ca40")] @pytest.fixture(scope="class") def plasma_state(self, nuclei): temp = 1e6 dens = 1e5 comp = pyna.Composition(nuclei) comp.set_solar_like() return make_plasma_state(temp, dens, comp.get_molar()) @pytest.fixture(scope="class") def scn_fac(self): c12 = pyna.Nucleus("c12") he4 = pyna.Nucleus("he4") return make_screen_factors(c12, he4) def test_plasma_state(self, plasma_state): assert plasma_state.temp == approx(1e6) assert plasma_state.dens == approx(1e5) assert plasma_state.abar == approx(1.2966614825934775) assert plasma_state.zbar == approx(1.1021622602044556) assert plasma_state.z2bar == approx(1.4036360549074394) assert plasma_state.n_e == approx(5.118819647768954e+28) assert plasma_state.gamma_e_fac == approx(10001498.09343337) def test_screen_factors(self, scn_fac): assert scn_fac.z1 == 6 assert scn_fac.a1 == 12 assert scn_fac.z2 == 2 assert scn_fac.a2 == 4 assert scn_fac.aznut == approx(7.55952629936924) assert scn_fac.ztilde == approx(1.5385208213635064) def test_chugunov_2007(self, plasma_state, scn_fac): scor = chugunov_2007(plasma_state, scn_fac) assert scor == approx(7.785569477042635e+33) def test_chugunov_2009(self, plasma_state, scn_fac): scor = chugunov_2009(plasma_state, scn_fac) assert scor == approx(2.87983449091315e+33) def test_potekhin_1998(self, plasma_state, scn_fac): scor = potekhin_1998(plasma_state, scn_fac) assert scor == approx(1.0508243810383098e+36)
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,702
pynucastro/pynucastro
refs/heads/main
/pynucastro/nucdata/tests/test_partition.py
import os from numpy import array from pynucastro.nucdata import (PartitionFunctionCollection, PartitionFunctionTable) nucdata_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) pf_dir = os.path.join(nucdata_dir, 'PartitionFunction') dir_etfsiq_low = os.path.join(pf_dir, 'etfsiq_low.txt') dir_frdm_low = os.path.join(pf_dir, 'frdm_low.txt') dir_etfsiq_high = os.path.join(pf_dir, 'etfsiq_high.txt') dir_frdm_high = os.path.join(pf_dir, 'frdm_high.txt') ANSWER_ETFSIQ_LOW = array([1.000271, 1.002656, 1.009124, 1.035543, 1.076750, 1.128518, 1.187847, 1.252797, 1.322103, 1.394926, 1.470693, 1.883077, 2.339548, 2.835353, 3.371056, 3.949365, 4.574281, 5.250894, 5.985411, 7.659520, 9.675912, 12.147961, 15.237089, 19.172457]) ANSWER_FRDM_LOW = array([1.000157, 1.001534, 1.005265, 1.020486, 1.044185, 1.073899, 1.107886, 1.145013, 1.184544, 1.225988, 1.269010, 1.501456, 1.755494, 2.027655, 2.317420, 2.625339, 2.952505, 3.300375, 3.670713, 4.487378, 5.423159, 6.505528, 7.771334, 9.270601]) ANSWER_ETFSIQ_HIGH = array([5.79E+000, 1.07E+001, 2.13E+001, 4.38E+001, 9.23E+001, 1.97E+002, 4.23E+002, 9.12E+002, 1.97E+003, 4.25E+003, 2.92E+004, 2.00E+005, 1.36E+006, 9.31E+006, 6.34E+007, 4.31E+008, 2.92E+009, 1.97E+010, 1.33E+011, 8.93E+011, 5.98E+012, 3.99E+013, 2.65E+014, 1.76E+015, 1.16E+016, 7.66E+016, 5.03E+017, 3.30E+018, 2.16E+019, 1.41E+020, 9.21E+020, 6.00E+021, 3.91E+022, 2.54E+023, 1.65E+024, 1.07E+025, 6.97E+025, 4.52E+026, 2.94E+027, 1.91E+028, 8.07E+029, 3.42E+031, 1.46E+033, 6.23E+034, 2.68E+036, 1.16E+038, 5.03E+039, 6.45E+043]) ANSWER_FRDM_HIGH = array([9.40e+007, 2.81e+009, 4.93e010, 1.95e+012, 8.84e+013, 3.66e+015, 1.44e+017, 5.48e+018, 2.04e+020, 7.48e+021, 5.72e+025, 4.07e+029, 2.69e+033, 1.66e+037, 9.60e+040, 5.20e+044, 2.65e+048, 1.28e+052, 5.85e+055, 2.55e+059, 1.06e+063, 4.27e+066, 1.65e+070, 6.16e+073, 2.23e+077, 7.87e+080, 2.71e+084, 9.15e+087, 3.03e+091, 9.86e+094, 3.17e+098, 1.00e+102, 3.14e+105, 9.77e+108, 3.01e+112, 9.23e+115, 2.82e+119, 8.56e+122, 2.59e+126, 7.85e+129, 7.18e+136, 6.59e+143, 6.11e+150, 5.74e+157, 5.48e+164, 5.35e+171, 5.34e+178, 1.88e+196]) TEMPERATURES_LOW = array([0.01E+9, 0.15E+9, 0.2E+9, 0.3E+9, 0.4E+9, 0.5E+9, 0.6E+9, 0.7E+9, 0.8E+9, 0.9E+9, 1.0E+9, 1.5E+9, 2.0E+9, 2.5E+9, 3.0E+9, 3.5E+9, 4.0E+9, 4.5E+9, 5.0E+9, 6.0E+9, 7.0E+9, 8.0E+9, 9.0E+9, 10.0E+9]) TEMPERATURES_HIGH = array([12.0E+9, 14.0E+9, 16.0E+9, 18.0E+9, 20.0E+9, 22.0E+9, 24.0E+9, 26.0E+9, 28.0E+9, 30.0E+9, 35.0E+9, 40.0E+9, 45.0E+9, 50.0E+9, 55.0E+9, 60.0E+9, 65.0E+9, 70.0E+9, 75.0E+9, 80.0E+9, 85.0E+9, 90.0E+9, 95.0E+9, 100.0E+9, 105.0E+9, 110.0E+9, 115.0E+9, 120.0E+9, 125.0E+9, 130.0E+9, 135.0E+9, 140.0E+9, 145.0E+9, 150.0E+9, 155.0E+9, 160.0E+9, 165.0E+9, 170.0E+9, 175.0E+9, 180.0E+9, 190.0E+9, 200.0E+9, 210.0E+9, 220.0E+9, 230.0E+9, 240.0E+9, 250.0E+9, 275.0E+9]) class TestPartition: @classmethod def setup_class(cls): """ this is run once for each class before any tests """ cls.pf_table_etfsiq_low = PartitionFunctionTable(dir_etfsiq_low) cls.pf_table_frdm_low = PartitionFunctionTable(dir_frdm_low) cls.pf_table_etfsiq_high = PartitionFunctionTable(dir_etfsiq_high) cls.pf_table_frdm_high = PartitionFunctionTable(dir_frdm_high) cls.pf_collection_frdm = PartitionFunctionCollection(use_high_temperatures=True, use_set='frdm') cls.pf_collection_etfsiq = PartitionFunctionCollection(use_high_temperatures=True, use_set='etfsiq') @classmethod def teardown_class(cls): """ this is run once for each class after all tests """ del cls.pf_table_etfsiq_low del cls.pf_table_frdm_low del cls.pf_table_etfsiq_high del cls.pf_table_frdm_high del cls.pf_collection_frdm del cls.pf_collection_etfsiq def setup_method(self): """ this is run before each test """ def teardown_method(self): """ this is run after each test """ def test_pf_table(self): co46_pf_etfsiq_low = self.pf_table_etfsiq_low.get_partition_function('co46') ne37_pf_frdm_low = self.pf_table_frdm_low.get_partition_function('ne37') fe47_pf_etfsiq_high = self.pf_table_etfsiq_high.get_partition_function('fe47') po188_pf_frdm_high = self.pf_table_frdm_high.get_partition_function('po188') assert all(co46_pf_etfsiq_low.partition_function == ANSWER_ETFSIQ_LOW) assert all(co46_pf_etfsiq_low.temperature == TEMPERATURES_LOW) assert all(ne37_pf_frdm_low.partition_function == ANSWER_FRDM_LOW) assert all(ne37_pf_frdm_low.temperature == TEMPERATURES_LOW) assert all(fe47_pf_etfsiq_high.partition_function == ANSWER_ETFSIQ_HIGH) assert all(fe47_pf_etfsiq_high.temperature == TEMPERATURES_HIGH) assert all(po188_pf_frdm_high.partition_function == ANSWER_FRDM_HIGH) assert all(po188_pf_frdm_high.temperature == TEMPERATURES_HIGH) def test_pfsum(self): ne19_pf_frdm_low = self.pf_table_frdm_low.get_partition_function('ne19') ne19_pf_frdm_high = self.pf_table_frdm_high.get_partition_function('ne19') co60_pf_etfsiq_low = self.pf_table_etfsiq_low.get_partition_function('co60') co60_pf_etfsiq_high = self.pf_table_etfsiq_high.get_partition_function('co60') assert self.pf_collection_frdm.get_partition_function('ne19') == ne19_pf_frdm_high + ne19_pf_frdm_low assert self.pf_collection_etfsiq.get_partition_function('co60') == co60_pf_etfsiq_low + co60_pf_etfsiq_high
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,703
pynucastro/pynucastro
refs/heads/main
/pynucastro/screening/screen.py
""" Python implementations of screening routines. """ import numpy as np from scipy import constants # use the jitclass placeholder from rate.py from pynucastro.rates.rate import jitclass, numba if numba is not None: njit = numba.njit else: def njit(func): return func __all__ = ["PlasmaState", "ScreenFactors", "chugunov_2007", "chugunov_2009", "make_plasma_state", "make_screen_factors", "potekhin_1998"] amu = constants.value("atomic mass constant") / constants.gram # kg to g q_e = constants.value("elementary charge") * (constants.c * 100) / 10 # C to statC (esu) hbar = constants.value("reduced Planck constant") / constants.erg # J*s to erg*s k_B = constants.value("Boltzmann constant") / constants.erg # J/K to erg/K @jitclass() class PlasmaState: """ Stores precomputed values that are reused for all screening correction factor calculations. :var temp: temperature in K :var dens: density in g/cm^3 :var abar: average atomic mass :var zbar: average ion charge :var z2bar: average (ion charge)^2 :var n_e: electron number density :var gamma_e_fac: temperature-independent part of Gamma_e """ temp: float dens: float abar: float zbar: float z2bar: float n_e: float gamma_e_fac: float def __init__(self, temp, dens, Ys, Zs): """ :param temp: temperature in K :param dens: density in g/cm^3 :param Ys: molar fractions of each ion :type Ys: numpy ndarray :param Zs: charge of each ion, in the same order as Ys :type Zs: numpy ndarray """ self.temp = temp self.dens = dens ytot = np.sum(Ys) self.abar = 1 / ytot self.zbar = np.sum(Zs * Ys) / ytot self.z2bar = np.sum(Zs ** 2 * Ys) / ytot # Average mass and total number density mbar = self.abar * amu ntot = self.dens / mbar # Electron number density # zbar * ntot works out to sum(z[i] * n[i]), after cancelling terms self.n_e = self.zbar * ntot # temperature-independent part of Gamma_e, from Chugunov 2009 eq. 6 self.gamma_e_fac = q_e ** 2 / k_B * np.cbrt(4 * np.pi / 3) * np.cbrt(self.n_e) @jitclass() class NseState: """ Stores precomputed values that are reused in the NSE state screening calculations :var temp: temperature in K :var dens: density in g/cm^3 :var ye: electron molar fraction :var n_e: electron number density :var gamma_e_fac: temperature-independent part of Gamma_e """ temp: float dens: float ye: float gamma_e_fac: float def __init__(self, temp, dens, ye): """ :param temp: temperature in K :param dens: density in g/cm^3 :param ye: electron molar fraction :param Xs: nucleon fraction of each ion :type Xs: numpy ndarray :param As: atomic mass number of each ion :type As: numpy ndarray :param Zs: atomic number of each ion :type Zs: numpy ndarray """ self.temp = temp self.dens = dens self.ye = ye self.gamma_e_fac = q_e ** 2 / k_B * np.cbrt(4.0 * np.pi / 3.0) def make_plasma_state(temp, dens, molar_fractions): """ Construct a PlasmaState object from simulation data. :param temp: temperature in K :param dens: density in g/cm^3 :param molar_fractions: dictionary of molar abundances for each ion, as returned by :meth:`.Composition.get_molar` """ nuclei = list(molar_fractions.keys()) Ys = np.asarray([molar_fractions[n] for n in nuclei]) Zs = np.asarray([n.Z for n in nuclei]) return PlasmaState(temp, dens, Ys, Zs) @jitclass() class ScreenFactors: """ Stores values that will be used to calculate the screening correction factor for a specific pair of nuclei. :var z1: atomic number of first nucleus :var z2: atomic number of second nucleus :var a1: atomic mass of first nucleus :var a2: atomic mass of second nucleus :var aznut: combination of a1, z1, a2, z2 raised to 1/3 power :var ztilde: effective ion radius factor for a MCP """ z1: int z2: int a1: int a2: int aznut: float ztilde: float def __init__(self, z1, a1, z2, a2): self.z1 = z1 self.z2 = z2 self.a1 = a1 self.a2 = a2 self.aznut = np.cbrt(z1 ** 2 * z2 ** 2 * a1 * a2 / (a1 + a2)) self.ztilde = 0.5 * (np.cbrt(z1) + np.cbrt(z2)) def make_screen_factors(n1, n2): """ Construct a ScreenFactors object from a pair of nuclei. :param Nucleus n1: first nucleus :param Nucleus n2: second nucleus """ return ScreenFactors(n1.Z, n1.A, n2.Z, n2.A) @njit def smooth_clip(x, limit, start): """Smoothly transition between y=limit and y=x with a half-cosine. Clips smaller values if limit < start and larger values if start < limit. :param x: the value to clip :param limit: the constant value to clip x to :param start: the x-value at which to start the transition :returns: y """ if limit < start: lower = limit upper = x else: lower = x upper = limit if x < min(limit, start): return lower if x > max(limit, start): return upper tmp = np.pi * (x - min(limit, start)) / (start - limit) f = (1 - np.cos(tmp)) / 2 return (1 - f) * lower + f * upper @njit def chugunov_2007(state, scn_fac): """Calculates screening factors based on Chugunov et al. 2007. Follows the approach in Yakovlev 2006 to extend to a multi-component plasma. :param PlasmaState state: the precomputed plasma state factors :param ScreenFactors scn_fac: the precomputed ion pair factors :returns: screening correction factor References: | Chugunov, DeWitt, and Yakovlev 2007, PhRvD, 76, 025028 | Yakovlev, Gasques, Afanasjev, Beard, and Wiescher 2006, PhRvC, 74, 035803 | Chugunov and DeWitt 2009, PhRvC, 80, 014611 """ # Plasma temperature T_p # This formula comes from working backwards from zeta_ij (Chugunov 2009 eq. 12) # through Chugunov 2007 eq. 3 to Chugunov 2007 eq. 2. # Ultimately, the changes from the expression in Chugunov 2007 are: # Z^2 -> Z1 * Z2 # n_i -> n_e / ztilde^3, where ztilde = (Z1^(1/3) + Z2^(1/3)) / 2 # m_i -> 2 mu12 (reduced mass) # This prescription reduces to the expressions from Chugunov 2007 in the case # of an OCP, and to Chugunov 2009 in the case of a binary ionic mixture. # This also matches Yakovlev et al. 2006, eq. 10. # # For reference, MESA r21.12.1 does: # Z^2 -> Z1 * Z2 # n_i -> n_e / zbar (=ntot) # m_i -> m_u * abar # # Sam Jones' Fortran implementation does: # Z^2 -> zbar^2 # n_i -> ntot # m_i -> m_u * abar mu12 = scn_fac.a1 * scn_fac.a2 / (scn_fac.a1 + scn_fac.a2) z_factor = scn_fac.z1 * scn_fac.z2 n_i = state.n_e / scn_fac.ztilde ** 3 m_i = 2 * mu12 * amu T_p = hbar / k_B * q_e * np.sqrt(4 * np.pi * z_factor * n_i / m_i) # Normalized temperature T_norm = state.temp / T_p # The fit has only been verified down to T ~ 0.1 T_p, below which the rate # should be nearly temperature-independent (in the pycnonuclear regime), # and we clip the temperature to 0.1 T_p at small T. # start the transition here T_norm_fade = 0.2 # minimum value of T/T_p T_norm_min = 0.1 T_norm = smooth_clip(T_norm, limit=T_norm_min, start=T_norm_fade) # Coulomb coupling parameter from Yakovlev 2006, eq. 10 Gamma = state.gamma_e_fac * scn_fac.z1 * scn_fac.z2 / (scn_fac.ztilde * T_norm * T_p) # The fit for Gamma is only applicable up to ~600, so smoothly cap its value Gamma_fade = 590 Gamma_max = 600 Gamma = smooth_clip(Gamma, limit=Gamma_max, start=Gamma_fade) # Chugunov 2007 eq. 3 zeta = np.cbrt(4 / (3 * np.pi ** 2 * T_norm ** 2)) # Gamma tilde from Chugunov 2007 eq. 21 fit_alpha = 0.022 fit_beta = 0.41 - 0.6 / Gamma fit_gamma = 0.06 + 2.2 / Gamma # Polynomial term in Gamma tilde poly = 1 + zeta*(fit_alpha + zeta*(fit_beta + fit_gamma*zeta)) gamtilde = Gamma / np.cbrt(poly) # fit parameters just after Chugunov 2007 eq. 19 A1 = 2.7822 A2 = 98.34 A3 = np.sqrt(3) - A1 / np.sqrt(A2) B1 = -1.7476 B2 = 66.07 B3 = 1.12 B4 = 65 gamtilde2 = gamtilde ** 2 # Chugunov 2007 eq. 19 term1 = 1 / np.sqrt(A2 + gamtilde) term2 = 1 / (1 + gamtilde) term3 = gamtilde ** 2 / (B2 + gamtilde) term4 = gamtilde2 / (B4 + gamtilde2) h = gamtilde ** (3 / 2) * (A1 * term1 + A3 * term2) + B1 * term3 + B3 * term4 # machine limit the output h_max = 300 h = min(h, h_max) scor = np.exp(h) return scor @njit def f0(gamma): r"""Calculate the free energy per ion in a OCP from Chugunov & DeWitt 2009 eq. 24 :param gamma: Coulomb coupling parameter :returns: free energy """ A1 = -0.907 A2 = 0.62954 A3 = -np.sqrt(3) / 2 - A1 / np.sqrt(A2) B1 = 0.00456 B2 = 211.6 B3 = -1e-4 B4 = 0.00462 term1 = np.sqrt(gamma * (A2 + gamma)) term2 = np.log(np.sqrt(gamma / A2) + np.sqrt(1 + gamma / A2)) gamma_12 = np.sqrt(gamma) term3 = gamma_12 - np.arctan(gamma_12) term4 = np.log1p(gamma / B2) term5 = np.log1p(gamma ** 2 / B4) return ( A1 * (term1 - A2 * term2) + 2 * A3 * term3 + B1 * (gamma - B2 * term4) + B3 / 2 * term5 ) @njit def chugunov_2009(state, scn_fac): """Calculates screening factors based on Chugunov & DeWitt 2009. :param PlasmaState state: the precomputed plasma state factors :param ScreenFactors scn_fac: the precomputed ion pair factors :returns: screening correction factor References: | Chugunov and DeWitt 2009, PhRvC, 80, 014611 """ z1z2 = scn_fac.z1 * scn_fac.z2 zcomp = scn_fac.z1 + scn_fac.z2 # Gamma_e from eq. 6 Gamma_e = state.gamma_e_fac / state.temp # Coulomb coupling parameters for ions and compound nucleus, eqs. 7 & 9 Gamma_1 = Gamma_e * scn_fac.z1 ** (5 / 3) Gamma_2 = Gamma_e * scn_fac.z2 ** (5 / 3) Gamma_comp = Gamma_e * zcomp ** (5 / 3) Gamma_12 = Gamma_e * z1z2 / scn_fac.ztilde # Coulomb barrier penetrability, eq. 10 tau_factor = np.cbrt(27 / 2 * (np.pi * q_e ** 2 / hbar) ** 2 * amu / k_B) tau_12 = tau_factor * scn_fac.aznut / np.cbrt(state.temp) # eq. 12 zeta = 3 * Gamma_12 / tau_12 # additional fit parameters, eq. 25 y_12 = 4 * z1z2 / zcomp ** 2 c1 = 0.013 * y_12 ** 2 c2 = 0.406 * y_12 ** 0.14 c3 = 0.062 * y_12 ** 0.19 + 1.8 / Gamma_12 poly = 1 + zeta*(c1 + zeta*(c2 + c3*zeta)) t_12 = np.cbrt(poly) # strong screening enhancement factor, eq. 23, replacing tau_ij with t_ij # Using Gamma/tau_ij gives extremely low values, while Gamma/t_ij gives # values similar to those from Chugunov 2007. term1 = f0(Gamma_1 / t_12) term2 = f0(Gamma_2 / t_12) term3 = f0(Gamma_comp / t_12) h_fit = term1 + term2 - term3 # weak screening correction term, eq. A3 corr_C = ( 3 * z1z2 * np.sqrt(state.z2bar / state.zbar) / (zcomp ** 2.5 - scn_fac.z1 ** 2.5 - scn_fac.z2 ** 2.5) ) # corrected enhancement factor, eq. A4 Gamma_12_2 = Gamma_12 ** 2 numer = corr_C + Gamma_12_2 denom = 1 + Gamma_12_2 h12 = numer / denom * h_fit # machine limit the output h12_max = 300 h12 = min(h12, h12_max) scor = np.exp(h12) return scor @njit def potekhin_1998(state, scn_fac): """Calculates screening factors based on Chabrier & Potekhin 1998. :param PlasmaState state: the precomputed plasma state factors :param ScreenFactors scn_fac: the precomputed ion pair factors :returns: screening correction factor References: Chabrier and Potekhin 1998, PhRvE, 58, 4941 """ Gamma_e = state.gamma_e_fac / state.temp zcomp = scn_fac.z1 + scn_fac.z2 Gamma_1 = Gamma_e * scn_fac.z1 ** (5 / 3) Gamma_2 = Gamma_e * scn_fac.z2 ** (5 / 3) Gamma_comp = Gamma_e * zcomp ** (5 / 3) A_1 = -0.9052 A_2 = 0.6322 A_3 = -0.5 * np.sqrt(3) - A_1/np.sqrt(A_2) f1 = A_1 * (np.sqrt(Gamma_1 * (A_2 + Gamma_1)) - A_2 * np.log(np.sqrt(Gamma_1 / A_2) + np.sqrt(1.0 + Gamma_1/A_2))) + 2.0 * A_3 * (np.sqrt(Gamma_1) - np.arctan(np.sqrt(Gamma_1))) f2 = A_1 * (np.sqrt(Gamma_2 * (A_2 + Gamma_2)) - A_2 * np.log(np.sqrt(Gamma_2 / A_2) + np.sqrt(1.0 + Gamma_2/A_2))) + 2.0 * A_3 * (np.sqrt(Gamma_2) - np.arctan(np.sqrt(Gamma_2))) f12 = A_1 * (np.sqrt(Gamma_comp * (A_2 + Gamma_comp)) - A_2 * np.log(np.sqrt(Gamma_comp / A_2) + np.sqrt(1.0 + Gamma_comp/A_2))) + 2.0 * A_3 * (np.sqrt(Gamma_comp) - np.arctan(np.sqrt(Gamma_comp))) h12 = f1 + f2 - f12 # machine limit the output h12_max = 300 h12 = min(h12, h12_max) scor = np.exp(h12) return scor
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,704
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/simple_cxx_network.py
"""A simple C++ reaction network for integrating into other C++ codes""" import glob import os from pynucastro.networks.base_cxx_network import BaseCxxNetwork class SimpleCxxNetwork(BaseCxxNetwork): def __init__(self, *args, **kwargs): # Initialize BaseCxxNetwork parent class super().__init__(*args, **kwargs) self.function_specifier = "inline" self.dtype = "Real" def _get_template_files(self): template_pattern = os.path.join(self.pynucastro_dir, 'templates', 'simple-cxx-network', '*.template') return glob.glob(template_pattern) def _write_network(self, odir=None): """ This writes the RHS, jacobian and ancillary files for the system of ODEs that this network describes, using the template files. """ # at the moment, we don't support TabularRates assert len(self.tabular_rates) == 0, "SimpleCxxNetwork does not support tabular rates" super()._write_network(odir=odir) if odir is None: odir = os.getcwd() # create a header file with the nuclei properties with open(os.path.join(odir, "network_properties.H"), "w") as of: of.write("#ifndef NETWORK_PROPERTIES_H\n") of.write("#define NETWORK_PROPERTIES_H\n") of.write("#include <vector>\n") of.write("#include <string>\n") of.write("#include <amrex_bridge.H>\n\n") of.write(f"constexpr int NumSpec = {len(self.unique_nuclei)};\n\n") of.write("constexpr Real aion[NumSpec] = {\n") for n, nuc in enumerate(self.unique_nuclei): of.write(f" {nuc.A:6.1f}, // {n}\n") of.write(" };\n\n") of.write("constexpr Real aion_inv[NumSpec] = {\n") for n, nuc in enumerate(self.unique_nuclei): of.write(f" 1.0/{nuc.A:6.1f}, // {n}\n") of.write(" };\n\n") of.write("constexpr Real zion[NumSpec] = {\n") for n, nuc in enumerate(self.unique_nuclei): of.write(f" {nuc.Z:6.1f}, // {n}\n") of.write(" };\n\n") of.write("static const std::vector<std::string> spec_names = {\n") for n, nuc in enumerate(self.unique_nuclei): of.write(f" \"{nuc.short_spec_name.capitalize()}\", // {n}\n") of.write(" };\n\n") of.write("namespace Species {\n") of.write(" enum NetworkSpecies {\n") for n, nuc in enumerate(self.unique_nuclei): if n == 0: of.write(f" {nuc.short_spec_name.capitalize()}=1,\n") else: of.write(f" {nuc.short_spec_name.capitalize()},\n") of.write(" };\n") of.write("}\n\n") of.write("#endif\n")
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,705
pynucastro/pynucastro
refs/heads/main
/pynucastro/__init__.py
"""pynucastro is a python module that interprets the nuclear reaction rates, including those cataloged by the JINA ReacLib project: https://reaclib.jinaweb.org/ It provides both interactive access to the rates, for use in Jupyter notebooks as well as methods for writing python and C++ nuclear reaction networks, including the the righthand side and Jacobian routines. Several different packages provide the data structures needed to interpret rates and build networks. library ------- library stores Reaclib rate files in Reaclib 1 or 2 formats as well as the directory `library/tabular` containing tabulated rates. pynucastro will search these directories for rate files as well as the current working directory. Adding Reaclib rate files simply requires downloading them from the JINA ReacLib project and placing them in the library folder. They must be in the Reaclib 1 format. nucdata ------- nucdata provides: * Nucleus : a single nucleus, with a descriptive name and its properties. nucdata provides tables of binding energy per nucleon in MeV, partition function and the number of spin states for nuclides specified by their number of neutrons N and atomic number Z. The data for these tables is derived from the Atomic Mass Evaluations 2012, 2016 and 2020. By default, pynucastro uses Atomic Mass Evaluation 2016, and Nucleus Spin Evaluation 2020. Scripts for reading the Atomic Mass Evaluation tables and generating binding energy tables for pynucastro are provided in `pynucastro/nucdata/AtomicMassEvaluation`. networks -------- networks provides classes and functions for organizing collection of rates, including: * Composition : this is a container of Nucleus objects along with associated mass fractions. This is used for evaluating rates when doing interactive exploration with pynucastro. * RateCollection : this is simply a collection of rates. It will determine all of the links between the rates and allow you to visualize the dependencies. * Explorer : an explorer takes a rate composition and composition and produces an interactive visualization that can be explored in Jupyter notebooks. * PythonNetwork : this extends the RateCollection to enable output of python code that can be used with ODE integrators to solve a network. * BaseCxxNetwork : this extends the RateCollection to enable output of C++ code. * AmrexAstroCxxNetwork : this extends the RateCollection to enable output of C++ code that can be used to add a network to the hydrodynamics codes Castro and MAESTROeX via the AMReX-Astro Microphysics repository. * SimpleCxxNetwork : this extends the RateCollection to enable output of basic C++ code that can be as the starting point for incorporating a pynucastro network into a non-AMReX simulation code. rates ----- rates provides classes and functions for interpreting individual reaction rates, including: * Rate : a single Reaclib rate, with methods for plotting and evaluating it. * RatePair : a pair of rates representing the corresponding forward and reverse rates * Tfactors : this is a simple container class that holds the various temperature powers needed to evaluate a rate. * RateLibrary: a container class for Reaclib rates that provides a high level interface for reading Reaclib-formatted files containing one or more rates. * RateFilter: a class implementing search constraints to look up a desired rate or group of rates from a RateLibrary. screening --------- screening provides python screening routines for the rates. templates --------- templates contains subdirectories for generating AmrexAstroCxxNetwork C++ files implementing the ODE right hand side, jacobian, and integration driver routines. pynucastro processes these template files by replacing tags of the form `<tag>` with generated code specific to a given choice of reaction rates. """ from ._version import version __version__ = version import pynucastro.screening from pynucastro.networks import (AmrexAstroCxxNetwork, BaseCxxNetwork, Composition, Explorer, PythonNetwork, RateCollection, SimpleCxxNetwork, StarKillerCxxNetwork, SympyRates) from pynucastro.nucdata import Nucleus, get_nuclei_in_range from pynucastro.rates import (ApproximateRate, DerivedRate, LangankeLibrary, Library, Rate, RateFilter, ReacLibLibrary, SuzukiLibrary, TabularLibrary, Tfactors, list_known_rates, load_rate) from pynucastro.screening import make_plasma_state, make_screen_factors
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,706
pynucastro/pynucastro
refs/heads/main
/pynucastro/reduction/generate_data.py
#!/usr/bin/env python3 import numpy as np from pynucastro import Composition, Nucleus from pynucastro.reduction.load_network import load_network def dataset(network, n=10, permute=True, b_rho=None, b_T=None, b_Z=None): """ Generate a dataset with *n* datapoints. Will either be returned as a sequence of tuples, each with order (composition, density, temperature) if *permute* is *True* (default), or the transpose of that if *permute* is *False*. The parameters *b_rho*, *b_T*, and *b_Z* are tuples giving the bounds on density, temperature, and metallicity respectively. """ if isinstance(n, int): n = np.ones(3, dtype=np.int32) * n else: n = np.array(list(n), dtype=np.int32) # Bounds on each variable if b_rho is None: b_rho = (1e2, 1e6) # density (g/cm^3) if b_T is None: b_T = (8e6, 1.5e9) # temperature (K) if b_Z is None: b_Z = (0.02, 0.2) # metallicity rho = np.geomspace(*b_rho, num=n[1]) T = np.geomspace(*b_T, num=n[2]) comp_list = [] for Z in np.linspace(*b_Z, num=n[0]): comp = Composition(network.get_nuclei()) # 75/25 H1/He4 ratio comp.X[Nucleus("p")] = (1. - Z) * 0.75 comp.X[Nucleus("he4")] = (1. - Z) * 0.25 # 50% of remaining stuff in carbon-12 comp.X[Nucleus("c12")] = Z * 0.5 # Split the rest across all other nuclei omit = {Nucleus("p"), Nucleus("he4"), Nucleus("c12")} rem = 0.5 * Z / (len(comp.X) - len(omit)) for nuc in comp.X: if nuc not in omit: comp.X[nuc] = rem comp.normalize() comp_list.append(comp) if not permute: yield comp_list yield rho yield T return for rho_i in rho: for T_i in T: for comp in comp_list: yield (comp, rho_i, T_i) def main(): network = load_network(Nucleus("ni56")) conds_list = list(dataset(network)) rho = sorted({conds[1] for conds in conds_list}) T = sorted({conds[2] for conds in conds_list}) comp = {conds[0] for conds in conds_list} print("ρ") print(rho) print() print("T") print(T) print() def comp_converter(comp): X = comp.X[Nucleus("p")] Y = comp.X[Nucleus("he4")] ZC12 = comp.X[Nucleus("c12")] Zmin = min(comp.X.values()) return (X, Y, ZC12, Zmin) print("X") print(np.array(list(map(comp_converter, comp)))) if __name__ == "__main__": main()
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,707
pynucastro/pynucastro
refs/heads/main
/pynucastro/nucdata/tests/test_nucleus.py
from pytest import approx from pynucastro.nucdata import Nucleus, get_nuclei_in_range class TestNucleus: @classmethod def setup_class(cls): """ this is run once for each class before any tests """ @classmethod def teardown_class(cls): """ this is run once for each class after all tests """ def setup_method(self): """ this is run before each test """ self.p = Nucleus("p") self.n = Nucleus("n") self.h1 = Nucleus("H1") self.d = Nucleus("d") self.he4 = Nucleus("He4") self.c12 = Nucleus("C12") self.o16 = Nucleus("O16") self.ni56 = Nucleus("Ni56") self.u238 = Nucleus("U238") self.he4_also = Nucleus("he4") self.ne41 = Nucleus("ne41") self.ni61 = Nucleus("ni61") self.pb237 = Nucleus("pb237") def teardown_method(self): """ this is run after each test """ def test_atomic_weights(self): assert self.d.A == 2 assert self.he4.A == 4 assert self.c12.A == 12 assert self.ni56.A == 56 assert self.u238.A == 238 def test_atomic_numbers(self): assert self.d.Z == 1 assert self.he4.Z == 2 assert self.c12.Z == 6 assert self.ni56.Z == 28 assert self.u238.Z == 92 def test_comparisons(self): assert self.p == self.h1 assert self.d != self.he4 assert self.d < self.he4 assert self.ni56 > self.c12 assert self.he4_also == self.he4 def test_names(self): assert self.ni56.c() == "Ni56" assert self.ni56.pretty == "{}^{56}\\mathrm{Ni}" def test_binding(self): assert self.ni56.nucbind == approx(8.642779) def test_spin(self): assert int(self.p.spin_states) == 2 assert int(self.he4.spin_states) == 1 assert int(self.d.spin_states) == 3 assert int(self.c12.spin_states) == 1 assert int(self.ni56.spin_states) == 1 def test_partition_low_temp(self): assert not self.p.partition_function assert not self.h1.partition_function assert self.ne41.partition_function.eval(0.35e9) == approx(1.0121446711436666) assert self.ni61.partition_function.eval(0.35e9) == approx(1.160524742683722) assert self.pb237.partition_function.eval(0.35e9) == approx(1.4410114805045504) def test_partition_high_temp(self): assert not self.p.partition_function assert not self.h1.partition_function assert self.ne41.partition_function.eval(32.0e9) == approx(4.901052000000001) assert self.ni61.partition_function.eval(32.0e9) == approx(1927800.437886083) assert self.pb237.partition_function.eval(32.0e9) == approx(5.05620611030359e+28) def test_mass(self): assert self.p.A_nuc == approx(1.0078250307554963) assert self.n.A_nuc == approx(1.0086649179839473) assert self.o16.A_nuc == approx(15.994914621587304) assert self.c12.A_nuc == 12.0 def test_range(self): nuc_list = get_nuclei_in_range(6, 8, 12, 16) assert len(nuc_list) == 15 assert nuc_list[0] == Nucleus("c12") assert nuc_list[1] == Nucleus("c13") assert nuc_list[2] == Nucleus("c14") assert nuc_list[3] == Nucleus("c15") assert nuc_list[4] == Nucleus("c16") assert nuc_list[5] == Nucleus("n12") assert nuc_list[6] == Nucleus("n13") assert nuc_list[7] == Nucleus("n14") assert nuc_list[8] == Nucleus("n15") assert nuc_list[9] == Nucleus("n16") assert nuc_list[10] == Nucleus("o12") assert nuc_list[11] == Nucleus("o13") assert nuc_list[12] == Nucleus("o14") assert nuc_list[13] == Nucleus("o15") assert nuc_list[14] == Nucleus("o16")
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,708
pynucastro/pynucastro
refs/heads/main
/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py
#!/usr/bin/env python """ Reformat Table 2 and Table 3 of Rauscher 2003 into a standard format for pynucastro. These tables corresponds to: Thomas Rauscher, Astrophysical Journal Supplement Series, 147:403-408, 2003 These table txt files are published together with the paper above and are read unmodified by this script. """ import argparse from pynucastro.nucdata import PeriodicTable #Create a parser variable that demands for a table and creates an option to add a name to the formatted table parser = argparse.ArgumentParser() parser.add_argument('table', type=str, help='Name of the input table. "E.g. datafile2.txt"') parser.add_argument('-o', '--output', type=str, default='frdm_high', help='Name of the formatted table e.g fdrm_high.txt') args = parser.parse_args() finput = open(args.table, 'r') temp = ['12.0', '14.0', '16.0', '18.0', '20.0', '22.0', '24.0', '26.0', '28.0', '30.0', '35.0', '40.0', '45.0', '50.0', '55.0', '60.0', '65.0', '70.0', '75.0', '80.0', '85.0', '90.0', '95.0', '100.0', '105.0', '110.0', '115.0', '120.0', '125.0', '130.0', '135.0', '140.0', '145.0', '150.0', '155.0', '160.0', '165.0', '170.0', '175.0', '180.0', '190.0', '200.0', '210.0', '220.0', '230.0', '240.0', '250.0', '275.0'] temperatures = ['{}E+9'.format(t) for t in temp] fout = open(args.output+'.txt', 'w') fout.write('# Partition function evaluation name: {}\n'.format(args.output)) fout.write('# Each entry is of the form:\n') fout.write('#\n') fout.write('# [nucleus name, e.g. ni56]\n') fout.write('# [List of partition function values]\n') fout.write('#\n') fout.write('# Partition functions all evaluated at these temperatures (K):\n') fout.write(' '.join(temperatures) + '\n\n') for _ in range(63): finput.readline() count = 0 for line in finput: count += 1 nucleus_stats = line.strip().split()[1:] Z = int(nucleus_stats.pop(0)) A = int(nucleus_stats.pop(0)) J = float(nucleus_stats.pop(0)) if Z == 0: assert A == 1 abbrev = 'n' else: element = PeriodicTable.lookup_Z(Z) abbrev = '{}{}'.format(element.abbreviation, A) fout.write('{}\n'.format(abbrev)) fout.write(' '.join(nucleus_stats) + '\n\n') fout.close() finput.close()
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,709
pynucastro/pynucastro
refs/heads/main
/pynucastro/nucdata/nucleus.py
""" Classes and methods to interface with files storing rate data. """ import os import re from scipy.constants import physical_constants from pynucastro.nucdata.binding_table import BindingTable from pynucastro.nucdata.elements import PeriodicTable from pynucastro.nucdata.mass_table import MassTable from pynucastro.nucdata.partition_function import PartitionFunctionCollection from pynucastro.nucdata.spin_table import SpinTable _pynucastro_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) _pynucastro_rates_dir = os.path.join(_pynucastro_dir, 'library') _pynucastro_tabular_dir = os.path.join(_pynucastro_rates_dir, 'tabular') #set the atomic mass unit constant in MeV m_u, _, _ = physical_constants['atomic mass constant energy equivalent in MeV'] #read the mass excess table once and store it at the module-level _mass_table = MassTable() #read the spin table once and store it at the module-level _spin_table = SpinTable(reliable=True) # read the binding energy table once and store it at the module-level _binding_table = BindingTable() # read the partition function table once and store it at the module-level _pcollection = PartitionFunctionCollection(use_high_temperatures=True, use_set='frdm') class UnsupportedNucleus(Exception): pass class Nucleus: """ a nucleus that participates in a reaction -- we store it in a class to hold its properties, define a sorting, and give it a pretty printing string. :var Z: atomic number :var N: neutron number :var A: atomic mass :var nucbind: nuclear binding energy (MeV / nucleon) :var short_spec_name: nucleus abbreviation (e.g. "he4") :var caps_name: capitalized short species name (e.g. "He4") :var el: element name (e.g. "he") :var pretty: LaTeX formatted version of the nucleus name :var A_nuc: Nuclear Mass in amu """ _cache = {} def __init__(self, name, dummy=False): name = name.lower() self.raw = name # a dummy nucleus is one that we can use where a nucleus is needed # but it is not considered to be part of the network self.dummy = dummy # element symbol and atomic weight if name == "p": self.el = "h" self.A = 1 self.short_spec_name = "h1" self.caps_name = "p" elif name == "d": self.el = "h" self.A = 2 self.short_spec_name = "h2" self.caps_name = "H2" elif name == "t": self.el = "h" self.A = 3 self.short_spec_name = "h3" self.caps_name = "H3" elif name == "a": #this is a convenience, enabling the use of a commonly-used alias: # He4 --> \alpha --> "a" , e.g. c12(a,g)o16 self.el = "he" self.A = 4 self.short_spec_name = "he4" self.raw = "he4" self.caps_name = "He4" elif name == "n": self.el = "n" self.A = 1 self.Z = 0 self.N = 1 self.short_spec_name = "n" self.spec_name = "neutron" self.pretty = fr"\mathrm{{{self.el}}}" self.caps_name = "n" elif name.strip() in ("al-6", "al*6"): raise UnsupportedNucleus() else: e = re.match(r"([a-zA-Z]*)(\d*)", name) self.el = e.group(1).title() # chemical symbol assert self.el self.A = int(e.group(2)) assert self.A >= 0 self.short_spec_name = name self.caps_name = name.capitalize() # use lowercase element abbreviation regardless the case of the input self.el = self.el.lower() # atomic number comes from periodic table if name != "n": i = PeriodicTable.lookup_abbreviation(self.el) self.Z = i.Z assert isinstance(self.Z, int) assert self.Z >= 0 self.N = self.A - self.Z assert isinstance(self.N, int) assert self.N >= 0 # long name self.spec_name = f'{i.name}-{self.A}' # latex formatted style self.pretty = fr"{{}}^{{{self.A}}}\mathrm{{{self.el.capitalize()}}}" # set the number of spin states try: self.spin_states = _spin_table.get_spin_states(a=self.A, z=self.Z) except NotImplementedError: self.spin_states = None # set a partition function object to every nucleus try: self.partition_function = _pcollection.get_partition_function(self.short_spec_name) except ValueError: self.partition_function = None try: self.nucbind = _binding_table.get_binding_energy(n=self.N, z=self.Z) except NotImplementedError: # the binding energy table doesn't know about this nucleus self.nucbind = None # Now we will define the Nuclear Mass, try: self.A_nuc = float(self.A) + _mass_table.get_mass_diff(a=self.A, z=self.Z) / m_u except NotImplementedError: self.A_nuc = None @classmethod def from_cache(cls, name, dummy=False): key = (name.lower(), dummy) if key not in cls._cache: cls._cache[key] = Nucleus(name, dummy) return cls._cache[key] def __repr__(self): return self.raw def __hash__(self): return hash((self.Z, self.A)) def c(self): """return the capitalized-style name""" return self.caps_name def cindex(self): """return the name for C++ indexing""" return self.short_spec_name.capitalize() def __eq__(self, other): if isinstance(other, Nucleus): return self.el == other.el and \ self.Z == other.Z and self.A == other.A if isinstance(other, tuple): return (self.Z, self.A) == other return NotImplemented def __lt__(self, other): if not self.Z == other.Z: return self.Z < other.Z return self.A < other.A def get_nuclei_in_range(zmin, zmax, amin, amax): """given a range of Z = [zmin, zmax], and A = [amin, amax], return a list of Nucleus objects for all nuclei in this range""" nuc_list = [] assert zmax >= zmin, "zmax must be >= zmin" assert amax >= amin, "amax must be >= amin" for z in range(zmin, zmax+1): element = PeriodicTable.lookup_Z(z) for a in range(amin, amax+1): name = f"{element.abbreviation}{a}" nuc_list.append(Nucleus(name)) return nuc_list
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,710
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/tests/test_validate.py
# unit tests for rates import io import pytest import pynucastro as pyna ANSWER = \ """validation: ni56 produced in Fe52 + He4 ⟶ Ni56 + 𝛾 never consumed. validation: ni56 produced in Co55 + p ⟶ Ni56 + 𝛾 never consumed. validation: missing He4 + He4 + He4 ⟶ p + B11 as alternative to He4 + He4 + He4 ⟶ C12 + 𝛾 (Q = -8.682 MeV). validation: missing He4 + He4 + He4 ⟶ n + C11 as alternative to He4 + He4 + He4 ⟶ C12 + 𝛾 (Q = -11.4466 MeV). validation: missing C12 + He4 ⟶ p + N15 as alternative to C12 + He4 ⟶ O16 + 𝛾 (Q = -4.966 MeV). validation: missing C12 + He4 ⟶ n + O15 as alternative to C12 + He4 ⟶ O16 + 𝛾 (Q = -8.502 MeV). validation: missing C14 + He4 ⟶ n + O17 as alternative to C14 + He4 ⟶ O18 + 𝛾 (Q = -1.81745 MeV). validation: missing C14 ⟶ He4 + Be10 as alternative to C14 ⟶ N14 + e⁻ + 𝜈 (Q = -12.0119 MeV). validation: missing C14 ⟶ n + C13 as alternative to C14 ⟶ N14 + e⁻ + 𝜈 (Q = -8.1763 MeV). validation: missing N13 + n ⟶ He4 + B10 as alternative to N13 + n ⟶ N14 + 𝛾 (Q = -1.059 MeV). validation: missing N13 + n ⟶ p + C13 as alternative to N13 + n ⟶ N14 + 𝛾 (Q = 3.003 MeV). validation: missing N13 + He4 ⟶ n + F16 as alternative to N13 + He4 ⟶ p + O16 (Q = -10.981 MeV). validation: missing N14 + n ⟶ He4 + B11 as alternative to N14 + n ⟶ p + C14 (Q = -0.158 MeV). validation: missing N14 + n ⟶ H2 + C13 as alternative to N14 + n ⟶ p + C14 (Q = -5.32663 MeV). validation: missing N14 + n ⟶ N15 + 𝛾 as alternative to N14 + n ⟶ p + C14 (Q = 10.8333 MeV). validation: missing N14 + He4 ⟶ p + O17 as alternative to N14 + He4 ⟶ F18 + 𝛾 (Q = -1.19182 MeV). validation: missing N14 + He4 ⟶ n + F17 as alternative to N14 + He4 ⟶ F18 + 𝛾 (Q = -4.735 MeV). validation: missing O16 + He4 ⟶ p + F19 as alternative to O16 + He4 ⟶ Ne20 + 𝛾 (Q = -8.114 MeV). validation: missing O16 + He4 ⟶ n + Ne19 as alternative to O16 + He4 ⟶ Ne20 + 𝛾 (Q = -12.1348 MeV). validation: missing O18 + He4 ⟶ p + F21 as alternative to O18 + He4 ⟶ n + Ne21 (Q = -5.599 MeV). validation: missing O18 + He4 ⟶ Ne22 + 𝛾 as alternative to O18 + He4 ⟶ n + Ne21 (Q = 9.6681 MeV). validation: missing F18 + n ⟶ He4 + N15 as alternative to F18 + n ⟶ p + O18 (Q = 6.41745 MeV). validation: missing F18 + n ⟶ F19 + 𝛾 as alternative to F18 + n ⟶ p + O18 (Q = 10.432 MeV). validation: missing F18 + He4 ⟶ n + Na21 as alternative to F18 + He4 ⟶ p + Ne21 (Q = -2.58854 MeV). validation: missing F18 + He4 ⟶ Na22 + 𝛾 as alternative to F18 + He4 ⟶ p + Ne21 (Q = 8.48 MeV). validation: missing F18 ⟶ p + O17 as alternative to F18 ⟶ O18 + e⁺ + 𝜈 (Q = -5.6065 MeV). validation: missing F18 ⟶ n + F17 as alternative to F18 ⟶ O18 + e⁺ + 𝜈 (Q = -9.15 MeV). validation: missing Ne20 + n ⟶ He4 + O17 as alternative to Ne20 + n ⟶ Ne21 + 𝛾 (Q = -0.586 MeV). validation: missing Ne20 + n ⟶ p + F20 as alternative to Ne20 + n ⟶ Ne21 + 𝛾 (Q = -6.242 MeV). validation: missing Ne21 + He4 ⟶ p + Na24 as alternative to Ne21 + He4 ⟶ n + Mg24 (Q = -2.178 MeV). validation: missing Ne21 + He4 ⟶ Mg25 + 𝛾 as alternative to Ne21 + He4 ⟶ n + Mg24 (Q = 9.882 MeV). validation: missing Na23 + He4 ⟶ p + Mg26 as alternative to Na23 + He4 ⟶ Al27 + 𝛾 (Q = 1.82067 MeV). validation: missing Na23 + He4 ⟶ n + Al26 as alternative to Na23 + He4 ⟶ Al27 + 𝛾 (Q = -2.96595 MeV). validation: missing Mg23 + He4 ⟶ p + Al26 as alternative to Mg23 + He4 ⟶ Si27 + 𝛾 (Q = 1.87249 MeV). validation: missing Mg23 + He4 ⟶ n + Si26 as alternative to Mg23 + He4 ⟶ Si27 + 𝛾 (Q = -3.97554 MeV). validation: missing Mg23 ⟶ He4 + Ne19 as alternative to Mg23 ⟶ Na23 + e⁺ + 𝜈 (Q = -9.65012 MeV). validation: missing Mg23 ⟶ p + Na22 as alternative to Mg23 ⟶ Na23 + e⁺ + 𝜈 (Q = -7.5803 MeV). validation: missing Mg23 ⟶ n + Mg22 as alternative to Mg23 ⟶ Na23 + e⁺ + 𝜈 (Q = -13.1481 MeV). validation: missing Al27 + He4 ⟶ p + Si30 as alternative to Al27 + He4 ⟶ P31 + 𝛾 (Q = 2.37222 MeV). validation: missing Al27 + He4 ⟶ n + P30 as alternative to Al27 + He4 ⟶ P31 + 𝛾 (Q = -2.643 MeV). validation: missing Si27 + He4 ⟶ p + P30 as alternative to Si27 + He4 ⟶ S31 + 𝛾 (Q = 2.95222 MeV). validation: missing Si27 + He4 ⟶ n + S30 as alternative to Si27 + He4 ⟶ S31 + 𝛾 (Q = -3.96817 MeV). validation: missing Si27 ⟶ p + Al26 as alternative to Si27 ⟶ Al27 + e⁺ + 𝜈 (Q = -7.464 MeV). validation: missing Si27 ⟶ n + Si26 as alternative to Si27 ⟶ Al27 + e⁺ + 𝜈 (Q = -13.311 MeV). validation: missing P31 + He4 ⟶ p + S34 as alternative to P31 + He4 ⟶ Cl35 + 𝛾 (Q = 0.626848 MeV). validation: missing P31 + He4 ⟶ n + Cl34 as alternative to P31 + He4 ⟶ Cl35 + 𝛾 (Q = -5.64751 MeV). validation: missing S31 ⟶ p + P30 as alternative to S31 ⟶ P31 + e⁺ + 𝜈 (Q = -6.13304 MeV). validation: missing S31 ⟶ n + S30 as alternative to S31 ⟶ P31 + e⁺ + 𝜈 (Q = -13.0534 MeV). validation: missing S32 + He4 ⟶ n + Ar35 as alternative to S32 + He4 ⟶ Ar36 + 𝛾 (Q = -8.61469 MeV). validation: missing Cl35 + p ⟶ n + Ar35 as alternative to Cl35 + p ⟶ He4 + S32 (Q = -6.74847 MeV). validation: missing Cl35 + p ⟶ n + Ar35 as alternative to Cl35 + p ⟶ Ar36 + 𝛾 (Q = -6.74847 MeV). validation: missing Cl35 + He4 ⟶ p + Ar38 as alternative to Cl35 + He4 ⟶ K39 + 𝛾 (Q = 0.836956 MeV). validation: missing Cl35 + He4 ⟶ n + K38 as alternative to Cl35 + He4 ⟶ K39 + 𝛾 (Q = -5.85925 MeV). validation: missing Ar36 + He4 ⟶ n + Ca39 as alternative to Ar36 + He4 ⟶ Ca40 + 𝛾 (Q = -8.60354 MeV). validation: missing K39 + p ⟶ n + Ca39 as alternative to K39 + p ⟶ He4 + Ar36 (Q = -7.31496 MeV). validation: missing K39 + p ⟶ n + Ca39 as alternative to K39 + p ⟶ Ca40 + 𝛾 (Q = -7.31496 MeV). validation: missing K39 + He4 ⟶ p + Ca42 as alternative to K39 + He4 ⟶ Sc43 + 𝛾 (Q = -0.123994 MeV). validation: missing K39 + He4 ⟶ n + Sc42 as alternative to K39 + He4 ⟶ Sc43 + 𝛾 (Q = -7.33217 MeV). validation: missing Ca40 + He4 ⟶ n + Ti43 as alternative to Ca40 + He4 ⟶ Ti44 + 𝛾 (Q = -11.1716 MeV). validation: missing Sc43 + p ⟶ n + Ti43 as alternative to Sc43 + p ⟶ He4 + Ca40 (Q = -7.64917 MeV). validation: missing Sc43 + p ⟶ n + Ti43 as alternative to Sc43 + p ⟶ Ti44 + 𝛾 (Q = -7.64917 MeV). validation: missing Sc43 + He4 ⟶ p + Ti46 as alternative to Sc43 + He4 ⟶ V47 + 𝛾 (Q = 3.07144 MeV). validation: missing Sc43 + He4 ⟶ n + V46 as alternative to Sc43 + He4 ⟶ V47 + 𝛾 (Q = -4.76132 MeV). validation: missing Ti44 + He4 ⟶ n + Cr47 as alternative to Ti44 + He4 ⟶ p + V47 (Q = -8.63648 MeV). validation: missing Ti44 + He4 ⟶ n + Cr47 as alternative to Ti44 + He4 ⟶ Cr48 + 𝛾 (Q = -8.63648 MeV). validation: missing V47 + p ⟶ n + Cr47 as alternative to V47 + p ⟶ Cr48 + 𝛾 (Q = -8.22601 MeV). validation: missing V47 + He4 ⟶ p + Cr50 as alternative to V47 + He4 ⟶ Mn51 + 𝛾 (Q = 3.39339 MeV). validation: missing V47 + He4 ⟶ n + Mn50 as alternative to V47 + He4 ⟶ Mn51 + 𝛾 (Q = -5.02164 MeV). validation: missing Cr48 + He4 ⟶ n + Fe51 as alternative to Cr48 + He4 ⟶ p + Mn51 (Q = -8.24324 MeV). validation: missing Cr48 + He4 ⟶ n + Fe51 as alternative to Cr48 + He4 ⟶ Fe52 + 𝛾 (Q = -8.24324 MeV). validation: missing Mn51 + p ⟶ n + Fe51 as alternative to Mn51 + p ⟶ Fe52 + 𝛾 (Q = -8.80135 MeV). validation: missing Mn51 + He4 ⟶ p + Fe54 as alternative to Mn51 + He4 ⟶ Co55 + 𝛾 (Q = 3.14706 MeV). validation: missing Mn51 + He4 ⟶ n + Co54 as alternative to Mn51 + He4 ⟶ Co55 + 𝛾 (Q = -5.8782 MeV). validation: missing Fe52 + He4 ⟶ n + Ni55 as alternative to Fe52 + He4 ⟶ p + Co55 (Q = -8.64244 MeV). validation: missing Fe52 + He4 ⟶ n + Ni55 as alternative to Fe52 + He4 ⟶ Ni56 + 𝛾 (Q = -8.64244 MeV). validation: missing Co55 + p ⟶ n + Ni55 as alternative to Co55 + p ⟶ Ni56 + 𝛾 (Q = -9.47432 MeV). """ class TestValidate: @pytest.fixture(scope="class") def reduced_library(self, reaclib_library): all_reactants = ["n", "p", "he4", "c12", "o16", "ne20", "mg24", "si28", "s32", "ar36", "ca40", "ti44", "cr48", "fe52", "ni56", "al27", "p31", "cl35", "k39", "sc43", "v47", "mn51", "co55", "c14", "n13", "n14", "o18", "f18", "ne21", "mg23", "na23", "si27", "s31"] return reaclib_library.linking_nuclei(all_reactants) def test_validate(self, reduced_library, reaclib_library): output = io.StringIO() rc = pyna.RateCollection(libraries=[reduced_library]) rc.validate(reaclib_library, ostream=output) assert ANSWER == output.getvalue()
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,711
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/__init__.py
"""The pynucastro modules that support the creation of networks. There are several main submodules here: :meth:`rate_collection <pynucastro.networks.rate_collection>`: this is simply a collection of rates that knows about the links connecting nuclei. This is used as the base for the different classes the write code to output networks for integration. :meth:`python_network <pynucastro.networks.python_network>`: the support routines to generate a full, integrable network in python. :meth:`base_cxx_network <pynucastro.networks.base_cxx_network>`: the support routines to generate a standalone integrable network in pure C++. :meth:`simple_cxx_network <pynucastro.networks.simple_cxx_network>`: the support routines to generate a simple pure C++ network for interfacing with simulation codes. :meth:`amrexastro_cxx_network <pynucastro.networks.amrexastro_cxx_network>`: the support routines to generate a C++ network that can be incorporated into the AMReX-Astro Microphysics routines supported by astrophysical hydrodynamics codes. """ #__all__ = ["python_network", "rate_collection", "sympy_network_support"] from .amrexastro_cxx_network import AmrexAstroCxxNetwork from .base_cxx_network import BaseCxxNetwork from .python_network import PythonNetwork from .rate_collection import Composition, Explorer, RateCollection from .simple_cxx_network import SimpleCxxNetwork from .sympy_network_support import SympyRates StarKillerCxxNetwork = AmrexAstroCxxNetwork
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,712
pynucastro/pynucastro
refs/heads/main
/pynucastro/rates/tests/test_jacobian_term.py
# unit tests for rates import pytest from pytest import approx from pynucastro.networks import Composition from pynucastro.nucdata import Nucleus class TestJacTerm: @pytest.fixture(scope="class") def comp(self): nuc_list = [Nucleus("he4"), Nucleus("c12"), Nucleus("o16"), Nucleus("ne20"), Nucleus("f20"), Nucleus("mg24")] comp = Composition(nuc_list) comp.set_solar_like() return comp def test_jac_3alpha(self, comp, reaclib_library): r = reaclib_library.get_rate_by_name("he4(aa,g)c12") rho = 1.e6 T = 3.e8 ymolar = comp.get_molar() # the full rate is Y(alpha)**3 rho**2 N_A <sigma v> / 6 # where the 6 is the 3! that comes from like nuclei # consider drate/d(he4) # the derivative with respect to alpha is: # 3*Y(alpha)**2 rho**2 N_A <sigma v> / 6 dr_dalpha = 3 * ymolar[Nucleus("he4")]**2 * rho**2 * r.eval(T) / 6 assert r.eval_jacobian_term(T, rho, comp, Nucleus("he4")) == approx(dr_dalpha) # now consider the rate with respect to c12 -- the derivative # should be zero assert r.eval_jacobian_term(T, rho, comp, Nucleus("c12")) == 0.0 def test_c12ag(self, comp, reaclib_library): r = reaclib_library.get_rate_by_name("c12(a,g)o16") rho = 1.e6 T = 3.e8 ymolar = comp.get_molar() # the full rate is Y(c12) Y(alpha) rho N_A <sigma v> # consider drate/d(he4) dr_dalpha = ymolar[Nucleus("c12")] * rho * r.eval(T) assert r.eval_jacobian_term(T, rho, comp, Nucleus("he4")) == approx(dr_dalpha) # now drate/d(c12) dr_dc12 = ymolar[Nucleus("he4")] * rho * r.eval(T) assert r.eval_jacobian_term(T, rho, comp, Nucleus("c12")) == approx(dr_dc12) # now drate/d(o16) should be 0 assert r.eval_jacobian_term(T, rho, comp, Nucleus("o16")) == 0.0 def test_tabular_rate(self, comp, tabular_library): r = tabular_library.get_rate_by_name("ne20(,)f20") rho = 5.e9 T = 3.e8 # this full rate is Y(ne20) lambda, where lambda is the 1/tau # read from the table # the rate does not dependent on alpha assert r.eval_jacobian_term(T, rho, comp, Nucleus("he4")) == 0.0 # for dr/dY(ne20), we just have the raw rate from the table dr_dne20 = r.eval(T, rhoY=rho*comp.eval_ye()) assert r.eval_jacobian_term(T, rho, comp, Nucleus("ne20")) == dr_dne20
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,713
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/tests/test_nse.py
import pytest import pynucastro as pyna class TestNSE: @pytest.fixture(scope="class") def pynet(self, reaclib_library): lib = reaclib_library.linking_nuclei(["p", "he4", "fe52", "co55", "ni56"]) return pyna.RateCollection(libraries=lib) def test_nse_coul(self, pynet): rho = 1.0e7 T = 6.0e9 ye = 0.5 nse_comp = pynet.get_comp_nse(rho, T, ye, use_coulomb_corr=True) nse_Xs = list(nse_comp.X.values()) xsum = sum(nse_Xs) assert xsum == pytest.approx(1.0, rel=1.0e-10) assert nse_Xs[0] == pytest.approx(0.009432528259141131, rel=1.0e-10) assert nse_Xs[1] == pytest.approx(0.44084190707382365, rel=1.0e-10) assert nse_Xs[2] == pytest.approx(0.007118438690709681, rel=1.0e-10) assert nse_Xs[3] == pytest.approx(0.5187890542527211, rel=1.0e-10) assert nse_Xs[4] == pytest.approx(0.023818071723544595, rel=1.0e-10) def test_nse_no_coul(self, pynet): rho = 1.0e7 T = 6.0e9 ye = 0.5 nse_comp = pynet.get_comp_nse(rho, T, ye, use_coulomb_corr=False) nse_Xs = list(nse_comp.X.values()) xsum = sum(nse_Xs) assert xsum == pytest.approx(1.0, rel=1.0e-10) assert nse_Xs[0] == pytest.approx(0.009096572438869752, rel=1.0e-10) assert nse_Xs[1] == pytest.approx(0.4630929175748844, rel=1.0e-10) assert nse_Xs[2] == pytest.approx(0.006684804511147247, rel=1.0e-10) assert nse_Xs[3] == pytest.approx(0.5003114841378136, rel=1.0e-10) assert nse_Xs[4] == pytest.approx(0.020814221337257847, rel=1.0e-10)
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,714
pynucastro/pynucastro
refs/heads/main
/pynucastro/reduction/load_network.py
#!/usr/bin/env python3 import sys from pynucastro.networks import PythonNetwork from pynucastro.nucdata import Nucleus from pynucastro.rates import Library, RateFilter def load_network(endpoint=Nucleus('te108'), library_name='rp-process-lib'): """ Load a network from a library, filtering the library so only nuclei with Z and A less than the endpoint's Z and A are included. """ def ff(rate): react_meet_conds = \ ( r.Z <= endpoint.Z and r.A <= endpoint.A for r in rate.reactants ) prod_meet_conds = \ ( p.Z <= endpoint.Z and p.A <= endpoint.A for p in rate.products ) return all(react_meet_conds) and all(prod_meet_conds) filt = RateFilter(filter_function=ff) lib = Library(library_name) lib = lib.filter(filt) return PythonNetwork(libraries=[lib]) if __name__ == "__main__": args = {} if len(sys.argv) == 3: args = {"endpoint": Nucleus(sys.argv[1]), "library_name": sys.argv[2]} elif len(sys.argv) == 2: args = {"endpoint": Nucleus(sys.argv[1])} elif len(sys.argv) != 1: print("Usage: ./load_network.py [endpoint] [library_name]") sys.exit(0) net = load_network(**args) print("Network loaded!") print(f"Number of species: {len(net.unique_nuclei)}") print(f"Number of rates: {len(net.rates)}")
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,715
pynucastro/pynucastro
refs/heads/main
/pynucastro/rates/tests/test_approx_rate.py
# unit tests for rates import pytest from pytest import approx import pynucastro as pyna class TestTfactors: @pytest.fixture(scope="class") def rc(self, reaclib_library): mylib = reaclib_library.linking_nuclei(["mg24", "al27", "si28", "he4", "p"]) return pyna.RateCollection(libraries=[mylib]) @pytest.fixture(scope="class") def rp(self, rc): return rc.get_rate("he4_mg24__si28") @pytest.fixture(scope="class") def rs(self, rc): return [rc.get_rate("he4_mg24__p_al27"), rc.get_rate("p_al27__si28")] @pytest.fixture(scope="class") def ar(self, rc, rp, rs): rp_reverse = rc.get_rate("si28__he4_mg24") rs_reverse = [rc.get_rate("si28__p_al27"), rc.get_rate("p_al27__he4_mg24")] # approximate Mg24(a,g)Si28 together with Mg24(a,p)Al27(p,g)Si28 return pyna.ApproximateRate(primary_rate=rp, secondary_rates=rs, primary_reverse=rp_reverse, secondary_reverse=rs_reverse) def test_label(self, ar): assert ar.fname == "mg24_he4__si28__approx" def test_low_temp(self, ar, rp, rs): # at low temperatures, the approximate (a,g) should be ~ (a,g) + (a,p) T = 5.e8 assert ar.eval(T) == approx(rp.eval(T) + rs[0].eval(T), 1.e-6) T = 1.e9 assert ar.eval(T) == approx(rp.eval(T) + rs[0].eval(T), 0.1) def test_child_rates(self, ar): cr = ar.get_child_rates() assert cr[0].fname == "he4_mg24__si28" assert cr[1].fname == "he4_mg24__p_al27" assert cr[2].fname == "p_al27__si28" assert cr[3].fname == "si28__he4_mg24" assert cr[4].fname == "si28__p_al27" assert cr[5].fname == "p_al27__he4_mg24" assert len(cr) == 6
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,716
pynucastro/pynucastro
refs/heads/main
/pynucastro/reduction/drgep.py
import numpy as np from pynucastro.reduction.reduction_utils import (mpi_importer, mpi_numpy_decomp, to_list) MPI = mpi_importer() def calc_interaction_matrix(net, rvals): """Calculate direct interaction coefficients.""" N_species = len(net.unique_nuclei) # create index mapping j_map = {} for idx, n in enumerate(net.unique_nuclei): j_map[n] = idx # Calculate coefficients for A p_A = np.zeros(N_species, dtype=np.float64) c_A = np.zeros(N_species, dtype=np.float64) # A along rows, B along columns p_AB = np.zeros((N_species, N_species)) c_AB = np.zeros((N_species, N_species)) for i in range(N_species): n = net.unique_nuclei[i] for r in net.nuclei_produced[n]: rval = r.products.count(n) * rvals[r] p_A[i] += rval bs = set(r.products) | set(r.reactants) for b in bs: p_AB[i, j_map[b]] += rval for r in net.nuclei_consumed[n]: rval = r.reactants.count(n) * rvals[r] c_A[i] += rval bs = set(r.products) | set(r.reactants) for b in bs: c_AB[i, j_map[b]] += rval denom = np.maximum(p_A, c_A)[:, np.newaxis] # Calculate direct interaction coefficients r_AB = np.abs(p_AB - c_AB) / denom return r_AB def calc_interaction_matrix_numpy(net, rvals_arr): """Calculate direct interaction coefficients using NumPy.""" # Evaluate terms on RHS of ODE system prod_terms = net.nuc_prod_count * rvals_arr cons_terms = net.nuc_cons_count * rvals_arr # Calculate total production and consumption of each nucleus A p_A = prod_terms.sum(axis=1) c_A = cons_terms.sum(axis=1) # Calculate production / consumption of A in reactions involving B p_AB = prod_terms @ net.nuc_used c_AB = cons_terms @ net.nuc_used # We will normalize by maximum of production and consumption fluxes denom = np.maximum(p_A, c_A)[:, np.newaxis] # Calculate direct interaction coefficients r_AB = np.abs(p_AB - c_AB) / denom return r_AB def get_adj_nuc(net): """ Get set of adjacent nuclei for each nucleus in the net. Returns dictionary keyed by nuclei. """ adj_nuc = {} for n in net.unique_nuclei: bs = set() for r in net.nuclei_produced[n]: bs |= set(r.products) | set(r.reactants) for r in net.nuclei_consumed[n]: bs |= set(r.products) | set(r.reactants) adj_nuc[n] = bs return adj_nuc def drgep_dijkstras(net, r_AB, target, adj_nuc): """ Modified Dijkstra's algorithm to find paths that maximize the overall interaction coefficient between the target and each other nucleus in the net. """ # Number of species nspec = len(net.unique_nuclei) # Create data structures j_map = {} inf = float('inf') dist = np.zeros(nspec, dtype=np.float64) R_TB = np.zeros(nspec, dtype=np.float64) for idx, n in enumerate(net.unique_nuclei): j_map[n] = idx dist[idx] = -inf R_TB[idx] = -inf dist[j_map[target]] = 1.0 R_TB[j_map[target]] = inf imax = np.argmax(dist) # Main loop while dist[imax] > -inf: r_TA = dist[imax] R_TB[imax] = r_TA n = net.unique_nuclei[imax] bs = adj_nuc[n] for b in bs: jb = j_map[b] if R_TB[jb] > -inf: continue dist[jb] = max(dist[jb], r_TA * r_AB[imax, jb]) dist[imax] = -inf imax = np.argmax(dist) return R_TB def _drgep_kernel(net, R_TB, rvals, targets, tols, adj_nuc): r_AB = calc_interaction_matrix(net, rvals) for target, tol in zip(targets, tols): R_TB_i = drgep_dijkstras(net, r_AB, target, adj_nuc) np.maximum(R_TB, R_TB_i, out=R_TB, where=R_TB_i >= tol) def _drgep_kernel_numpy(net, R_TB, rvals, targets, tols, adj_nuc): r_AB = calc_interaction_matrix_numpy(net, rvals) for target, tol in zip(targets, tols): R_TB_i = drgep_dijkstras(net, r_AB, target, adj_nuc) np.maximum(R_TB, R_TB_i, out=R_TB, where=R_TB_i >= tol) def _drgep(net, conds, targets, tols): #----------------------------------- # Calculate interaction coefficients #----------------------------------- R_TB = np.zeros(len(net.unique_nuclei), dtype=np.float64) adj_nuc = get_adj_nuc(net) for comp, rho, T in conds: rvals = net.evaluate_rates(rho=rho, T=T, composition=comp) _drgep_kernel(net, R_TB, rvals, targets, tols, adj_nuc) return R_TB def _drgep_mpi(net, conds, targets, tols): #---------- # Init. MPI #---------- comm = MPI.COMM_WORLD MPI_N = comm.Get_size() MPI_rank = comm.Get_rank() #----------------------------------------------- # Calculate interaction coefficients in parallel #----------------------------------------------- R_TB_loc = np.zeros(len(net.unique_nuclei), dtype=np.float64) adj_nuc = get_adj_nuc(net) for i in range(MPI_rank, len(conds), MPI_N): comp, rho, T = conds[i] rvals = net.evaluate_rates(rho=rho, T=T, composition=comp) _drgep_kernel(net, R_TB_loc, rvals, targets, tols, adj_nuc) R_TB = np.zeros_like(R_TB_loc) comm.Allreduce([R_TB_loc, MPI.DOUBLE], [R_TB, MPI.DOUBLE], op=MPI.MAX) return R_TB def _drgep_numpy(net, conds, targets, tols): #---------------------------------------- # Unpack conditions; make precalculations #---------------------------------------- comp_L, rho_L, T_L = conds net.calc_count_matrices() net.update_rate_coef_arr() adj_nuc = get_adj_nuc(net) #------------------------------------------------ # Calculate interaction coefficients (vectorized) #------------------------------------------------ R_TB = np.zeros(len(net.unique_nuclei), dtype=np.float64) for comp in comp_L: net.update_yfac_arr(comp) for rho in rho_L: net.update_prefac_arr(rho, comp) for T in T_L: rvals_arr = net.evaluate_rates_arr(T) _drgep_kernel_numpy(net, R_TB, rvals_arr, targets, tols, adj_nuc) net.clear_arrays() return R_TB def _drgep_mpi_numpy(net, conds, targets, tols): #---------------------------------------- # Unpack conditions; make precalculations #---------------------------------------- n = tuple(map(len, conds)) comp_L, rho_L, T_L = conds net.calc_count_matrices() net.update_rate_coef_arr() adj_nuc = get_adj_nuc(net) #----------------------------------- # Init. MPI and divide up conditions #----------------------------------- comm = MPI.COMM_WORLD MPI_N = comm.Get_size() MPI_rank = comm.Get_rank() comp_idx, comp_step, rho_idx, rho_step, T_idx, T_step = mpi_numpy_decomp(MPI_N, MPI_rank, n) #-------------------------------------------------------------- # Calculate interaction coefficients (vectorized and using MPI) #-------------------------------------------------------------- R_TB_loc = np.zeros(len(net.unique_nuclei), dtype=np.float64) for i in range(comp_idx, n[0], comp_step): comp = comp_L[i] net.update_yfac_arr(comp) for j in range(rho_idx, n[1], rho_step): rho = rho_L[j] net.update_prefac_arr(rho, comp) for k in range(T_idx, n[2], T_step): T = T_L[k] rvals_arr = net.evaluate_rates_arr(T) _drgep_kernel_numpy(net, R_TB_loc, rvals_arr, targets, tols, adj_nuc) R_TB = np.zeros_like(R_TB_loc) comm.Allreduce([R_TB_loc, MPI.DOUBLE], [R_TB, MPI.DOUBLE], op=MPI.MAX) net.clear_arrays() return R_TB def drgep(net, conds, targets, tols, returnobj='net', use_mpi=False, use_numpy=False): """ Implementation of Directed Relation Graph with Error Propagation (DRGEP) reduction method described in Pepiot-Desjardins and Pitch 2008 (doi:10.1016/j.combustflame.2007.10.020) and Niemeyer and Sung 2011 (doi:10.1016/j.combustflame.2010.12.010). :param net: The network (RateCollection) to reduce. :param conds: A set of conditions to reduce over. Should either be a sequence of (composition, density, temperature) sequences/tuples if running in standard mode, or a sequence of 3 sequences ((composition, density, temperature) ordering) if running in NumPy mode. In the latter case, the sequences will be permuted to create the dataset. The compositions should be pynucastro Composition objects. :param targets: A collection of target nuclei (or a single target nucleus) to run the graph search algorithm from. Should be supplied as pynucastro Nucleus objects. :param tols: Tolerance(s) or cutoff threshold(s) to use for paths from each of the target nuclei. Nuclei whose interaction coefficients do not meet the specified tolerance will have their interaction coefficients set to 0.0. Can be a single number (will be the same for all targets) or a separate value for each target nucleus. :param returnobj: The type of object to return. Options are 'net' (a reduced network, the default setting), 'nuclei' (unique nuclei with nonzero interaction coefficients, ordered so the interaction coefficients are descending), and 'coeff' (the interaction coefficients as a NumPy array, with entries corresponding to nuclei in *net.unique_nuclei*). :param use_mpi: Whether to divide up the set of conditions across MPI processes or not. Default setting is *False*. :param use_numpy: Whether to use NumPy to vectorize the interaction coefficient calculations or not. This is more memory intensive and may actually hinder performance for some setups. Conditions should be supplied as 3 lists that will be permuted to form the dataset (see *conds* parameter). Default setting is *False*. """ #------------------ # Process arguments #------------------ if returnobj not in {'net', 'nuclei', 'coeff'}: raise ValueError(f"Invalid 'returnobj' argument: '{returnobj}'.") targets = to_list(targets) tols = to_list(tols, len(targets)) #------------------------------------------------------- # Determine operation mode and launch appropriate helper #------------------------------------------------------- if use_mpi: if use_numpy: R_TB = _drgep_mpi_numpy(net, conds, targets, tols) else: R_TB = _drgep_mpi(net, conds, targets, tols) elif use_numpy: R_TB = _drgep_numpy(net, conds, targets, tols) else: R_TB = _drgep(net, conds, targets, tols) #------------------------ # Return requested object #------------------------ if returnobj == 'net': nuclei = [net.unique_nuclei[i] for i in range(len(net.unique_nuclei)) if R_TB[i] > 0.0] return net.linking_nuclei(nuclei) if returnobj == 'nuclei': idx = sorted(range(len(R_TB)), key=lambda i: R_TB[i], reverse=True) return [net.unique_nuclei[i] for i in idx if R_TB[i] > 0.0] if returnobj == 'coeff': return R_TB # returnobj was checked at the start of the function assert False
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,717
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/sympy_network_support.py
"""This is a module that interprets the rates, ydots, and Jacobian through sympy""" import re import sympy from pynucastro.rates import TabularRate class SympyRates: def __init__(self): self.symbol_ludict = {} # Symbol lookup dictionary self._ydot_term_cache = {} self.name_density = 'state.rho' self.name_electron_fraction = 'state.y_e' # Define these for the particular network self.name_rate_data = 'screened_rates' self.name_y = 'Y' self.name_ydot = 'ydot' self.name_ydot_nuc = 'ydot_nuc' self.name_jacobian = 'jac' self.name_jacobian_nuc = 'jac' self.symbol_ludict['__dens__'] = self.name_density self.symbol_ludict['__y_e__'] = self.name_electron_fraction self.float_explicit_num_digits = 17 def ydot_term_symbol(self, rate, y_i): """ return a sympy expression containing this rate's contribution to the ydot term for nuclide y_i. """ key = (rate.cname(), y_i) if key in self._ydot_term_cache: return self._ydot_term_cache[key] srate = self.specific_rate_symbol(rate) # Check if y_i is a reactant or product c_reac = rate.reactants.count(y_i) c_prod = rate.products.count(y_i) if c_reac == 0 and c_prod == 0: # The rate doesn't contribute to the ydot for this y_i ydot_sym = float(sympy.sympify(0.0)) else: # y_i appears as a product or reactant ydot_sym = (c_prod - c_reac) * srate result = ydot_sym.evalf(n=self.float_explicit_num_digits) self._ydot_term_cache[key] = result return result def specific_rate_symbol(self, rate): """ return a sympy expression containing the term in a dY/dt equation in a reaction network corresponding to this rate. Also enter the symbol and substitution in the lookup table. """ # composition dependence Y_sym = 1 for r in sorted(set(rate.reactants)): c = rate.reactants.count(r) sym_final = f'{self.name_y}({r.cindex()})' sym_temp = f'Y__j{r}__' self.symbol_ludict[sym_temp] = sym_final Y_sym = Y_sym * sympy.symbols(sym_temp)**c # density dependence dens_sym = sympy.symbols('__dens__')**rate.dens_exp # electron fraction if electron capture reaction y_e_sym = sympy.sympify(1) if not isinstance(rate, TabularRate): if rate.weak_type == 'electron_capture' and not rate.tabular: y_e_sym = sympy.symbols('__y_e__') # prefactor prefactor_sym = sympy.sympify(1)/sympy.sympify(rate.inv_prefactor) # screened rate sym_final = self.name_rate_data + f'(k_{rate.cname()})' sym_temp = f'NRD__k_{rate.cname()}__' self.symbol_ludict[sym_temp] = sym_final screened_rate_sym = sympy.symbols(sym_temp) srate_sym = prefactor_sym * dens_sym * y_e_sym * Y_sym * screened_rate_sym return srate_sym def jacobian_term_symbol(self, rate, ydot_j, y_i): """ return a sympy expression containing the term in a jacobian matrix in a reaction network corresponding to this rate Returns the derivative of the j-th YDOT wrt. the i-th Y If the derivative is zero, returns 0. ydot_j and y_i are objects of the class 'Nucleus' """ ydot_sym = self.ydot_term_symbol(rate, ydot_j) deriv_sym = sympy.symbols(f'Y__j{y_i}__') jac_sym = sympy.diff(ydot_sym, deriv_sym) symbol_is_null = False if jac_sym.equals(0): symbol_is_null = True return (jac_sym.evalf(n=self.float_explicit_num_digits), symbol_is_null) def cxxify(self, s): """ Given string s, will replace the symbols appearing as keys in self.symbol_ludict with their corresponding entries. """ for k, v in self.symbol_ludict.items(): s = s.replace(k, v) if s == '0': s = '0.0e0' # Replace all double precision literals with custom real type # literals # constant type specifier const_spec = "_rt" # we want append any "e" scientific notation with "_rt". This # matches stuff like -1.25d-10, and gives us separate groups # for the prefix and exponent. The [^\w] makes sure a letter # isn't right in front of the match (like # 'k3d-1'). Alternately, we allow for a match at the start of # the string. e_re = re.compile(r"([^\w\+\-]|\A)([\+\-0-9.][0-9.]+)[eE]([\+\-]?[0-9]+)", re.IGNORECASE | re.DOTALL) # update "d" scientific notation -- allow for multiple # constants in a single string for ee in e_re.finditer(s): old_num = ee.group(0).strip() s = s.replace(old_num, f"{old_num}{const_spec}") return s
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,718
pynucastro/pynucastro
refs/heads/main
/conftest.py
""" Recent versions of numpy use AVX-512 routines from SVML to speed up some math functions on processors that support it. These implementations allow a maximum error of 4 ULP, which is looser than in previous versions. Our tests for write_network() (and probably some others) expect exactly reproducible floating point values, which may differ between the AVX-512 and fallback implementations. Unfortunately, not all of Github's runners support AVX-512, so we get unpredictable CI failures depending on what hardware the tests run on. For now, we're disabling these features when running the test suite with the NPY_DISABLE_CPU_FEATURES environment variable. This needs to be set before numpy is imported for the first time, and will emit a RuntimeWarning if the disabled features are not supported by the machine. This may be fixed by https://github.com/numpy/numpy/pull/24006, which uses the high accuracy (within 1 ULP) SVML routines for float64 values. Related numpy PRs and issues: https://github.com/numpy/numpy/pull/19478 https://github.com/numpy/numpy/pull/20991 https://github.com/numpy/numpy/pull/22240 https://github.com/numpy/numpy/issues/23523 """ import os import warnings os.environ["NPY_DISABLE_CPU_FEATURES"] = "AVX512F AVX512CD AVX512_SKX" # ignore all NPY_DISABLE_CPU_FEATURES warnings in any subprocesses # need this for nbval as it expects stderr to be empty os.environ["PYTHONWARNINGS"] = "ignore:During parsing environment variable 'NPY_DISABLE_CPU_FEATURES':RuntimeWarning::" with warnings.catch_warnings(): # ignore just the "not supported by your machine" warning for the standard pytest tests warnings.filterwarnings( action="ignore", message=r"(?s)During parsing environment variable 'NPY_DISABLE_CPU_FEATURES'.*not supported by your machine", category=RuntimeWarning ) import numpy # noqa[F401] # pylint: disable=unused-import
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,719
pynucastro/pynucastro
refs/heads/main
/pynucastro/rates/tests/test_rates.py
# unit tests for rates import math import pytest from pytest import approx from pynucastro import rates from pynucastro.nucdata import Nucleus class TestTfactors: @pytest.fixture(scope="class") def tf(self): return rates.Tfactors(2.e9) def test_tfactors(self, tf): assert tf.T9 == approx(2.0) assert tf.T9i == approx(0.5) assert tf.T913i == approx(0.5**(1./3.)) assert tf.T913 == approx(2.0**(1./3.)) assert tf.T953 == approx(2.0**(5./3.)) assert tf.lnT9 == approx(math.log(2.0)) class TestRate: @classmethod def setup_class(cls): """ this is run once for each class before any tests """ @classmethod def teardown_class(cls): """ this is run once for each class after all tests """ def setup_method(self): """ this is run before each test """ # chapter-1 self.rate1 = rates.load_rate("o15--n15-wc12") # chapter-2 self.rate2 = rates.load_rate("t-gn-d-nk06") # chapter-3 self.rate3 = rates.load_rate("he6-gnn-he4-cf88") # chapter-4 self.rate4 = rates.load_rate("c12-ag-o16-nac2") # chapter-5 self.rate5 = rates.load_rate("n15-pa-c12-nacr") # chapter-6 self.rate6 = rates.load_rate("he3-he3pp-he4-nacr") # chapter-7 self.rate7 = rates.load_rate("li7-tnna-he4-mafo") # chapter-8 self.rate8 = rates.load_rate("he4-aag-c12-fy05") # chapter-8, historical format (same rate as chapter-9) self.rate8_hist = rates.load_rate("he4-pphe3-he3-nacr-historical") # chapter-9 self.rate9 = rates.load_rate("he4-pphe3-he3-nacr") # chapter-10 self.rate10 = rates.load_rate("he4-npahe3-li7-mafo") # chapter-11 self.rate11 = rates.load_rate("b17-nnn-c14-wc12") self.n = Nucleus("n") self.p = Nucleus("p") self.h1 = Nucleus("H1") self.d = Nucleus("d") self.h3 = Nucleus("H3") self.he3 = Nucleus("He3") self.he4 = Nucleus("He4") self.he6 = Nucleus("He6") self.li7 = Nucleus("Li7") self.b17 = Nucleus("B17") self.c12 = Nucleus("C12") self.c14 = Nucleus("C14") self.n15 = Nucleus("N15") self.o15 = Nucleus("O15") self.o16 = Nucleus("O16") self.ni56 = Nucleus("Ni56") self.u238 = Nucleus("U238") self.he4_also = Nucleus("he4") def teardown_method(self): """ this is run after each test """ def test_reactants(self): # o15--n15-wc12 assert self.rate1.reactants[0] == self.o15 assert len(self.rate1.reactants) == 1 # t-gn-d-nk06 assert self.rate2.reactants[0] == self.h3 assert len(self.rate2.reactants) == 1 # he6-gnn-he4-cf88 assert self.rate3.reactants[0] == self.he6 assert len(self.rate3.reactants) == 1 # c12-ag-o16-nac2 assert self.rate4.reactants[0] == self.he4 assert self.rate4.reactants[1] == self.c12 assert len(self.rate4.reactants) == 2 # n15-pa-c12-nacr assert self.rate5.reactants[0] == self.h1 assert self.rate5.reactants[1] == self.n15 assert len(self.rate5.reactants) == 2 # he3-he3pp-he4-nacr assert self.rate6.reactants[0] == self.he3 assert self.rate6.reactants[1] == self.he3 assert len(self.rate6.reactants) == 2 # li7-tnna-he4-mafo assert self.rate7.reactants[0] == self.h3 assert self.rate7.reactants[1] == self.li7 assert len(self.rate7.reactants) == 2 # he4-aag-c12-fy05 assert self.rate8.reactants[0] == self.he4 assert self.rate8.reactants[1] == self.he4 assert self.rate8.reactants[2] == self.he4 assert len(self.rate8.reactants) == 3 # he4-pphe3-he3-nacr-historical assert self.rate8_hist.reactants[0] == self.p assert self.rate8_hist.reactants[1] == self.h1 assert self.rate8_hist.reactants[2] == self.he4 assert len(self.rate8_hist.reactants) == 3 # he4-pphe3-he3-nacr assert self.rate9.reactants[0] == self.p assert self.rate9.reactants[1] == self.h1 assert self.rate9.reactants[2] == self.he4 assert len(self.rate9.reactants) == 3 # he4-npahe3-li7-mafo assert self.rate10.reactants[0] == self.n assert self.rate10.reactants[1] == self.h1 assert self.rate10.reactants[2] == self.he4 assert self.rate10.reactants[3] == self.he4 assert len(self.rate10.reactants) == 4 # b17-nnn-c14-wc12 assert self.rate11.reactants[0] == self.b17 assert len(self.rate11.reactants) == 1 def test_products(self): assert self.rate4.products[0] == self.o16 assert self.rate8.products[0] == self.c12 assert len(self.rate8.products) == 1 # he4-pphe3-he3-nacr-historical assert self.rate8_hist.products[0] == self.he3 assert self.rate8_hist.products[1] == self.he3 assert len(self.rate8_hist.products) == 2 # he4-pphe3-he3-nacr assert self.rate9.products[0] == self.he3 assert self.rate9.products[1] == self.he3 assert len(self.rate9.products) == 2 def test_prefactor(self): assert self.rate4.prefactor == 1.0 assert self.rate8.prefactor == approx(0.16666666) def test_rate_exponent(self): assert self.rate8.get_rate_exponent(1.e8) == approx(40.9106396) def test_eval(self): assert self.rate8.eval(1.e8) == approx(2.0403192412842946e-24, rel=1.e-6, abs=1.e-40) def test_eval_deriv(self): T0 = 1.e8 eps = 1.e-8 # compare finite diff to analytic diff # rate4 diff = (self.rate4.eval(T0*(1.0+eps)) - self.rate4.eval(T0)) / (T0 * eps) err = abs(diff - self.rate4.eval_deriv(T0)) / diff assert err < 1.e-6 # rate5 diff = (self.rate5.eval(T0*(1.0+eps)) - self.rate5.eval(T0)) / (T0 * eps) err = abs(diff - self.rate5.eval_deriv(T0)) / diff assert err < 1.e-6 # rate6 diff = (self.rate6.eval(T0*(1.0+eps)) - self.rate6.eval(T0)) / (T0 * eps) err = abs(diff - self.rate6.eval_deriv(T0)) / diff assert err < 1.e-6 def test_comparison(self): assert self.rate1 > self.rate2 assert self.rate1 > self.rate4 assert self.rate8 > self.rate9 def test_weak(self): assert self.rate1.weak assert not self.rate2.weak def test_screen(self): assert not self.rate1.ion_screen assert self.rate4.ion_screen == [Nucleus("he4"), Nucleus("c12")] assert self.rate8.ion_screen == 3*[Nucleus("he4")] def test_heaviest_lightest(self): assert self.rate4.heaviest() == Nucleus("o16") assert self.rate4.lightest() == Nucleus("he4") assert self.rate2.lightest() == Nucleus("n") assert self.rate2.heaviest() == Nucleus("t") class TestDerivedRate: def a_a_ag_c12(self, reaclib_library): """ Here we test the inverse rate, computed by the use of detailed balance of a: A + B -> C reaction type. """ a_a_ag_c12 = reaclib_library.get_rate('he4 + he4 + he4 --> c12 <fy05_reaclib__>') c12_ga_a_a_reaclib = reaclib_library.get_rate('c12 --> he4 + he4 + he4 <fy05_reaclib__reverse>') c12_ga_a_a_derived = rates.DerivedRate(rate=a_a_ag_c12, compute_Q=False, use_pf=False) assert c12_ga_a_a_reaclib.eval(T=2.0e9) == approx(c12_ga_a_a_derived.eval(T=2.0e9), rel=1.7e-5) def test_a_a_ag_c12_with_pf(self, reaclib_library): """ This function test the correct rate value if we take in consideration the partition functions on the range 1.0e9 to 100.0e9 """ a_a_ag_c12 = reaclib_library.get_rate('he4 + he4 + he4 --> c12 <fy05_reaclib__>') c12_ga_a_a_derived = rates.DerivedRate(rate=a_a_ag_c12, compute_Q=False, use_pf=True) assert c12_ga_a_a_derived.eval(T=2.0e9) == approx(2.8953989705969484e-07) def test_a_a_ag_c12_with_Q(self, reaclib_library): """ This function test the correct rate value if we take in consideration the exact values of atomic nuclear weight in order to compute the Q capture value of the reaction rate. """ a_a_ag_c12 = reaclib_library.get_rate('he4 + he4 + he4 --> c12 <fy05_reaclib__>') c12_ga_a_a_derived = rates.DerivedRate(rate=a_a_ag_c12, compute_Q=True, use_pf=False) assert c12_ga_a_a_derived.eval(T=2.0e9) == approx(2.899433744446781e-07) class TestWeakRates: @pytest.fixture(scope="class") def rate1(self): return rates.TabularRate("o18--f18-toki") @pytest.fixture(scope="class") def rate2(self): return rates.TabularRate("na22--ne22-toki") @pytest.fixture(scope="class") def rate3(self): return rates.TabularRate("sc45--ca45-toki") @pytest.fixture(scope="class") def rate4(self): return rates.TabularRate("ti45--sc45-toki") @pytest.fixture(scope="class") def rate5(self): return rates.TabularRate("v45--ti45-toki") @pytest.fixture(scope="class") def rate6(self): return rates.TabularRate("ca45--sc45-toki") def test_reactants(self, rate1, rate2, rate3, rate4, rate5, rate6): assert len(rate1.reactants) == 1 and len(rate1.products) == 1 assert rate1.products[0] == Nucleus("f18") assert rate1.reactants[0] == Nucleus("o18") assert rate1.eval(1.e10, 1.e7) == approx(3.990249e-11, rel=1.e-6, abs=1.e-20) assert len(rate2.reactants) == 1 and len(rate2.products) == 1 assert rate2.products[0] == Nucleus("ne22") assert rate2.reactants[0] == Nucleus("na22") assert rate2.eval(1.e9, 1.e6) == approx(1.387075e-05) assert len(rate3.reactants) == 1 and len(rate3.products) == 1 assert rate3.products[0] == Nucleus("ca45") assert rate3.reactants[0] == Nucleus("sc45") assert math.log10(rate3.eval(1.e9, 1.e11)) == approx(3.440) assert len(rate4.reactants) == 1 and len(rate4.products) == 1 assert rate4.products[0] == Nucleus("sc45") assert rate4.reactants[0] == Nucleus("ti45") assert math.log10(rate4.eval(1.e9, 1.e11)) == approx(3.853) assert len(rate5.reactants) == 1 and len(rate5.products) == 1 assert rate5.products[0] == Nucleus("ti45") assert rate5.reactants[0] == Nucleus("v45") assert math.log10(rate5.eval(1.e9, 1.e11)) == approx(4.715) assert len(rate6.reactants) == 1 and len(rate6.products) == 1 assert rate6.products[0] == Nucleus("sc45") assert rate6.reactants[0] == Nucleus("ca45") assert math.log10(rate6.eval(1.e9, 1.e11)) == approx(-99.999) class TestModify: @pytest.fixture(scope="function") def rate(self): return rates.load_rate("c12-c12n-mg23-cf88") def test_modify(self, rate): rate.modify_products("mg24") assert rate.Q == approx(13.93356) assert rate.products == [Nucleus("mg24")] assert rate.modified
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,720
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/tests/test_dupes.py
# unit tests for rates import pytest import pynucastro as pyna class TestDuplicates: @pytest.fixture(scope="class") def ecsn_rc(self, reaclib_library): all_nuclei = ["p", "he4", "ne20", "o20", "f20", "mg24", "al27", "o16", "si28", "s32", "p31"] ecsn_rl_lib = reaclib_library.linking_nuclei(all_nuclei, with_reverse=True) tabular_lib = pyna.TabularLibrary() ecsn_tabular_lib = tabular_lib.linking_nuclei(["f20", "o20", "ne20"]) return pyna.RateCollection(libraries=[ecsn_rl_lib, ecsn_tabular_lib]) def test_validate(self, ecsn_rc): dupes = ecsn_rc.find_duplicate_links() assert len(dupes) == 2 d1 = dupes[0][0] assert d1.reactants == [pyna.Nucleus("o20")] assert d1.products == [pyna.Nucleus("f20")] d2 = dupes[1][0] assert d2.reactants == [pyna.Nucleus("f20")] assert d2.products == [pyna.Nucleus("ne20")]
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,721
pynucastro/pynucastro
refs/heads/main
/.github/workflows/simple_cxx_network/test_simple_cxx.py
import pynucastro as pyna lib = pyna.ReacLibLibrary().linking_nuclei(["he4", "c12", "o16", "ne20"]) net = pyna.SimpleCxxNetwork(libraries=[lib]) net.write_network()
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,722
pynucastro/pynucastro
refs/heads/main
/pynucastro/screening/__init__.py
"""Screening routines""" __all__ = ["screen"] from .screen import (PlasmaState, ScreenFactors, chugunov_2007, chugunov_2009, make_plasma_state, make_screen_factors, potekhin_1998)
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,723
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/tests/test_python_net.py
# unit tests for rates import pytest from pynucastro import rates class TestPythonNetwork: @pytest.fixture(scope="class") def rate1(self): return rates.ReacLibRate("c13-pg-n14-nacr") @pytest.fixture(scope="class") def rate2(self): return rates.ReacLibRate("he4-pphe3-he3-nacr") @pytest.fixture(scope="class") def rate3(self): return rates.ReacLibRate("he4-npahe3-li7-mafo") @pytest.fixture(scope="class") def rate4(self): return rates.ReacLibRate("p-p-d-ec") def test_ydot_string(self, rate1, rate2, rate3, rate4): ydot1 = rate1.ydot_string_py() assert ydot1 == "rho*Y[jp]*Y[jc13]*rate_eval.p_c13__n14" ydot2 = rate2.ydot_string_py() assert ydot2 == "5.00000000000000e-01*rho**2*Y[jp]**2*Y[jhe4]*rate_eval.p_p_he4__he3_he3" ydot3 = rate3.ydot_string_py() assert ydot3 == "5.00000000000000e-01*rho**3*Y[jn]*Y[jp]*Y[jhe4]**2*rate_eval.n_p_he4_he4__he3_li7" ydot4 = rate4.ydot_string_py() assert ydot4 == "5.00000000000000e-01*rho**2*ye(Y)*Y[jp]**2*rate_eval.p_p__d__weak__electron_capture" def test_jacobian_string(self, rate1, rate2, rate3, rate4): jac1 = rate1.jacobian_string_py(rate1.reactants[0]) assert jac1 == "rho*Y[jc13]*rate_eval.p_c13__n14" jac2 = rate2.jacobian_string_py(rate2.reactants[0]) assert jac2 == "5.00000000000000e-01*rho**2*2*Y[jp]*Y[jhe4]*rate_eval.p_p_he4__he3_he3" jac3 = rate3.jacobian_string_py(rate3.reactants[0]) assert jac3 == "5.00000000000000e-01*rho**3*Y[jp]*Y[jhe4]**2*rate_eval.n_p_he4_he4__he3_li7" jac4 = rate4.jacobian_string_py(rate4.reactants[0]) assert jac4 == "5.00000000000000e-01*rho**2*ye(Y)*2*Y[jp]*rate_eval.p_p__d__weak__electron_capture" def test_function_string(self, rate1, rate2, rate3, rate4): ostr1 = """ @numba.njit() def p_c13__n14(rate_eval, tf): # c13 + p --> n14 rate = 0.0 # nacrn rate += np.exp( 18.5155 + -13.72*tf.T913i + -0.450018*tf.T913 + 3.70823*tf.T9 + -1.70545*tf.T953 + -0.666667*tf.lnT9) # nacrr rate += np.exp( 13.9637 + -5.78147*tf.T9i + -0.196703*tf.T913 + 0.142126*tf.T9 + -0.0238912*tf.T953 + -1.5*tf.lnT9) # nacrr rate += np.exp( 15.1825 + -13.5543*tf.T9i + -1.5*tf.lnT9) rate_eval.p_c13__n14 = rate """ ostr2 = """ @numba.njit() def p_p_he4__he3_he3(rate_eval, tf): # p + p + he4 --> he3 + he3 rate = 0.0 # nacrn rate += np.exp( 2.98257 + -149.222*tf.T9i + -12.277*tf.T913i + -0.103699*tf.T913 + -0.0649967*tf.T9 + 0.0168191*tf.T953 + -2.16667*tf.lnT9) rate_eval.p_p_he4__he3_he3 = rate """ ostr3 = """ @numba.njit() def n_p_he4_he4__he3_li7(rate_eval, tf): # n + p + he4 + he4 --> he3 + li7 rate = 0.0 # mafon rate += np.exp( -14.8862 + -111.725*tf.T9i + -17.989*tf.T913i + -1.57523e-09*tf.T913 + 1.45934e-10*tf.T9 + -1.15341e-11*tf.T953 + -3.66667*tf.lnT9) rate_eval.n_p_he4_he4__he3_li7 = rate """ ostr4 = """ @numba.njit() def p_p__d__weak__electron_capture(rate_eval, tf): # p + p --> d rate = 0.0 # bet+w rate += np.exp( -34.7863 + -3.51193*tf.T913i + 3.10086*tf.T913 + -0.198314*tf.T9 + 0.0126251*tf.T953 + -1.02517*tf.lnT9) # ecw rate += np.exp( -43.6499 + -0.00246064*tf.T9i + -2.7507*tf.T913i + -0.424877*tf.T913 + 0.015987*tf.T9 + -0.000690875*tf.T953 + -0.207625*tf.lnT9) rate_eval.p_p__d__weak__electron_capture = rate """ assert rate1.function_string_py().strip() == ostr1.strip() assert rate2.function_string_py().strip() == ostr2.strip() assert rate3.function_string_py().strip() == ostr3.strip() assert rate4.function_string_py().strip() == ostr4.strip()
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,724
pynucastro/pynucastro
refs/heads/main
/examples/CNO/cno.py
# CNO rate module generator from pynucastro.networks import PythonNetwork files = ["c12-pg-n13-ls09", "c13-pg-n14-nacr", "n13--c13-wc12", "n13-pg-o14-lg06", "n14-pg-o15-im05", "n15-pa-c12-nacr", "o14--n14-wc12", "o15--n15-wc12"] cno_net = PythonNetwork(files) cno_net.write_network("cno_rhs.py")
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,725
pynucastro/pynucastro
refs/heads/main
/pynucastro/nucdata/AtomicMassEvaluation/extract_spin.py
""" This script extract the spin data for each ground state (gs) nuclei, characterized by the pair (A, Z), from nubase_3.mas20.txt, published in: Kondev, F. G., Wang, M., Huang, W. J., Naimi, S., & Audi, G. Chinese Physics C, 45(3), 030001. (2021) doi:10.1088/1674-1137/abddae located in Table I. """ import argparse def num_states(spin_str_element): """ This function evaluates de spin number string, formatted as s=a/b and returns the number of states 2*s + 1. In the table we have three type of strings: 1. spin numbers integers formatted with 1 or 2 characters, e.g s=1, and s=10. 2. spin numbers formatted with 3 characters. e.g. s=3/2. 3. spin numbers formatted with 4 characters. e.g. s=11/2 Parameters ---------- :var spin_str_element: This string class element contains the information in [88:102], about spin, parity, and isospin charge. Returns: -------- :var states: this integer variable contains the number of states associated to the `spin_str_element` string """ if len(spin_str_element) == 1 or len(spin_str_element) == 2: states = 2*int(spin_str_element) + 1 return states elif len(spin_str_element) == 3: num = int(spin_str_element[0]) den = int(spin_str_element[2]) states = 2*num//den + 1 return states elif len(spin_str_element) == 4: num = int(spin_str_element[0:2]) den = int(spin_str_element[3]) states = 2*num//den + 1 return states else: return None parser = argparse.ArgumentParser() parser.add_argument('table', type=str, help='Name of the input spin stable') parser.add_argument('-o', '--output', type=str, default='nubase2020', help='Pynucastro Formatted Table') args = parser.parse_args() finput = open(args.table, 'r') # First, we need to get rid of the first 25 lines. for _ in range(25): finput.readline() fout = open(args.output+'.txt', 'w') # Write the content of the new formatted types of A, Z, Spin, Number of States # in a new file. fout.write('# Ground state spin evaluation table: {}\n'.format(args.output)) fout.write('# if the ==Spin== column contain more than two values, the gs state is uncertain.\n') fout.write('#\n') fout.write('#==A=='+' '*22+'==Z=='+' '*18+'==Spin=='+' '*18+'==Number=of=States==\n') # For each consecutive line, we extract: for line in finput: A_string = line[0:3] # The string that contains A Z_string = line[4:7] # The string that contains Z i_str = line[7] # The string that defines gs spin_str_list = line[88:102].strip().split() # A list of strings ["spin+parity", "Isospin"] # We convert the first three string variables to integers A = int(A_string) Z = int(Z_string) i = int(i_str) # We extract the "spin+parity" string from spin_str_list if spin_str_list: spin_str = spin_str_list.pop(0) else: continue # We remove the characters from the string "+-,*()#". # The meaning of each (set of) character(s) is(are) the following: # # "*" : The spin/parity measurement is provided by # strong experimental arguments. # "+-" : The parity associated to each nucleus. # "()" : The spin/parity measurement is provided by # weak experimental arguments. # "#" : The spin/parity measurement is provided by # theoretical arguments. special_chars = "+-*()#," for c in special_chars: spin_str = spin_str.replace(c, ' ') #From spin_str we remove the parity #and source information; however: # 1. Some `spin_str` strings contains two values, # that contains uncertain measurements # from a particular nuclei state gs. # 2. Some nucleus information may have been # extrapolated without taking experimental # measurements. spin_str = spin_str.strip().split() if i == 0: output_str = '{0:5}'.format(A) output_str += ' '*21 output_str += '{0:5}'.format(Z) if spin_str: output_str += ' '*23 spin_str_1 = spin_str.pop(0) output_str += '{0:<4}'.format(spin_str_1) state1 = str(num_states(spin_str_1)) if spin_str: output_str += ' ' spin_str_2 = spin_str.pop(0) output_str += '{0:<5}'.format(spin_str_2) state2 = str(num_states(spin_str_2)) else: state2 = None else: continue if state2: output_str += ' '*21 else: output_str += ' '*27 output_str += '{0:<3}'.format(state1) if state2: output_str += ' ' output_str += '{0:<3}'.format(state2) output_str += '\n' fout.write(output_str) else: continue fout.close() finput.close()
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,726
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/rate_collection.py
"""A collection of classes and methods to deal with collections of rates that together make up a network.""" import collections import copy import functools import math import os import warnings from operator import mul import matplotlib as mpl import matplotlib.pyplot as plt import networkx as nx import numpy as np from ipywidgets import interact from matplotlib.colors import SymLogNorm from matplotlib.patches import ConnectionPatch from matplotlib.scale import SymmetricalLogTransform from matplotlib.ticker import MaxNLocator from mpl_toolkits.axes_grid1 import make_axes_locatable from scipy import constants from scipy.optimize import fsolve # Import Rate from pynucastro.nucdata import Nucleus, PeriodicTable from pynucastro.rates import (ApproximateRate, DerivedRate, Library, Rate, RateFileError, RatePair, TabularRate, Tfactors, load_rate) from pynucastro.rates.library import _rate_name_to_nuc from pynucastro.screening import make_plasma_state, make_screen_factors from pynucastro.screening.screen import NseState mpl.rcParams['figure.dpi'] = 100 def _skip_xalpha(n, p, r): """utility function to consider if we show an (a, x) or (x, a) rate. Here, p is the product we want to link to""" # first check if alpha is the heaviest nucleus on the RHS rhs_heavy = max(r.products) if not (rhs_heavy.Z == 2 and rhs_heavy.A == 4): # for rates that are A (x, alpha) B, where A and B are heavy nuclei, # don't show the connection of the nucleus to alpha, only show it to B if p.Z == 2 and p.A == 4: return True # likewise, hide A (alpha, x) B, unless A itself is an alpha c = r.reactants n_alpha = 0 for nuc in c: if nuc.Z == 2 and nuc.A == 4: n_alpha += 1 # if there is only 1 alpha and we are working on the alpha node, # then skip if n_alpha == 1 and n.Z == 2 and n.A == 4: return True return False def _skip_xp(n, p, r): """utility function to consider if we show an (p, x) or (x, p) rate. Here, p is the product we want to link to""" # for rates that are A (x, p) B, where A and B are heavy nuclei, # don't show the connection of the nucleus to p, only show it to B if p.Z == 1 and p.A == 1: return True # likewise, hide A (p, x) B, unless A itself is an p c = r.reactants n_p = 0 for nuc in c: if nuc.Z == 1 and nuc.A == 1: n_p += 1 # if there is only 1 p and we are working on the p node, # then skip if n_p == 1 and n.Z == 1 and n.A == 1: return True return False class Composition: """a composition holds the mass fractions of the nuclei in a network -- useful for evaluating the rates """ def __init__(self, nuclei, small=1.e-16): """nuclei is an iterable of the nuclei (Nucleus objects) in the network""" if not isinstance(nuclei[0], Nucleus): raise ValueError("must supply an iterable of Nucleus objects") self.X = {k: small for k in nuclei} def set_solar_like(self, Z=0.02): """ approximate a solar abundance, setting p to 0.7, He4 to 0.3 - Z and the remainder evenly distributed with Z """ num = len(self.X) rem = Z/(num-2) for k in self.X: if k == Nucleus("p"): self.X[k] = 0.7 elif k.raw == "he4": self.X[k] = 0.3 - Z else: self.X[k] = rem self.normalize() def set_all(self, xval): """ set all species to a particular value """ for k in self.X: self.X[k] = xval def set_nuc(self, name, xval): """ set nuclei name to the mass fraction xval """ for k in self.X: if k.raw == name: self.X[k] = xval break def normalize(self): """ normalize the mass fractions to sum to 1 """ X_sum = sum(self.X[k] for k in self.X) for k in self.X: self.X[k] /= X_sum def get_molar(self): """ return a dictionary of molar fractions""" molar_frac = {k: v/k.A for k, v in self.X.items()} return molar_frac def eval_ye(self): """ return the electron fraction """ zvec = [] avec = [] xvec = [] for n in self.X: zvec.append(n.Z) avec.append(n.A) xvec.append(self.X[n]) zvec = np.array(zvec) avec = np.array(avec) xvec = np.array(xvec) electron_frac = np.sum(zvec*xvec/avec)/np.sum(xvec) return electron_frac def eval_abar(self): """ return the mean molecular weight """ avec = np.zeros(len(self.X), dtype=np.int32) xvec = np.zeros(len(self.X), dtype=np.float64) for i, n in enumerate(self.X): avec[i] = n.A xvec[i] = self.X[n] return 1. / np.sum(xvec / avec) def __str__(self): ostr = "" for k in self.X: ostr += f" X({k}) : {self.X[k]}\n" return ostr def plot(self, trace_threshold=0.1, hard_limit=None, size=(9, 5)): """ Make a pie chart of Composition. group trace nuclei together and explode into bar chart parameters ---------- trace_threshold : the threshold to consider a component to be trace. hard_limit : hard limit for nuclei to be labeled in the plot. Default is None which will set the limit to 5% of total trace abundance size: tuple giving width x height of the plot in inches """ # find trace nuclei trace_keys = [] trace_tot = 0. main_keys = [] for k in self.X: # if below threshold, count as trace element if self.X[k] < trace_threshold: trace_keys.append(k) trace_tot += self.X[k] else: main_keys.append(k) # check if any trace nuclei if not trace_keys: # just do pie chart without including trace fig, ax = plt.subplots(1, 1, figsize=size) ax.pie(self.X.values(), labels=self.X.keys(), autopct=lambda p: f"{p/100:0.3f}") else: # find trace nuclei which contribute little to trace proportion if hard_limit is None: # make hardlimit proportional to trace abundance hard_limit = 0.05*trace_tot limited_trace_keys = [] other_trace_tot = 0. for k in trace_keys: if self.X[k] < hard_limit: other_trace_tot += self.X[k] else: limited_trace_keys.append(k) # make figure and assign axis objects fig, (ax1, ax2) = plt.subplots(1, 2, figsize=size) fig.subplots_adjust(wspace=0) # pie chart parameters main_values = [trace_tot] + [self.X[k] for k in main_keys] main_labels = ['trace'] + main_keys explode = [0.2] + [0. for i in range(len(main_keys))] # rotate so that first wedge is split by the x-axis angle = -180 * main_values[0] wedges, *_ = ax1.pie(main_values, autopct=lambda p: f"{p/100:0.3f}", startangle=angle, labels=main_labels, explode=explode) # bar chart parameters trace_values = [self.X[k] for k in limited_trace_keys] + [other_trace_tot] trace_labels = [k.short_spec_name for k in limited_trace_keys] + ['other'] bottom = 1 width = 0.1 # Adding from the top matches the legend. alpha_list = np.linspace(0.1, 1, len(trace_values)) trace_wedge_color = wedges[0].get_facecolor() for j, (height, label) in enumerate([*zip(trace_values, trace_labels)]): bottom -= height bc = ax2.bar(0, height, width, bottom=bottom, color=trace_wedge_color, label=label, alpha=alpha_list[j]) ax2.bar_label(bc, labels=[f"{height:.2e}"], label_type='center') ax2.bar_label(bc, labels=[f"{label:>30}"], label_type='center') ax2.set_title('Composition of Trace Nuclei') ax2.axis('off') ax2.set_xlim(- 2.5 * width, 2.5 * width) # use ConnectionPatch to draw lines between the two plots theta1, theta2 = wedges[0].theta1, wedges[0].theta2 center, r = wedges[0].center, wedges[0].r bar_height = sum(trace_values) # draw top connecting line x = r * np.cos(np.pi / 180 * theta2) + center[0] y = r * np.sin(np.pi / 180 * theta2) + center[1] con = ConnectionPatch(xyA=(-width / 2, bar_height+bottom), coordsA=ax2.transData, xyB=(x, y), coordsB=ax1.transData) con.set_color(trace_wedge_color) con.set_linewidth(4) ax2.add_artist(con) # draw bottom connecting line x = r * np.cos(np.pi / 180 * theta1) + center[0] y = r * np.sin(np.pi / 180 * theta1) + center[1] con = ConnectionPatch(xyA=(-width / 2, bottom), coordsA=ax2.transData, xyB=(x, y), coordsB=ax1.transData) con.set_color(trace_wedge_color) ax2.add_artist(con) con.set_linewidth(4) plt.show() return fig class ScreeningPair: """a pair of nuclei that will have rate screening applied. We store a list of all rates that match this pair of nuclei""" def __init__(self, name, nuc1, nuc2, rate=None): self.name = name self.n1 = nuc1 self.n2 = nuc2 if rate is None: self.rates = [] else: self.rates = [rate] def add_rate(self, rate): if rate not in self.rates: self.rates.append(rate) def __str__(self): ostr = f"screening for {self.n1} + {self.n2}\n" ostr += "rates:\n" for r in self.rates: ostr += f" {r}\n" return ostr def __eq__(self, other): """all we care about is whether the names are the same -- that conveys what the reaction is""" return self.name == other.name class RateCollection: """ a collection of rates that together define a network """ # pylint: disable=too-many-public-methods pynucastro_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) def __init__(self, rate_files=None, libraries=None, rates=None, precedence=(), inert_nuclei=None, symmetric_screening=False, do_screening=True): """rate_files are the files that together define the network. This can be any iterable or single string. This can include Reaclib library files storing multiple rates. If libraries is supplied, initialize a RateCollection using the rates in the Library object(s) in list 'libraries'. If rates is supplied, initialize a RateCollection using the Rate objects in the list 'rates'. Precedence should be sequence of rate labels (e.g. wc17) to be used to resolve name conflicts. If a nonempty sequence is provided, the rate collection will automatically be scanned for multiple rates with the same name. If all of their labels were given a ranking, the rate with the label that comes first in the sequence will be retained and the rest discarded. inert_nuclei is a list of nuclei (as Nucleus objects) that should be part of the collection but are not linked via reactions to the other nuclei in the network. symmetric_screening means that we screen the reverse rates using the same factor as the forward rates, for rates computed via detailed balance. Any combination of these options may be supplied. """ self.files = [] self.rates = [] combined_library = Library() self.inert_nuclei = inert_nuclei self.symmetric_screening = symmetric_screening self.do_screening = do_screening self.inert_nuclei = inert_nuclei if rate_files: if isinstance(rate_files, str): rate_files = [rate_files] combined_library += self._read_rate_files(rate_files) if rates: if isinstance(rates, Rate): rates = [rates] for r in rates: if not isinstance(r, Rate): raise ValueError('Expected Rate object or list of Rate objects passed as the rates argument.') rlib = Library(rates=rates) combined_library += rlib if libraries: if isinstance(libraries, Library): libraries = [libraries] for lib in libraries: if not isinstance(lib, Library): raise ValueError('Expected Library object or list of Library objects passed as the libraries argument.') for lib in libraries: combined_library += lib self.rates = self.rates + combined_library.get_rates() if precedence: self._make_distinguishable(precedence) self._build_collection() # cached values for vectorized evaluation self.nuc_prod_count = None self.nuc_cons_count = None self.nuc_used = None self.coef_arr = None self.coef_mask = None self.prefac = None self.yfac = None def _build_collection(self): # get the unique nuclei u = [] for r in self.rates: t = set(r.reactants + r.products) u = set(list(u) + list(t)) self.unique_nuclei = sorted(u) # approx nuclei are used in approximate rates self.approx_nuclei = [] for r in self.rates: if isinstance(r, ApproximateRate): if r.intermediate_nucleus not in self.unique_nuclei + self.approx_nuclei: self.approx_nuclei.append(r.intermediate_nucleus) if self.inert_nuclei: for n in self.inert_nuclei: if isinstance(n, Nucleus): nuc = n else: nuc = Nucleus(n) if nuc not in self.unique_nuclei: self.unique_nuclei.append(nuc) # now make a list of each rate that touches each nucleus # we'll store this in a dictionary keyed on the nucleus self.nuclei_consumed = {} self.nuclei_produced = {} for n in self.unique_nuclei: self.nuclei_consumed[n] = [r for r in self.rates if n in r.reactants] self.nuclei_produced[n] = [r for r in self.rates if n in r.products] self.nuclei_rate_pairs = {} _rp = self.get_rate_pairs() for n in self.unique_nuclei: self.nuclei_rate_pairs[n] = \ [rp for rp in _rp if rp.forward is not None and n in rp.forward.reactants + rp.forward.products or rp.reverse is not None and n in rp.reverse.reactants + rp.reverse.products] # Re-order self.rates so Reaclib rates come first, # followed by Tabular rates. This is needed if # reaclib coefficients are targets of a pointer array. # It is desired to avoid wasting array size # storing meaningless Tabular coefficient pointers. self.rates = sorted(self.rates, key=lambda r: r.chapter == 't') self.tabular_rates = [] self.reaclib_rates = [] self.approx_rates = [] self.derived_rates = [] for r in self.rates: if isinstance(r, ApproximateRate): self.approx_rates.append(r) for cr in r.get_child_rates(): assert cr.chapter != "t" # child rates may be ReacLibRates or DerivedRates # make sure we don't double count if isinstance(cr, DerivedRate): # Here we check whether this child rate is removed or not. # removed means that this rate is never used on its own to connect two nuclei in the network # it is only used in one or more ApproximateRate. if cr not in self.rates: cr.removed = True else: cr.removed = False cr.fname = None # pylint: disable-next=protected-access cr._set_print_representation() if cr not in self.derived_rates: self.derived_rates.append(cr) else: if cr not in self.rates: cr.removed = True else: cr.removed = False cr.fname = None # pylint: disable-next=protected-access cr._set_print_representation() if cr not in self.reaclib_rates: self.reaclib_rates.append(cr) elif r.chapter == 't': self.tabular_rates.append(r) elif isinstance(r, DerivedRate): if r not in self.derived_rates: self.derived_rates.append(r) elif isinstance(r.chapter, int): if r not in self.reaclib_rates: self.reaclib_rates.append(r) else: raise NotImplementedError(f"Chapter type unknown for rate chapter {r.chapter}") self.all_rates = self.reaclib_rates + self.tabular_rates + self.approx_rates + self.derived_rates def _read_rate_files(self, rate_files): # get the rates self.files = rate_files combined_library = Library() for rf in self.files: # create the appropriate rate object first try: rate = load_rate(rf) except RateFileError as ex: raise RateFileError(f"Error reading rate from file: {rf}") from ex # now create a library: rflib = Library(rates=[rate]) combined_library += rflib return combined_library def get_forward_rates(self): """return a list of the forward (exothermic) rates""" # first handle the ones that have Q defined forward_rates = [r for r in self.rates if r.Q is not None and r.Q >= 0.0] # e-capture tabular rates don't have a Q defined, so just go off of the binding energy forward_rates += [r for r in self.rates if r.Q is None and r.reactants[0].nucbind <= r.products[0].nucbind] return forward_rates def get_reverse_rates(self): """return a list of the reverse (endothermic) rates)""" # first handle the ones that have Q defined reverse_rates = [r for r in self.rates if r.Q is not None and r.Q < 0.0] # e-capture tabular rates don't have a Q defined, so just go off of the binding energy reverse_rates += [r for r in self.rates if r.Q is None and r.reactants[0].nucbind > r.products[0].nucbind] return reverse_rates def find_reverse(self, forward_rate, reverse_rates=None): """given a forward rate, locate the rate that is its reverse""" if reverse_rates is None: reverse_rates = self.get_reverse_rates() reverse = None for rr in reverse_rates: if sorted(forward_rate.reactants, key=lambda x: x.A) == sorted(rr.products, key=lambda x: x.A) and \ sorted(forward_rate.products, key=lambda x: x.A) == sorted(rr.reactants, key=lambda x: x.A): reverse = rr break return reverse def get_rate_pairs(self): """ return a list of RatePair objects, grouping the rates together by forward and reverse""" rate_pairs = [] reverse_rates = self.get_reverse_rates() # loop over all the forward rates and find the matching reverse rate # if it exists for fr in self.get_forward_rates(): rp = RatePair(forward=fr) rr = self.find_reverse(fr, reverse_rates=reverse_rates) # since we found a match, remove the reverse rate we paired # from out list so no other forward rate can match with it if rr is not None: rp.reverse = rr reverse_rates.remove(rp.reverse) rate_pairs.append(rp) # we might have some reverse rates remaining for which there # were no forward rates -- add those now for rr in reverse_rates: rp = RatePair(reverse=rr) rate_pairs.append(rp) return rate_pairs def get_nuclei(self): """ get all the nuclei that are part of the network """ return self.unique_nuclei def linking_nuclei(self, nuclei, return_type=None, **kwargs): """ Return a new RateCollection/Network object containing only rates linking the given nuclei (parameter *nuclei*). Nuclei can be provided as an iterable of Nucleus objects or a list of abbreviations. The *return_type* parameter allows the caller to specify a different constructor (e.g. superclass constructor) if the current class does not take a 'libraries' keyword. See method of same name in Library class for valid keyword arguments. """ if return_type is None: return_type = self.__class__ lib = Library(rates=self.rates) return return_type(libraries=lib.linking_nuclei(nuclei, **kwargs)) def get_rates(self): """ get a list of the reaction rates in this network""" return self.rates def get_rate(self, rid): """ Return a rate matching the id provided. Here rid should be the string return by Rate.fname""" try: return [r for r in self.rates if r.fname == rid][0] except IndexError: raise LookupError(f"rate identifier {rid!r} does not match a rate in this network.") from None def get_rate_by_nuclei(self, reactants, products): """given a list of reactants and products, return any matching rates""" _tmp = [r for r in self.rates if sorted(r.reactants) == sorted(reactants) and sorted(r.products) == sorted(products)] if not _tmp: return None return _tmp def get_rate_by_name(self, name): """given a rate in the form 'A(x,y)B' return the Rate""" reactants, products = _rate_name_to_nuc(name) _r = self.get_rate_by_nuclei(reactants, products) if _r is None: return None if len(_r) == 1: return _r[0] return _r def get_nuclei_needing_partition_functions(self): """return a list of Nuclei that require partition functions for one or more DerivedRates in the collection""" nuclei_pfs = set() for r in self.all_rates: if isinstance(r, DerivedRate) and r.use_pf: for nuc in r.reactants + r.products: if nuc.partition_function is not None: nuclei_pfs.add(nuc) return sorted(nuclei_pfs) def dedupe_partition_function_temperatures(self): """return a list of unique temperature arrays, along with a dictionary mapping each Nucleus to the corresponding index into that list""" nuclei = self.get_nuclei_needing_partition_functions() temp_arrays = [] temp_indices = {} # nuclei must be sorted, so the output is deterministic for nuc in nuclei: nuc_temp = nuc.partition_function.temperature # do a sequential search on temp_arrays, since it should be short for i, temp in enumerate(temp_arrays): # np.array_equal handles comparing arrays of different shapes if np.array_equal(nuc_temp, temp): temp_indices[nuc] = i break else: # no match found, add a new entry temp_indices[nuc] = len(temp_arrays) temp_arrays.append(nuc_temp) return temp_arrays, temp_indices def remove_nuclei(self, nuc_list): """remove the nuclei in nuc_list from the network along with any rates that directly involve them (this doesn't affect approximate rates that may have these nuclei as hidden intermediate links)""" rates_to_delete = [] for nuc in nuc_list: nn = nuc if not isinstance(nuc, Nucleus): nn = Nucleus(nuc) for rate in self.rates: if nn in rate.reactants + rate.products: print(f"looking to remove {rate}") rates_to_delete.append(rate) for rate in set(rates_to_delete): self.rates.remove(rate) self._build_collection() def remove_rates(self, rates): """remove the Rate objects in rates from the network. Note, if rate list is a dict, then the keys are assumed to be the rates to remove""" if isinstance(rates, Rate): self.rates.remove(rates) else: for r in rates: self.rates.remove(r) self._build_collection() def add_rates(self, rates): """add the Rate objects in rates from the network.""" if isinstance(rates, Rate): if rates not in self.rates: self.rates.append(rates) else: for r in rates: if r not in self.rates: self.rates.append(r) self._build_collection() def make_ap_pg_approx(self, intermediate_nuclei=None): """combine the rates A(a,g)B and A(a,p)X(p,g)B (and the reverse) into a single effective approximate rate.""" # make sure that the intermediate_nuclei list are Nuclei objects _inter_nuclei_remove = [] if intermediate_nuclei is not None: for nn in intermediate_nuclei: if isinstance(nn, Nucleus): _inter_nuclei_remove.append(nn) else: _inter_nuclei_remove.append(Nucleus(nn)) # find all of the (a,g) rates ag_rates = [] for r in self.rates: if (len(r.reactants) == 2 and Nucleus("he4") in r.reactants and len(r.products) == 1): ag_rates.append(r) # for each (a,g), check to see if the remaining rates are present approx_rates = [] for r_ag in ag_rates: prim_nuc = sorted(r_ag.reactants)[-1] prim_prod = sorted(r_ag.products)[-1] inter_nuc_Z = prim_nuc.Z + 1 inter_nuc_A = prim_nuc.A + 3 element = PeriodicTable.lookup_Z(inter_nuc_Z) inter_nuc = Nucleus(f"{element.abbreviation}{inter_nuc_A}") if intermediate_nuclei and inter_nuc not in _inter_nuclei_remove: continue # look for A(a,p)X _r = self.get_rate_by_nuclei([prim_nuc, Nucleus("he4")], [inter_nuc, Nucleus("p")]) if _r: r_ap = _r[-1] else: continue # look for X(p,g)B _r = self.get_rate_by_nuclei([inter_nuc, Nucleus("p")], [prim_prod]) if _r: r_pg = _r[-1] else: continue # look for reverse B(g,a)A _r = self.get_rate_by_nuclei([prim_prod], [prim_nuc, Nucleus("he4")]) if _r: r_ga = _r[-1] else: continue # look for reverse B(g,p)X _r = self.get_rate_by_nuclei([prim_prod], [inter_nuc, Nucleus("p")]) if _r: r_gp = _r[-1] else: continue # look for reverse X(p,a)A _r = self.get_rate_by_nuclei([inter_nuc, Nucleus("p")], [Nucleus("he4"), prim_nuc]) if _r: r_pa = _r[-1] else: continue # build the approximate rates ar = ApproximateRate(r_ag, [r_ap, r_pg], r_ga, [r_gp, r_pa], approx_type="ap_pg") ar_reverse = ApproximateRate(r_ag, [r_ap, r_pg], r_ga, [r_gp, r_pa], is_reverse=True, approx_type="ap_pg") print(f"using approximate rate {ar}") print(f"using approximate rate {ar_reverse}") # approximate rates approx_rates += [ar, ar_reverse] # remove the old rates from the rate list and add the approximate rate for ar in approx_rates: for r in ar.get_child_rates(): try: self.rates.remove(r) print(f"removing rate {r}") except ValueError: pass # add the approximate rates self.rates.append(ar) # regenerate the links self._build_collection() def evaluate_rates(self, rho, T, composition, screen_func=None): """evaluate the rates for a specific density, temperature, and composition, with optional screening""" rvals = {} ys = composition.get_molar() y_e = composition.eval_ye() if screen_func is not None: screen_factors = self.evaluate_screening(rho, T, composition, screen_func) else: screen_factors = {} for r in self.rates: val = r.prefactor * rho**r.dens_exp * r.eval(T, rho * y_e) if (r.weak_type == 'electron_capture' and not isinstance(r, TabularRate)): val = val * y_e yfac = functools.reduce(mul, [ys[q] for q in r.reactants]) rvals[r] = yfac * val * screen_factors.get(r, 1.0) return rvals def evaluate_jacobian(self, rho, T, comp, screen_func=None): """return an array of the form J_ij = dYdot_i/dY_j for the network""" # the rate.eval_jacobian_term does not compute the screening, # so we multiply by the factors afterwards if screen_func is not None: screen_factors = self.evaluate_screening(rho, T, comp, screen_func) else: screen_factors = {} nnuc = len(self.unique_nuclei) jac = np.zeros((nnuc, nnuc), dtype=np.float64) for i, n_i in enumerate(self.unique_nuclei): for j, n_j in enumerate(self.unique_nuclei): # we are considering dYdot(n_i) / dY(n_j) jac[i, j] = 0.0 for r in self.nuclei_consumed[n_i]: # how many of n_i are destroyed by this reaction c = r.reactants.count(n_i) jac[i, j] -= c * screen_factors.get(r, 1.0) *\ r.eval_jacobian_term(T, rho, comp, n_j) for r in self.nuclei_produced[n_i]: # how many of n_i are produced by this reaction c = r.products.count(n_i) jac[i, j] += c * screen_factors.get(r, 1.0) *\ r.eval_jacobian_term(T, rho, comp, n_j) return jac def validate(self, other_library, forward_only=True, ostream=None): """perform various checks on the library, comparing to other_library, to ensure that we are not missing important rates. The idea is that self should be a reduced library where we filtered out a few rates and then we want to compare to the larger other_library to see if we missed something important. ostream is the I/O stream to send output to (for instance, a file object or StringIO object). If it is None, then output is to stdout. """ current_rates = sorted(self.get_rates()) # check the forward rates to see if any of the products are # not consumed by other forward rates passed_validation = True for rate in current_rates: if rate.reverse: continue for p in rate.products: found = False for orate in current_rates: if orate == rate: continue if orate.reverse: continue if p in orate.reactants: found = True break if not found: passed_validation = False msg = f"validation: {p} produced in {rate} never consumed." if ostream is None: print(msg) else: ostream.write(msg + "\n") # now check if we are missing any rates from other_library with the exact same reactants other_by_reactants = collections.defaultdict(list) for rate in sorted(other_library.get_rates()): other_by_reactants[tuple(sorted(rate.reactants))].append(rate) for rate in current_rates: if forward_only and rate.reverse: continue key = tuple(sorted(rate.reactants)) for other_rate in other_by_reactants[key]: # check to see if other_rate is already in current_rates found = True if other_rate not in current_rates: found = False if not found: msg = f"validation: missing {other_rate} as alternative to {rate} (Q = {other_rate.Q} MeV)." if ostream is None: print(msg) else: ostream.write(msg + "\n") return passed_validation def find_duplicate_links(self): """report on an rates where another rate exists that has the same reactants and products. These may not be the same Rate object (e.g., one could be tabular the other a simple decay), but they will present themselves in the network as the same link. We return a list, where each entry is a list of all the rates that share the same link""" duplicates = [] for rate in self.get_rates(): same_links = [q for q in self.get_rates() if q != rate and sorted(q.reactants) == sorted(rate.reactants) and sorted(q.products) == sorted(rate.products)] if same_links: new_entry = [rate] + same_links already_found = False # we may have already found this pair for dupe in duplicates: if new_entry[0] in dupe: already_found = True break if not already_found: duplicates.append(new_entry) return duplicates def find_unimportant_rates(self, states, cutoff_ratio, screen_func=None): """evaluate the rates at multiple thermodynamic states, and find the rates that are always less than `cutoff_ratio` times the fastest rate for each state Here, states is a list of tuple of the form (density, temperature, composition), where composition is of type `Composition`. """ largest_ratio = {r: 0 for r in self.rates} for rho, T, comp in states: rvals = self.evaluate_rates(rho, T, comp, screen_func) fastest = max(rvals.values()) for r, value in rvals.items(): largest_ratio[r] = max(largest_ratio[r], value / fastest) return {r: ratio for r, ratio in largest_ratio.items() if ratio < cutoff_ratio} def evaluate_screening(self, rho, T, composition, screen_func): """Evaluate the screening factors for each rate, using one of the methods in :py:mod:`pynucastro.screening`""" # this follows the same logic as BaseCxxNetwork._compute_screening_factors() factors = {} ys = composition.get_molar() plasma_state = make_plasma_state(T, rho, ys) screening_map = self.get_screening_map() for i, scr in enumerate(screening_map): if not (scr.n1.dummy or scr.n2.dummy): scn_fac = make_screen_factors(scr.n1, scr.n2) scor = screen_func(plasma_state, scn_fac) if scr.name == "he4_he4_he4": # we don't need to do anything here, but we want to avoid # immediately applying the screening pass elif scr.name == "he4_he4_he4_dummy": # make sure the previous iteration was the first part of 3-alpha assert screening_map[i - 1].name == "he4_he4_he4" # handle the second part of the screening for 3-alpha scn_fac2 = make_screen_factors(scr.n1, scr.n2) scor2 = screen_func(plasma_state, scn_fac2) # there might be both the forward and reverse 3-alpha # if we are doing symmetric screening for r in scr.rates: # use scor from the previous loop iteration factors[r] = scor * scor2 else: # there might be several rates that have the same # reactants and therefore the same screening applies # -- handle them all now for r in scr.rates: factors[r] = scor return factors def _evaluate_n_e(self, state, Xs): m_u = constants.value("unified atomic mass unit") * 1.0e3 # atomic unit mass in g n_e = 0.0 for nuc in self.unique_nuclei: n_e += nuc.Z * state.dens * Xs[nuc] / (nuc.A * m_u) return n_e def _evaluate_mu_c(self, n_e, state, use_coulomb_corr=True): """ A helper equation that finds the mass fraction of each nuclide in NSE state, u[0] is chemical potential of proton while u[1] is chemical potential of neutron""" # If there is proton included in network, upper limit of ye is 1 # And if neutron is included in network, lower limit of ye is 0. # However, there are networks where either of them are included # So here I add a general check to find the upper and lower limit of ye # so the input doesn't go outside of the scope and the solver won't be able to converge if it did ye_low = min(nuc.Z/nuc.A for nuc in self.unique_nuclei) ye_max = max(nuc.Z/nuc.A for nuc in self.unique_nuclei) assert state.ye >= ye_low and state.ye <= ye_max, "input electron fraction goes outside of scope for current network" # Setting up the constants needed to compute mu_c k = constants.value("Boltzmann constant") * 1.0e7 # boltzmann in erg/K Erg2MeV = 624151.0 # These are three constants for calculating coulomb corrections of chemical energy, see Calders paper: iopscience 510709, appendix if use_coulomb_corr: A_1 = -0.9052 A_2 = 0.6322 A_3 = -0.5 * np.sqrt(3.0) - A_1 / np.sqrt(A_2) # u_c is the coulomb correction term for NSE # Calculate the composition at NSE, equations found in appendix of Calder paper u_c = {} for nuc in set(list(self.unique_nuclei) + [Nucleus("p")]): if use_coulomb_corr: Gamma = state.gamma_e_fac * n_e ** (1.0/3.0) * nuc.Z ** (5.0 / 3.0) / state.temp u_c[nuc] = Erg2MeV * k * state.temp * (A_1 * (np.sqrt(Gamma * (A_2 + Gamma)) - A_2 * np.log(np.sqrt(Gamma / A_2) + np.sqrt(1.0 + Gamma / A_2))) + 2.0 * A_3 * (np.sqrt(Gamma) - np.arctan(np.sqrt(Gamma)))) else: u_c[nuc] = 0.0 return u_c def _nucleon_fraction_nse(self, u, u_c, state): # Define constants: amu, boltzmann, planck, and electron charge m_u = constants.value("unified atomic mass unit") * 1.0e3 # atomic unit mass in g k = constants.value("Boltzmann constant") * 1.0e7 # boltzmann in erg/K h = constants.value("Planck constant") * 1.0e7 # in cgs Erg2MeV = 624151.0 Xs = {} up_c = u_c[Nucleus("p")] for nuc in self.unique_nuclei: if nuc.partition_function: pf = nuc.partition_function.eval(state.temp) else: pf = 1.0 if not nuc.spin_states: raise ValueError(f"The spin of {nuc} is not implemented for now.") nse_exponent = (nuc.Z * u[0] + nuc.N * u[1] - u_c[nuc] + nuc.Z * up_c + nuc.nucbind * nuc.A) / k / state.temp / Erg2MeV nse_exponent = min(500.0, nse_exponent) Xs[nuc] = m_u * nuc.A_nuc * pf * nuc.spin_states / state.dens * (2.0 * np.pi * m_u * nuc.A_nuc * k * state.temp / h**2) ** (3. / 2.) \ * np.exp(nse_exponent) return Xs def _constraint_eq(self, u, u_c, state): """ Constraint Equations used to evaluate chemical potential for proton and neutron, which is used when evaluating composition at NSE""" # Don't use eval_ye() since it does automatic mass fraction normalization. # However, we should force normalization through constraint eq1. # m_u = constants.value("unified atomic mass unit") * 1.0e3 # atomic unit mass in g Xs = self._nucleon_fraction_nse(u, u_c, state) eq1 = 0.0 for nuc in self.unique_nuclei: eq1 += Xs[nuc] eq1 += - 1.0 eq2 = 0.0 for nuc in self.unique_nuclei: eq2 += Xs[nuc] * nuc.Z / nuc.A # for nuc in self.unique_nuclei: # eq2 += ((state.ye - 1.0) * nuc.Z + state.ye * nuc.N ) * Xs[nuc] / (nuc.A_nuc * m_u) eq2 += - state.ye return [eq1, eq2] def get_comp_nse(self, rho, T, ye, init_guess=(-3.5, -15), tol=1.0e-11, use_coulomb_corr=False, return_sol=False): """ Returns the NSE composition given density, temperature and prescribed electron fraction using scipy.fsolve, `tol` is an optional parameter for the tolerance of scipy.fsolve. init_guess is optional, however one should change init_guess accordingly if unable or taking long time to find solution. One can enable printing the actual guess that found the solution after fine-tuning, which is useful when calling this method multiple times such as making a plot. """ #From here we convert the init_guess list into a np.array object: init_guess = np.array(init_guess) state = NseState(T, rho, ye) u_c = {} for nuc in set(list(self.unique_nuclei) + [Nucleus("p")]): u_c[nuc] = 0.0 Xs = {} j = 0 init_guess = np.array(init_guess) is_pos_old = False found_sol = False # Filter out runtimewarnings from fsolve, here we check convergence by np.isclose warnings.filterwarnings("ignore", category=RuntimeWarning) # This nested loops should fine-tune the initial guess if fsolve is unable to find a solution while j < 20: i = 0 guess = copy.deepcopy(init_guess) init_dx = 0.5 while i < 20: u = fsolve(self._constraint_eq, guess, args=(u_c, state), xtol=tol, maxfev=800) Xs = self._nucleon_fraction_nse(u, u_c, state) n_e = self._evaluate_n_e(state, Xs) u_c = self._evaluate_mu_c(n_e, state, use_coulomb_corr) res = self._constraint_eq(u, u_c, state) is_pos_new = all(k > 0 for k in res) found_sol = np.all(np.isclose(res, [0.0, 0.0], rtol=1.0e-7, atol=1.0e-7)) if found_sol: Xs = self._nucleon_fraction_nse(u, u_c, state) comp = Composition(self.unique_nuclei) comp.X = Xs if return_sol: return comp, u return comp if is_pos_old != is_pos_new: init_dx *= 0.8 if is_pos_new: guess -= init_dx else: guess += init_dx is_pos_old = is_pos_new i += 1 j += 1 init_guess[0] -= 0.5 raise ValueError("Unable to find a solution, try to adjust initial guess manually") def evaluate_ydots(self, rho, T, composition, screen_func=None): """evaluate net rate of change of molar abundance for each nucleus for a specific density, temperature, and composition""" rvals = self.evaluate_rates(rho, T, composition, screen_func) ydots = {} for nuc in self.unique_nuclei: # Rates that consume / produce nuc consuming_rates = self.nuclei_consumed[nuc] producing_rates = self.nuclei_produced[nuc] # Number of nuclei consumed / produced nconsumed = (r.reactants.count(nuc) for r in consuming_rates) nproduced = (r.products.count(nuc) for r in producing_rates) # Multiply each rate by the count consumed = (c * rvals[r] for c, r in zip(nconsumed, consuming_rates)) produced = (c * rvals[r] for c, r in zip(nproduced, producing_rates)) # Net change is difference between produced and consumed ydots[nuc] = sum(produced) - sum(consumed) return ydots def evaluate_energy_generation(self, rho, T, composition, screen_func=None): """evaluate the specific energy generation rate of the network for a specific density, temperature and composition""" ydots = self.evaluate_ydots(rho, T, composition, screen_func) enuc = 0. # compute constants and units m_n_MeV = constants.value('neutron mass energy equivalent in MeV') m_p_MeV = constants.value('proton mass energy equivalent in MeV') m_e_MeV = constants.value('electron mass energy equivalent in MeV') MeV2erg = (constants.eV * constants.mega) / constants.erg # ion binding energy contributions. basically e=mc^2 for nuc in self.unique_nuclei: # add up mass in MeV then convert to erg mass = ((nuc.A - nuc.Z) * m_n_MeV + nuc.Z * (m_p_MeV + m_e_MeV) - nuc.A * nuc.nucbind) * MeV2erg enuc += ydots[nuc] * mass #convert from molar value to erg/g/s enuc *= -1*constants.Avogadro #subtract neutrino losses for tabular weak reactions for r in self.rates: if isinstance(r, TabularRate): # get composition ys = composition.get_molar() y_e = composition.eval_ye() # need to get reactant nucleus nuc = r.reactants[0] enuc -= constants.Avogadro * ys[nuc] * r.get_nu_loss(T, rho * y_e) return enuc def evaluate_activity(self, rho, T, composition, screen_func=None): """sum over all of the terms contributing to ydot, neglecting sign""" rvals = self.evaluate_rates(rho, T, composition, screen_func) act = {} for nuc in self.unique_nuclei: # Rates that consume / produce nuc consuming_rates = self.nuclei_consumed[nuc] producing_rates = self.nuclei_produced[nuc] # Number of nuclei consumed / produced nconsumed = (r.reactants.count(nuc) for r in consuming_rates) nproduced = (r.products.count(nuc) for r in producing_rates) # Multiply each rate by the count consumed = (c * rvals[r] for c, r in zip(nconsumed, consuming_rates)) produced = (c * rvals[r] for c, r in zip(nproduced, producing_rates)) # Net activity is sum of produced and consumed act[nuc] = sum(produced) + sum(consumed) return act def calc_count_matrices(self): """ Compute and store 3 count matrices that can be used for vectorized rate calculations. Each matrix has shape *number_of_species × number_of_rates*. The first matrix (*nuc_prod_count*) stores the count of each nucleus in rates producing that nucleus. The second (*nuc_cons_count*) stores the count of each nucleus in rates consuming that nucleus. The third (*nuc_used*) stores a Boolean matrix of whether the nucleus is involved in the reaction or not. """ # Rate -> index mapping r_map = {} for i, r in enumerate(self.rates): r_map[r] = i N_species = len(self.unique_nuclei) N_rates = len(self.rates) # Counts for reactions producing nucleus self.nuc_prod_count = np.zeros((N_species, N_rates), dtype=np.int32) # Counts for reactions consuming nucleus self.nuc_cons_count = np.zeros((N_species, N_rates), dtype=np.int32) for i, n in enumerate(self.unique_nuclei): for r in self.nuclei_produced[n]: self.nuc_prod_count[i, r_map[r]] = r.products.count(n) for r in self.nuclei_consumed[n]: self.nuc_cons_count[i, r_map[r]] = r.reactants.count(n) # Whether the nucleus is involved in the reaction or not self.nuc_used = np.logical_or(self.nuc_prod_count, self.nuc_cons_count).T def update_rate_coef_arr(self): """ Store Reaclib rate coefficient array, as well as a Boolean mask array determining how many sets to include in the final rate evaluation. The first array (*coef_arr*) has shape *number_of_rates × number_of_species × 7*, while the second has shape *number_of_rates × number_of_species*. """ # coef arr can be precomputed if evaluate_rates_arr is called multiple times N_sets = max(len(r.sets) for r in self.rates) coef_arr = np.zeros((len(self.rates), N_sets, 7), dtype=np.float64) coef_mask = np.zeros((len(self.rates), N_sets), dtype=np.bool_) for i, r in enumerate(self.rates): for j, s in enumerate(r.sets): coef_arr[i, j, :] = s.a coef_mask[i, j] = True self.coef_arr = coef_arr self.coef_mask = coef_mask def update_yfac_arr(self, composition): """ Calculate and store molar fraction component of each rate (Y of each reactant raised to the appropriate power). The results are stored in an array called *yfac*. The method *calc_count_matrices* needs to have been called with this net beforehand. """ # yfac must be evaluated each time composition changes, probably pretty cheap yfac = np.ones((len(self.rates), len(self.unique_nuclei)), dtype=np.float64) ys = np.array(list(composition.get_molar().values()), dtype=np.float64) yfac *= ys**self.nuc_cons_count.T yfac = np.prod(yfac, axis=1) self.yfac = yfac def update_prefac_arr(self, rho, composition): """ Calculate and store rate prefactors, which include both statistical prefactors and mass density raised to the corresponding density exponents. The results are stored in an array called *prefac*. """ y_e = composition.eval_ye() prefac = np.zeros(len(self.rates)) for i, r in enumerate(self.rates): if r.label == "tabular": raise ValueError('Tabular rates are not supported in vectorized rate calculations.') prefac[i] = r.prefactor * rho**r.dens_exp if r.weak_type == 'electron_capture': prefac[i] *= y_e self.prefac = prefac def evaluate_rates_arr(self, T): """ Evaluate the rates in the network for a specific temperature, assuming necessary precalculations have been carried out (calling the methods *calc_count_matrices*, *update_rate_coef_arr*, *update_yfac_arr*, and *update_prefac_arr*). The latter two set the composition and density. This performs a vectorized calculation, and returns an array ordered by the rates in the *rates* member variable. This does not support tabular rates. See *evaluate_rates* method for non-vectorized version. Relative performance between the two varies based on the setup. See *clear_arrays* for freeing memory post calculation. """ # T9 arr only needs to be evaluated when T changes T9_arr = Tfactors(T).array[None, None, :] rvals = self.prefac*self.yfac*np.sum(np.exp(np.sum(self.coef_arr*T9_arr, axis=2))*self.coef_mask, axis=1) return rvals def evaluate_ydots_arr(self, T): """ Evaluate net rate of change of molar abundance for each nucleus in the network for a specific temperature, assuming necessary precalculations have been carried out (calling the methods *calc_count_matrices*, *update_rate_coef_arr*, *update_yfac_arr*, and *update_prefac_arr*). The latter two set the composition and density. This performs a vectorized calculation, and returns an array ordered by the nuclei in the *unique_nuclei* member variable. This does not support tabular rates. See *evaluate_ydots* method for non-vectorized version. Relative performance between the two varies based on the setup. See *clear_arrays* for freeing memory post calculation. """ rvals_arr = self.evaluate_rates_arr(T) p_A = np.sum(self.nuc_prod_count*rvals_arr, axis=1) c_A = np.sum(self.nuc_cons_count*rvals_arr, axis=1) return p_A - c_A def evaluate_activity_arr(self, T): """ sum over all of the terms contributing to dY/dt for a specific temperature, neglecting sign, assuming necessary precalculations have been carried out (calling the methods *calc_count_matrices*, *update_rate_coef_arr*, *update_yfac_arr*, and *update_prefac_arr*). The latter two set the composition and density. This performs a vectorized calculation, and returns an array ordered by the nuclei in the *unique_nuclei* member variable. This does not support tabular rates. See *evaluate_activity* method for non-vectorized version. Relative performance between the two varies based on the setup. See *clear_arrays* for freeing memory post calculation. """ rvals_arr = self.evaluate_rates_arr(T) p_A = np.sum(self.nuc_prod_count*rvals_arr, axis=1) c_A = np.sum(self.nuc_cons_count*rvals_arr, axis=1) return p_A + c_A def clear_arrays(self): """ Clear all temporary variables created/set by the *calc_count_matrices*, *update_rate_coef_arr*, *update_yfac_arr*, and *update_prefac_arr* member functions, freeing up memory. """ try: del self.nuc_prod_count except AttributeError: pass try: del self.nuc_cons_count except AttributeError: pass try: del self.nuc_used except AttributeError: pass try: del self.coef_arr except AttributeError: pass try: del self.coef_mask except AttributeError: pass try: del self.prefac except AttributeError: pass try: del self.yfac except AttributeError: pass def _get_network_chart(self, rho, T, composition): """a network chart is a dict, keyed by rate that holds a list of tuples (Nucleus, ydot)""" rvals = self.evaluate_rates(rho, T, composition) nc = {} for rate, rval in rvals.items(): nucs = [] for n in set(rate.reactants): nucs.append((n, -rate.reactants.count(n) * rval)) for n in set(rate.products): nucs.append((n, rate.products.count(n) * rval)) nc[rate] = nucs return nc def network_overview(self): """ return a verbose network overview """ ostr = "" for n in self.unique_nuclei: ostr += f"{n}\n" ostr += " consumed by:\n" for r in self.nuclei_consumed[n]: ostr += f" {r.string}\n" ostr += " produced by:\n" for r in self.nuclei_produced[n]: ostr += f" {r.string}\n" ostr += "\n" return ostr def rate_pair_overview(self): """ return a verbose network overview in terms of forward-reverse pairs""" ostr = "" for n in self.unique_nuclei: ostr += f"{n}\n" for rp in sorted(self.nuclei_rate_pairs[n]): ostr += f" {rp}\n" return ostr def get_nuclei_latex_string(self): """return a string listing the nuclei in latex format""" ostr = "" for i, n in enumerate(self.unique_nuclei): ostr += f"${n.pretty}$" if i != len(self.unique_nuclei)-1: ostr += ", " return ostr def get_rates_latex_table_string(self): ostr = "" for rp in sorted(self.get_rate_pairs()): if rp.forward: ostr += f"{rp.forward.pretty_string:38} & \n" else: ostr += f"{' ':38} \n &" if rp.reverse: ostr += rf" {rp.reverse.pretty_string:38} \\" else: ostr += rf" {' ':38} \\" ostr += "\n" return ostr def get_screening_map(self): """a screening map is just a list of tuples containing the information about nuclei pairs for screening: (descriptive name of nuclei, nucleus 1, nucleus 2, rate, 1-based index of rate). If symmetric_screening=True, then for reverse rates, we screen using the forward rate nuclei (assuming that we got here via detailed balance). """ screening_map = [] if not self.do_screening: return screening_map # we need to consider the child rates that come with ApproximateRate all_rates = [] for r in self.rates: if isinstance(r, ApproximateRate): all_rates += r.get_child_rates() else: all_rates.append(r) for r in all_rates: screen_nuclei = r.ion_screen if self.symmetric_screening: screen_nuclei = r.symmetric_screen # screen_nuclei may be [] if it is a decay, gamma-capture, or neutron-capture if not screen_nuclei: continue nucs = "_".join([str(q) for q in screen_nuclei]) scr = [q for q in screening_map if q.name == nucs] assert len(scr) <= 1 if scr: # we already have the reactants in our map, so we # will already be doing the screening factors. # Just append this new rate to the list we are # keeping of the rates where this screening is # needed -- if the rate is already in the list, then # this is a no-op scr[0].add_rate(r) # if we got here because nuc == "he4_he4_he4", # then we also have to add to "he4_he4_he4_dummy" if nucs == "he4_he4_he4": scr2 = [q for q in screening_map if q.name == nucs + "_dummy"] assert len(scr2) == 1 scr2[0].add_rate(r) else: # we handle 3-alpha specially -- we actually need # 2 screening factors for it if nucs == "he4_he4_he4": # he4 + he4 scr1 = ScreeningPair(nucs, screen_nuclei[0], screen_nuclei[1], r) # he4 + be8 be8 = Nucleus("Be8", dummy=True) scr2 = ScreeningPair(nucs + "_dummy", screen_nuclei[2], be8, r) screening_map.append(scr1) screening_map.append(scr2) else: scr1 = ScreeningPair(nucs, screen_nuclei[0], screen_nuclei[1], r) screening_map.append(scr1) return screening_map def write_network(self, *args, **kwargs): """Before writing the network, check to make sure the rates are distinguishable by name.""" assert self._distinguishable_rates(), "ERROR: Rates not uniquely identified by Rate.fname" self._write_network(*args, **kwargs) def _distinguishable_rates(self): """Every Rate in this RateCollection should have a unique Rate.fname, as the network writers distinguish the rates on this basis.""" names = [r.fname for r in self.rates] for n, r in zip(names, self.rates): k = names.count(n) if k > 1: print(f'Found rate {r} named {n} with {k} entries in the RateCollection.') print(f'Rate {r} has the original source:\n{r.original_source}') print(f'Rate {r} is in chapter {r.chapter}') return len(set(names)) == len(self.rates) def _make_distinguishable(self, precedence): """If multiple rates have the same name, eliminate the extraneous ones according to their labels' positions in the precedence list. Only do this if all of the labels have rankings in the list.""" nameset = {r.fname for r in self.rates} precedence = {lab: i for i, lab in enumerate(precedence)} def sorting_key(i): return precedence[self.rates[i].label] for n in nameset: # Count instances of name, and cycle if there is only one ind = [i for i, r in enumerate(self.rates) if r.fname == n] k = len(ind) if k <= 1: continue # If there were multiple instances, use the precedence settings to delete extraneous # rates labels = [self.rates[i].label for i in ind] if all(lab in precedence for lab in labels): sorted_ind = sorted(ind, key=sorting_key) r = self.rates[sorted_ind[0]] for i in sorted(sorted_ind[1:], reverse=True): del self.rates[i] print(f'Found rate {r} named {n} with {k} entries in the RateCollection.') print(f'Kept only entry with label {r.label} out of {labels}.') def _write_network(self, *args, **kwargs): """A stub for function to output the network -- this is implementation dependent.""" # pylint: disable=unused-argument print('To create network integration source code, use a class that implements a specific network type.') def plot(self, outfile=None, rho=None, T=None, comp=None, size=(800, 600), dpi=100, title=None, ydot_cutoff_value=None, show_small_ydot=False, node_size=1000, node_font_size=13, node_color="#A0CBE2", node_shape="o", curved_edges=False, N_range=None, Z_range=None, rotated=False, always_show_p=False, always_show_alpha=False, hide_xp=False, hide_xalpha=False, highlight_filter_function=None, nucleus_filter_function=None, rate_filter_function=None): """Make a plot of the network structure showing the links between nuclei. If a full set of thermodymamic conditions are provided (rho, T, comp), then the links are colored by rate strength. parameters ---------- outfile: output name of the plot -- extension determines the type rho: density to evaluate rates with T: temperature to evaluate rates with comp: composition to evaluate rates with size: tuple giving width x height of the plot in pixels dpi: pixels per inch used by matplotlib in rendering bitmap title: title to display on the plot ydot_cutoff_value: rate threshold below which we do not show a line corresponding to a rate show_small_ydot: if true, then show visible lines for rates below ydot_cutoff_value node_size: size of a node node_font_size: size of the font used to write the isotope in the node node_color: color to make the nodes node_shape: shape of the node (using matplotlib marker names) curved_edges: do we use arcs to connect the nodes? N_range: range of neutron number to zoom in on Z_range: range of proton number to zoom in on rotate: if True, we plot A - 2Z vs. Z instead of the default Z vs. N always_show_p: include p as a node on the plot even if we don't have p+p reactions always_show_alpha: include He4 as a node on the plot even if we don't have 3-alpha hide_xalpha=False: dont connect the links to alpha for heavy nuclei reactions of the form A(alpha,X)B or A(X,alpha)B, except if alpha is the heaviest product. hide_xp=False: dont connect the links to p for heavy nuclei reactions of the form A(p,X)B or A(X,p)B. highlight_filter_function: name of a custom function that takes a Rate object and returns true or false if we want to highlight the rate edge. nucleus_filter_funcion: name of a custom function that takes a Nucleus object and returns true or false if it is to be shown as a node. rate_filter_funcion: name of a custom function that takes a Rate object and returns true or false if it is to be shown as an edge. """ G = nx.MultiDiGraph() G.position = {} G.labels = {} fig, ax = plt.subplots() #divider = make_axes_locatable(ax) #cax = divider.append_axes('right', size='15%', pad=0.05) #ax.plot([0, 0], [8, 8], 'b-') # in general, we do not show p, n, alpha, # unless we have p + p, 3-a, etc. hidden_nuclei = ["n"] if not always_show_p: hidden_nuclei.append("p") if not always_show_alpha: hidden_nuclei.append("he4") # nodes -- the node nuclei will be all of the heavies # add all the nuclei into G.node node_nuclei = [] colors = [] for n in self.unique_nuclei: if n.raw not in hidden_nuclei: node_nuclei.append(n) colors.append(node_color) else: for r in self.rates: if r.reactants.count(n) > 1: node_nuclei.append(n) colors.append(node_color) break # approx nuclei are given a different color for n in self.approx_nuclei: node_nuclei.append(n) colors.append("#555555") if nucleus_filter_function is not None: node_nuclei = list(filter(nucleus_filter_function, node_nuclei)) # redo the colors: colors = [] for n in node_nuclei: if n in self.approx_nuclei: colors.append("#555555") else: colors.append(node_color) for n in node_nuclei: G.add_node(n) if rotated: G.position[n] = (n.Z, n.A - 2*n.Z) else: G.position[n] = (n.N, n.Z) G.labels[n] = fr"${n.pretty}$" # get the rates for each reaction if rho is not None and T is not None and comp is not None: ydots = self.evaluate_rates(rho, T, comp) else: ydots = None # Do not show rates on the graph if their corresponding ydot is less than ydot_cutoff_value invisible_rates = set() if ydot_cutoff_value is not None: for r in self.rates: if ydots[r] < ydot_cutoff_value: invisible_rates.add(r) # edges for the rates that are explicitly in the network for n in node_nuclei: if n not in self.nuclei_consumed: continue for r in self.nuclei_consumed[n]: if rate_filter_function is not None: if not rate_filter_function(r): continue highlight = False if highlight_filter_function is not None: highlight = highlight_filter_function(r) for p in r.products: if p not in node_nuclei: continue if hide_xalpha and _skip_xalpha(n, p, r): continue if hide_xp and _skip_xp(n, p, r): continue # networkx doesn't seem to keep the edges in # any particular order, so we associate data # to the edges here directly, in this case, # the reaction rate, which will be used to # color it # here real means that it is not an approximate rate if ydots is None: G.add_edges_from([(n, p)], weight=0.5, real=1, highlight=highlight) continue try: rate_weight = math.log10(ydots[r]) except ValueError: # if ydots[r] is zero, then set the weight # to roughly the minimum exponent possible # for python floats rate_weight = -308 if r in invisible_rates: if show_small_ydot: # use real -1 for displaying rates that are below ydot_cutoff G.add_edges_from([(n, p)], weight=rate_weight, real=-1, highlight=highlight) continue G.add_edges_from([(n, p)], weight=rate_weight, real=1, highlight=highlight) # now consider the rates that are approximated out of the network rate_seen = [] for r in self.rates: if not isinstance(r, ApproximateRate): continue for sr in r.secondary_rates + r.secondary_reverse: if sr in rate_seen: continue rate_seen.append(sr) highlight = False if highlight_filter_function is not None: highlight = highlight_filter_function(sr) for n in sr.reactants: if n not in node_nuclei: continue for p in sr.products: if p not in node_nuclei: continue if hide_xalpha and _skip_xalpha(n, p, sr): continue if hide_xp and _skip_xp(n, p, sr): continue G.add_edges_from([(n, p)], weight=0, real=0, highlight=highlight) # It seems that networkx broke backwards compatibility, and 'zorder' is no longer a valid # keyword argument. The 'linewidth' argument has also changed to 'linewidths'. nx.draw_networkx_nodes(G, G.position, # plot the element at the correct position node_color=colors, alpha=1.0, node_shape=node_shape, node_size=node_size, linewidths=2.0, ax=ax) nx.draw_networkx_labels(G, G.position, G.labels, # label the name of element at the correct position font_size=node_font_size, font_color="w", ax=ax) # now we'll draw edges in two groups -- real links and approximate links if curved_edges: connectionstyle = "arc3, rad = 0.2" else: connectionstyle = "arc3" real_edges = [(u, v) for u, v, e in G.edges(data=True) if e["real"] == 1] real_weights = [e["weight"] for u, v, e in G.edges(data=True) if e["real"] == 1] edge_color = real_weights ww = np.array(real_weights) min_weight = ww.min() max_weight = ww.max() dw = (max_weight - min_weight)/4 widths = np.ones_like(ww) if dw > 0: widths[ww > min_weight + dw] = 1.5 widths[ww > min_weight + 2*dw] = 2.5 widths[ww > min_weight + 3*dw] = 4 else: widths *= 2 # plot the arrow of reaction real_edges_lc = nx.draw_networkx_edges(G, G.position, width=list(widths), edgelist=real_edges, edge_color=edge_color, connectionstyle=connectionstyle, node_size=node_size, edge_cmap=plt.cm.viridis, ax=ax) approx_edges = [(u, v) for u, v, e in G.edges(data=True) if e["real"] == 0] _ = nx.draw_networkx_edges(G, G.position, width=1, edgelist=approx_edges, edge_color="0.5", connectionstyle=connectionstyle, style="dotted", node_size=node_size, ax=ax) # plot invisible rates, rates that are below ydot_cutoff_value invis_edges = [(u, v) for u, v, e in G.edges(data=True) if e["real"] == -1] _ = nx.draw_networkx_edges(G, G.position, width=1, edgelist=invis_edges, edge_color="gray", connectionstyle=connectionstyle, style="dashed", node_size=node_size, ax=ax) # highlight edges highlight_edges = [(u, v) for u, v, e in G.edges(data=True) if e["highlight"]] _ = nx.draw_networkx_edges(G, G.position, width=5, edgelist=highlight_edges, edge_color="C0", alpha="0.25", connectionstyle=connectionstyle, node_size=node_size, ax=ax) if ydots is not None: pc = mpl.collections.PatchCollection(real_edges_lc, cmap=plt.cm.viridis) pc.set_array(real_weights) if not rotated: plt.colorbar(pc, ax=ax, label="log10(rate)") else: plt.colorbar(pc, ax=ax, label="log10(rate)", orientation="horizontal", fraction=0.05) Ns = [n.N for n in node_nuclei] Zs = [n.Z for n in node_nuclei] if not rotated: ax.set_xlim(min(Ns)-1, max(Ns)+1) else: ax.set_xlim(min(Zs)-1, max(Zs)+1) #plt.ylim(min(Zs)-1, max(Zs)+1) if not rotated: plt.xlabel(r"$N$", fontsize="large") plt.ylabel(r"$Z$", fontsize="large") else: plt.xlabel(r"$Z$", fontsize="large") plt.ylabel(r"$A - 2Z$", fontsize="large") ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.xaxis.set_major_locator(MaxNLocator(integer=True)) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) if Z_range is not None and N_range is not None: if not rotated: ax.set_xlim(N_range[0], N_range[1]) ax.set_ylim(Z_range[0], Z_range[1]) else: ax.set_xlim(Z_range[0], Z_range[1]) if not rotated: ax.set_aspect("equal", "datalim") fig.set_size_inches(size[0]/dpi, size[1]/dpi) if title is not None: fig.suptitle(title) if outfile is not None: plt.tight_layout() plt.savefig(outfile, dpi=dpi) return fig def plot_jacobian(self, outfile=None, rho=None, T=None, comp=None, screen_func=None, size=(800, 800), dpi=100): jac = self.evaluate_jacobian(rho, T, comp, screen_func=screen_func) valid_max = np.abs(jac).max() # pylint: disable-next=redundant-keyword-arg norm = SymLogNorm(valid_max/1.e10, vmin=-valid_max, vmax=valid_max) fig, ax = plt.subplots() fig.set_size_inches(size[0]/dpi, size[1]/dpi) ax.set_xticks(np.arange(len(self.unique_nuclei)), labels=[f"${n.pretty}$" for n in self.unique_nuclei], rotation=90) ax.set_yticks(np.arange(len(self.unique_nuclei)), labels=[f"${n.pretty}$" for n in self.unique_nuclei]) im = ax.imshow(jac, norm=norm, cmap=plt.cm.bwr) ax.set_aspect("equal") # Turn spines off and create white grid. #ax.spines[:].set_visible(False) ax.set_xticks(np.arange(jac.shape[1]+1)-.5, minor=True) ax.set_yticks(np.arange(jac.shape[0]+1)-.5, minor=True) ax.grid(which="minor", color="w", linestyle='-', linewidth=2) ax.tick_params(which="minor", bottom=False, left=False) fig.colorbar(im, ax=ax, shrink=0.75) if outfile is not None: fig.savefig(outfile, bbox_inches="tight") return fig def plot_network_chart(self, outfile=None, rho=None, T=None, comp=None, size=(800, 800), dpi=100, force_one_column=False): nc = self._get_network_chart(rho, T, comp) # find the limits _ydot = [] for r in self.rates: for _, y in nc[r]: _ydot.append(y) _ydot = np.asarray(_ydot) valid_max = np.abs(_ydot[_ydot != 0]).max() # pylint: disable-next=redundant-keyword-arg norm = SymLogNorm(valid_max/1.e15, vmin=-valid_max, vmax=valid_max) # if there are a lot of rates, we split the network chart into # two side-by-side panes, with the first half of the rates on # the left and the second half of the rates on the right # how many panes? if len(self.rates) > 3 * len(self.unique_nuclei): npanes = 2 else: npanes = 1 if force_one_column: npanes = 1 fig, _ax = plt.subplots(1, npanes, constrained_layout=True) fig.set_size_inches(size[0]/dpi, size[1]/dpi) if npanes == 1: drate = len(self.rates) else: drate = (len(self.rates) + 1) // 2 _rates = sorted(self.rates) for ipane in range(npanes): if npanes == 2: ax = _ax[ipane] else: ax = _ax istart = ipane * drate iend = min((ipane + 1) * drate - 1, len(self.rates)-1) nrates = iend - istart + 1 data = np.zeros((nrates, len(self.unique_nuclei)), dtype=np.float64) # loop over rates -- each rate is a line in a grid of nuclei vs rate #ax = grid[ipane] for irate, r in enumerate(_rates): if istart <= irate <= iend: irow = irate - istart for n, ydot in nc[r]: icol = self.unique_nuclei.index(n) assert data[irow, icol] == 0.0 data[irow, icol] = ydot # each pane has all the nuclei ax.set_xticks(np.arange(len(self.unique_nuclei)), labels=[f"${n.pretty}$" for n in self.unique_nuclei], rotation=90) # each pane only has its subset of rates ax.set_yticks(np.arange(nrates), labels=[f"{r.pretty_string}" for irate, r in enumerate(_rates) if istart <= irate <= iend]) im = ax.imshow(data, norm=norm, cmap=plt.cm.bwr) ax.set_aspect("equal") # Turn spines off and create white grid. ax.spines[:].set_visible(False) ax.set_xticks(np.arange(data.shape[1]+1)-.5, minor=True) ax.set_yticks(np.arange(data.shape[0]+1)-.5, minor=True) ax.grid(which="minor", color="w", linestyle='-', linewidth=3) ax.tick_params(which="minor", bottom=False, left=False) if npanes == 1: fig.colorbar(im, ax=ax, orientation="horizontal", shrink=0.75) else: fig.colorbar(im, ax=ax, orientation="vertical", shrink=0.25) if outfile is not None: fig.savefig(outfile, bbox_inches="tight") return fig @staticmethod def _safelog(arr, small): arr = np.copy(arr) if np.any(arr < 0.0): raise ValueError("Negative values not allowed for logscale - try symlog instead.") zeros = arr == 0.0 arr[zeros] = min(small, arr[~zeros].min() / 10) return np.log10(arr) @staticmethod def _symlog(arr, linthresh=1.0, linscale=1.0): symlog_transform = SymmetricalLogTransform(10, linthresh, linscale) arr = symlog_transform.transform_non_affine(arr) return arr @staticmethod def _scale(arr, minval=None, maxval=None): if minval is None: minval = arr.min() if maxval is None: maxval = arr.max() if minval != maxval: scaled = (arr - minval) / (maxval - minval) else: scaled = np.zeros_like(arr) scaled[scaled < 0.0] = 0.0 scaled[scaled > 1.0] = 1.0 return scaled def gridplot(self, comp=None, color_field="X", rho=None, T=None, **kwargs): """ Plot nuclides as cells on a grid of Z vs. N, colored by *color_field*. If called without a composition, the function will just plot the grid with no color field. :param comp: Composition of the environment. :param color_field: Field to color by. Must be one of 'X' (mass fraction), 'Y' (molar abundance), 'Xdot' (time derivative of X), 'Ydot' (time derivative of Y), or 'activity' (sum of contributions to Ydot of all rates, ignoring sign). :param rho: Density to evaluate rates at. Needed for fields involving time derivatives. :param T: Temperature to evaluate rates at. Needed for fields involving time derivatives. :Keyword Arguments: - *scale* -- One of 'linear', 'log', and 'symlog'. Linear by default. - *small* -- If using logarithmic scaling, zeros will be replaced with this value. 1e-30 by default. - *linthresh* -- Linearity threshold for symlog scaling. - *linscale* -- The number of decades to use for each half of the linear range. Stretches linear range relative to the logarithmic range. - *filter_function* -- A callable to filter Nucleus objects with. Should return *True* if the nuclide should be plotted. - *outfile* -- Output file to save the plot to. The plot will be shown if not specified. - *dpi* -- DPI to save the image file at. - *cmap* -- Name of the matplotlib colormap to use. Default is 'magma'. - *edgecolor* -- Color of grid cell edges. - *area* -- Area of the figure without the colorbar, in square inches. 64 by default. - *no_axes* -- Set to *True* to omit axis spines. - *no_ticks* -- Set to *True* to omit tickmarks. - *no_cbar* -- Set to *True* to omit colorbar. - *cbar_label* -- Colorbar label. - *cbar_bounds* -- Explicit colorbar bounds. - *cbar_format* -- Format string or Formatter object for the colorbar ticks. """ # Process kwargs outfile = kwargs.pop("outfile", None) scale = kwargs.pop("scale", "linear") cmap = kwargs.pop("cmap", "viridis") edgecolor = kwargs.pop("edgecolor", "grey") small = kwargs.pop("small", 1e-30) area = kwargs.pop("area", 64) no_axes = kwargs.pop("no_axes", False) no_ticks = kwargs.pop("no_ticks", False) no_cbar = kwargs.pop("no_cbar", False) cbar_label = kwargs.pop("cbar_label", None) cbar_format = kwargs.pop("cbar_format", None) cbar_bounds = kwargs.pop("cbar_bounds", None) filter_function = kwargs.pop("filter_function", None) dpi = kwargs.pop("dpi", 100) linthresh = kwargs.pop("linthresh", 1.0) linscale = kwargs.pop("linscale", 1.0) cbar_ticks = kwargs.pop("cbar_ticks", None) if kwargs: warnings.warn(f"Unrecognized keyword arguments: {kwargs.keys()}") # Get figure, colormap fig, ax = plt.subplots() cmap = mpl.cm.get_cmap(cmap) # Get nuclei and all 3 numbers nuclei = self.unique_nuclei if filter_function is not None: nuclei = list(filter(filter_function, nuclei)) Ns = np.array([n.N for n in nuclei]) Zs = np.array([n.Z for n in nuclei]) As = Ns + Zs # Compute weights color_field = color_field.lower() if color_field not in {"x", "y", "ydot", "xdot", "activity"}: raise ValueError(f"Invalid color field: '{color_field}'") if comp is None: values = np.zeros(len(nuclei)) elif color_field == "x": values = np.array([comp.X[nuc] for nuc in nuclei]) elif color_field == "y": ys = comp.get_molar() values = np.array([ys[nuc] for nuc in nuclei]) elif color_field in {"ydot", "xdot"}: if rho is None or T is None: raise ValueError("Need both rho and T to evaluate rates!") ydots = self.evaluate_ydots(rho, T, comp) values = np.array([ydots[nuc] for nuc in nuclei]) if color_field == "xdot": values *= As elif color_field == "activity": if rho is None or T is None: raise ValueError("Need both rho and T to evaluate rates!") act = self.evaluate_activity(rho, T, comp) values = np.array([act[nuc] for nuc in nuclei]) if scale == "log": values = self._safelog(values, small) elif scale == "symlog": values = self._symlog(values, linthresh, linscale) if cbar_bounds is None: cbar_bounds = values.min(), values.max() weights = self._scale(values, *cbar_bounds) # Plot a square for each nucleus for nuc, weight in zip(nuclei, weights): square = plt.Rectangle((nuc.N - 0.5, nuc.Z - 0.5), width=1, height=1, facecolor=cmap(weight), edgecolor=edgecolor) ax.add_patch(square) # Set limits maxN, minN = max(Ns), min(Ns) maxZ, minZ = max(Zs), min(Zs) plt.xlim(minN - 0.5, maxN + 0.6) plt.ylim(minZ - 0.5, maxZ + 0.6) # Set plot appearance rat = (maxN - minN) / (maxZ - minZ) width = np.sqrt(area * rat) height = area / width fig.set_size_inches(width, height) plt.xlabel(r"N $\rightarrow$") plt.ylabel(r"Z $\rightarrow$") if no_axes or no_ticks: plt.tick_params( axis='both', which='both', bottom=False, left=False, labelbottom=False, labelleft=False ) else: ax.xaxis.set_major_locator(MaxNLocator(integer=True)) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) if no_axes: ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) # Colorbar stuff if not no_cbar and comp is not None: divider = make_axes_locatable(ax) cax = divider.append_axes('right', size='3.5%', pad=0.1) if scale == "symlog": cbar_norm = mpl.colors.SymLogNorm(linthresh, linscale, *cbar_bounds) else: cbar_norm = mpl.colors.Normalize(*cbar_bounds) smap = mpl.cm.ScalarMappable(norm=cbar_norm, cmap=cmap) if not cbar_label: capfield = color_field.capitalize() if scale == "log": cbar_label = f"log[{capfield}]" elif scale == "symlog": cbar_label = f"symlog[{capfield}]" else: cbar_label = capfield # set number of ticks if cbar_ticks is not None: tick_locator = mpl.ticker.MaxNLocator(nbins=cbar_ticks) tick_labels = tick_locator.tick_values(values.min(), values.max()) # for some reason tick_locator doesn't give the label of the first tick # add them manually if scale == "symlog": tick_labels = np.append(tick_labels, [linthresh, -linthresh]) if cbar_format is None: cbar_format = mpl.ticker.FormatStrFormatter("%.3g") else: tick_labels = None fig.colorbar(smap, cax=cax, orientation="vertical", ticks=tick_labels, label=cbar_label, format=cbar_format) if outfile is not None: plt.tight_layout() plt.savefig(outfile, dpi=dpi) return fig def __repr__(self): string = "" for r in self.rates: string += f"{r.string}\n" return string class Explorer: """ interactively explore a rate collection """ def __init__(self, rc, comp, **kwargs): """ take a RateCollection and a composition """ self.rc = rc self.comp = comp self.kwargs = kwargs # we will override any T and rho passed in kwargs.pop("T", None) kwargs.pop("rho", None) def _make_plot(self, logrho, logT): self.rc.plot(rho=10.0**logrho, T=10.0**logT, comp=self.comp, **self.kwargs) def explore(self, logrho=(2, 6, 0.1), logT=(7, 9, 0.1)): """Perform interactive exploration of the network structure.""" interact(self._make_plot, logrho=logrho, logT=logT)
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,727
pynucastro/pynucastro
refs/heads/main
/pynucastro/nucdata/tests/test_spin.py
from pynucastro.nucdata import SpinTable class TestSpin: @classmethod def setup_class(cls): """ this is run once for each class before any tests """ @classmethod def teardown_class(cls): """ this is run once for each class before any tests """ def setup_method(self): """ this is run once for each class before any tests """ #Is import to remark that the spin state gs is unique. #However, due to some experimental uncertainties two values #are proposed. self.spintable_gs_reliable = SpinTable(reliable=True) self.spintable_gs_not_reliable = SpinTable(reliable=False) def teardown_method(self): """ this is run once for each class before any tests """ def test_spin_table(self): assert self.spintable_gs_reliable.get_spin_states(a=1, z=0) == 2 assert self.spintable_gs_reliable.get_spin_states(a=14, z=4) == 1 assert self.spintable_gs_reliable.get_spin_states(a=219, z=89) == 10 assert self.spintable_gs_not_reliable.get_spin_states(a=1, z=0) == 2 assert self.spintable_gs_not_reliable.get_spin_states(a=14, z=4) == 1 assert self.spintable_gs_not_reliable.get_spin_states(a=219, z=89) == 10 assert self.spintable_gs_not_reliable.get_spin_states(a=91, z=46) == 8 assert self.spintable_gs_not_reliable.get_spin_states(a=275, z=107) == 6 assert self.spintable_gs_not_reliable.get_spin_states(a=11, z=8) == 4
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,728
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/tests/test_rc_jacobian.py
# unit tests for a rate collection import pytest from pytest import approx import pynucastro as pyna class TestRateCollectionJacobian: @pytest.fixture(scope="class") def rc(self, reaclib_library): mylib = reaclib_library.linking_nuclei(["he4", "c12", "o16", "ne20"], with_reverse=False) return pyna.RateCollection(libraries=[mylib]) @pytest.fixture(scope="class") def comp(self, rc): _comp = pyna.Composition(rc.unique_nuclei) _comp.set_solar_like() return _comp def test_jac(self, rc, comp): rho = 1.e6 T = 5.e8 ymolar = comp.get_molar() jac = rc.evaluate_jacobian(rho, T, comp) # let's look now at jac(0, 0), which should be dYdot(He4)/dY(He4) # and jac(1, 1), which should be dYdot(C12)/dY(C12) # there are 4 terms that go into this, which we will compute manually jac_alpha_alpha = 0.0 jac_c12_c12 = 0.0 # 3-alpha # r = rho**2 Y(alpha)**3 N_A<sigma v> / 6 # 3 alphas are destroyed r = rc.get_rate_by_name("he4(aa,g)c12") jac_alpha_alpha += -3.0 * rho**2 * 3 * ymolar[pyna.Nucleus("he4")]**2 * r.eval(T) / 6.0 # does not depend on c12 # C12(a,g)O16 # r = rho * Y(alpha) * Y(c12) N_A<sigma v> r = rc.get_rate_by_name("c12(a,g)o16") jac_alpha_alpha += -rho * ymolar[pyna.Nucleus("c12")] * r.eval(T) jac_c12_c12 += -rho * ymolar[pyna.Nucleus("he4")] * r.eval(T) # C12(C12,a)Ne20 # r = rho * Y(c12)**2 N_A<sigma v> / 2 r = rc.get_rate_by_name("c12(c12,a)ne20") # but the rate does not depend on alpha jac_c12_c12 += -2.0 * rho * 2.0 * ymolar[pyna.Nucleus("c12")] * r.eval(T) / 2.0 # O16(a,g)Ne20 # r = rho * Y(o16) * Y(alpha) N_A<sigma v> r = rc.get_rate_by_name("o16(a,g)ne20") jac_alpha_alpha += -rho * ymolar[pyna.Nucleus("o16")] * r.eval(T) # rate does not depend on c12 assert jac_alpha_alpha == approx(jac[0, 0]) assert jac_c12_c12 == approx(jac[1, 1])
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,729
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py
# unit tests for rates import shutil import pytest import pynucastro as pyna from pynucastro.networks.tests.helpers import compare_network_files class TestAmrexAstroCxxNetwork: @pytest.fixture(scope="class") def fn(self, reaclib_library): mylib = reaclib_library.linking_nuclei(["mg24", "al27", "si28", "p31", "s32", "he4", "p"]) net = pyna.AmrexAstroCxxNetwork(libraries=[mylib]) net.make_ap_pg_approx() net.remove_nuclei(["al27", "p31"]) fn = net return fn def test_write_network(self, fn): """ test the write_network function""" test_path = "_test_cxx_approx/" # subdirectory of pynucastro/networks/tests/ reference_path = "_amrexastro_cxx_approx_reference/" # files that will be ignored if present in the generated directory skip_files = [] # remove any previously generated files shutil.rmtree(test_path, ignore_errors=True) fn.write_network(odir=test_path) compare_network_files(test_path, reference_path, skip_files) # clean up generated files if the test passed shutil.rmtree(test_path)
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,730
pynucastro/pynucastro
refs/heads/main
/pynucastro/nucdata/tests/test_mass.py
from pytest import approx from pynucastro.nucdata import MassTable class TestMass: def test_mass_table(self): _dm = MassTable() assert _dm.get_mass_diff(a=1, z=0) == approx(8.07132) assert _dm.get_mass_diff(a=4, z=2) == approx(2.42492) assert _dm.get_mass_diff(a=295, z=118) == approx(201.37)
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,731
pynucastro/pynucastro
refs/heads/main
/pynucastro/reduction/sensitivity_analysis.py
import numpy as np from pynucastro.reduction.reduction_utils import mpi_importer MPI = mpi_importer() def binary_search_trim(network, nuclei, errfunc, thresh=0.05): """ Given an array of nuclei sorted roughly by relative importance, perform a binary search to trim out nuclei from the network until the error is as close as possible to the given threshold without exceeding it. Nuclei whose removal will result in only a small increase in error need to be packed towards the back of the array for the binary search to work effectively. :param network: The network to reduce. :param nuclei: Nuclei to consider for the final network, sorted by decreasing importance (i.e. most important nuclei first). Importance can be determined by something like the *drgep* function. :param errfunc: Error function to use when evaluating error. Should take a reduced network as an argument and return the relative error produced by the reduction. This can be a parallel (MPI) function. :param thresh: Threshold for acceptable error. Default is 0.05. :return: A reduced reaction network with an evaluated error approximately equal to the supplied threshold. """ start_idx = 0 seg_size = len(nuclei) / 2 while seg_size >= 0.5: # Divide up into segments end_idx = start_idx + round(seg_size) red_net = network.linking_nuclei(nuclei[:end_idx]) # Evaluate error err = errfunc(red_net) if err <= thresh: seg_size /= 2 else: start_idx += round(seg_size) seg_size /= 2 return network.linking_nuclei(nuclei[:start_idx+1]) def _progress_bar(frac, size=50): n = round(size*frac) progress_bar = '[' + '⊙'*n + ' '*(size-n) + ']' if frac < 1.0: end = '\r' else: end = '\n' print(progress_bar, f'{round(100*frac)}%', end=end) def sens_analysis(network, errfunc, thresh=0.05, use_mpi=False, print_prog=True): """ Given a reaction network, remove nuclei from the network one-by-one until the induced error is as close to the given threshold as possible without exceeding it. This will test nuclei for removal individually and remove the one that induces the smallest error on each pass. Since it requires O(n^2) error function evaluations, this routine is much more expensive than *binary_search*, but it will typically trim the network down significantly more. :param network: The network to reduce. :param errfunc: Error function to use when evaluating error. Should take a reduced network as an argument and return the relative error produced by the reduction. If *use_mpi* is *False*, the error function can be parallelized with MPI. Otherwise *sens_analysis* will be parallelized and the error function should not be. :param thresh: Threshold for acceptable error. Default is 0.05. :param use_mpi: Whether to parallelize the loop over nuclei with each pass or not using MPI. For *p* MPI processes, the parallelized function will require O(n^2/p) error function evaluations per process. This option is *False* by default. If the error function is parallelized using MPI, this option should be set to *False*. :param print_prog: Whether to print out the progress of the function as it runs or not. Includes a progress bar for each pass and messages indicating when the algorithm starts and ends. :return: A reduced reaction network with an evaluated error approximately equal to the supplied threshold. """ if use_mpi: comm = MPI.COMM_WORLD MPI_N = comm.Get_size() MPI_rank = comm.Get_rank() else: MPI_N = 1 MPI_rank = 0 nuclei = list(network.unique_nuclei) err = 0.0 nrem = 0 print_prog = print_prog and (MPI_rank == 0) if print_prog: print("Performing sensitivity analysis...") while True: err = float('inf') for i in range(MPI_rank, len(nuclei), MPI_N): if print_prog: print(f"Pass {nrem+1}:", end=' ') _progress_bar(i/len(nuclei)) nuc = nuclei.pop(i) err_i = errfunc(network.linking_nuclei(nuclei, print_warning=False)) if err_i < err: err = err_i min_idx = i nuclei.insert(i, nuc) if use_mpi: err = comm.gather(err, root=0) min_idx = comm.gather(min_idx, root=0) if MPI_rank == 0: min_rank = np.argmin(err) err = err[min_rank] min_idx = min_idx[min_rank] err = comm.bcast(err, root=0) min_idx = comm.bcast(min_idx, root=0) if print_prog: print(f"Pass {nrem+1}:", end=' ') _progress_bar(1.0) if err <= thresh: nuclei.pop(min_idx) nrem += 1 else: break if print_prog: print(f"Done. Removed {nrem} nuclei.") return network.linking_nuclei(nuclei)
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,732
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/tests/test_approx_python_net.py
# unit tests for rates import importlib import os import sys import numpy as np import pytest from pytest import approx from scipy.integrate import solve_ivp import pynucastro as pyna from pynucastro.screening import chugunov_2007 class TestPythonNetwork: @pytest.fixture(scope="class") def pynet(self, reaclib_library): mynet = reaclib_library.linking_nuclei(["p", "he4", "mg24", "al27", "si28", "p31", "s32"]) pynet = pyna.PythonNetwork(libraries=[mynet]) pynet.make_ap_pg_approx() pynet.remove_nuclei(["al27", "p31"]) return pynet def test_num_rates(self, pynet): assert len(pynet.rates) == 4 def test_num_reaclib_rates(self, pynet): assert len(pynet.reaclib_rates) == 12 def test_num_approx_rates(self, pynet): assert len(pynet.approx_rates) == 4 def test_full_ydot_string(self, pynet): ostr = \ """dYdt[jhe4] = ( -rho*Y[jhe4]*Y[jmg24]*rate_eval.mg24_he4__si28__approx -rho*Y[jhe4]*Y[jsi28]*rate_eval.si28_he4__s32__approx +Y[jsi28]*rate_eval.si28__mg24_he4__approx +Y[js32]*rate_eval.s32__si28_he4__approx ) """ assert pynet.full_ydot_string(pyna.Nucleus("he4")) == ostr def test_approx_function_string(self, pynet): ostr = \ """@numba.njit() def mg24_he4__si28__approx(rate_eval, tf): r_ag = rate_eval.he4_mg24__si28__removed r_ap = rate_eval.he4_mg24__p_al27__removed r_pg = rate_eval.p_al27__si28__removed r_pa = rate_eval.p_al27__he4_mg24__removed rate = r_ag + r_ap * r_pg / (r_pg + r_pa) rate_eval.mg24_he4__si28__approx = rate """ r = pynet.get_rate("mg24_he4__si28__approx") assert r.function_string_py() == ostr def test_function_string(self, pynet): ostr = \ """@numba.njit() def he4_mg24__si28__removed(rate_eval, tf): # mg24 + he4 --> si28 rate = 0.0 # st08r rate += np.exp( -50.5494 + -12.8332*tf.T9i + 21.3721*tf.T913i + 37.7649*tf.T913 + -4.10635*tf.T9 + 0.249618*tf.T953 + -1.5*tf.lnT9) # st08r rate += np.exp( 8.03977 + -15.629*tf.T9i + -1.5*tf.lnT9) rate_eval.he4_mg24__si28__removed = rate """ r = pynet.get_rate("mg24_he4__si28__approx") assert r.get_child_rates()[0].function_string_py().strip() == ostr.strip() def test_integrating(self, pynet): pynet.write_network("app.py") app = importlib.import_module("app") rho = 1.e7 T = 3e9 X0 = np.zeros(app.nnuc) X0[app.jhe4] = 0.5 X0[app.jmg24] = 0.5 Y0 = X0 / app.A tmax = 1.e-3 sol = solve_ivp(app.rhs, [0, tmax], Y0, method="BDF", jac=app.jacobian, dense_output=True, args=(rho, T, chugunov_2007), rtol=1.e-6, atol=1.e-10) # these are the final molar fractions answer = [8.33333490e-02, 9.24569852e-20, 1.56798113e-08, 2.08333177e-02] for i in range(app.nnuc): assert answer[i] == approx(sol.y[i, -1]) # clean up generated files if the test passed os.remove("app.py") # remove imported module from cache del app del sys.modules["app"] def test_to_composition(self, pynet): pynet.write_network("app.py") app = importlib.import_module("app") comp_orig = pyna.Composition(pynet.unique_nuclei) comp_orig.set_solar_like() Y = np.zeros(app.nnuc) for nuc, molar_fraction in comp_orig.get_molar().items(): Y[app.names.index(nuc.short_spec_name)] = molar_fraction comp_new = app.to_composition(Y) assert comp_new.X == comp_orig.X # clean up generated files if the test passed os.remove("app.py") # remove imported module from cache del app del sys.modules["app"]
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,733
pynucastro/pynucastro
refs/heads/main
/pynucastro/rates/__init__.py
"""The core routines needed to read and interpret nuclear reaction rates""" __all__ = ["rate", "library"] from .library import (LangankeLibrary, Library, RateFilter, ReacLibLibrary, SuzukiLibrary, TabularLibrary, list_known_rates) from .rate import (ApproximateRate, DerivedRate, Rate, RateFileError, RatePair, ReacLibRate, TableIndex, TableInterpolator, TabularRate, Tfactors, _find_rate_file, load_rate)
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,734
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/tests/test_cxx_amrexastro_net.py
# unit tests for rates import io import shutil import pytest from pynucastro import networks from pynucastro.networks.tests.helpers import compare_network_files class TestAmrexAstroCxxNetwork: # pylint: disable=protected-access @pytest.fixture(scope="class") def fn(self): files = ["c12-c12a-ne20-cf88", "c12-c12n-mg23-cf88", "c12-c12p-na23-cf88", "c12-ag-o16-nac2", "na23--ne23-toki", "ne23--na23-toki", "n--p-wc12"] fn = networks.AmrexAstroCxxNetwork(files) return fn def cromulent_ftag(self, ftag, answer, n_indent=1): """ check to see if function ftag returns answer """ output = io.StringIO() ftag(n_indent, output) result = output.getvalue() == answer output.close() return result def test_nrat_reaclib(self, fn): """ test the _nrat_reaclib function """ answer = ' const int NrateReaclib = 5;\n' assert self.cromulent_ftag(fn._nrat_reaclib, answer, n_indent=1) def test_nrat_tabular(self, fn): """ test the _nrat_tabular function """ answer = ' const int NrateTabular = 2;\n' assert self.cromulent_ftag(fn._nrat_tabular, answer, n_indent=1) def test_nrxn(self, fn): """ test the _nrxn function """ answer = (' k_c12_c12_to_he4_ne20 = 1,\n' + ' k_c12_c12_to_n_mg23 = 2,\n' + ' k_c12_c12_to_p_na23 = 3,\n' + ' k_he4_c12_to_o16 = 4,\n' + ' k_n_to_p_weak_wc12 = 5,\n' + ' k_na23_to_ne23 = 6,\n' + ' k_ne23_to_na23 = 7,\n' + ' NumRates = k_ne23_to_na23\n') assert self.cromulent_ftag(fn._nrxn, answer, n_indent=1) def test_ebind(self, fn): """ test the _ebind function """ answer = (' ebind_per_nucleon(N) = 0.0_rt;\n' + ' ebind_per_nucleon(H1) = 0.0_rt;\n' + ' ebind_per_nucleon(He4) = 7.073915_rt;\n' + ' ebind_per_nucleon(C12) = 7.680144_rt;\n' + ' ebind_per_nucleon(O16) = 7.976206_rt;\n' + ' ebind_per_nucleon(Ne20) = 8.03224_rt;\n' + ' ebind_per_nucleon(Ne23) = 7.955256_rt;\n' + ' ebind_per_nucleon(Na23) = 8.111493000000001_rt;\n' + ' ebind_per_nucleon(Mg23) = 7.901115_rt;\n') assert self.cromulent_ftag(fn._ebind, answer, n_indent=2) def test_write_network(self, fn): """ test the write_network function""" test_path = "_test_cxx/" # subdirectory of pynucastro/networks/tests/ reference_path = "_amrexastro_cxx_reference/" # files that will be ignored if present in the generated directory skip_files = [] # remove any previously generated files shutil.rmtree(test_path, ignore_errors=True) fn.write_network(odir=test_path) compare_network_files(test_path, reference_path, skip_files) # clean up generated files if the test passed shutil.rmtree(test_path)
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,735
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/tests/test_simple_cxx_net.py
# unit tests for rates import shutil import pytest from pynucastro import networks from pynucastro.networks.tests.helpers import compare_network_files class TestSimpleCxxNetwork: # pylint: disable=protected-access @pytest.fixture(scope="class") def fn(self): files = ["c12-c12a-ne20-cf88", "c12-c12n-mg23-cf88", "c12-c12p-na23-cf88", "c12-ag-o16-nac2", "n--p-wc12"] fn = networks.SimpleCxxNetwork(files) return fn def test_write_network(self, fn): """ test the write_network function""" test_path = "_test_simple_cxx/" # subdirectory of pynucastro/networks/tests/ reference_path = "_simple_cxx_reference/" # files that will be ignored if present in the generated directory skip_files = [] # remove any previously generated files shutil.rmtree(test_path, ignore_errors=True) fn.write_network(odir=test_path) compare_network_files(test_path, reference_path, skip_files) # clean up generated files if the test passed shutil.rmtree(test_path)
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,736
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/tests/helpers.py
import filecmp import os def compare_network_files(test_path, ref_path, skip_files=()): base_path = os.path.relpath(os.path.dirname(__file__)) ref_path = os.path.join(base_path, ref_path) skip_files = set(skip_files) test_files = set(os.listdir(test_path)) - skip_files ref_files = set(os.listdir(ref_path)) - skip_files assert test_files == ref_files, "missing/extra files" errors = [] for file in sorted(test_files): # note, _test is written under whatever directory pytest is run from, # so it is not necessarily at the same place as _amrexastro_reference if not filecmp.cmp(os.path.normpath(os.path.join(test_path, file)), os.path.normpath(os.path.join(ref_path, file)), shallow=False): errors.append(file) assert not errors, f"files don't match: {' '.join(errors)}"
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,737
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/tests/test_rate_collection.py
# unit tests for a rate collection import pytest import pynucastro as pyna class TestRateCollection: @pytest.fixture(scope="class") def rc(self, reaclib_library): mylib = reaclib_library.linking_nuclei(["he4", "c12", "o16"]) return pyna.RateCollection(libraries=[mylib]) def test_get_ratesg(self, rc): rr = rc.get_rates() assert len(rr) == 4 assert rr[0].fname == "o16__he4_c12" assert rr[1].fname == "c12__he4_he4_he4" assert rr[2].fname == "he4_c12__o16" assert rr[3].fname == "he4_he4_he4__c12" def test_get_rate(self, rc): r = rc.get_rate("he4_he4_he4__c12") assert r.fname == "he4_he4_he4__c12" def test_find_reverse(self, rc): rr = rc.find_reverse(rc.get_rate("he4_c12__o16")) assert rr.fname == "o16__he4_c12" def test_evaluate_energy_gen(self, rc): # define a composition comp = pyna.Composition(rc.unique_nuclei) comp.set_all(0.3) comp.normalize() rho = 1e5 T = 1e8 assert rc.evaluate_energy_generation(rho, T, comp) == 32.24796008826701 def test_add_rates(self, rc, reaclib_library): new_rate_names = ["o16(a,g)ne20", "ne20(a,g)mg24", "mg24(a,g)si28"] new_rates = reaclib_library.get_rate_by_name(new_rate_names) # test adding only a single rate rc.add_rates(new_rates[0]) # check to see if the rate is added assert new_rates[0] in rc.get_rates() # now add them all -- and make sure we don't duplicate a rate rc.add_rates(new_rates) for r in new_rates: assert r in rc.get_rates() assert rc.get_rates().count(new_rates[0]) == 1 # note: this modifies the fixture rc so tests that follow # will see the additional rates def test_remove_rates(self, rc): rate = rc.get_rates()[-1] rc.remove_rates(rate) assert rate not in rc.get_rates() assert len(rc.get_rates()) == 6 class TestUnimportantRates: @pytest.fixture(scope="class") def rc(self): files = ["c12-pg-n13-ls09", "c13-pg-n14-nacr", "n13--c13-wc12", "n13-pg-o14-lg06", "n14-pg-o15-im05", "n15-pa-c12-nacr", "o14--n14-wc12", "o15--n15-wc12"] return pyna.RateCollection(files) @pytest.fixture(scope="class") def comp(self, rc): # define a composition comp = pyna.Composition(rc.unique_nuclei) comp.set_all(1.0) comp.normalize() return comp def test_temp_1e8(self, rc, comp): rho = 1e5 T = 1e8 expected = {rc.rates[i] for i in [2, 3, 4, 6, 7]} unimportant = rc.find_unimportant_rates([(rho, T, comp)], cutoff_ratio=1e-4) assert rc.rates[0] not in unimportant assert unimportant.keys() == expected def test_temp_1e10(self, rc, comp): rho = 1e5 T = 1e10 expected = {rc.rates[i] for i in [0, 2, 4, 6, 7]} unimportant = rc.find_unimportant_rates([(rho, T, comp)], cutoff_ratio=1e-4) assert rc.rates[3] not in unimportant assert unimportant.keys() == expected def test_temp_both(self, rc, comp): states = [(1.e5, 1.e8, comp), (1.e5, 1.e10, comp)] expected = {rc.rates[i] for i in [2, 4, 6, 7]} unimportant = rc.find_unimportant_rates(states, cutoff_ratio=1e-4) # C12(p,g)N13 (rate 0) is important at T=1e8, but not T=1e10. # N13(p,g)O14 (rate 3) is important at T=1e10, but not T=1e8. # If we include both temperatures, then both rates should be considered important. assert rc.rates[0] not in unimportant assert rc.rates[3] not in unimportant assert unimportant.keys() == expected
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,738
pynucastro/pynucastro
refs/heads/main
/pynucastro/nucdata/spin_table.py
import os class SpinTable: """ This class stores the nubase2020_1.txt table information in a dictionary data structure that maps nuclides to their number of nuclear spin states. Therefore, after setting an SpinTable class in rates.py, we can retrieve the spin states for a designated Nucleus class. The variable reliable switch between using all the values of the tables, excluding the nuclei where only intervals are given and the values measured by strong experimental arguments. """ def __init__(self, datafile=None, reliable=False): self._spin_states = {} self.reliable = reliable if datafile: self.datafile = datafile else: datafile_name = 'nubase2020_1.txt' nucdata_dir = os.path.dirname(os.path.realpath(__file__)) self.datafile = os.path.join(os.path.join(nucdata_dir, 'AtomicMassEvaluation'), datafile_name) self._read_table() def _read_table(self): finput = open(self.datafile, 'r') for _ in range(4): finput.readline() for line in finput: ls = line.strip().split() A = int(ls.pop(0)) Z = int(ls.pop(0)) ls.pop(0) # Spin spin_states = int(ls.pop(0)) experimental = ls.pop(0) if self.reliable: if experimental == 's': self._spin_states[A, Z] = spin_states else: continue else: self._spin_states[A, Z] = spin_states finput.close() def get_spin_states(self, a, z): if (a, z) in self._spin_states: return self._spin_states[a, z] raise NotImplementedError("nuclear spin data is not available for the selected nucleus")
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,739
pynucastro/pynucastro
refs/heads/main
/pynucastro/nucdata/AtomicMassEvaluation/extract_mass_excess.py
import argparse """ This module extract the (A,Z, dm) tuples from `nubase_3.mas20.txt`, where: :var A: is the atomic weight measured in atomic mass units. :var Z: is the atomic number. :var dm: is the mass difference A_{nuc}-A. """ #os.path.dirname(os.path.realpath(__file__)) parser = argparse.ArgumentParser() parser.add_argument('input', type=str, help='Name of the input table') parser.add_argument('-o', '--output', type=str, default='mass_excess2020', help='Name of the formatted mass escess table') args = parser.parse_args() finput = open(args.input, 'r') for _ in range(25): finput.readline() fout = open(args.output+'.txt', 'w') fout.write('# Mass difference evaluation table: {} \n'.format(args.output)) fout.write('# only ground states are tabulated \n') fout.write('#\n') fout.write('#\n') fout.write('==A== {:18s} ==Z== {:10s} ======dm===== \n'.format(' ', ' ')) for line in finput: isomer_string = line[7] isomer = int(isomer_string) if isomer != 0: continue A_string = line[0:3].strip() Z_string = line[4:7].strip() dm_string = line[18:31].strip().strip('#') A = int(A_string) Z = int(Z_string) #dm is measured in keV, but we want MeV dm = float(dm_string)/1.0e3 fout.write('{:3d} {:20s} {:3d} {:10s} {:15.6} \n'.format(A, ' ', Z, ' ', dm)) finput.close() fout.close()
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,740
pynucastro/pynucastro
refs/heads/main
/examples/triple-alpha/triple-alpha-cxx.py
# triple-alpha rate module generator from pynucastro.networks import AmrexAstroCxxNetwork files = ["c12-gaa-he4-fy05", "he4-aag-c12-fy05"] triple_alpha_net = AmrexAstroCxxNetwork(files) triple_alpha_net.write_network()
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,741
pynucastro/pynucastro
refs/heads/main
/pynucastro/nucdata/AtomicMassEvaluation/extract_table.py
#!/usr/bin/env python """ Uses AMETable class to extract binding energy from an AME Table. """ import argparse from ame_table import AMETable parser = argparse.ArgumentParser() parser.add_argument('table', type=str, help='Name of AME Table file. E.g. "mass.mas12".') parser.add_argument('-o', '--output', type=str, default='binding.txt', help='Name of output file to store binding energies. Default is "binding.txt".') args = parser.parse_args() ame = AMETable(args.table) fout = open(args.output, 'w') fout.write('# AME Table file name: {}\n'.format(args.table)) fout.write('N Z Ebind(MeV)/Nucleon\n') for nuc in ame.nuclides: ostr = '{:<20}'.format(nuc.n) ostr += '{:<20}'.format(nuc.z) ostr += '{:0.17e}\n'.format(nuc.nucbind) fout.write(ostr) fout.close()
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,742
pynucastro/pynucastro
refs/heads/main
/pynucastro/nucdata/AtomicMassEvaluation/ame_table.py
""" Reads AME tabular mass data file and supplies table data. """ # Common Imports import os from ame_nuclide import AMENuclide def str_head_pop(s, n): """ Pop n characters from string s from the beginning. Returns a tuple consisting of the new s and the popped characters. """ if n >= len(s): return ('', s) s = list(s) return (''.join(s[n:]), ''.join(s[:n])) def cleanup(s): """ Given string s, removes "#" and "*". # is a standin for a decimal point for estimated values. * represents a non-computable quantity. """ s = s.replace('#', '.') s = s.replace('*', '') s = s.replace(' ', '') return s class AMETable(object): """A simple class to manage reading and parsing the AME Table data files (2012, 2016).""" header_length = 39 def __init__(self, datfile=None): """ Initialize """ self.datfile = None if datfile: self.datfile = datfile else: thisdir = os.path.dirname(os.path.realpath(__file__)) fname = os.path.join(thisdir, 'mass.mas12') if os.path.isfile(fname): self.datfile = fname self.nuclides = [] if self.datfile: self.read() def read(self): """ Read the AME data file 'datfile' """ try: f = open(self.datfile, 'r') except IOError: print('ERROR: data file not found!') exit() # Get rid of the header for _ in range(self.header_length): f.readline() # Read nuclide mass data for line in f: ls = line.strip() if ls: # Pull data out of the line line, _ = str_head_pop(line, 4) line, n = str_head_pop(line, 5) line, z = str_head_pop(line, 5) line, a = str_head_pop(line, 5) line, _ = str_head_pop(line, 1) line, element = str_head_pop(line, 3) line, origin = str_head_pop(line, 4) line, _ = str_head_pop(line, 1) line, mexcess = str_head_pop(line, 13) mexcess = cleanup(mexcess) line, d_mexcess = str_head_pop(line, 11) d_mexcess = cleanup(d_mexcess) line, nucbind = str_head_pop(line, 11) nucbind = cleanup(nucbind) line, d_nucbind = str_head_pop(line, 9) d_nucbind = cleanup(d_nucbind) line, _ = str_head_pop(line, 1) line, decay_type = str_head_pop(line, 2) line, ebeta = str_head_pop(line, 11) ebeta = cleanup(ebeta) line, d_ebeta = str_head_pop(line, 9) d_ebeta = cleanup(d_ebeta) line, _ = str_head_pop(line, 1) line, mass = str_head_pop(line, 16) mass = cleanup(mass) line, d_mass = str_head_pop(line, 11) d_mass = cleanup(d_mass) # Store nuclide data nuclide = AMENuclide(n, z, a, element.strip(), origin.strip(), mexcess, d_mexcess, nucbind, d_nucbind, decay_type.strip(), ebeta, d_ebeta, mass, d_mass) self.nuclides.append(nuclide) f.close() def abbrev_get_nuclide(self, isostring): """ Returns the nuclide object given an identifying string isostring which consists of: [A]-[Abbreviation] E.g. "4-He", "7-li", etc. """ try: a, abb = tuple(isostring.split('-')) except ValueError: print('ERROR: Supply an isotope string in the form "4-He"') raise a = int(a) abb = abb.strip().lower() for nuc in self.nuclides: if nuc.a == a and nuc.element.lower() == abb: return nuc print('ERROR: Could not find a nuclide by the specification {}'.format(isostring)) def get_nuclide(self, n=-1, z=-1, a=-1): """ Returns the nuclide object given at least 2 of n, z, a. Complains if A-Z-N != 0. """ if n >= 0 and z >= 0 and a >= 0: if a - z - n != 0: print('ERROR: Z+N != A') exit() else: if n == -1: n = a - z elif z == -1: z = a - n else: a = n + z for nuc in self.nuclides: if nuc.n == n and nuc.z == z: return nuc print('Nuclide not found for (N, Z, A) = ({}, {}, {})!'.format(n, z, a))
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,743
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/amrexastro_cxx_network.py
"""A C++ reaction network for integration into the AMReX Astro Microphysics set of reaction networks used by astrophysical hydrodynamics codes""" import glob import os from pynucastro.networks.base_cxx_network import BaseCxxNetwork from pynucastro.nucdata import Nucleus from pynucastro.rates import ReacLibRate class AmrexAstroCxxNetwork(BaseCxxNetwork): def __init__(self, *args, **kwargs): # this network can have a special kwarg called disable_rate_params try: disable_rate_params = kwargs.pop("disable_rate_params") except KeyError: disable_rate_params = [] # Initialize BaseCxxNetwork parent class super().__init__(*args, **kwargs) self.ftags['<rate_param_tests>'] = self._rate_param_tests self.ftags['<rate_indices>'] = self._fill_rate_indices self.ftags['<npa_index>'] = self._fill_npa_index self.disable_rate_params = disable_rate_params self.function_specifier = "AMREX_GPU_HOST_DEVICE AMREX_INLINE" self.dtype = "Real" def _get_template_files(self): template_pattern = os.path.join(self.pynucastro_dir, 'templates', 'amrexastro-cxx-microphysics', '*.template') return glob.glob(template_pattern) def _rate_param_tests(self, n_indent, of): for _, r in enumerate(self.rates): if r in self.disable_rate_params: of.write(f"{self.indent*n_indent}if (disable_{r.cname()}) {{\n") of.write(f"{self.indent*n_indent} rate_eval.screened_rates(k_{r.cname()}) = 0.0;\n") of.write(f"{self.indent*n_indent} if constexpr (std::is_same<T, rate_derivs_t>::value) {{\n") of.write(f"{self.indent*n_indent} rate_eval.dscreened_rates_dT(k_{r.cname()}) = 0.0;\n") of.write(f"{self.indent*n_indent} }}\n") # check for the reverse too -- we disable it with the same parameter rr = self.find_reverse(r) if rr is not None: of.write(f"{self.indent*n_indent} rate_eval.screened_rates(k_{rr.cname()}) = 0.0;\n") of.write(f"{self.indent*n_indent} if constexpr (std::is_same<T, rate_derivs_t>::value) {{\n") of.write(f"{self.indent*n_indent} rate_eval.dscreened_rates_dT(k_{rr.cname()}) = 0.0;\n") of.write(f"{self.indent*n_indent} }}\n") of.write(f"{self.indent*n_indent}}}\n\n") def _write_network(self, odir=None): """ This writes the RHS, jacobian and ancillary files for the system of ODEs that this network describes, using the template files. """ super()._write_network(odir=odir) if odir is None: odir = os.getcwd() # create a .net file with the nuclei properties with open(os.path.join(odir, "pynucastro.net"), "w") as of: for nuc in self.unique_nuclei: of.write(f"{nuc.spec_name:25} {nuc.short_spec_name:6} {nuc.A:6.1f} {nuc.Z:6.1f}\n") for nuc in self.approx_nuclei: of.write(f"__extra_{nuc.spec_name:17} {nuc.short_spec_name:6} {nuc.A:6.1f} {nuc.Z:6.1f}\n") # write the _parameters file with open(os.path.join(odir, "_parameters"), "w") as of: of.write("@namespace: network\n\n") if self.disable_rate_params: for r in self.disable_rate_params: of.write(f"disable_{r.cname()} int 0\n") def _fill_npa_index(self, n_indent, of): #Get the index of h1, neutron, and helium-4 if they're present in the network. LIG = list(map(Nucleus, ["p", "n", "he4"])) for nuc in LIG: if nuc in self.unique_nuclei: of.write(f"{self.indent*n_indent}constexpr int {nuc.short_spec_name}_index = {self.unique_nuclei.index(nuc)};\n") else: of.write(f"{self.indent*n_indent}constexpr int {nuc.short_spec_name}_index = -1;\n") def _fill_rate_indices(self, n_indent, of): """ Fills the index needed for the NSE_NET algorithm. Fill rate_indices: 2D array with 1-based index of shape of size (NumRates, 7). - Each row represents a rate in self.all_rates. - The first 3 elements of the row represents the index of reactants in self.unique_nuclei - The next 3 elements of the row represents the index of the products in self.unique_nuclei. - The 7th element of the row represents the index of the corresponding reverse rate (set to -1 if no corresponding reverse rate). This is a 1-based instead of 0-based index. - Set all elements of the current row to -1 if the rate has removed suffix indicating its not directly in the network. """ # Fill in the rate indices of.write(f"{self.indent*n_indent}AMREX_GPU_MANAGED amrex::Array2D<int, 1, Rates::NumRates, 1, 7, Order::C> rate_indices {{\n") for n, rate in enumerate(self.all_rates): tmp = ',' if n == len(self.all_rates) - 1: tmp = '' # meaning it is removed. if isinstance(rate, ReacLibRate) and rate.removed is not None: of.write(f"{self.indent*n_indent} -1, -1, -1, -1, -1, -1, -1{tmp}\n") continue # Find the reactants and products indices reactant_ind = [-1 for n in range(3 - len(rate.reactants))] product_ind = [-1 for n in range(3 - len(rate.products))] for nuc in rate.reactants: reactant_ind.append(self.unique_nuclei.index(nuc)) for nuc in rate.products: product_ind.append(self.unique_nuclei.index(nuc)) reactant_ind.sort() product_ind.sort() # Find the reverse rate index rr_ind = -1 rr = self.find_reverse(rate) # Note that rate index is 1-based if rr is not None: rr_ind = self.all_rates.index(rr) + 1 of.write(f"{self.indent*n_indent} {reactant_ind[0]}, {reactant_ind[1]}, {reactant_ind[2]}, {product_ind[0]}, {product_ind[1]}, {product_ind[2]}, {rr_ind}{tmp}\n") of.write(f"{self.indent*n_indent}}};\n")
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,744
pynucastro/pynucastro
refs/heads/main
/pynucastro/nucdata/tests/test_binding.py
# unit tests for Binding Energy database taken from AME 2016. from pytest import approx from pynucastro.nucdata import BindingTable class TestAME: def test_get(self): bintable = BindingTable() assert bintable.get_binding_energy(n=1, z=1) == approx(1.112283) assert bintable.get_binding_energy(n=5, z=6) == approx(6.676456) assert bintable.get_binding_energy(n=17, z=23) == approx(7.317) assert bintable.get_binding_energy(n=90, z=78) == approx(7.773605)
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,745
pynucastro/pynucastro
refs/heads/main
/pynucastro/rates/rate.py
""" Classes and methods to interface with files storing rate data. """ import io import os from collections import Counter from enum import Enum import matplotlib.pyplot as plt import numpy as np from scipy.constants import physical_constants try: import numba from numba.experimental import jitclass except ImportError: numba = None import functools # no-op jitclass placeholder def jitclass(cls_or_spec=None, spec=None): if (cls_or_spec is not None and spec is None and not isinstance(cls_or_spec, type)): # Used like # @jitclass([("x", intp)]) # class Foo: # ... spec = cls_or_spec cls_or_spec = None def wrap(cls): # this copies the function name and docstring to the wrapper function @functools.wraps(cls) def wrapper(*args, **kwargs): return cls(*args, **kwargs) return wrapper if cls_or_spec is None: return wrap return wrap(cls_or_spec) from pynucastro.nucdata import Nucleus, UnsupportedNucleus amu_mev, _, _ = physical_constants['atomic mass constant energy equivalent in MeV'] hbar, _, _ = physical_constants['reduced Planck constant'] amu, _, _ = physical_constants['atomic mass constant'] k_B_mev_k, _, _ = physical_constants['Boltzmann constant in eV/K'] k_B_mev_k /= 1.0e6 k_B, _, _ = physical_constants['Boltzmann constant'] N_a, _, _ = physical_constants['Avogadro constant'] _pynucastro_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) _pynucastro_rates_dir = os.path.join(_pynucastro_dir, 'library') _pynucastro_tabular_dir = os.path.join(_pynucastro_rates_dir, 'tabular') _pynucastro_suzuki_dir = os.path.join(_pynucastro_tabular_dir, 'suzuki') _pynucastro_langanke_dir = os.path.join(_pynucastro_tabular_dir, 'langanke') def get_rates_dir(): return _pynucastro_rates_dir def get_tabular_dir(): return _pynucastro_tabular_dir class RateFileError(Exception): """An error occurred while trying to read a Rate from a file.""" def load_rate(rfile=None): """Try to load a rate of any type. :raises: :class:`.RateFileError`, :class:`.UnsupportedNucleus` """ rate: Rate try: rate = TabularRate(rfile=rfile) except (RateFileError, UnsupportedNucleus): rate = ReacLibRate(rfile=rfile) return rate def _find_rate_file(ratename): """locate the Reaclib or tabular rate or library file given its name. Return None if the file cannot be located, otherwise return its path.""" # check to see if the rate file is in the working dir or # is already the full path x = ratename if os.path.isfile(x): return os.path.realpath(x) # check to see if the rate file is in pynucastro/library x = os.path.join(_pynucastro_rates_dir, ratename) if os.path.isfile(x): return os.path.realpath(x) # check to see if the rate file is in pynucastro/library/tabular x = os.path.join(_pynucastro_tabular_dir, ratename) if os.path.isfile(x): return os.path.realpath(x) # check to see if the rate file is in pynucastro/library/tabular/suzuki x = os.path.join(_pynucastro_suzuki_dir, ratename) if os.path.isfile(x): return os.path.realpath(x) # check to see if the rate file is in pynucastro/library/tabular/langanke x = os.path.join(_pynucastro_langanke_dir, ratename) if os.path.isfile(x): return os.path.realpath(x) # notify user we can't find the file raise RateFileError(f'File {ratename!r} not found in the working directory, {_pynucastro_rates_dir}, or {_pynucastro_tabular_dir}') if numba is not None: Tfactor_spec = [ ('T9', numba.float64), ('T9i', numba.float64), ('T913', numba.float64), ('T913i', numba.float64), ('T953', numba.float64), ('lnT9', numba.float64) ] else: Tfactor_spec = [] @jitclass(Tfactor_spec) class Tfactors: """ precompute temperature factors for speed :param float T: input temperature (Kelvin) :var T9: T / 1.e9 K :var T9i: 1.0 / T9 :var T913i: 1.0 / T9 ** (1/3) :var T913: T9 ** (1/3) :var T953: T9 ** (5/3) :var lnT9: log(T9) """ def __init__(self, T): """ return the Tfactors object. Here, T is temperature in Kelvin """ self.T9 = T/1.e9 self.T9i = 1.0/self.T9 self.T913i = self.T9i**(1./3.) self.T913 = self.T9**(1./3.) self.T953 = self.T9**(5./3.) self.lnT9 = np.log(self.T9) @property def array(self): """return t factors as array in order of lambda function""" return np.array([1, self.T9i, self.T913i, self.T913, self.T9, self.T953, self.lnT9]) class SingleSet: """ a set in Reaclib is one piece of a rate, in the form lambda = exp[ a_0 + sum_{i=1}^5 a_i T_9**(2i-5)/3 + a_6 log T_9] A single rate in Reaclib can be composed of multiple sets :param a: the coefficients of the exponential fit :param labelprops: a collection of flags that classify a ReacLib rate """ def __init__(self, a, labelprops): """here a is iterable (e.g., list or numpy array), storing the coefficients, a0, ..., a6 """ self.a = a self.labelprops = labelprops self.label = None self.resonant = None self.weak = None self.reverse = None self._update_label_properties() def _update_label_properties(self): """ Set label and flags indicating Set is resonant, weak, or reverse. """ assert isinstance(self.labelprops, str) assert len(self.labelprops) == 6 self.label = self.labelprops[0:4] self.resonant = self.labelprops[4] == 'r' self.weak = self.labelprops[4] == 'w' self.reverse = self.labelprops[5] == 'v' def __eq__(self, other): """ Determine whether two SingleSet objects are equal to each other. """ x = True for ai, aj in zip(self.a, other.a): x = x and (ai == aj) x = x and (self.label == other.label) x = x and (self.resonant == other.resonant) x = x and (self.weak == other.weak) x = x and (self.reverse == other.reverse) return x def f(self): """ return a function for rate(tf) where tf is a Tfactors object """ return lambda tf: np.exp(self.a[0] + self.a[1]*tf.T9i + self.a[2]*tf.T913i + self.a[3]*tf.T913 + self.a[4]*tf.T9 + self.a[5]*tf.T953 + self.a[6]*tf.lnT9) def dfdT(self): """ return a function for this dratedT(tf), where tf is a Tfactors object """ # we have lambda = exp(f(T_9)) # so dlambda/dT9 = lambda * df/dT9 # and dlambda/dT = dlambda/dT9 / 1.e9 return lambda tf: self.f()(tf) * (-self.a[1] * tf.T9i * tf.T9i + -(1./3.) * self.a[2] * tf.T913i * tf.T9i + (1./3.) * self.a[3] * tf.T913i * tf.T913i + self.a[4] + (5./3.) * self.a[5] * tf.T913 * tf.T913 + self.a[6] * tf.T9i) / 1.e9 def set_string_py(self, prefix="set", plus_equal=False): """ return a string containing the python code for this set """ if plus_equal: string = f"{prefix} += np.exp( " else: string = f"{prefix} = np.exp( " string += f" {self.a[0]}" if not self.a[1] == 0.0: string += f" + {self.a[1]}*tf.T9i" if not self.a[2] == 0.0: string += f" + {self.a[2]}*tf.T913i" if not self.a[3] == 0.0: string += f" + {self.a[3]}*tf.T913" if not (self.a[4] == 0.0 and self.a[5] == 0.0 and self.a[6] == 0.0): indent = len(prefix)*" " string += f"\n{indent} " if not self.a[4] == 0.0: string += f" + {self.a[4]}*tf.T9" if not self.a[5] == 0.0: string += f" + {self.a[5]}*tf.T953" if not self.a[6] == 0.0: string += f" + {self.a[6]}*tf.lnT9" string += ")" return string def set_string_cxx(self, prefix="set", plus_equal=False, with_exp=True): """ return a string containing the C++ code for this set """ if plus_equal: string = f"{prefix} += " else: string = f"{prefix} = " if with_exp: string += "std::exp( " string += f" {self.a[0]}" if not self.a[1] == 0.0: string += f" + {self.a[1]} * tfactors.T9i" if not self.a[2] == 0.0: string += f" + {self.a[2]} * tfactors.T913i" if not self.a[3] == 0.0: string += f" + {self.a[3]} * tfactors.T913" if not (self.a[4] == 0.0 and self.a[5] == 0.0 and self.a[6] == 0.0): indent = len(prefix)*" " string += f"\n{indent} " if not self.a[4] == 0.0: string += f" + {self.a[4]} * tfactors.T9" if not self.a[5] == 0.0: string += f" + {self.a[5]} * tfactors.T953" if not self.a[6] == 0.0: string += f" + {self.a[6]} * tfactors.lnT9" if with_exp: string += ");" else: string += ";" if all(q == 0.0 for q in self.a[1:]): string += "\namrex::ignore_unused(tfactors);" return string def dln_set_string_dT9_cxx(self, prefix="dset_dT", plus_equal=False): """ return a string containing the C++ code for d/dT9 ln(set) """ if plus_equal: string = f"{prefix} += " else: string = f"{prefix} = " if all(q == 0.0 for q in self.a[1:]): string += "0.0;" return string if not self.a[1] == 0.0: string += f" {-self.a[1]} * tfactors.T9i * tfactors.T9i" if not self.a[2] == 0.0: string += f" + -(1.0/3.0) * {self.a[2]} * tfactors.T943i" if not self.a[3] == 0.0: string += f" + (1.0/3.0) * {self.a[3]} * tfactors.T923i" if not (self.a[4] == 0.0 and self.a[5] == 0.0 and self.a[6] == 0.0): indent = len(prefix)*" " string += f"\n{indent} " if not self.a[4] == 0.0: string += f" + {self.a[4]}" if not self.a[5] == 0.0: string += f" + (5.0/3.0) * {self.a[5]} * tfactors.T923" if not self.a[6] == 0.0: string += f" + {self.a[6]} * tfactors.T9i" string += ";" return string class Rate: """The base reaction rate class. Most rate types will subclass this and extend to their particular format. """ def __init__(self, reactants=None, products=None, Q=None, weak_type=""): """a generic Rate class that acts as a base class for specific sources. Here we only specify the reactants and products and Q value""" self.fname = None if reactants: self.reactants = reactants else: self.reactants = [] if products: self.products = products else: self.products = [] self.label = "generic" self.Q = Q self.weak_type = weak_type self._set_rhs_properties() self._set_screening() self._set_print_representation() self.tabular = False def __repr__(self): return self.string def __hash__(self): return hash(self.__repr__()) def __eq__(self, other): """ Determine whether two Rate objects are equal. They are equal if they contain identical reactants and products""" x = True x = x and (self.reactants == other.reactants) x = x and (self.products == other.products) return x def __lt__(self, other): """sort such that lightest reactants come first, and then look at products""" # this sort will make two nuclei with the same A be in order of Z # (assuming there are no nuclei with A > 999 # we want to compare based on the heaviest first, so we reverse self_react_sorted = sorted(self.reactants, key=lambda x: 1000*x.A + x.Z, reverse=True) other_react_sorted = sorted(other.reactants, key=lambda x: 1000*x.A + x.Z, reverse=True) if self_react_sorted != other_react_sorted: # reactants are different, so now we can check them for srn, orn in zip(self_react_sorted, other_react_sorted): if not srn == orn: return srn < orn else: # reactants are the same, so consider products self_prod_sorted = sorted(self.products, key=lambda x: 1000*x.A + x.Z, reverse=True) other_prod_sorted = sorted(other.products, key=lambda x: 1000*x.A + x.Z, reverse=True) for spn, opn in zip(self_prod_sorted, other_prod_sorted): if not spn == opn: return spn < opn # if we made it here, then the rates are the same return True def _set_q(self): """set the Q value of the reaction (in MeV)""" # from the binding energy of the nuclei, Q = -B_reactants + B_products # but note that nucbind is the binding energy *per* nucleon, so we need # to multiply by the number of nucleons self.Q = 0 for n in self.reactants: self.Q += -n.A * n.nucbind for n in self.products: self.Q += n.A * n.nucbind def _set_print_representation(self): # string is output to the terminal, rid is used as a dict key, # and pretty_string is latex # some rates will have no nuclei particles (e.g. gamma) on the left or # right -- we'll try to infer those here lhs_other = [] rhs_other = [] self.string = "" self.rid = "" self.pretty_string = r"$" # put p, n, and alpha second treactants = [] for n in self.reactants: if n.raw not in ["p", "he4", "n"]: treactants.insert(0, n) else: treactants.append(n) # figure out if there are any non-nuclei present # for the moment, we just handle strong rates # there should be the same number of protons on each side and # the same number of neutrons on each side strong_test = sum(n.Z for n in self.reactants) == sum(n.Z for n in self.products) and \ sum(n.A for n in self.reactants) == sum(n.A for n in self.products) if strong_test: if len(self.products) == 1: rhs_other.append("gamma") else: # this is a weak rate if self.weak_type == "electron_capture": # we assume that all the tabular rates are electron capture for now # we expect an electron on the left -- let's make sure # the charge on the left should be +1 the charge on the right assert sum(n.Z for n in self.reactants) == sum(n.Z for n in self.products) + 1 lhs_other.append("e-") rhs_other.append("nu") elif self.weak_type == "beta_decay": # we expect an electron on the right assert sum(n.Z for n in self.reactants) + 1 == sum(n.Z for n in self.products) rhs_other.append("e-") rhs_other.append("nubar") elif "_pos_" in self.weak_type: # we expect a positron on the right -- let's make sure assert sum(n.Z for n in self.reactants) == sum(n.Z for n in self.products) + 1 rhs_other.append("e+") rhs_other.append("nu") elif "_neg_" in self.weak_type: # we expect an electron on the right -- let's make sure assert sum(n.Z for n in self.reactants) + 1 == sum(n.Z for n in self.products) rhs_other.append("e-") rhs_other.append("nubar") else: # we need to figure out what the rate is. We'll assume that it is # not an electron capture if sum(n.Z for n in self.reactants) == sum(n.Z for n in self.products) + 1: rhs_other.append("e+") rhs_other.append("nu") elif sum(n.Z for n in self.reactants) + 1 == sum(n.Z for n in self.products): rhs_other.append("e-") rhs_other.append("nubar") for n, r in enumerate(treactants): self.string += f"{r.c()}" self.rid += f"{r}" self.pretty_string += fr"{r.pretty}" if not n == len(self.reactants)-1: self.string += " + " self.rid += " + " self.pretty_string += r" + " for o in lhs_other: if o == "e-": self.string += " + e⁻" self.pretty_string += r" + \mathrm{e}^-" self.string += " ⟶ " self.rid += " --> " self.pretty_string += r" \rightarrow " for n, p in enumerate(self.products): self.string += f"{p.c()}" self.rid += f"{p}" self.pretty_string += fr"{p.pretty}" if not n == len(self.products)-1: self.string += " + " self.rid += " + " self.pretty_string += r" + " for o in rhs_other: if o == "gamma": self.string += " + 𝛾" self.pretty_string += r"+ \gamma" elif o == "nu": self.string += " + 𝜈" self.pretty_string += r"+ \nu_e" elif o == "nubar": self.string += " + 𝜈" self.pretty_string += r"+ \bar{\nu}_e" if o == "e-": self.string += " + e⁻" self.pretty_string += r" + \mathrm{e}^-" if o == "e+": self.string += " + e⁺" self.pretty_string += r" + \mathrm{e}^+" self.pretty_string += r"$" def _set_rhs_properties(self): """ compute statistical prefactor and density exponent from the reactants. """ self.prefactor = 1.0 # this is 1/2 for rates like a + a (double counting) self.inv_prefactor = 1 for r in set(self.reactants): self.inv_prefactor = self.inv_prefactor * np.math.factorial(self.reactants.count(r)) self.prefactor = self.prefactor/float(self.inv_prefactor) self.dens_exp = len(self.reactants)-1 if self.weak_type == 'electron_capture': self.dens_exp = self.dens_exp + 1 def _set_screening(self): """ determine if this rate is eligible for screening and the nuclei to use. """ # Tells if this rate is eligible for screening # using screenz.f90 provided by StarKiller Microphysics. # If not eligible for screening, set to None # If eligible for screening, then # Rate.ion_screen is a 2-element (3 for 3-alpha) list of Nucleus objects for screening self.ion_screen = [] nucz = [q for q in self.reactants if q.Z != 0] if len(nucz) > 1: nucz.sort(key=lambda x: x.Z) self.ion_screen = [] self.ion_screen.append(nucz[0]) self.ion_screen.append(nucz[1]) if len(nucz) == 3: self.ion_screen.append(nucz[2]) # if the rate is a reverse rate (defined as Q < 0), then we # might actually want to compute the screening based on the # reactants of the forward rate that was used in the detailed # balance. Rate.symmetric_screen is what should be used in # the screening in this case self.symmetric_screen = [] if self.Q < 0: nucz = [q for q in self.products if q.Z != 0] if len(nucz) > 1: nucz.sort(key=lambda x: x.Z) self.symmetric_screen = [] self.symmetric_screen.append(nucz[0]) self.symmetric_screen.append(nucz[1]) if len(nucz) == 3: self.symmetric_screen.append(nucz[2]) else: self.symmetric_screen = self.ion_screen def cname(self): """a C++-safe version of the rate name""" # replace the "__" separating reactants and products with "_to_" # and convert all other "__" to single "_" return self.fname.replace("__", "_to_", 1).replace("__", "_") def get_rate_id(self): """ Get an identifying string for this rate.""" return f'{self.rid} <{self.label.strip()}>' def heaviest(self): """ Return the heaviest nuclide in this Rate. If two nuclei are tied in mass number, return the one with the lowest atomic number. """ nuc = self.reactants[0] for n in self.reactants + self.products: if n.A > nuc.A or (n.A == nuc.A and n.Z < nuc.Z): nuc = n return nuc def lightest(self): """ Return the lightest nuclide in this Rate. If two nuclei are tied in mass number, return the one with the highest atomic number. """ nuc = self.reactants[0] for n in self.reactants + self.products: if n.A < nuc.A or (n.A == nuc.A and n.Z > nuc.Z): nuc = n return nuc def ydot_string_py(self): """ Return a string containing the term in a dY/dt equation in a reaction network corresponding to this rate. """ ydot_string_components = [] # prefactor if self.prefactor != 1.0: ydot_string_components.append(f"{self.prefactor:1.14e}") # density dependence if self.dens_exp == 1: ydot_string_components.append("rho") elif self.dens_exp != 0: ydot_string_components.append(f"rho**{self.dens_exp}") # electron fraction dependence if self.weak_type == 'electron_capture' and not self.tabular: ydot_string_components.append("ye(Y)") # composition dependence for r in sorted(set(self.reactants)): c = self.reactants.count(r) if c > 1: ydot_string_components.append(f"Y[j{r}]**{c}") else: ydot_string_components.append(f"Y[j{r}]") # rate_eval.{fname} ydot_string_components.append(f"rate_eval.{self.fname}") return "*".join(ydot_string_components) def eval(self, T, rhoY=None): raise NotImplementedError("base Rate class does not know how to eval()") def jacobian_string_py(self, y_i): """ Return a string containing the term in a jacobian matrix in a reaction network corresponding to this rate differentiated with respect to y_i y_i is an object of the class ``Nucleus``. """ if y_i not in self.reactants: return "" jac_string_components = [] # prefactor if self.prefactor != 1.0: jac_string_components.append(f"{self.prefactor:1.14e}") # density dependence if self.dens_exp == 1: jac_string_components.append("rho") elif self.dens_exp != 0: jac_string_components.append(f"rho**{self.dens_exp}") # electron fraction dependence if self.weak_type == 'electron_capture' and not self.tabular: jac_string_components.append("ye(Y)") # composition dependence for r in sorted(set(self.reactants)): c = self.reactants.count(r) if y_i == r: # take the derivative if c == 1: continue if c > 2: jac_string_components.append(f"{c}*Y[j{r}]**{c-1}") elif c == 2: jac_string_components.append(f"2*Y[j{r}]") else: # this nucleus is in the rate form, but we are not # differentiating with respect to it if c > 1: jac_string_components.append(f"Y[j{r}]**{c}") else: jac_string_components.append(f"Y[j{r}]") # rate_eval.{fname} jac_string_components.append(f"rate_eval.{self.fname}") return "*".join(jac_string_components) def eval_jacobian_term(self, T, rho, comp, y_i): """Evaluate drate/d(y_i), y_i is a Nucleus object. This rate term has the full composition and density dependence, i.e.: rate = rho**n Y1**a Y2**b ... N_A <sigma v> The derivative is only non-zero if this term depends on nucleus y_i. """ if y_i not in self.reactants: return 0.0 ymolar = comp.get_molar() # composition dependence Y_term = 1.0 for r in sorted(set(self.reactants)): c = self.reactants.count(r) if y_i == r: # take the derivative if c == 1: continue Y_term *= c * ymolar[r]**(c-1) else: # this nucleus is in the rate form, but we are not # differentiating with respect to it Y_term *= ymolar[r]**c # density dependence dens_term = rho**self.dens_exp # electron fraction dependence if self.weak_type == 'electron_capture' and not self.tabular: y_e_term = comp.eval_ye() else: y_e_term = 1.0 # finally evaluate the rate -- for tabular rates, we need to set rhoY rate_eval = self.eval(T, rhoY=rho*comp.eval_ye()) return self.prefactor * dens_term * y_e_term * Y_term * rate_eval class TableIndex(Enum): """a simple enum-like container for indexing the electron-capture tables""" RHOY = 0 T = 1 MU = 2 DQ = 3 VS = 4 RATE = 5 NU = 6 GAMMA = 7 class ReacLibRate(Rate): """A single reaction rate. Currently, this is a ReacLib rate, which can be composed of multiple sets, or a tabulated electron capture rate. :raises: :class:`.RateFileError`, :class:`.UnsupportedNucleus` """ def __init__(self, rfile=None, chapter=None, original_source=None, reactants=None, products=None, sets=None, labelprops=None, Q=None): """ rfile can be either a string specifying the path to a rate file or an io.StringIO object from which to read rate information. """ # pylint: disable=super-init-not-called self.rfile_path = None self.rfile = None if isinstance(rfile, str): self.rfile_path = _find_rate_file(rfile) self.rfile = os.path.basename(rfile) self.chapter = chapter # the Reaclib chapter for this reaction self.original_source = original_source # the contents of the original rate file self.fname = None if reactants: self.reactants = reactants else: self.reactants = [] if products: self.products = products else: self.products = [] if sets: self.sets = sets else: self.sets = [] # a modified rate is one where we manually changed some of its # properties self.modified = False self.labelprops = labelprops self.approx = False if self.labelprops == "approx": self.approx = True self.derived = False if self.labelprops == "derived": self.derived = True self.label = None self.resonant = None self.weak = None self.weak_type = None self.reverse = None self.removed = None self.Q = Q self.tabular = False if isinstance(rfile, str): # read in the file, parse the different sets and store them as # SingleSet objects in sets[] f = open(self.rfile_path) elif isinstance(rfile, io.StringIO): # Set f to the io.StringIO object f = rfile else: f = None if f: self._read_from_file(f) f.close() else: self._set_label_properties() self._set_rhs_properties() self._set_screening() self._set_print_representation() def _set_print_representation(self): """ compose the string representations of this Rate. """ super()._set_print_representation() if not self.fname: # This is used to determine which rates to detect as the same reaction # from multiple sources in a Library file, so it should not be unique # to a given source, e.g. wc12, but only unique to the reaction. reactants_str = '_'.join([repr(nuc) for nuc in self.reactants]) products_str = '_'.join([repr(nuc) for nuc in self.products]) self.fname = f'{reactants_str}__{products_str}' if self.weak: self.fname += f'__weak__{self.weak_type}' if self.modified: self.fname += "__modified" if self.approx: self.fname += "__approx" if self.derived: self.fname += "__derived" if self.removed: self.fname += "__removed" def modify_products(self, new_products): if not isinstance(new_products, (set, list, tuple)): new_products = [new_products] self.products = [] for p in new_products: if isinstance(p, Nucleus): self.products.append(p) else: self.products.append(Nucleus(p)) self.modified = True # we need to update the Q value and the print string for the rate self._set_q() self._set_screening() self.fname = None # reset so it will be updated self._set_print_representation() def __hash__(self): return hash(self.__repr__()) def __eq__(self, other): """ Determine whether two Rate objects are equal. They are equal if they contain identical reactants and products and if they contain the same SingleSet sets and if their chapters are equal.""" if not isinstance(other, ReacLibRate): return False x = (self.chapter == other.chapter) and (self.products == other.products) and \ (self.reactants == other.reactants) if not x: return x x = len(self.sets) == len(other.sets) if not x: return x for si in self.sets: scomp = False for sj in other.sets: if si == sj: scomp = True break x = x and scomp return x def __add__(self, other): """Combine the sets of two Rate objects if they describe the same reaction. Must be Reaclib rates.""" assert self.reactants == other.reactants assert self.products == other.products assert self.chapter == other.chapter assert isinstance(self.chapter, int) assert self.label == other.label assert self.weak == other.weak assert self.weak_type == other.weak_type assert self.reverse == other.reverse if self.resonant != other.resonant: self._labelprops_combine_resonance() new_rate = ReacLibRate(chapter=self.chapter, original_source='\n'.join([self.original_source, other.original_source]), reactants=self.reactants, products=self.products, sets=self.sets + other.sets, labelprops=self.labelprops, Q=self.Q) return new_rate def _set_label_properties(self, labelprops=None): """ Calls _update_resonance_combined and then _update_label_properties. """ if labelprops: self.labelprops = labelprops # Update labelprops based on the Sets in this Rate # to set the resonance_combined flag properly self._update_resonance_combined() self._update_label_properties() def _update_resonance_combined(self): """ Checks the Sets in this Rate and updates the resonance_combined flag as well as self.labelprops[4] """ sres = [s.resonant for s in self.sets] if True in sres and False in sres: self._labelprops_combine_resonance() def _labelprops_combine_resonance(self): """ Update self.labelprops[4] = 'c'""" llp = list(self.labelprops) llp[4] = 'c' self.labelprops = ''.join(llp) def _update_label_properties(self): """ Set label and flags indicating Rate is resonant, weak, or reverse. """ assert isinstance(self.labelprops, str) if self.labelprops == "approx": self.label = "approx" self.resonant = False self.weak = False self.weak_type = None self.reverse = False elif self.labelprops == "derived": self.label = "derived" self.resonant = False # Derived may be resonant in some cases self.weak = False self.weak_type = None self.reverse = False else: assert len(self.labelprops) == 6 self.label = self.labelprops[0:4] self.resonant = self.labelprops[4] == 'r' self.weak = self.labelprops[4] == 'w' if self.weak: if self.label.strip() == 'ec' or self.label.strip() == 'bec': self.weak_type = 'electron_capture' else: self.weak_type = self.label.strip().replace('+', '_pos_').replace('-', '_neg_') else: self.weak_type = None self.reverse = self.labelprops[5] == 'v' def _read_from_file(self, f): """ given a file object, read rate data from the file. """ lines = f.readlines() f.close() self.original_source = "".join(lines) # first line is the chapter self.chapter = lines[0].strip() self.chapter = int(self.chapter) # remove any blank lines set_lines = [l for l in lines[1:] if not l.strip() == ""] # the rest is the sets first = 1 while len(set_lines) > 0: # check for a new chapter id in case of Reaclib v2 format check_chapter = set_lines[0].strip() try: # see if there is a chapter number preceding the set check_chapter = int(check_chapter) # check that the chapter number is the same as the first # set in this rate file if check_chapter != self.chapter: raise RateFileError(f'read chapter {check_chapter}, expected chapter {self.chapter} for this rate set.') # get rid of chapter number so we can read a rate set set_lines.pop(0) except (TypeError, ValueError): # there was no chapter number, proceed reading a set pass # sets are 3 lines long s1 = set_lines.pop(0) s2 = set_lines.pop(0) s3 = set_lines.pop(0) # first line of a set has up to 6 nuclei, then the label, # and finally the Q value # get rid of first 5 spaces s1 = s1[5:] # next follows 6 fields of 5 characters containing nuclei # the 6 fields are padded with spaces f = [] for i in range(6): ni = s1[:5] s1 = s1[5:] ni = ni.strip() if ni: f.append(ni) # next come 8 spaces, so get rid of them s1 = s1[8:] # next is a 4-character set label and 2 character flags labelprops = s1[:6] s1 = s1[6:] # next come 3 spaces s1 = s1[3:] # next comes a 12 character Q value followed by 10 spaces Q = float(s1.strip()) if first: self.Q = Q # what's left are the nuclei -- their interpretation # depends on the chapter if self.chapter == 1: # e1 -> e2 self.reactants.append(Nucleus.from_cache(f[0])) self.products.append(Nucleus.from_cache(f[1])) elif self.chapter == 2: # e1 -> e2 + e3 self.reactants.append(Nucleus.from_cache(f[0])) self.products += [Nucleus.from_cache(f[1]), Nucleus.from_cache(f[2])] elif self.chapter == 3: # e1 -> e2 + e3 + e4 self.reactants.append(Nucleus.from_cache(f[0])) self.products += [Nucleus.from_cache(f[1]), Nucleus.from_cache(f[2]), Nucleus.from_cache(f[3])] elif self.chapter == 4: # e1 + e2 -> e3 self.reactants += [Nucleus.from_cache(f[0]), Nucleus.from_cache(f[1])] self.products.append(Nucleus.from_cache(f[2])) elif self.chapter == 5: # e1 + e2 -> e3 + e4 self.reactants += [Nucleus.from_cache(f[0]), Nucleus.from_cache(f[1])] self.products += [Nucleus.from_cache(f[2]), Nucleus.from_cache(f[3])] elif self.chapter == 6: # e1 + e2 -> e3 + e4 + e5 self.reactants += [Nucleus.from_cache(f[0]), Nucleus.from_cache(f[1])] self.products += [Nucleus.from_cache(f[2]), Nucleus.from_cache(f[3]), Nucleus.from_cache(f[4])] elif self.chapter == 7: # e1 + e2 -> e3 + e4 + e5 + e6 self.reactants += [Nucleus.from_cache(f[0]), Nucleus.from_cache(f[1])] self.products += [Nucleus.from_cache(f[2]), Nucleus.from_cache(f[3]), Nucleus.from_cache(f[4]), Nucleus.from_cache(f[5])] elif self.chapter == 8: # e1 + e2 + e3 -> e4 self.reactants += [Nucleus.from_cache(f[0]), Nucleus.from_cache(f[1]), Nucleus.from_cache(f[2])] self.products.append(Nucleus.from_cache(f[3])) # support historical format, where chapter 8 also handles what are # now chapter 9 rates if len(f) == 5: self.products.append(Nucleus.from_cache(f[4])) elif self.chapter == 9: # e1 + e2 + e3 -> e4 + e5 self.reactants += [Nucleus.from_cache(f[0]), Nucleus.from_cache(f[1]), Nucleus.from_cache(f[2])] self.products += [Nucleus.from_cache(f[3]), Nucleus.from_cache(f[4])] elif self.chapter == 10: # e1 + e2 + e3 + e4 -> e5 + e6 self.reactants += [Nucleus.from_cache(f[0]), Nucleus.from_cache(f[1]), Nucleus.from_cache(f[2]), Nucleus.from_cache(f[3])] self.products += [Nucleus.from_cache(f[4]), Nucleus.from_cache(f[5])] elif self.chapter == 11: # e1 -> e2 + e3 + e4 + e5 self.reactants.append(Nucleus.from_cache(f[0])) self.products += [Nucleus.from_cache(f[1]), Nucleus.from_cache(f[2]), Nucleus.from_cache(f[3]), Nucleus.from_cache(f[4])] else: raise RateFileError(f'Chapter could not be identified in {self.original_source}') first = 0 # the second line contains the first 4 coefficients # the third lines contains the final 3 # we can't just use split() here, since the fields run into one another n = 13 # length of the field a = [s2[i:i+n] for i in range(0, len(s2), n)] a += [s3[i:i+n] for i in range(0, len(s3), n)] a = [float(e) for e in a if not e.strip() == ""] self.sets.append(SingleSet(a, labelprops=labelprops)) self._set_label_properties(labelprops) def write_to_file(self, f): """ Given a file object, write rate data to the file. """ if self.original_source is None: raise NotImplementedError( f"Original source is not stored for this rate ({self})." " At present, we cannot reconstruct the rate representation without" " storing the original source." ) print(self.original_source, file=f) def get_rate_id(self): """ Get an identifying string for this rate. Don't include resonance state since we combine resonant and non-resonant versions of reactions. """ srev = '' if self.reverse: srev = 'reverse' sweak = '' if self.weak: sweak = 'weak' ssrc = 'reaclib' return f'{self.rid} <{self.label.strip()}_{ssrc}_{sweak}_{srev}>' def function_string_py(self): """ Return a string containing python function that computes the rate """ fstring = "" fstring += "@numba.njit()\n" fstring += f"def {self.fname}(rate_eval, tf):\n" fstring += f" # {self.rid}\n" fstring += " rate = 0.0\n\n" for s in self.sets: fstring += f" # {s.labelprops[0:5]}\n" set_string = s.set_string_py(prefix="rate", plus_equal=True) for t in set_string.split("\n"): fstring += " " + t + "\n" fstring += "\n" fstring += f" rate_eval.{self.fname} = rate\n\n" return fstring def function_string_cxx(self, dtype="double", specifiers="inline", leave_open=False): """ Return a string containing C++ function that computes the rate """ fstring = "" fstring += "template <int do_T_derivatives>\n" fstring += f"{specifiers}\n" fstring += f"void rate_{self.cname()}(const tf_t& tfactors, {dtype}& rate, {dtype}& drate_dT) {{\n\n" fstring += f" // {self.rid}\n\n" fstring += " rate = 0.0;\n" fstring += " drate_dT = 0.0;\n\n" fstring += f" {dtype} ln_set_rate{{0.0}};\n" fstring += f" {dtype} dln_set_rate_dT9{{0.0}};\n" fstring += f" {dtype} set_rate{{0.0}};\n\n" for s in self.sets: fstring += f" // {s.labelprops[0:5]}\n" set_string = s.set_string_cxx(prefix="ln_set_rate", plus_equal=False, with_exp=False) for t in set_string.split("\n"): fstring += " " + t + "\n" fstring += "\n" fstring += " if constexpr (do_T_derivatives) {\n" dln_set_string_dT9 = s.dln_set_string_dT9_cxx(prefix="dln_set_rate_dT9", plus_equal=False) for t in dln_set_string_dT9.split("\n"): fstring += " " + t + "\n" fstring += " }\n" fstring += "\n" fstring += " // avoid underflows by zeroing rates in [0.0, 1.e-100]\n" fstring += " ln_set_rate = std::max(ln_set_rate, -230.0);\n" fstring += " set_rate = std::exp(ln_set_rate);\n" fstring += " rate += set_rate;\n" fstring += " if constexpr (do_T_derivatives) {\n" fstring += " drate_dT += set_rate * dln_set_rate_dT9 / 1.0e9;\n" fstring += " }\n\n" if not leave_open: fstring += "}\n\n" return fstring def eval(self, T, rhoY=None): """ evauate the reaction rate for temperature T """ tf = Tfactors(T) r = 0.0 for s in self.sets: f = s.f() r += f(tf) return r def eval_deriv(self, T, rhoY=None): """ evauate the derivative of reaction rate with respect to T """ _ = rhoY # unused by this subclass tf = Tfactors(T) drdT = 0.0 for s in self.sets: dfdT = s.dfdT() drdT += dfdT(tf) return drdT def get_rate_exponent(self, T0): """ for a rate written as a power law, r = r_0 (T/T0)**nu, return nu corresponding to T0 """ # nu = dln r /dln T, so we need dr/dT r1 = self.eval(T0) dT = 1.e-8*T0 r2 = self.eval(T0 + dT) drdT = (r2 - r1)/dT return (T0/r1)*drdT def plot(self, Tmin=1.e8, Tmax=1.6e9, rhoYmin=3.9e8, rhoYmax=2.e9, figsize=(10, 10)): """plot the rate's temperature sensitivity vs temperature :param float Tmin: minimum temperature for plot :param float Tmax: maximum temperature for plot :param float rhoYmin: minimum electron density to plot (e-capture rates only) :param float rhoYmax: maximum electron density to plot (e-capture rates only) :param tuple figsize: figure size specification for matplotlib :return: a matplotlib figure object :rtype: matplotlib.figure.Figure """ _ = (rhoYmin, rhoYmax) # unused by this subclass fig, ax = plt.subplots(figsize=figsize) temps = np.logspace(np.log10(Tmin), np.log10(Tmax), 100) r = np.zeros_like(temps) for n, T in enumerate(temps): r[n] = self.eval(T) ax.loglog(temps, r) ax.set_xlabel(r"$T$") if self.dens_exp == 0: ax.set_ylabel(r"\tau") elif self.dens_exp == 1: ax.set_ylabel(r"$N_A <\sigma v>$") elif self.dens_exp == 2: ax.set_ylabel(r"$N_A^2 <n_a n_b n_c v>$") ax.set_title(fr"{self.pretty_string}") return fig if numba is not None: interpolator_spec = [ ('data', numba.float64[:, :]), ('table_rhoy_lines', numba.int32), ('table_temp_lines', numba.int32), ('rhoy', numba.float64[:]), ('temp', numba.float64[:]) ] else: interpolator_spec = [] @jitclass(interpolator_spec) class TableInterpolator: """A simple class that holds a pointer to the table data and methods that allow us to interpolate a variable""" def __init__(self, table_rhoy_lines, table_temp_lines, table_data): self.data = table_data self.table_rhoy_lines = table_rhoy_lines self.table_temp_lines = table_temp_lines # for easy indexing, store a 1-d array of T and rhoy self.rhoy = self.data[::self.table_temp_lines, TableIndex.RHOY.value] self.temp = self.data[0:self.table_temp_lines, TableIndex.T.value] def _get_logT_idx(self, logt0): """return the index into the temperatures such that T[i-1] < t0 <= T[i]. We return i-1 here, corresponding to the lower value. Note: we work in terms of log10() """ return max(0, np.searchsorted(self.temp, logt0) - 1) def _get_logT_nearest_idx(self, logt0): """return the index into the temperatures that is closest to the input t0. Note: we work in terms of log10() """ return np.abs(10**self.temp - 10**logt0).argmin() #return np.abs(self.temp - logt0).argmin() def _get_logrhoy_idx(self, logrhoy0): """return the index into rho*Y such that rhoY[i-1] < rhoy0 <= rhoY[i]. We return i-1 here, corresponding to the lower value. Note: we work in terms of log10() """ return max(0, np.searchsorted(self.rhoy, logrhoy0) - 1) def _get_logrhoy_nearest_idx(self, logrhoy0): """return the index into rho*Y that is the closest to the input rhoy. Note: we work in terms of log10() """ return np.abs(10**self.rhoy - 10**logrhoy0).argmin() #return np.abs(self.rhoy - logrhoy0).argmin() def _rhoy_T_to_idx(self, irhoy, jtemp): """given a pair (irhoy, jtemp) into the table, return the 1-d index into the underlying data array assuming row-major ordering""" return irhoy * self.table_temp_lines + jtemp def interpolate(self, logrhoy, logT, component): """given logrhoy and logT, do nearest interpolation to find the value of the data component in the table""" # find the nearest value of T and rhoY in the data table rhoy_index = self._get_logrhoy_nearest_idx(logrhoy) t_index = self._get_logT_nearest_idx(logT) idx = self._rhoy_T_to_idx(rhoy_index, t_index) r = self.data[idx, component] return r class TabularRate(Rate): """A tabular rate. :raises: :class:`.RateFileError`, :class:`.UnsupportedNucleus` """ def __init__(self, rfile=None): """ rfile can be either a string specifying the path to a rate file or an io.StringIO object from which to read rate information. """ super().__init__() self.rfile_path = None self.rfile = None if isinstance(rfile, str): self.rfile_path = _find_rate_file(rfile) self.rfile = os.path.basename(rfile) self.fname = None self.label = "tabular" self.tabular = True # we should initialize this somehow self.weak_type = "" if isinstance(rfile, str): # read in the file, parse the different sets and store them as # SingleSet objects in sets[] f = open(self.rfile_path) elif isinstance(rfile, io.StringIO): # Set f to the io.StringIO object f = rfile else: f = None if f: self._read_from_file(f) f.close() self._set_rhs_properties() self._set_screening() self._set_print_representation() self.get_tabular_rate() self.interpolator = TableInterpolator(self.table_rhoy_lines, self.table_temp_lines, self.tabular_data_table) def __hash__(self): return hash(self.__repr__()) def __eq__(self, other): """ Determine whether two Rate objects are equal. They are equal if they contain identical reactants and products.""" if not isinstance(other, TabularRate): return False return self.reactants == other.reactants and self.products == other.products def __add__(self, other): raise NotImplementedError("addition not defined for tabular rates") def _read_from_file(self, f): """ given a file object, read rate data from the file. """ lines = f.readlines() f.close() self.original_source = "".join(lines) # first line is the chapter self.chapter = lines[0].strip() if self.chapter != "t": raise RateFileError(f"Invalid chapter for TabularRate ({self.chapter})") # remove any blank lines set_lines = [l for l in lines[1:] if not l.strip() == ""] # e1 -> e2, Tabulated s1 = set_lines.pop(0) s2 = set_lines.pop(0) s3 = set_lines.pop(0) s4 = set_lines.pop(0) s5 = set_lines.pop(0) f = s1.split() try: self.reactants.append(Nucleus.from_cache(f[0])) self.products.append(Nucleus.from_cache(f[1])) except UnsupportedNucleus as ex: raise RateFileError(f'Nucleus objects could not be identified in {self.original_source}') from ex self.table_file = s2.strip() self.table_header_lines = int(s3.strip()) self.table_rhoy_lines = int(s4.strip()) self.table_temp_lines = int(s5.strip()) self.table_num_vars = 6 # Hard-coded number of variables in tables for now. self.table_index_name = f'j_{self.reactants[0]}_{self.products[0]}' self.labelprops = 'tabular' # set weak type if "electroncapture" in self.table_file: self.weak_type = "electron_capture" elif "betadecay" in self.table_file: self.weak_type = "beta_decay" def _set_rhs_properties(self): """ compute statistical prefactor and density exponent from the reactants. """ self.prefactor = 1.0 # this is 1/2 for rates like a + a (double counting) self.inv_prefactor = 1 for r in set(self.reactants): self.inv_prefactor = self.inv_prefactor * np.math.factorial(self.reactants.count(r)) self.prefactor = self.prefactor/float(self.inv_prefactor) self.dens_exp = len(self.reactants)-1 def _set_screening(self): """ tabular rates are not currently screened (they are e-capture or beta-decay)""" self.ion_screen = [] self.symmetric_screen = [] if not self.fname: # This is used to determine which rates to detect as the same reaction # from multiple sources in a Library file, so it should not be unique # to a given source, e.g. wc12, but only unique to the reaction. reactants_str = '_'.join([repr(nuc) for nuc in self.reactants]) products_str = '_'.join([repr(nuc) for nuc in self.products]) self.fname = f'{reactants_str}__{products_str}' def get_rate_id(self): """ Get an identifying string for this rate. Don't include resonance state since we combine resonant and non-resonant versions of reactions. """ ssrc = 'tabular' return f'{self.rid} <{self.label.strip()}_{ssrc}>' def function_string_py(self): """ Return a string containing python function that computes the rate """ fstring = "" fstring += "@numba.njit()\n" fstring += f"def {self.fname}(rate_eval, T, rhoY):\n" fstring += f" # {self.rid}\n" fstring += f" {self.fname}_interpolator = TableInterpolator(*{self.fname}_info)\n" fstring += f" r = {self.fname}_interpolator.interpolate(np.log10(rhoY), np.log10(T), TableIndex.RATE.value)\n" fstring += f" rate_eval.{self.fname} = 10.0**r\n\n" return fstring def get_tabular_rate(self): """read the rate data from .dat file """ # find .dat file and read it self.table_path = _find_rate_file(self.table_file) t_data2d = [] with open(self.table_path) as tabular_file: for i, line in enumerate(tabular_file): # skip header lines if i < self.table_header_lines: continue line = line.strip() # skip empty lines if not line: continue # split the column values on whitespace t_data2d.append(line.split()) # convert the nested list of string values into a numpy float array self.tabular_data_table = np.array(t_data2d, dtype=np.float64) def eval(self, T, rhoY=None): """ evauate the reaction rate for temperature T """ r = self.interpolator.interpolate(np.log10(rhoY), np.log10(T), TableIndex.RATE.value) return 10.0**r def get_nu_loss(self, T, rhoY): """ get the neutrino loss rate for the reaction if tabulated""" r = self.interpolator.interpolate(np.log10(rhoY), np.log10(T), TableIndex.NU.value) return r def plot(self, Tmin=1.e8, Tmax=1.6e9, rhoYmin=3.9e8, rhoYmax=2.e9, color_field='rate', figsize=(10, 10)): """plot the rate's temperature sensitivity vs temperature :param float Tmin: minimum temperature for plot :param float Tmax: maximum temperature for plot :param float rhoYmin: minimum electron density to plot (e-capture rates only) :param float rhoYmax: maximum electron density to plot (e-capture rates only) :param tuple figsize: figure size specification for matplotlib :return: a matplotlib figure object :rtype: matplotlib.figure.Figure """ fig, ax = plt.subplots(figsize=figsize) data = self.tabular_data_table inde1 = data[:, TableIndex.T.value] <= np.log10(Tmax) inde2 = data[:, TableIndex.T.value] >= np.log10(Tmin) inde3 = data[:, TableIndex.RHOY.value] <= np.log10(rhoYmax) inde4 = data[:, TableIndex.RHOY.value] >= np.log10(rhoYmin) data_heatmap = data[inde1 & inde2 & inde3 & inde4].copy() rows, row_pos = np.unique(data_heatmap[:, 0], return_inverse=True) cols, col_pos = np.unique(data_heatmap[:, 1], return_inverse=True) pivot_table = np.zeros((len(rows), len(cols)), dtype=data_heatmap.dtype) if color_field == 'rate': icol = TableIndex.RATE.value title = f"{self.weak_type} rate in log10(1/s)" cmap = 'magma' elif color_field == 'nu_loss': icol = TableIndex.NU.value title = "neutrino energy loss rate in log10(erg/s)" cmap = 'viridis' else: raise ValueError("color_field must be either 'rate' or 'nu_loss'.") try: pivot_table[row_pos, col_pos] = data_heatmap[:, icol] except ValueError: print("Divide by zero encountered in log10\nChange the scale of T or rhoY") im = ax.imshow(pivot_table, cmap=cmap) fig.colorbar(im, ax=ax) ax.set_xlabel(r"$\log(T)$ [K]") ax.set_ylabel(r"$\log(\rho Y_e)$ [g/cm$^3$]") ax.set_title(fr"{self.pretty_string}" + "\n" + title) ax.set_yticks(range(len(rows))) ylabels = [f"{q:4.2f}" for q in rows] ax.set_yticklabels(ylabels) ax.set_xticks(range(len(cols))) xlabels = [f"{q:4.2f}" for q in cols] ax.set_xticklabels(xlabels, rotation=90, ha="right", rotation_mode="anchor") ax.invert_yaxis() return fig class DerivedRate(ReacLibRate): """ This class is a derived class from `Rate` with the purpose of computing the inverse rate by the application of detailed balance to the forward reactions. """ def __init__(self, rate, compute_Q=False, use_pf=False): self.use_pf = use_pf self.rate = rate self.compute_Q = compute_Q if not isinstance(rate, Rate): raise TypeError('rate must be a Rate subclass') if (isinstance(rate, TabularRate) or self.rate.weak or self.rate.reverse): raise ValueError('The rate is reverse or weak or tabular') for nuc in self.rate.reactants: if not nuc.spin_states: raise ValueError('One of the reactants spin ground state, is not defined') for nuc in self.rate.products: if not nuc.spin_states: raise ValueError('One of the products spin ground state, is not defined') derived_sets = [] for ssets in self.rate.sets: a = ssets.a prefactor = 0.0 Q = 0.0 prefactor += -np.log(N_a) * (len(self.rate.reactants) - len(self.rate.products)) for nucr in self.rate.reactants: prefactor += 1.5*np.log(nucr.A) + np.log(nucr.spin_states) Q += nucr.A_nuc for nucp in self.rate.products: prefactor += -1.5*np.log(nucp.A) - np.log(nucp.spin_states) Q -= nucp.A_nuc if self.compute_Q: Q = Q * amu_mev else: Q = self.rate.Q prefactor += np.log(self.counter_factors()[1]) - np.log(self.counter_factors()[0]) if len(self.rate.reactants) == len(self.rate.products): prefactor += 0.0 else: F = (amu * k_B * 1.0e5 / (2.0*np.pi*hbar**2))**(1.5*(len(self.rate.reactants) - len(self.rate.products))) prefactor += np.log(F) a_rev = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] a_rev[0] = prefactor + a[0] a_rev[1] = a[1] - Q / (1.0e9 * k_B_mev_k) a_rev[2] = a[2] a_rev[3] = a[3] a_rev[4] = a[4] a_rev[5] = a[5] a_rev[6] = a[6] + 1.5*(len(self.rate.reactants) - len(self.rate.products)) sset_d = SingleSet(a=a_rev, labelprops=rate.labelprops) derived_sets.append(sset_d) super().__init__(rfile=self.rate.rfile, chapter=self.rate.chapter, original_source=self.rate.original_source, reactants=self.rate.products, products=self.rate.reactants, sets=derived_sets, labelprops="derived", Q=-Q) def eval(self, T, rhoY=None): r = super().eval(T=T, rhoY=rhoY) z_r = 1.0 z_p = 1.0 if self.use_pf: for nuc in set(self.rate.reactants + self.rate.products): if not nuc.partition_function and str(nuc) != 'h1' and str(nuc) != 'n' and str(nuc) != 'he4' and str(nuc) != 'p': print(f'WARNING: {nuc} partition function is not supported by tables: set pf = 1.0 by default') for nucr in self.rate.reactants: if not nucr.partition_function: continue #nucr.partition_function = lambda T: 1.0 z_r *= nucr.partition_function.eval(T) for nucp in self.rate.products: if not nucp.partition_function: continue #nucp.partition_function = lambda T: 1.0 z_p *= nucp.partition_function.eval(T) return r*z_r/z_p return r def function_string_py(self): """ Return a string containing python function that computes the rate """ for nuc in set(self.rate.reactants + self.rate.products): if not nuc.partition_function and str(nuc) not in ['h1', 'n', 'he4', 'p']: print(f'WARNING: {nuc} partition function is not supported by tables: set pf = 1.0 by default') fstring = super().function_string_py() if self.use_pf: fstring += "\n" for nuc in set(self.rate.reactants + self.rate.products): if nuc.partition_function: fstring += f" # interpolating {nuc} partition function\n" fstring += f" {nuc}_pf_exponent = np.interp(tf.T9, xp={nuc}_temp_array, fp=np.log10({nuc}_pf_array))\n" fstring += f" {nuc}_pf = 10.0**{nuc}_pf_exponent\n" else: fstring += f" # setting {nuc} partition function to 1.0 by default, independent of T\n" fstring += f" {nuc}_pf = 1.0\n" fstring += "\n" fstring += " " fstring += "z_r = " fstring += "*".join([f"{nucr}_pf" for nucr in self.rate.reactants]) fstring += "\n" fstring += " " fstring += "z_p = " fstring += "*".join([f"{nucp}_pf" for nucp in self.rate.products]) fstring += "\n" fstring += f" rate_eval.{self.fname} *= z_r/z_p\n" return fstring def function_string_cxx(self, dtype="double", specifiers="inline", leave_open=False): """ Return a string containing C++ function that computes the rate """ for nuc in set(self.rate.reactants + self.rate.products): if not nuc.partition_function and str(nuc) not in ['h1', 'n', 'he4', 'p']: print(f'WARNING: {nuc} partition function is not supported by tables: set pf = 1.0 by default') fstring = super().function_string_cxx(dtype=dtype, specifiers=specifiers, leave_open=True) # right now we have rate and drate_dT without the partition function # now the partition function corrections if self.use_pf: fstring += "\n" for nuc in set(self.rate.reactants + self.rate.products): fstring += f" Real {nuc}_pf, d{nuc}_pf_dT;\n" if nuc.partition_function: fstring += f" // interpolating {nuc} partition function\n" fstring += f" get_partition_function({nuc.cindex()}, tfactors, {nuc}_pf, d{nuc}_pf_dT);\n" else: fstring += f" // setting {nuc} partition function to 1.0 by default, independent of T\n" fstring += f" {nuc}_pf = 1.0_rt;\n" fstring += f" d{nuc}_pf_dT = 0.0_rt;\n" fstring += "\n" fstring += " Real z_r = " fstring += " * ".join([f"{nucr}_pf" for nucr in self.rate.reactants]) fstring += ";\n" fstring += " Real z_p = " fstring += " * ".join([f"{nucp}_pf" for nucp in self.rate.products]) fstring += ";\n\n" # now the derivatives, via chain rule chain_terms = [] for n in self.rate.reactants: chain_terms.append(" * ".join([f"{nucr}_pf" for nucr in self.rate.reactants if nucr != n] + [f"d{n}_pf_dT"])) fstring += " Real dz_r_dT = " fstring += " + ".join(chain_terms) fstring += ";\n" chain_terms = [] for n in self.rate.products: chain_terms.append(" * ".join([f"{nucp}_pf" for nucp in self.rate.products if nucp != n] + [f"d{n}_pf_dT"])) fstring += " Real dz_p_dT = " fstring += " + ".join(chain_terms) fstring += ";\n\n" fstring += " Real dzterm_dT = (z_p * dz_r_dT - z_r * dz_p_dT) / (z_p * z_p);\n\n" # final terms fstring += " drate_dT = dzterm_dT * rate + drate_dT * (z_r / z_p);\n" fstring += " rate *= z_r/z_p;\n\n" if not leave_open: fstring += "}\n\n" return fstring def counter_factors(self): """This function returns the nucr! = nucr_1! * ... * nucr_r! for each repeated nucr reactant and nucp! = nucp_1! * ... * nucp_p! for each reactant nucp product in a ordered pair (nucr!, nucp!). The factors nucr! and nucp! avoid overcounting when more than one nuclei is involve in the reaction, otherwise it will return 1.0. """ react_counts = Counter(self.rate.reactants) prod_counts = Counter(self.rate.products) reactant_factor = 1.0 for nuc in set(self.rate.reactants): reactant_factor *= np.math.factorial(react_counts[nuc]) product_factor = 1.0 for nuc in set(self.rate.products): product_factor *= np.math.factorial(prod_counts[nuc]) return (reactant_factor, product_factor) class RatePair: """the forward and reverse rates for a single reaction sequence. Forward rates are those with Q >= 0. :var forward: the forward reaction Rate object :var reverse: the reverse reaction Rate object """ def __init__(self, forward=None, reverse=None): self.forward = forward self.reverse = reverse def __repr__(self): return f"forward: {self.forward} ; reverse: {self.reverse}" def __lt__(self, other): if self.forward is not None and other.forward is not None: return self.forward < other.forward if self.forward is None: return False return True def __eq__(self, other): return self.forward == other.forward and self.reverse == other.reverse class ApproximateRate(ReacLibRate): def __init__(self, primary_rate, secondary_rates, primary_reverse, secondary_reverse, is_reverse=False, approx_type="ap_pg"): """the primary rate has the same reactants and products and the final approximate rate would have. The secondary rates are ordered such that together they would give the same sequence""" self.primary_rate = primary_rate self.secondary_rates = secondary_rates self.primary_reverse = primary_reverse self.secondary_reverse = secondary_reverse self.is_reverse = is_reverse self.approx_type = approx_type if self.approx_type == "ap_pg": # an ap_pg approximate rate combines A(a,g)B and A(a,p)X(p,g)B into a # single effective rate by assuming proton equilibrium. assert len(secondary_rates) == 2 # make sure that the primary forward rate makes sense # this should be A(a,g)B assert Nucleus("he4") in self.primary_rate.reactants and len(self.primary_rate.products) == 1 # we are going to define the product A and reactant B from this reaction self.primary_reactant = max(self.primary_rate.reactants) self.primary_product = max(self.primary_rate.products) # the first secondary rate should be A(a,p)X, where X is the # intermediate nucleus assert (self.primary_reactant in self.secondary_rates[0].reactants and Nucleus("he4") in self.secondary_rates[0].reactants and Nucleus("p") in self.secondary_rates[0].products) # the intermediate nucleus is not in our network, so make it # dummy self.intermediate_nucleus = max(self.secondary_rates[0].products) #self.intermediate_nucleus.dummy = True # now the second secondary rate show be X(p,g)B assert (self.intermediate_nucleus in self.secondary_rates[1].reactants and Nucleus("p") in self.secondary_rates[1].reactants and self.primary_product in secondary_rates[1].products) # now ensure that the reverse rate makes sense # the primary reverse rate is B(g,a)A assert (self.primary_product in self.primary_reverse.reactants and self.primary_reactant in self.primary_reverse.products) # now the first secondary reverse rate should be B(g,p)X assert (self.primary_product in self.secondary_reverse[0].reactants and self.intermediate_nucleus in secondary_reverse[0].products and Nucleus("p") in secondary_reverse[0].products) # and the second secondary reverse rate should be X(p,a)A assert (self.intermediate_nucleus in self.secondary_reverse[1].reactants and Nucleus("p") in self.secondary_reverse[1].reactants and self.primary_reactant in self.secondary_reverse[1].products and Nucleus("he4") in self.secondary_reverse[1].products) # now initialize the super class with these reactants and products if not self.is_reverse: super().__init__(reactants=[self.primary_reactant, Nucleus("he4")], products=[self.primary_product], labelprops="approx", chapter=-1) else: super().__init__(reactants=[self.primary_product], products=[self.primary_reactant, Nucleus("he4")], labelprops="approx", chapter=-1) else: raise NotImplementedError(f"approximation type {self.approx_type} not supported") # update the Q value self._set_q() def get_child_rates(self): """return a list of all of the rates that are used in this approximation""" tlist = [self.primary_rate] tlist += self.secondary_rates tlist += [self.primary_reverse] tlist += self.secondary_reverse return tlist def _set_screening(self): # the individual rates are screened -- we don't screen the combination of them pass def eval(self, T, rhoY=None): """evaluate the approximate rate""" if self.approx_type == "ap_pg": if not self.is_reverse: # pylint: disable=no-else-return # the approximate forward rate is r_ag + r_ap r_pg / (r_pg + r_pa) r_ag = self.primary_rate.eval(T) r_ap = self.secondary_rates[0].eval(T) r_pg = self.secondary_rates[1].eval(T) r_pa = self.secondary_reverse[1].eval(T) return r_ag + r_ap * r_pg / (r_pg + r_pa) else: # the approximate reverse rate is r_ga + r_pa r_gp / (r_pg + r_pa) r_ga = self.primary_reverse.eval(T) r_gp = self.secondary_reverse[0].eval(T) r_pa = self.secondary_reverse[1].eval(T) r_pg = self.secondary_rates[1].eval(T) return r_ga + r_pa * r_gp / (r_pg + r_pa) raise NotImplementedError(f"approximation type {self.approx_type} not supported") def function_string_py(self): """ Return a string containing python function that computes the approximate rate """ if self.approx_type != "ap_pg": raise NotImplementedError("don't know how to work with this approximation") string = "" string += "@numba.njit()\n" string += f"def {self.fname}(rate_eval, tf):\n" if not self.is_reverse: # first we need to get all of the rates that make this up string += f" r_ag = rate_eval.{self.primary_rate.fname}\n" string += f" r_ap = rate_eval.{self.secondary_rates[0].fname}\n" string += f" r_pg = rate_eval.{self.secondary_rates[1].fname}\n" string += f" r_pa = rate_eval.{self.secondary_reverse[1].fname}\n" # now the approximation string += " rate = r_ag + r_ap * r_pg / (r_pg + r_pa)\n" else: # first we need to get all of the rates that make this up string += f" r_ga = rate_eval.{self.primary_reverse.fname}\n" string += f" r_pa = rate_eval.{self.secondary_reverse[1].fname}\n" string += f" r_gp = rate_eval.{self.secondary_reverse[0].fname}\n" string += f" r_pg = rate_eval.{self.secondary_rates[1].fname}\n" # now the approximation string += " rate = r_ga + r_pa * r_gp / (r_pg + r_pa)\n" string += f" rate_eval.{self.fname} = rate\n\n" return string def function_string_cxx(self, dtype="double", specifiers="inline", leave_open=False): """ Return a string containing C++ function that computes the approximate rate """ if self.approx_type != "ap_pg": raise NotImplementedError("don't know how to work with this approximation") fstring = "" fstring = "template <typename T>\n" fstring += f"{specifiers}\n" fstring += f"void rate_{self.cname()}(const T& rate_eval, {dtype}& rate, {dtype}& drate_dT) {{\n\n" if not self.is_reverse: # first we need to get all of the rates that make this up fstring += f" {dtype} r_ag = rate_eval.screened_rates(k_{self.primary_rate.cname()});\n" fstring += f" {dtype} r_ap = rate_eval.screened_rates(k_{self.secondary_rates[0].cname()});\n" fstring += f" {dtype} r_pg = rate_eval.screened_rates(k_{self.secondary_rates[1].cname()});\n" fstring += f" {dtype} r_pa = rate_eval.screened_rates(k_{self.secondary_reverse[1].cname()});\n" # now the approximation fstring += f" {dtype} dd = 1.0_rt / (r_pg + r_pa);\n" fstring += " rate = r_ag + r_ap * r_pg * dd;\n" fstring += " if constexpr (std::is_same<T, rate_derivs_t>::value) {\n" fstring += f" {dtype} drdT_ag = rate_eval.dscreened_rates_dT(k_{self.primary_rate.cname()});\n" fstring += f" {dtype} drdT_ap = rate_eval.dscreened_rates_dT(k_{self.secondary_rates[0].cname()});\n" fstring += f" {dtype} drdT_pg = rate_eval.dscreened_rates_dT(k_{self.secondary_rates[1].cname()});\n" fstring += f" {dtype} drdT_pa = rate_eval.dscreened_rates_dT(k_{self.secondary_reverse[1].cname()});\n" fstring += " drate_dT = drdT_ag + drdT_ap * r_pg * dd + r_ap * drdT_pg * dd - r_ap * r_pg * dd * dd * (drdT_pg + drdT_pa);\n" fstring += " }\n" else: # first we need to get all of the rates that make this up fstring += f" {dtype} r_ga = rate_eval.screened_rates(k_{self.primary_reverse.cname()});\n" fstring += f" {dtype} r_pa = rate_eval.screened_rates(k_{self.secondary_reverse[1].cname()});\n" fstring += f" {dtype} r_gp = rate_eval.screened_rates(k_{self.secondary_reverse[0].cname()});\n" fstring += f" {dtype} r_pg = rate_eval.screened_rates(k_{self.secondary_rates[1].cname()});\n" # now the approximation fstring += f" {dtype} dd = 1.0_rt / (r_pg + r_pa);\n" fstring += " rate = r_ga + r_gp * r_pa * dd;\n" fstring += " if constexpr (std::is_same<T, rate_derivs_t>::value) {\n" fstring += f" {dtype} drdT_ga = rate_eval.dscreened_rates_dT(k_{self.primary_reverse.cname()});\n" fstring += f" {dtype} drdT_pa = rate_eval.dscreened_rates_dT(k_{self.secondary_reverse[1].cname()});\n" fstring += f" {dtype} drdT_gp = rate_eval.dscreened_rates_dT(k_{self.secondary_reverse[0].cname()});\n" fstring += f" {dtype} drdT_pg = rate_eval.dscreened_rates_dT(k_{self.secondary_rates[1].cname()});\n" fstring += " drate_dT = drdT_ga + drdT_gp * r_pa * dd + r_gp * drdT_pa * dd - r_gp * r_pa * dd * dd * (drdT_pg + drdT_pa);\n" fstring += " }\n" if not leave_open: fstring += "}\n\n" return fstring
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,746
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/tests/test_python_partition_functions.py
import importlib import os import sys import pytest import pynucastro as pyna class TestPythonPartitionNetwork: @pytest.fixture(scope="class") def pynet(self, reaclib_library): fwd_reactions = reaclib_library.derived_forward() nuclei = ["p", "he4", "fe52", "ni56", "co55"] fwd_rates_lib = fwd_reactions.linking_nuclei(nuclist=nuclei, with_reverse=False) derived = [] for r in fwd_rates_lib.get_rates(): d = pyna.DerivedRate(rate=r, compute_Q=False, use_pf=True) derived.append(d) der_rates_lib = pyna.Library(rates=derived) full_lib = fwd_rates_lib + der_rates_lib return pyna.PythonNetwork(libraries=[full_lib]) def test_partition_rates(self, pynet): """test the rate evaluation with partition functions from the python network""" pynet.write_network("der_net.py") der_net = importlib.import_module("der_net") T = 5.e9 tf = pyna.Tfactors(T) rate_eval = der_net.RateEval() der_net.p_co55__he4_fe52__derived(rate_eval, tf) der_net.ni56__p_co55__derived(rate_eval, tf) assert rate_eval.p_co55__he4_fe52__derived == pytest.approx(4.570999237208017, rel=1.e-10) assert rate_eval.ni56__p_co55__derived == pytest.approx(23790871.179938074, rel=1.e-10) T = 9.e9 tf = pyna.Tfactors(T) rate_eval = der_net.RateEval() der_net.p_co55__he4_fe52__derived(rate_eval, tf) der_net.ni56__p_co55__derived(rate_eval, tf) assert rate_eval.p_co55__he4_fe52__derived == pytest.approx(15485.753590182012, rel=1.e-10) assert rate_eval.ni56__p_co55__derived == pytest.approx(428973340937.6744, rel=1.e-10) # clean up generated files if the test passed os.remove("der_net.py") # remove imported module from cache del der_net del sys.modules["der_net"]
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,747
pynucastro/pynucastro
refs/heads/main
/pynucastro/nucdata/partition_function.py
import os import numpy as np from scipy.interpolate import InterpolatedUnivariateSpline class PartitionFunction: """ This class holds the tabulated data for the partition function for a specific nucleus, which can be combined with other (non-overlapping) partition functions by addition and evaluated for different temperature values. Adding two PartitionFunction objects is implemented by simply appending the temperature and partition function arrays of the higher-temperature partition function to those of the lower-temperature partition function. If the temperature ranges overlap, however, an exception is generated. If either of the PartitionFunction objects added have already had a spline interpolant constructed, then construct a new spline interpolant for the returned PartitionFunction of order equal to the maximum order of the added PartitionFunction objects. :var nucleus: a string composed by a lowercase element and the atomic number, e.g. ``"ni56"`` :var name: the name of the table on which the nucleus is read :var temperature: a sorted array of all the temperatures involved :var partition_function: an array with all the partition function values given in the same order as ``temperature`` :var interpolant_order: the interpolation spline order, must be between 1 and 5, inclusive """ def __init__(self, nucleus, name, temperature, partition_function, interpolant_order=3): assert isinstance(nucleus, str) temperature = np.asarray(temperature) partition_function = np.asarray(partition_function) assert temperature.shape == partition_function.shape assert np.all(temperature[:-1] <= temperature[1:]), "temperature array must be sorted" self.nucleus = nucleus self.name = name self.temperature = temperature self.partition_function = partition_function self.interpolant_order = interpolant_order self._interpolant = None def lower_partition(self): """Return the partition function value for :meth:`lower_temperature`.""" return self.partition_function[0] def upper_partition(self): """Return the partition function value for :meth:`upper_temperature`.""" return self.partition_function[-1] def lower_temperature(self): """Return the lowest temperature this object supports.""" return self.temperature[0] def upper_temperature(self): """Return the highest temperature this object supports.""" return self.temperature[-1] def __add__(self, other): assert self.nucleus == other.nucleus if self.upper_temperature() < other.lower_temperature(): lower = self upper = other else: lower = other upper = self if lower.upper_temperature() >= upper.lower_temperature(): raise ValueError("temperature ranges cannot overlap") temperature = np.concatenate([lower.temperature, upper.temperature]) partition_function = np.concatenate([lower.partition_function, upper.partition_function]) name = f'{lower.name}+{upper.name}' order = max(self.interpolant_order, other.interpolant_order) newpf = PartitionFunction(nucleus=self.nucleus, name=name, temperature=temperature, partition_function=partition_function, interpolant_order=order) return newpf def __eq__(self, other): return (np.all(self.partition_function == other.partition_function) and np.all(self.temperature == other.temperature)) def construct_spline_interpolant(self, order=3): """ Construct an interpolating univariate spline of order >= 1 and order <= 5 using the scipy InterpolatedUnivariateSpline implementation. Interpolate in log space for the partition function and in GK for temperature. """ self._interpolant = None self.interpolant_order = order def eval(self, T): """Return the interpolated partition function value for the temperature T.""" # lazily construct the interpolant object, since it's pretty expensive if not self._interpolant: self._interpolant = InterpolatedUnivariateSpline( self.temperature/1.0e9, np.log10(self.partition_function), k=self.interpolant_order ) try: T = float(T)/1.0e9 except ValueError: print("invalid temperature") raise return 10**self._interpolant(T, ext='const') # extrapolates keeping the boundaries fixed. class PartitionFunctionTable: """ Class for reading a partition function table file. A :class:`PartitionFunction` object is constructed for each nucleus and stored in a dictionary keyed by the lowercase nucleus name in the form e.g. "ni56". The table files are stored in the ``PartitionFunction`` subdirectory. :var name: the name of the table (as defined in the data file) :var temperatures: an array of temperature values """ def __init__(self, file_name): self._partition_function = {} self.name = None self.temperatures = None self._read_table(file_name) def _add_nuclide_pfun(self, nuc, pfun): assert isinstance(nuc, str) assert nuc not in self._partition_function self._partition_function[nuc] = pfun def get_nuclei(self): """Return a set of the nuclei this table supports.""" return set(self._partition_function) def get_partition_function(self, nuc): """Return the :class:`PartitionFunction` object for a specific nucleus.""" assert isinstance(nuc, str) if nuc in self._partition_function: return self._partition_function[nuc] return None def _read_table(self, file_name): with open(file_name, 'r') as fin: # get headers name fhead = fin.readline() hsplit = fhead.split('name: ') self.name = hsplit[-1].strip('\n') # throw away the six subsequent lines for _ in range(6): fin.readline() # Now, we want to read the lines of the file where # the temperatures are located temp_strings = fin.readline().strip().split() self.temperatures = np.array(temp_strings, dtype=np.float64) # Now, we append on the array lines = [] all the remaining file, the structure # 1. The nucleus # 2. The partition value relative to the nucleus defined in 1. lines = [] for line in fin: ls = line.strip() if ls: lines.append(ls) # Using .pop(0) twice we construct each nucleus partition function. while lines: nuc = lines.pop(0) pfun_strings = lines.pop(0).split() partitionfun = np.array(pfun_strings, dtype=np.float64) pfun = PartitionFunction(nuc, self.name, self.temperatures, partitionfun) self._add_nuclide_pfun(nuc, pfun) class PartitionFunctionCollection: """ This class holds a collection of :class:`PartitionFunctionTable` objects in a dictionary keyed by the name of the tables. In our discussion we have two different sets of tables: FRDM and ETFSI-Q. :var use_high_temperatures: whether to incorporate the high-temperature data tables :var use_set: selects between the FRDM (``'frdm'``) and ETFSI-Q (``'etfsiq'``) data sets. """ def __init__(self, use_high_temperatures=True, use_set='frdm'): self._partition_function_tables = {} self.use_high_temperatures = use_high_temperatures self.use_set = use_set self._read_collection() def _add_table(self, table): """Add a PartitionFunctionTable to this collection.""" assert table.name not in self._partition_function_tables self._partition_function_tables[table.name] = table def _read_collection(self): """Read and construct all the tables from the data files.""" nucdata_dir = os.path.dirname(os.path.realpath(__file__)) partition_function_dir = os.path.join(nucdata_dir, 'PartitionFunction') pft = PartitionFunctionTable(file_name=os.path.join(partition_function_dir, 'etfsiq_low.txt')) self._add_table(pft) pft = PartitionFunctionTable(file_name=os.path.join(partition_function_dir, 'frdm_low.txt')) self._add_table(pft) pft = PartitionFunctionTable(file_name=os.path.join(partition_function_dir, 'etfsiq_high.txt')) self._add_table(pft) pft = PartitionFunctionTable(file_name=os.path.join(partition_function_dir, 'frdm_high.txt')) self._add_table(pft) def get_nuclei(self): """Return a set of all the nuclei this collection supports.""" nuclei = set() for table in self._partition_function_tables.values(): nuclei.update(table.get_nuclei()) return nuclei def __iter__(self): for nuc in self.get_nuclei(): yield self.get_partition_function(nuc) def get_partition_function(self, nuc): """Return the :class:`PartitionFunction` object for a specific nucleus.""" assert isinstance(nuc, str) if self.use_set == 'frdm': pf_lo_table = self._partition_function_tables['frdm_low'] pf_lo = pf_lo_table.get_partition_function(nuc) pf_hi_table = self._partition_function_tables['frdm_high'] pf_hi = pf_hi_table.get_partition_function(nuc) elif self.use_set == 'etfsiq': pf_lo_table = self._partition_function_tables['etfsiq_low'] pf_lo = pf_lo_table.get_partition_function(nuc) pf_hi_table = self._partition_function_tables['etfsiq_high'] pf_hi = pf_hi_table.get_partition_function(nuc) else: raise ValueError("invalid partition function type") if self.use_high_temperatures: if pf_lo and pf_hi: pf = pf_lo + pf_hi elif pf_lo: pf = pf_lo elif pf_hi: pf = pf_hi else: #name = 'default' #pf_default = PartitionFunction(nuc, name, pf_lo_table.temperatures, np.ones_like(pf_lo_table.temperatures)) #pf = pf_default raise ValueError #if str(nuc) != 'h1' and str(nuc) != 'n' and str(nuc) != 'he4': # print(f'WARNING: {nuc} partition function is not supported: set pf = 1.0 by default') else: if pf_lo: pf = pf_lo else: raise ValueError #name = 'default' #pf_default = PartitionFunction(nuc, name, pf_lo_table.temperatures, np.ones_like(pf_lo_table.temperatures)) #pf = pf_default #if str(nuc) != 'p' and str(nuc) != 'n' and str(nuc) != 'he4': # print(f'WARNING: {nuc} partition function is not supported: set pf = 1.0 by default') return pf
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,748
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/tests/test_networks.py
# unit tests for networks import pytest from pytest import approx from pynucastro import networks from pynucastro.nucdata import Nucleus class TestComposition: @pytest.fixture(scope="class") def nuclei(self): return [Nucleus("h1"), Nucleus("he4"), Nucleus("c12"), Nucleus("o16"), Nucleus("n14"), Nucleus("ca40")] @pytest.fixture(scope="class") def comp(self, nuclei): return networks.Composition(nuclei) def test_solar(self, comp): comp.set_solar_like() xsum = sum(comp.X.values()) assert xsum == approx(1.0) assert comp.X[Nucleus("h1")] == approx(0.7) def test_set_all(self, nuclei, comp): val = 1.0/len(nuclei) comp.set_all(1.0/len(nuclei)) for n in nuclei: assert comp.X[n] == val def test_set_nuc(self, nuclei, comp): n = nuclei[0] comp.set_nuc(n.raw, 0.55) assert comp.X[n] == 0.55 def test_get_molar(self, comp): comp.set_solar_like(Z=0.02) molar = comp.get_molar() assert molar[Nucleus("he4")] == approx((0.3-0.02)/4.0) class TestRateCollection: @pytest.fixture(scope="class") def rc(self): files = ["c12-pg-n13-ls09", "c13-pg-n14-nacr", "n13--c13-wc12", "n13-pg-o14-lg06", "n14-pg-o15-im05", "n15-pa-c12-nacr", "o14--n14-wc12", "o15--n15-wc12"] return networks.RateCollection(files) def test_nuclei(self, rc): nuc = rc.get_nuclei() assert nuc == [Nucleus("p"), Nucleus("he4"), Nucleus("c12"), Nucleus("c13"), Nucleus("n13"), Nucleus("n14"), Nucleus("n15"), Nucleus("o14"), Nucleus("o15")] def test_eval(self, rc): c = networks.Composition(rc.unique_nuclei) c.set_solar_like() rates = {"c12 + p --> n13 <ls09_reaclib__>": 4.3825344233265815e-05, "c13 + p --> n14 <nacr_reaclib__>": 0.00012943869407433355, "n13 --> c13 <wc12_reaclib_weak_>": 2.5475016632596765e-07, "n13 + p --> o14 <lg06_reaclib__>": 4.8517620910445875e-06, "n14 + p --> o15 <im05_reaclib__>": 9.8137074572314962e-07, "n15 + p --> he4 + c12 <nacr_reaclib__>": 0.087518552257659241, "o14 --> n14 <wc12_reaclib_weak_>": 2.0036691481625654e-06, "o15 --> n15 <wc12_reaclib_weak_>": 1.0822012944765837e-06} rv = rc.evaluate_rates(1.e4, 1.e8, c) for r in rv: assert rv[r] == approx(rates[r.get_rate_id()]) def test_overview(self, rc): ostr = """ p consumed by: C12 + p ⟶ N13 + 𝛾 C13 + p ⟶ N14 + 𝛾 N13 + p ⟶ O14 + 𝛾 N14 + p ⟶ O15 + 𝛾 N15 + p ⟶ He4 + C12 produced by: he4 consumed by: produced by: N15 + p ⟶ He4 + C12 c12 consumed by: C12 + p ⟶ N13 + 𝛾 produced by: N15 + p ⟶ He4 + C12 c13 consumed by: C13 + p ⟶ N14 + 𝛾 produced by: N13 ⟶ C13 + e⁺ + 𝜈 n13 consumed by: N13 ⟶ C13 + e⁺ + 𝜈 N13 + p ⟶ O14 + 𝛾 produced by: C12 + p ⟶ N13 + 𝛾 n14 consumed by: N14 + p ⟶ O15 + 𝛾 produced by: C13 + p ⟶ N14 + 𝛾 O14 ⟶ N14 + e⁺ + 𝜈 n15 consumed by: N15 + p ⟶ He4 + C12 produced by: O15 ⟶ N15 + e⁺ + 𝜈 o14 consumed by: O14 ⟶ N14 + e⁺ + 𝜈 produced by: N13 + p ⟶ O14 + 𝛾 o15 consumed by: O15 ⟶ N15 + e⁺ + 𝜈 produced by: N14 + p ⟶ O15 + 𝛾 """ assert rc.network_overview().replace(" ", "").strip() == ostr.replace(" ", "").strip()
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,749
pynucastro/pynucastro
refs/heads/main
/pynucastro/reduction/reduction.py
#!/usr/bin/env python3 import argparse import sys import time from collections import namedtuple import numpy as np from pynucastro import Composition, Nucleus from pynucastro.reduction import drgep, mpi_importer, sens_analysis from pynucastro.reduction.generate_data import dataset from pynucastro.reduction.load_network import load_network MPI = mpi_importer() def _wrap_conds(conds): """Return [conds] if conds has 1 dimension, and give back conds otherwise.""" try: _ = conds[0] try: _ = conds[0][0] return conds except IndexError: return [conds] except IndexError: raise ValueError('Conditions must be non-empty subscriptable object') from None NetInfo = namedtuple("NetInfo", "y ydot z a ebind m") def get_net_info(net, comp, rho, T): y_dict = comp.get_molar() # Can alternatively use the NumPy-based method (evaluate_ydots_arr) ydots_dict = net.evaluate_ydots(rho, T, comp) y = np.zeros(len(net.unique_nuclei), dtype=np.float64) ydot = np.zeros(len(net.unique_nuclei), dtype=np.float64) z = np.zeros(len(net.unique_nuclei), dtype=np.float64) a = np.zeros(len(net.unique_nuclei), dtype=np.float64) ebind = np.zeros(len(net.unique_nuclei), dtype=np.float64) m = np.zeros(len(net.unique_nuclei), dtype=np.float64) mass_neutron = 1.67492721184e-24 mass_proton = 1.67262163783e-24 c_light = 2.99792458e10 for i, n in enumerate(net.unique_nuclei): y[i] = y_dict[n] ydot[i] = ydots_dict[n] z[i] = n.Z a[i] = n.A ebind[i] = n.nucbind or 0.0 m[i] = mass_proton * n.Z + mass_neutron * n.N - ebind[i] / c_light**2 return NetInfo(y, ydot, z, a, ebind, m) def enuc_dot(net_info): """Calculate the nuclear energy generation rate.""" avo = 6.0221417930e23 c_light = 2.99792458e10 return -np.sum(net_info.ydot * net_info.m) * avo * c_light**2 def ye_dot(net_info): """Calculate the time rate of change of electron fraction.""" y, ydot, z, a, _, _ = net_info norm_fac = np.sum(y * a) return np.sum(ydot * z) / norm_fac - np.sum(y * z) / norm_fac**2 * np.sum(ydot * a) def abar_dot(net_info): """Calculate the time rate of change of mean molecular weight.""" abar_inv = np.sum(net_info.y) return -1 / abar_inv**2 * np.sum(net_info.ydot) def map_comp(comp, net): """Create new composition object with nuclei in net, and copy their mass fractions over.""" comp_new = Composition(net.unique_nuclei) for nuc in comp_new.X: comp_new.X[nuc] = comp.X[nuc] return comp_new def rel_err(x, x0): """Compute the relative error between two NumPy arrays.""" return np.abs((x - x0) / x0) def get_errfunc_enuc(net_old, conds): """Function for computing error in nuclear energy generation.""" enucdot_list = [] for comp, rho, T in conds: net_info_old = get_net_info(net_old, comp, rho, T) enucdot_list.append(enuc_dot(net_info_old)) def erf(net_new): err = 0.0 for cond, enucdot_old in zip(conds, enucdot_list): net_info_new = get_net_info(net_new, *cond) enucdot_new = enuc_dot(net_info_new) err = max(err, rel_err(enucdot_new, enucdot_old)) return err return erf def main(): #----------------------------------- # Setup parser and process arguments #----------------------------------- description = "Example/test script for running a selected reduction algorithm." algorithm_help = "The algorithm to use. Currently only supports 'drgep'." endpoint_help = "The nucleus to use as an endpoint in the unreduced network." datadim_help = """The dimensions of the dataset to generate. Ordering is the number of densities, then temperatures, then metallicities. Default is [4, 4, 4].""" drho_help = "Number of density points to include in the dataset." dtemp_help = "Number of temperature points to include in the dataset." dmetal_help = "Number of metallicity points to include in the dataset." brho_help = "Range of densities to include in the dataset (in g/cm^3)." btemp_help = "Range of temperatures to include in the dataset (in K)." bmetal_help = """Range of metallicities to include in the dataset. Half of the metallicity will be in C12, and the rest will be divided evenly among the remaining nuclei.""" library_help = "Name of the library to use to load the network." targets_help = """Target nuclei to use for the algorithm. Will be protons and the endpoint by default.""" tol_help = """Tolerance(s) to use for the algorithm. Will be [1e-3] + [1e-2]*(len(targets)-1) by default for 'drgep'.""" use_mpi_help = "Enable MPI for this run." use_numpy_help = """If the algorithm has a 'use_numpy' option, turn it on. Some algorithms always run as if use_numpy=True.""" sa_help = "Error threshold to use when performing sensitivity analysis." parser = argparse.ArgumentParser(description=description) parser.add_argument('-a', '--algorithm', default='drgep', help=algorithm_help) parser.add_argument('-e', '--endpoint', default=Nucleus('te108'), type=Nucleus, help=endpoint_help) parser.add_argument('-d', '--datadim', nargs=3, default=[4]*3, help=datadim_help) parser.add_argument('-dr', '--drho', type=int, help=drho_help) parser.add_argument('-dt', '--dtemp', help=dtemp_help) parser.add_argument('-dz', '--dmetal', type=int, help=dmetal_help) parser.add_argument('-br', '--brho', nargs=2, type=float, help=brho_help) parser.add_argument('-bt', '--btemp', nargs=2, type=float, help=btemp_help) parser.add_argument('-bz', '--bmetal', nargs=2, type=float, help=bmetal_help) parser.add_argument('-l', '--library', default="rp-process-lib", help=library_help) parser.add_argument('-t', '--targets', nargs='*', type=Nucleus, help=targets_help) parser.add_argument('--tol', nargs='*', type=float, help=tol_help) parser.add_argument('--use_mpi', action='store_true', help=use_mpi_help) parser.add_argument('--use_numpy', action='store_true', help=use_numpy_help) parser.add_argument('-s', '--sens_analysis', default=0.05, type=float, help=sa_help) args = parser.parse_args(sys.argv[1:]) args.algorithm = args.algorithm.lower() if args.algorithm == 'drgep': alg = drgep permute = not args.use_numpy else: raise ValueError(f'Algorithm {args.algorithm} is not supported.') if args.drho: args.datadim[0] = args.drho if args.dtemp: args.datadim[1] = args.dtemp if args.dmetal: args.datadim[2] = args.dmetal if not args.targets: args.targets = [Nucleus('p'), args.endpoint] if not args.tol: if args.algorithm == 'drgep': args.tol = [1e-3] + [1e-2] * (len(args.targets)-1) else: if args.algorithm == 'drgep': if len(args.tol) == 1: args.tol = [args.tol] * len(args.targets) elif len(args.tol) != len(args.targets): raise ValueError( f"For '{args.algorithm}', there should be one tolerance for" " each target nucleus." ) #----------------------------- # Load the network and dataset #----------------------------- net = load_network(args.endpoint, library_name=args.library) data = list(dataset(net, args.datadim, permute, args.brho, args.btemp, args.bmetal)) #----------------------------- # Prepare to run the algorithm #----------------------------- alg_args = \ { 'net': net, 'conds': data, 'targets': args.targets, 'tols': args.tol, 'returnobj': 'nuclei', 'use_mpi': args.use_mpi, 'use_numpy': args.use_numpy } if args.algorithm == 'drgep': args.algorithm = args.algorithm.upper() #------------------ # Run the algorithm #------------------ if args.use_mpi and MPI.COMM_WORLD.Get_rank() == 0: print(f"Commencing reduction with {MPI.COMM_WORLD.Get_size()} processes.\n") elif not args.use_mpi: print("Commencing reduction without MPI.\n") t0 = time.time() nuclei = alg(**alg_args) dt = time.time() - t0 red_net = net.linking_nuclei(nuclei) second_data = list(dataset(net, args.datadim, True, args.brho, args.btemp, args.bmetal)) errfunc = get_errfunc_enuc(net, second_data) if not args.use_mpi or MPI.COMM_WORLD.Get_rank() == 0: print() print(f"{args.algorithm} reduction took {dt:.3f} s.") print("Number of species in full network: ", len(net.unique_nuclei)) print(f"Number of species in {args.algorithm} reduced network: ", len(nuclei)) print("Reduced Network Error:", f"{errfunc(red_net)*100:.2f}%") print() # Perform sensitivity analysis if args.use_mpi: MPI.COMM_WORLD.Barrier() t0 = time.time() red_net = sens_analysis(red_net, errfunc, args.sens_analysis, args.use_mpi) dt = time.time() - t0 if not args.use_mpi or MPI.COMM_WORLD.Get_rank() == 0: print(f"Greedy sensitivity analysis reduction took {dt:.3f} s.") print(f"Number of species in {args.algorithm} + sensitivity analysis reduced network: ", len(red_net.unique_nuclei)) print("Error: ", f"{errfunc(red_net)*100:.2f}%") if __name__ == "__main__": main()
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,750
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/tests/test_derived_network.py
# unit tests for rates import numpy as np import pytest import pynucastro as pyna class TestPythonDerivedNetwork: @pytest.fixture(scope='class') def pynet(self, reaclib_library): fwd_reactions = reaclib_library.derived_forward() intermediate_nuclei = ['cr48', 'mn51', 'fe52', 'ni56', 'p', 'n', 'he4', 'co55'] beta_decay_modes = ['fe54', 'fe55', 'fe54', 'fe56', 'cr56', 'mn56'] all_nuclei = intermediate_nuclei + beta_decay_modes fwd_rates_lib = fwd_reactions.linking_nuclei(nuclist=all_nuclei, with_reverse=False) derived = [] for r in fwd_rates_lib.get_rates(): d = pyna.rates.DerivedRate(rate=r, compute_Q=False, use_pf=True) derived.append(d) der_rates_lib = pyna.Library(rates=derived) full_library = fwd_rates_lib + der_rates_lib pynet = pyna.PythonNetwork(libraries=full_library) return pynet def test_num_rates(self, pynet): assert len(pynet.rates) == 28 def test_num_reaclib_rates(self, pynet): assert len(pynet.reaclib_rates) == 14 def test_num_derived_rates(self, pynet): assert len(pynet.derived_rates) == 14 def test_full_ydot_string(self, pynet): ostr = \ """dYdt[jcr48] = ( -rho*Y[jhe4]*Y[jcr48]*rate_eval.he4_cr48__fe52 -rho*Y[jhe4]*Y[jcr48]*rate_eval.he4_cr48__p_mn51 +Y[jfe52]*rate_eval.fe52__he4_cr48__derived +rho*Y[jp]*Y[jmn51]*rate_eval.p_mn51__he4_cr48__derived ) """ assert pynet.full_ydot_string(pyna.Nucleus("cr48")) == ostr def test_approx_function_string(self, pynet): dispute_values = np.array([61.72798916565748, 61.72798916565747]) ostr = [""" """, """ """] for i in range(2): ostr[i] = \ """@numba.njit() def fe52__p_mn51__derived(rate_eval, tf): # fe52 --> p + mn51 rate = 0.0 # ths8r rate += np.exp( {:.14f} + -85.6326403498911*tf.T9i + -36.1825*tf.T913i + 0.873042*tf.T913 + -2.89731*tf.T9 + 0.364394*tf.T953 + 0.833333*tf.lnT9) rate_eval.fe52__p_mn51__derived = rate # interpolating mn51 partition function mn51_pf_exponent = np.interp(tf.T9, xp=mn51_temp_array, fp=np.log10(mn51_pf_array)) mn51_pf = 10.0**mn51_pf_exponent # setting p partition function to 1.0 by default, independent of T p_pf = 1.0 # interpolating fe52 partition function fe52_pf_exponent = np.interp(tf.T9, xp=fe52_temp_array, fp=np.log10(fe52_pf_array)) fe52_pf = 10.0**fe52_pf_exponent z_r = p_pf*mn51_pf z_p = fe52_pf rate_eval.fe52__p_mn51__derived *= z_r/z_p """.format(dispute_values[i]) r = pynet.get_rate("fe52__p_mn51__derived") assert r.function_string_py() == ostr[0] or r.function_string_py() == ostr[1]
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,751
pynucastro/pynucastro
refs/heads/main
/pynucastro/nucdata/elements.py
class Element: def __init__(self, abbreviation, name, Z): self.abbreviation = abbreviation self.name = name self.Z = Z class UnidentifiedElement(Exception): pass class PeriodicTable: table = {'h': Element('h', 'hydrogen', 1), 'he': Element('he', 'helium', 2), 'li': Element('li', 'lithium', 3), 'be': Element('be', 'beryllium', 4), 'b': Element('b', 'boron', 5), 'c': Element('c', 'carbon', 6), 'n': Element('n', 'nitrogen', 7), 'o': Element('o', 'oxygen', 8), 'f': Element('f', 'fluorine', 9), 'ne': Element('ne', 'neon', 10), 'na': Element('na', 'sodium', 11), 'mg': Element('mg', 'magnesium', 12), 'al': Element('al', 'aluminum', 13), 'si': Element('si', 'silicon', 14), 'p': Element('p', 'phosphorus', 15), 's': Element('s', 'sulfur', 16), 'cl': Element('cl', 'chlorine', 17), 'ar': Element('ar', 'argon', 18), 'k': Element('k', 'potassium', 19), 'ca': Element('ca', 'calcium', 20), 'sc': Element('sc', 'scandium', 21), 'ti': Element('ti', 'titanium', 22), 'v': Element('v', 'vanadium', 23), 'cr': Element('cr', 'chromium', 24), 'mn': Element('mn', 'manganese', 25), 'fe': Element('fe', 'iron', 26), 'co': Element('co', 'cobalt', 27), 'ni': Element('ni', 'nickel', 28), 'cu': Element('cu', 'copper', 29), 'zn': Element('zn', 'zinc', 30), 'ga': Element('ga', 'gallium', 31), 'ge': Element('ge', 'germanium', 32), 'as': Element('as', 'arsenic', 33), 'se': Element('se', 'selenium', 34), 'br': Element('br', 'bromine', 35), 'kr': Element('kr', 'krypton', 36), 'rb': Element('rb', 'rubidium', 37), 'sr': Element('sr', 'strontium', 38), 'y': Element('y', 'yttrium', 39), 'zr': Element('zr', 'zirconium', 40), 'nb': Element('nb', 'niobium', 41), 'mo': Element('mo', 'molybdenum', 42), 'tc': Element('tc', 'technetium', 43), 'ru': Element('ru', 'ruthenium', 44), 'rh': Element('rh', 'rhodium', 45), 'pd': Element('pd', 'palladium', 46), 'ag': Element('ag', 'silver', 47), 'cd': Element('cd', 'cadmium', 48), 'in': Element('in', 'indium', 49), 'sn': Element('sn', 'tin', 50), 'sb': Element('sb', 'antimony', 51), 'te': Element('te', 'tellurium', 52), 'i': Element('i', 'iodine', 53), 'xe': Element('xe', 'xenon', 54), 'cs': Element('cs', 'cesium', 55), 'ba': Element('ba', 'barium', 56), 'la': Element('la', 'lanthanum', 57), 'ce': Element('ce', 'cerium', 58), 'pr': Element('pr', 'praseodymium', 59), 'nd': Element('nd', 'neodymium', 60), 'pm': Element('pm', 'promethium', 61), 'sm': Element('sm', 'samarium', 62), 'eu': Element('eu', 'europium', 63), 'gd': Element('gd', 'gadolinium', 64), 'tb': Element('tb', 'terbium', 65), 'dy': Element('dy', 'dysprosium', 66), 'ho': Element('ho', 'holmium', 67), 'er': Element('er', 'erbium', 68), 'tm': Element('tm', 'thulium', 69), 'yb': Element('yb', 'ytterbium', 70), 'lu': Element('lu', 'lutetium', 71), 'hf': Element('hf', 'hafnium', 72), 'ta': Element('ta', 'tantalum', 73), 'w': Element('w', 'tungsten', 74), 're': Element('re', 'rhenium', 75), 'os': Element('os', 'osmium', 76), 'ir': Element('ir', 'iridium', 77), 'pt': Element('pt', 'platinum', 78), 'au': Element('au', 'gold', 79), 'hg': Element('hg', 'mercury', 80), 'tl': Element('tl', 'thallium', 81), 'pb': Element('pb', 'lead', 82), 'bi': Element('bi', 'bismuth', 83), 'po': Element('po', 'polonium', 84), 'at': Element('at', 'astatine', 85), 'rn': Element('rn', 'radon', 86), 'fr': Element('fr', 'francium', 87), 'ra': Element('ra', 'radium', 88), 'ac': Element('ac', 'actinium', 89), 'th': Element('th', 'thorium', 90), 'pa': Element('pa', 'protactinium', 91), 'u': Element('u', 'uranium', 92), 'np': Element('np', 'neptunium', 93), 'pu': Element('pu', 'plutonium', 94), 'am': Element('am', 'americium', 95), 'cm': Element('cm', 'curium', 96), 'bk': Element('bk', 'berkelium', 97), 'cf': Element('cf', 'californium', 98), 'es': Element('es', 'einsteinium', 99), 'fm': Element('fm', 'fermium', 100), 'md': Element('md', 'mendelevium', 101), 'no': Element('no', 'nobelium', 102), 'lr': Element('lr', 'lawrencium', 103), 'rf': Element('rf', 'rutherfordium', 104), 'db': Element('db', 'dubnium', 105), 'sg': Element('sg', 'seaborgium', 106), 'bh': Element('bh', 'bohrium', 107), 'hs': Element('hs', 'hassium', 108), 'mt': Element('mt', 'meitnerium', 109), 'ds': Element('ds', 'darmstadtium', 110), 'rg': Element('rg', 'roentgenium', 111), 'cn': Element('cn', 'copernicium', 112), 'nh': Element('nh', 'nihonium', 113), 'fl': Element('fl', 'flerovium', 114), 'mc': Element('mc', 'moscovium', 115), 'lv': Element('lv', 'livermorium', 116), 'ts': Element('ts', 'tennessine', 117), 'og': Element('og', 'oganesson', 118)} @classmethod def lookup_abbreviation(cls, abbrev): try: return cls.table[abbrev.lower()] except IndexError: raise UnidentifiedElement(f'Could not identify element: {abbrev}') from None @classmethod def lookup_Z(cls, Z): for element in cls.table.values(): if element.Z == Z: return element return None
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,752
pynucastro/pynucastro
refs/heads/main
/examples/CNO/burn.py
import matplotlib.pyplot as plt import numpy as np from scipy.integrate import ode import cno_rhs as cno def burn(Y0, rho, T, tmax, nsave): r = ode(cno.rhs).set_integrator("vode", method="bdf", with_jacobian=False, atol=1.e-8, rtol=1.e-8, nsteps = 1500000, order=5) #, min_step=dt) t = 0.0 r.set_initial_value(Y0, t) r.set_f_params(rho, T) dt = tmax/nsave t_out = [] H_out = [] He_out = [] O14_out = [] O15_out = [] print(t, Y0[cno.jp], Y0[cno.jo14]) istep = 1 while r.successful() and istep <= nsave: r.integrate(t+dt*istep) if r.successful(): print(r.t, r.y[cno.jp], r.y[cno.jo14]) t_out.append(r.t) H_out.append(r.y[cno.jp]) He_out.append(r.y[cno.jhe4]) O14_out.append(r.y[cno.jo14]) O15_out.append(r.y[cno.jo15]) istep = istep + 1 else: print(f"An integration error occurred at time {r.t}") return t_out, H_out, He_out, O14_out, O15_out if __name__ == "__main__": # initialize as mass fractions first Y0 = np.zeros((cno.nnuc), dtype=np.float64) Y0[cno.jp] = 0.7 Y0[cno.jhe4] = 0.28 Y0[cno.jc12] = 0.02 Y0[:] = Y0[:]/cno.A[:] rho = 10000.0 T = 1.e8 # estimate the H destruction time Ydot = cno.rhs(0.0, Y0, rho, T) tmax = 10.0*np.abs(Y0[cno.jp]/Ydot[cno.jp]) print(f"tmax: {tmax}") nsteps = 100 t, Y_H, Y_He, Y_O14, Y_O15 = burn(Y0, rho, T, tmax, nsteps) plt.loglog(t, np.array(Y_H)*cno.A[cno.jp], label="H1") plt.loglog(t, np.array(Y_He)*cno.A[cno.jhe4], label="He4") plt.loglog(t, np.array(Y_O14)*cno.A[cno.jo14], label="O14") plt.loglog(t, np.array(Y_O15)*cno.A[cno.jo15], label="O15") plt.xlabel("time [s]") plt.ylabel("mass fraction, X") plt.legend(frameon=False) plt.savefig("burn.png")
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,753
pynucastro/pynucastro
refs/heads/main
/setup.py
from setuptools import setup, find_packages setup(name='pynucastro', description='A python library for nuclear astrophysics', long_description=open('README.md', 'r').read(), long_description_content_type='text/markdown', url='https://github.com/pynucastro/pynucastro', author='pynucastro development group', author_email='michael.zingale@stonybrook.edu', license='BSD', packages=find_packages(), package_data={"pynucastro": ["library/*", "library/tabular/*", "library/tabular/suzuki/*", "library/tabular/langanke/*", "templates/*", "templates/amrexastro-cxx-microphysics/*", "templates/simple-cxx-network/*", "nucdata/*", "nucdata/AtomicMassEvaluation/*", "nucdata/PartitionFunction/*"]}, install_requires=['networkx', 'numpy', 'sympy', 'scipy', 'matplotlib', 'ipywidgets'], extras_require={"numba": ["numba"]}, use_scm_version={"version_scheme": "post-release", "write_to": "pynucastro/_version.py"}, setup_requires=["setuptools_scm"], zip_safe=False)
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,754
pynucastro/pynucastro
refs/heads/main
/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py
# unit test for C++ network with derived rates using partition functions import shutil import pytest import pynucastro as pyna from pynucastro.networks.tests.helpers import compare_network_files class TestAmrexAstroCxxNetwork: @pytest.fixture(scope="class") def fn(self, reaclib_library): # based on the partition_test network in Microphysics nuclei = ["p", "he4", "fe52", "ni56", "co55"] lib = reaclib_library.linking_nuclei(nuclist=nuclei, with_reverse=False) fwd_rates = [] derived = [] for r in lib.get_rates(): try: d = pyna.DerivedRate(rate=r, compute_Q=False, use_pf=True) except ValueError: continue fwd_rates.append(r) derived.append(d) fwd_rates_lib = pyna.Library(rates=fwd_rates) der_rates_lib = pyna.Library(rates=derived) full_lib = fwd_rates_lib + der_rates_lib return pyna.AmrexAstroCxxNetwork(libraries=[full_lib]) def test_write_network(self, fn): """ test the write_network function""" test_path = "_test_cxx_derived/" # subdirectory of pynucastro/networks/tests/ reference_path = "_amrexastro_cxx_derived_reference/" # files that will be ignored if present in the generated directory skip_files = [] # remove any previously generated files shutil.rmtree(test_path, ignore_errors=True) fn.write_network(odir=test_path) compare_network_files(test_path, reference_path, skip_files) # clean up generated files if the test passed shutil.rmtree(test_path)
{"/pynucastro/reduction/__init__.py": ["/pynucastro/reduction/drgep.py", "/pynucastro/reduction/reduction_utils.py", "/pynucastro/reduction/sensitivity_analysis.py"], "/pynucastro/networks/tests/_python_reference/network.py": ["/pynucastro/rates/__init__.py", "/pynucastro/screening/__init__.py", "/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_screening.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2000.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_net2.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_approx_screening.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/python_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/library.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/rate.py"], "/pynucastro/rates/tests/test_library.py": ["/pynucastro/__init__.py"], "/pynucastro/nucdata/__init__.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/nucleus.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/logo/logo_base.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/tests/test_full_python_net.py": ["/pynucastro/__init__.py"], "/examples/rp-process/rp_process.py": ["/pynucastro/rates/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/networks/__init__.py"], "/pynucastro/rates/tests/conftest.py": ["/pynucastro/networks/tests/conftest.py"], "/pynucastro/networks/base_cxx_network.py": ["/pynucastro/networks/rate_collection.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/networks/tests/conftest.py": ["/pynucastro/__init__.py"], "/pynucastro/rates/tests/test_ratefilter.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/tests/test_screen.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/nucdata/tests/test_partition.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/screening/screen.py": ["/pynucastro/rates/rate.py"], "/pynucastro/networks/simple_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py"], "/pynucastro/__init__.py": ["/pynucastro/screening/__init__.py", "/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/reduction/generate_data.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/nucdata/tests/test_nucleus.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/PartitionFunction/convert_rathpf_2003.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/nucdata/nucleus.py": ["/pynucastro/nucdata/binding_table.py", "/pynucastro/nucdata/elements.py", "/pynucastro/nucdata/mass_table.py", "/pynucastro/nucdata/partition_function.py", "/pynucastro/nucdata/spin_table.py"], "/pynucastro/networks/tests/test_validate.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/__init__.py": ["/pynucastro/networks/amrexastro_cxx_network.py", "/pynucastro/networks/base_cxx_network.py", "/pynucastro/networks/python_network.py", "/pynucastro/networks/rate_collection.py", "/pynucastro/networks/simple_cxx_network.py", "/pynucastro/networks/sympy_network_support.py"], "/pynucastro/rates/tests/test_jacobian_term.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_nse.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/load_network.py": ["/pynucastro/networks/__init__.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_approx_rate.py": ["/pynucastro/__init__.py"], "/pynucastro/reduction/drgep.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/sympy_network_support.py": ["/pynucastro/rates/__init__.py"], "/pynucastro/rates/tests/test_rates.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_dupes.py": ["/pynucastro/__init__.py"], "/.github/workflows/simple_cxx_network/test_simple_cxx.py": ["/pynucastro/__init__.py"], "/pynucastro/screening/__init__.py": ["/pynucastro/screening/screen.py"], "/pynucastro/networks/tests/test_python_net.py": ["/pynucastro/__init__.py"], "/examples/CNO/cno.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/rate_collection.py": ["/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py", "/pynucastro/rates/library.py", "/pynucastro/screening/__init__.py", "/pynucastro/screening/screen.py"], "/pynucastro/nucdata/tests/test_spin.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_rc_jacobian.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_approx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/nucdata/tests/test_mass.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/sensitivity_analysis.py": ["/pynucastro/reduction/reduction_utils.py"], "/pynucastro/networks/tests/test_approx_python_net.py": ["/pynucastro/__init__.py", "/pynucastro/screening/__init__.py"], "/pynucastro/rates/__init__.py": ["/pynucastro/rates/library.py", "/pynucastro/rates/rate.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_simple_cxx_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"], "/pynucastro/networks/tests/test_rate_collection.py": ["/pynucastro/__init__.py"], "/examples/triple-alpha/triple-alpha-cxx.py": ["/pynucastro/networks/__init__.py"], "/pynucastro/networks/amrexastro_cxx_network.py": ["/pynucastro/networks/base_cxx_network.py", "/pynucastro/nucdata/__init__.py", "/pynucastro/rates/__init__.py"], "/pynucastro/nucdata/tests/test_binding.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/rates/rate.py": ["/pynucastro/nucdata/__init__.py"], "/pynucastro/networks/tests/test_python_partition_functions.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_networks.py": ["/pynucastro/__init__.py", "/pynucastro/nucdata/__init__.py"], "/pynucastro/reduction/reduction.py": ["/pynucastro/__init__.py", "/pynucastro/reduction/__init__.py", "/pynucastro/reduction/generate_data.py", "/pynucastro/reduction/load_network.py"], "/pynucastro/networks/tests/test_derived_network.py": ["/pynucastro/__init__.py"], "/pynucastro/networks/tests/test_cxx_amrexastro_derived_net.py": ["/pynucastro/__init__.py", "/pynucastro/networks/tests/helpers.py"]}
46,778
evinceng/mvc
refs/heads/master
/Controller.py
# -*- coding: utf-8 -*- """ Created on Wed Apr 04 13:13:48 2018 @author: evin """ import Model import View import Tkinter as Tk import matplotlib.animation as animation class Controller(): def __init__(self): self.root = Tk.Tk() self.model=Model.Model() self.view=View.View(self.root) self.view.sidepanel.plotBut.bind("<Button>",self.my_plot) self.view.sidepanel.clearButton.bind("<Button>",self.clear) def run(self): self.root.title("MVC") self.root.deiconify() self.root.mainloop() def clear(self,event): self.view.ax0.clear() self.view.fig.canvas.draw() def my_plot(self,event): ani = animation.FuncAnimation(self.view.fig, self.model.calculate(), interval=1000) self.view.ax0.clear() self.view.ax0.plot(self.model.xs,self.model.ys) self.view.fig.canvas.draw()
{"/Controller.py": ["/Model.py", "/View.py"]}
46,779
evinceng/mvc
refs/heads/master
/View.py
# -*- coding: utf-8 -*- """ Created on Wed Apr 04 13:12:21 2018 @author: evin """ import Tkinter as Tk from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import matplotlib.pyplot as plt class View(): def __init__(self, master): self.frame = Tk.Frame(master) self.fig = plt.figure() self.ax0 = self.fig.add_subplot(1,1,1) self.frame.pack(side=Tk.LEFT, fill=Tk.BOTH, expand=1) self.sidepanel=SidePanel(master) self.canvas = FigureCanvasTkAgg(self.fig, master=self.frame) self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.canvas.show() class SidePanel(): def __init__(self, root): self.frame2 = Tk.Frame( root ) self.frame2.pack(side=Tk.LEFT, fill=Tk.BOTH, expand=1) self.plotBut = Tk.Button(self.frame2, text="Start ") self.plotBut.pack(side="top",fill=Tk.BOTH) self.clearButton = Tk.Button(self.frame2, text="Stop") self.clearButton.pack(side="top",fill=Tk.BOTH)
{"/Controller.py": ["/Model.py", "/View.py"]}
46,780
evinceng/mvc
refs/heads/master
/Model.py
# -*- coding: utf-8 -*- """ Created on Wed Apr 04 13:13:48 2018 @author: evin """ import time from random import randint import collections class Model(): def __init__(self): self.xs=collections.deque(5*[0], 5) self.ys=collections.deque(5*[0], 5) def calculate(self): self.xs.append(time.strftime("%H:%M:%S")) self.ys.append(randint(0,10))
{"/Controller.py": ["/Model.py", "/View.py"]}
46,798
asymworks/fitbit2influx
refs/heads/main
/fitbit2influx/error.py
# Fitbit2Influx Error Classes class Error(Exception): '''Base Class for Fitbit2Influx Errors''' default_code = 500 def __init__(self, *args, **kwargs): self.status_code = kwargs.pop( 'status_code', self.__class__.default_code ) super(Error, self).__init__(*args, **kwargs) class AuthError(Error): '''Base Class for Authentication/Authorization Errors''' pass class Unauthorized(AuthError): '''Exception raised when access to a resource is not allowed''' pass class ConfigError(Error): ''' Exception raised for invalid or missing configuration values. .. attribute:: config_key :type: str Configuration key which is missing or invalid ''' def __init__(self, *args, config_key=None): super(ConfigError, self).__init__(*args) self.config_key = config_key class ApiError(Error): '''Exception Raised when the Fitbit API returns an error''' @classmethod def from_response(cls, json): '''Construct an API Error from a JSON Response''' if 'success' not in json: return ApiError('Unexpected Response') if json['success']: return ApiError('Success') if 'errors' not in json: return ApiError('Unknown Error') if len(json['errors']) == 1: err_type = json['errors'][0].get('errorType', 'unknown') err_msg = json['errors'][0].get('message', '(no message)') return ApiError(f'{err_msg} ({err_type})') errs = '\n'.join([ f'{e.get("message", "[no message]")} ' f'({e.get("errorType", "unknown")})' for e in json['errors'] ]) return ApiError(f'Multiple API Errors: {errs}') class NeedAuthError(Error): '''Exception Raised when the client has not authorized with Fitbit''' pass
{"/fitbit2influx/scheduler.py": ["/fitbit2influx/influx.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/blueprints/status.py": ["/fitbit2influx/influx.py", "/fitbit2influx/scheduler.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/wsgi.py": ["/fitbit2influx/factory.py"], "/fitbit2influx/factory.py": ["/fitbit2influx/__init__.py"], "/fitbit2influx/blueprints/oauth.py": ["/fitbit2influx/error.py"], "/fitbit2influx/service/fitbit.py": ["/fitbit2influx/error.py", "/fitbit2influx/service/oauth.py"], "/fitbit2influx/service/oauth.py": ["/fitbit2influx/error.py"]}
46,799
asymworks/fitbit2influx
refs/heads/main
/fitbit2influx/scheduler.py
# Fitbit2Influx Scheduler Support import datetime import shelve from apscheduler.schedulers.background import BackgroundScheduler from flask import current_app from functools import wraps from fitbit2influx.influx import influx from fitbit2influx.service.fitbit import get_heartrate, get_user_profile class APScheduler(object): '''Flask Integration for APScheduler''' def __init__(self, scheduler=None, app=None): self._scheduler = scheduler or BackgroundScheduler() self.app = None if app: self.init_app(app) def init_app(self, app): '''Register the extension with the application''' self.app = app self.app.apscheduler = self self.app.logger.debug( 'Registering APScheduler with ' f'{self._scheduler.__class__.__name__} worker' ) @property def running(self): '''Return the Scheduler State''' return self._scheduler.state @property def scheduler(self): '''Get the currently active Scheduler''' return self._scheduler @property def task(self): '''Return a Task Decorator for the Scheduler''' return self._scheduler.scheduled_job @property def with_appcontext(self): ''' Decorator to add a Flask Application Context to a Job Use this in conjunction with `APScheduler.task` as follows: ``` from flask import current_app scheduler = APScheduler(app) @scheduler.task('cron', minutes='*') @scheduler.with_appcontext def run_every_minute(): current_app.logger.info('Called run_every_minute()') ``` ''' def wrapper(func): @wraps(func) def inner(*args, **kwargs): with self.app.app_context(): func(*args, **kwargs) return inner return wrapper def start(self, paused=False): '''Start the scheduler, optionally in a paused state''' self.app.logger.info('Starting Scheduler') self._scheduler.start(paused=paused) #: Fitbit2Influx Import Scheduler scheduler = APScheduler() # TODO: Make cron setup configurable @scheduler.task('cron', minute='*/15') @scheduler.with_appcontext def import_data(): current_app.logger.info('Downloading new Fitbit data') # Get the User Profile profile = get_user_profile(current_app) utc_offset = datetime.timedelta( milliseconds=profile['user']['offsetFromUTCMillis'] ) # Try and look up the last inserted timestamp last_pt = None with shelve.open(current_app.config['SHELVE_FILENAME'], 'r') as shelf: if 'last_point' in shelf: last_pt = shelf['last_point'] # Load heart rate data hr_data = get_heartrate(current_app, last_pt or 'today') if not len(hr_data): current_app.logger.info('No new heart rate points to send to InfluxDB') return # Insert new data points json_pts = [ { 'measurement': 'heartRate', 'time': (pt[0] - utc_offset).isoformat(), 'fields': { 'bpm': pt[1], }, } for pt in hr_data ] ret = influx.client.write_points( json_pts, protocol='json', time_precision='s', tags={ 'userId': profile['user']['encodedId'], }, ) if not ret: current_app.logger.error('Failed to write data to Influx') # Save last retrieved data point current_app.logger.info(f'Inserting {len(hr_data)} new heart rate points') with shelve.open(current_app.config['SHELVE_FILENAME'], 'c') as shelf: shelf['last_point'] = hr_data[-1][0] shelf['last_count'] = len(hr_data) def init_app(app): '''Register the Scheduler with the Flask Application''' scheduler.init_app(app)
{"/fitbit2influx/scheduler.py": ["/fitbit2influx/influx.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/blueprints/status.py": ["/fitbit2influx/influx.py", "/fitbit2influx/scheduler.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/wsgi.py": ["/fitbit2influx/factory.py"], "/fitbit2influx/factory.py": ["/fitbit2influx/__init__.py"], "/fitbit2influx/blueprints/oauth.py": ["/fitbit2influx/error.py"], "/fitbit2influx/service/fitbit.py": ["/fitbit2influx/error.py", "/fitbit2influx/service/oauth.py"], "/fitbit2influx/service/oauth.py": ["/fitbit2influx/error.py"]}
46,800
asymworks/fitbit2influx
refs/heads/main
/fitbit2influx/__init__.py
# Fitbit2Influx Flask Application from dotenv import find_dotenv, load_dotenv load_dotenv(find_dotenv(), verbose=True)
{"/fitbit2influx/scheduler.py": ["/fitbit2influx/influx.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/blueprints/status.py": ["/fitbit2influx/influx.py", "/fitbit2influx/scheduler.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/wsgi.py": ["/fitbit2influx/factory.py"], "/fitbit2influx/factory.py": ["/fitbit2influx/__init__.py"], "/fitbit2influx/blueprints/oauth.py": ["/fitbit2influx/error.py"], "/fitbit2influx/service/fitbit.py": ["/fitbit2influx/error.py", "/fitbit2influx/service/oauth.py"], "/fitbit2influx/service/oauth.py": ["/fitbit2influx/error.py"]}
46,801
asymworks/fitbit2influx
refs/heads/main
/fitbit2influx/settings.py
# Default Settings File APP_SESSION_KEY = 'fitbit2influx-test-session-key' # Fitbit Web Hosts FITBIT_WEB_HOST = 'www.fitbit.com' FITBIT_API_HOST = 'api.fitbit.com' # Fitbit Application Information # CLIENT_ID = None # CLIENT_SECRET = None CALLBACK_URL = '/authorize' # Token Validity in ms (default: 1 hr per Fitbit) TOKEN_VALIDITY = 604800 # ShelveDB Settings SHELVE_FILENAME = 'instance/shelf.db'
{"/fitbit2influx/scheduler.py": ["/fitbit2influx/influx.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/blueprints/status.py": ["/fitbit2influx/influx.py", "/fitbit2influx/scheduler.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/wsgi.py": ["/fitbit2influx/factory.py"], "/fitbit2influx/factory.py": ["/fitbit2influx/__init__.py"], "/fitbit2influx/blueprints/oauth.py": ["/fitbit2influx/error.py"], "/fitbit2influx/service/fitbit.py": ["/fitbit2influx/error.py", "/fitbit2influx/service/oauth.py"], "/fitbit2influx/service/oauth.py": ["/fitbit2influx/error.py"]}
46,802
asymworks/fitbit2influx
refs/heads/main
/fitbit2influx/blueprints/status.py
# Fitbit2Influx Status Page import shelve from flask import Blueprint, current_app, render_template from ..influx import influx from ..scheduler import scheduler bp = Blueprint('status', __name__, url_prefix='/', template_folder='templates') @bp.route('/', methods=['GET']) def status_index(): '''Show the Index Status Page''' last_time = None last_count = None token_expires = None user_id = None with shelve.open(current_app.config['SHELVE_FILENAME'], 'r') as shelf: if 'last_point' in shelf: last_time = shelf['last_point'] if 'last_count' in shelf: last_count = shelf['last_count'] if 'expires' in shelf: token_expires = shelf['expires'] if 'user_id' in shelf: user_id = shelf['user_id'] return render_template( 'status.html.j2', last_time=last_time, last_count=last_count, token_expires=token_expires, user_id=user_id, scheduler=scheduler, influx_uri=influx.client._baseurl, influx_db=influx.client._database, ) @bp.route('/debug', methods=['GET']) def oauth_debug(): '''Print OAuth2 Information''' oauth_data = {} with shelve.open(current_app.config['SHELVE_FILENAME'], 'r') as shelf: oauth_data = { 'access_token': shelf['access_token'], 'refresh_token': shelf['refresh_token'], 'scope': shelf['scope'], 'expires': shelf['expires'].isoformat(), 'user_id': shelf['user_id'], } return oauth_data @bp.route('/test', methods=['GET']) def oauth_test(): '''Print User Profile''' from ..service.fitbit import get_user_profile return get_user_profile(current_app)
{"/fitbit2influx/scheduler.py": ["/fitbit2influx/influx.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/blueprints/status.py": ["/fitbit2influx/influx.py", "/fitbit2influx/scheduler.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/wsgi.py": ["/fitbit2influx/factory.py"], "/fitbit2influx/factory.py": ["/fitbit2influx/__init__.py"], "/fitbit2influx/blueprints/oauth.py": ["/fitbit2influx/error.py"], "/fitbit2influx/service/fitbit.py": ["/fitbit2influx/error.py", "/fitbit2influx/service/oauth.py"], "/fitbit2influx/service/oauth.py": ["/fitbit2influx/error.py"]}
46,803
asymworks/fitbit2influx
refs/heads/main
/fitbit2influx/influx.py
# Fitbit2InfluxDB Influx Connection import influxdb class InfluxDB(object): '''InfluxDB Helper for Flask''' def __init__(self, app=None): self._client = None self.app = app if app: self.init_app(app) def init_app(self, app): '''Setup the InfluxDB Connection''' client_args = { 'host': app.config.get('INFLUX_HOST', 'localhost'), 'port': app.config.get('INFLUX_PORT', 8086), 'database': app.config.get('INFLUX_DATABASE', None), 'username': app.config.get('INFLUX_USERNAME', None), 'password': app.config.get('INFLUX_PASSWORD', None), 'ssl': app.config.get('INFLUX_SSL', False), 'verify_ssl': app.config.get('INFLUX_VERIFY_SSL', False), } self._client = influxdb.InfluxDBClient(**client_args) self.app = app self.app.influx = self @property def client(self): return self._client #: InfluxDB Client influx = InfluxDB() def init_app(app): '''Initialize the InfluxDB Connection''' influx.init_app(app) app.logger.info('Initialized InfluxDB')
{"/fitbit2influx/scheduler.py": ["/fitbit2influx/influx.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/blueprints/status.py": ["/fitbit2influx/influx.py", "/fitbit2influx/scheduler.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/wsgi.py": ["/fitbit2influx/factory.py"], "/fitbit2influx/factory.py": ["/fitbit2influx/__init__.py"], "/fitbit2influx/blueprints/oauth.py": ["/fitbit2influx/error.py"], "/fitbit2influx/service/fitbit.py": ["/fitbit2influx/error.py", "/fitbit2influx/service/oauth.py"], "/fitbit2influx/service/oauth.py": ["/fitbit2influx/error.py"]}
46,804
asymworks/fitbit2influx
refs/heads/main
/fitbit2influx/wsgi.py
# Fitbit2Influx WSGI Helper from .factory import create_app app = create_app()
{"/fitbit2influx/scheduler.py": ["/fitbit2influx/influx.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/blueprints/status.py": ["/fitbit2influx/influx.py", "/fitbit2influx/scheduler.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/wsgi.py": ["/fitbit2influx/factory.py"], "/fitbit2influx/factory.py": ["/fitbit2influx/__init__.py"], "/fitbit2influx/blueprints/oauth.py": ["/fitbit2influx/error.py"], "/fitbit2influx/service/fitbit.py": ["/fitbit2influx/error.py", "/fitbit2influx/service/oauth.py"], "/fitbit2influx/service/oauth.py": ["/fitbit2influx/error.py"]}
46,805
asymworks/fitbit2influx
refs/heads/main
/fitbit2influx/factory.py
# Fitbit2Influx Applicatin Factory import configparser import pathlib import os from flask import Flask def read_version(): '''Read the Name and Version String from pyproject.toml''' # Search for pyproject.toml d = pathlib.Path(__file__) name = None version = None while d.parent != d: d = d.parent path = d / 'pyproject.toml' if path.exists(): # Use configparser to parse toml like INI to avoid dependency on # tomlkit or similar config = configparser.ConfigParser() config.read(str(path)) if 'tool.poetry' in config: name = config['tool.poetry'].get('name').strip('"\'') version = config['tool.poetry'].get('version').strip('"\'') return (name, version) return (None, None) def create_app(app_config=None, app_name=None): ''' Create and Configure the Application with the Flask `Application Factory`_ pattern. The `app_config` dictionary will override configuration keys set via other methods, and is intended primarily for use in test frameworks to provide a predictable configuration for testing. :param app_config: configuration override values :type app_config: dict or None :param app_name: application name override :type app_name: str :returns: Flask application instance :rtype: :class:`Flask` ''' app = Flask( 'jadetree', static_folder='frontend/static', template_folder='frontend/templates' ) # Load Application Name and Version from pyproject.toml pkg_name, pkg_version = read_version() app.config['APP_NAME'] = pkg_name app.config['APP_VERSION'] = pkg_version # Load Default Settings app.config.from_object('fitbit2influx.settings') # Load Configuration File from Environment if 'FB2I_CONFIG' in os.environ: app.config.from_envvar('FB2I_CONFIG') # Load Configuration Variables from Environment for k, v in os.environ.items(): if k.startswith('FB2I_') and k != 'FB2I_CONFIG': app.config[k[5:]] = v # Load Factory Configuration if app_config is not None: if isinstance(app_config, dict): app.config.update(app_config) elif app_config.endswith('.py'): app.config.from_pyfile(app_config) # Override Application Name if app_name is not None: app.name = app_name try: # Initialize OAuth2 from .service import oauth as oauth_service oauth_service.init_oauth(app) # Initialize InfluxDB from . import influx influx.init_app(app) # Register Blueprints from .blueprints import oauth, status app.register_blueprint(oauth.bp) app.register_blueprint(status.bp) app.logger.info('Registered Blueprints') # Initialize Import Scheduler and start. Note that Flask Debug mode # causes this to run twice, so the check ensures that the scheduler # is only set up in the Werkzeug main worker thread. is_dev = app.debug or os.environ.get('FLASK_ENV') == 'development' if not is_dev or os.environ.get("WERKZEUG_RUN_MAIN") == "true": from . import scheduler scheduler.init_app(app) scheduler.scheduler.start() # Return Application return app except Exception as e: # Ensure startup exceptions get logged app.logger.exception( 'Startup Error (%s): %s', e.__class__.__name__, str(e) ) raise e
{"/fitbit2influx/scheduler.py": ["/fitbit2influx/influx.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/blueprints/status.py": ["/fitbit2influx/influx.py", "/fitbit2influx/scheduler.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/wsgi.py": ["/fitbit2influx/factory.py"], "/fitbit2influx/factory.py": ["/fitbit2influx/__init__.py"], "/fitbit2influx/blueprints/oauth.py": ["/fitbit2influx/error.py"], "/fitbit2influx/service/fitbit.py": ["/fitbit2influx/error.py", "/fitbit2influx/service/oauth.py"], "/fitbit2influx/service/oauth.py": ["/fitbit2influx/error.py"]}
46,806
asymworks/fitbit2influx
refs/heads/main
/fitbit2influx/blueprints/oauth.py
# Fitbit2Influx OAuth2 Helpers from flask import Blueprint, current_app, redirect, request from fitbit2influx.error import NeedAuthError from fitbit2influx.service import oauth as oauth_service bp = Blueprint('oauth', __name__, url_prefix='/') @bp.route('/authorize', methods=['GET']) def oauth_authorize(): '''Redirect to the Fitbit Authorization page''' if not current_app.config.get('OAUTH_AUTH_URL'): oauth_service.init_oauth(current_app) return redirect(current_app.config['OAUTH_AUTH_URL']) @bp.route('/callback', methods=['GET']) def oauth_callback(): '''Receive an Authorization Token from Fitbit API''' oauth_service.request_tokens(current_app, request.args.get('code')) return redirect('/debug') @bp.route('/refresh', methods=['GET']) def oauth_refresh(): '''Refresh OAuth2 Access Token''' try: oauth_service.refresh_tokens(current_app) return redirect('/debug') except NeedAuthError: return redirect('/authorize')
{"/fitbit2influx/scheduler.py": ["/fitbit2influx/influx.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/blueprints/status.py": ["/fitbit2influx/influx.py", "/fitbit2influx/scheduler.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/wsgi.py": ["/fitbit2influx/factory.py"], "/fitbit2influx/factory.py": ["/fitbit2influx/__init__.py"], "/fitbit2influx/blueprints/oauth.py": ["/fitbit2influx/error.py"], "/fitbit2influx/service/fitbit.py": ["/fitbit2influx/error.py", "/fitbit2influx/service/oauth.py"], "/fitbit2influx/service/oauth.py": ["/fitbit2influx/error.py"]}
46,807
asymworks/fitbit2influx
refs/heads/main
/fitbit2influx/service/fitbit.py
# Fitbit2Influx Fitbit Service import datetime import requests from urllib.parse import quote, urlencode, urlunparse from fitbit2influx.error import ApiError from .oauth import get_api_token def api_get(app, url_endpoint, query=None, headers={}, **kwargs): '''Perform a GET request to the Fitbit API''' token = get_api_token(app) url_host = app.config['FITBIT_API_HOST'] url_params = None if query is not None: url_params = urlencode(query, quote_via=quote) url = urlunparse(('https', url_host, url_endpoint, None, url_params, None)) headers['Authorization'] = f'Bearer {token}' app.logger.debug(f'Sending GET to {url_endpoint}') response = requests.get(url, headers=headers, **kwargs) if response.status_code != 200: raise ApiError.from_response(response.json()) return response.json() def get_user_profile(app): '''Get the User Profile Data''' return api_get(app, '/1/user/-/profile.json') def get_heartrate(app, since='today', detail='1min'): ''' Get Heart Rate Data This calls the Fitbit Heart Rate Intraday Time Series endpoint with the parameters taken from argument values. The `since` parameter specifies the starting date and time for the measurement or can contain the string `today`, which will return all points from today. Note that the Fitbit API only returns intraday data within a single day, so this method will send multiple requests for each day of data from the `since` parameter until today. If the `since` parameter is a `datetime` object, the time will also be used to filter out points before the time given. Note that the `datetime` instances will be interpreted as user-local time by Fitbit and no timezone data is passed, so the instances should be naive objects without timezone data. The return value is an array of (`dt`, `bpm`) tuples where the `dt` value is a naive `datetime` object in the Fitbit-local time zone and `bpm` is the heart rate in beats per minute. ''' today = datetime.date.today() f_date = datetime.date.today() f_time = datetime.datetime.now().replace( hour=0, minute=0, second=0, microsecond=0, ) if isinstance(since, datetime.datetime): f_date = since.date() f_time = since elif isinstance(since, datetime.date): f_date = since f_time = datetime.datetime.combine(since, datetime.time()) # Fetch day by day through today ret_data = [] while f_date <= today: hr_endpoint = f'date/{f_date.strftime("%Y-%m-%d")}/1d/{detail}.json' hr_data = api_get(app, f'/1/user/-/activities/heart/{hr_endpoint}') if 'activities-heart-intraday' not in hr_data: raise ApiError( f'Did not receive intraday heart rate data from {hr_endpoint}' ) # Convert Fitbit hh:mm:ss tags to datetime objects for pt in hr_data['activities-heart-intraday']['dataset']: h, m, s = [int(x) for x in pt['time'].split(':')] dt = datetime.datetime.combine(f_date, datetime.time(h, m, s)) if dt >= f_time: ret_data.append((dt, pt['value'])) # Increment the Fetch Day f_date += datetime.timedelta(days=1) # Return fetched data return ret_data
{"/fitbit2influx/scheduler.py": ["/fitbit2influx/influx.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/blueprints/status.py": ["/fitbit2influx/influx.py", "/fitbit2influx/scheduler.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/wsgi.py": ["/fitbit2influx/factory.py"], "/fitbit2influx/factory.py": ["/fitbit2influx/__init__.py"], "/fitbit2influx/blueprints/oauth.py": ["/fitbit2influx/error.py"], "/fitbit2influx/service/fitbit.py": ["/fitbit2influx/error.py", "/fitbit2influx/service/oauth.py"], "/fitbit2influx/service/oauth.py": ["/fitbit2influx/error.py"]}
46,808
asymworks/fitbit2influx
refs/heads/main
/fitbit2influx/service/oauth.py
# Fitbit2Influx OAuth2 Service import datetime import requests import shelve from urllib.parse import quote, urlencode, urlunparse from fitbit2influx.error import ApiError, ConfigError, NeedAuthError def init_oauth(app): ''' Construct the Fitbit Authorization URL Construct the URL for Fitbit OAuth2 Authorization Code grants based on application configuration and store the URL back in the application config. ''' cfg_keys = ( 'FITBIT_WEB_HOST', 'FITBIT_API_HOST', 'CLIENT_ID', 'CLIENT_SECRET', 'CALLBACK_URL', 'SHELVE_FILENAME', ) for k in cfg_keys: if k not in app.config: raise ConfigError( '{} must be defined in the application configuration' .format(k), config_key=k ) # Currently this is hard-coded grants = ' '.join([ 'activity', 'heartrate', 'nutrition', 'profile', 'settings', 'sleep', ]) # Construct the Authorization URL auth_url_host = app.config['FITBIT_WEB_HOST'] auth_url_path = '/oauth2/authorize' auth_url_args = urlencode( { 'response_type': 'code', 'client_id': app.config['CLIENT_ID'], 'redirect_uri': app.config['CALLBACK_URL'], 'scope': grants, 'expires_in': str(app.config.get('TOKEN_VALIDITY', 604800)), }, quote_via=quote ) app.config['OAUTH_AUTH_URL'] = urlunparse( ('https', auth_url_host, auth_url_path, None, auth_url_args, None) ) app.logger.info('Fitbit OAuth2 Initialized') def update_tokens(app, token_data): '''Update the ShelveDB with the Token Data''' keys = ('access_token', 'refresh_token', 'expires_in', 'scope', 'user_id') for k in keys: if k not in token_data: raise ApiError(f'Token request response did not include "{k}"') expires = datetime.datetime.utcnow() + datetime.timedelta( seconds=token_data['expires_in'], ) with shelve.open(app.config['SHELVE_FILENAME'], 'c') as shelf: shelf['access_token'] = token_data['access_token'] shelf['refresh_token'] = token_data['refresh_token'] shelf['scope'] = token_data['scope'].split(' ') shelf['expires'] = expires shelf['user_id'] = token_data['user_id'] def request_tokens(app, code): '''Request new OAuth2 Tokens for the Application''' app.logger.info('Requesting OAuth2 access and refresh tokens') url_host = app.config['FITBIT_API_HOST'] url_path = '/oauth2/token' response = requests.post( urlunparse(('https', url_host, url_path, None, None, None)), data={ 'clientid': app.config['CLIENT_ID'], 'grant_type': 'authorization_code', 'redirect_uri': app.config['CALLBACK_URL'], 'code': code, }, auth=(app.config['CLIENT_ID'], app.config['CLIENT_SECRET']), ) data = response.json() if 'success' in data and not data['success']: raise ApiError.from_response(data) app.logger.info('Successfully authenticated with Fitbit') update_tokens(app, data) def refresh_tokens(app): '''Refresh OAuth2 Tokens for the Application''' refresh_token = None with shelve.open(app.config['SHELVE_FILENAME'], 'r') as shelf: if 'refresh_token' in shelf: refresh_token = shelf['refresh_token'] if refresh_token is None: raise NeedAuthError('No Refresh Token set') app.logger.info('Refreshing OAuth2 access token') url_host = app.config['FITBIT_API_HOST'] url_path = '/oauth2/token' response = requests.post( urlunparse(('https', url_host, url_path, None, None, None)), data={ 'grant_type': 'refresh_token', 'redirect_uri': app.config['CALLBACK_URL'], 'refresh_token': refresh_token, }, auth=(app.config['CLIENT_ID'], app.config['CLIENT_SECRET']), ) data = response.json() if 'success' in data and not data['success']: raise ApiError.from_response(data) app.logger.info('Successfully refreshed OAuth2 access token') update_tokens(app, data) return data['access_token'] def get_api_token(app): ''' Get the current API Bearer Token Returns the current token to be sent as a Bearer Token for an authenticated API request. If the token is expired, the refresh flow will be called and a new token will be provided. ''' access_token = None expire_time = None with shelve.open(app.config['SHELVE_FILENAME'], 'r') as shelf: access_token = shelf.get('access_token', None) expire_time = shelf.get('expires', None) if access_token is None or expire_time is None: raise NeedAuthError('No Access Token set') expire_left = expire_time - datetime.datetime.utcnow() if expire_left < datetime.timedelta(seconds=1): app.logger.debug('Access token expired - refreshing') return refresh_tokens(app) app.logger.debug('Using cached access token') return access_token
{"/fitbit2influx/scheduler.py": ["/fitbit2influx/influx.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/blueprints/status.py": ["/fitbit2influx/influx.py", "/fitbit2influx/scheduler.py", "/fitbit2influx/service/fitbit.py"], "/fitbit2influx/wsgi.py": ["/fitbit2influx/factory.py"], "/fitbit2influx/factory.py": ["/fitbit2influx/__init__.py"], "/fitbit2influx/blueprints/oauth.py": ["/fitbit2influx/error.py"], "/fitbit2influx/service/fitbit.py": ["/fitbit2influx/error.py", "/fitbit2influx/service/oauth.py"], "/fitbit2influx/service/oauth.py": ["/fitbit2influx/error.py"]}
46,836
maciejbiesek/poleval-cyberbullying
refs/heads/master
/run_svm.py
import argparse from dataset import Dataset from models.svm_classifier import SVMClassifier def parse_args(): parent_parser = argparse.ArgumentParser(add_help=False) parent_parser.add_argument("--text_corpus", type=str, required=True, help="Path to twitter messages in txt file") parent_parser.add_argument("--tag_corpus", type=str, required=True, help="Path to labels in txt file") parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest="mode") # subparser for training subparsers.add_parser("train", parents=[parent_parser]) # subparser for tagging subparsers.add_parser("tagging", parents=[parent_parser]) return parser.parse_args() if __name__ == "__main__": args = parse_args() model = SVMClassifier() if args.mode == "train": dataset = Dataset(args.text_corpus, args.tag_corpus, True, True, False) model = SVMClassifier() acc, f1 = model.train(dataset) print("Model evaluation: \n" f"Model accuracy: {acc:.01%}, " f"Model F1: {f1:.01%}") else: dataset = Dataset(args.text_corpus, args.tag_corpus, False, True, False) tagged = model.tagging(dataset) tagged = [str(tag) for tag in tagged] with open("results.txt", 'w') as file: file.write("\n".join(tagged))
{"/run_svm.py": ["/dataset.py", "/models/svm_classifier.py"], "/utils.py": ["/config.py"], "/dataset.py": ["/config.py"], "/models/flair_classifier.py": ["/config.py"], "/run_rnn.py": ["/config.py", "/dataset.py", "/models/gru_classifier.py", "/utils.py"], "/models/svm_classifier.py": ["/config.py"], "/run_flair.py": ["/dataset.py", "/models/flair_classifier.py"], "/models/gru_classifier.py": ["/config.py"]}
46,837
maciejbiesek/poleval-cyberbullying
refs/heads/master
/utils.py
from random import randint from scipy import stats from sklearn.metrics import accuracy_score, f1_score from config import Parser def evaluate_baselines(true_y): args = Parser().get_section('GENERAL') most_frequent_label = stats.mode(true_y).mode[0] most_frequent_label_baseline = [most_frequent_label for _ in range(len(true_y))] random_baseline = [randint(0, int(args['num_classes']) - 1) for _ in range(len(true_y))] return ("Baselines: \n" f"random acc: {accuracy_score(true_y, random_baseline):.01%}, " f"random F1: {f1_score(true_y, random_baseline, average='macro'):.01%}, \n" f"most frequent label acc: {accuracy_score(true_y, most_frequent_label_baseline):.01%}, " f"most frequent label F1: {f1_score(true_y, most_frequent_label_baseline, average='macro'):.01%}")
{"/run_svm.py": ["/dataset.py", "/models/svm_classifier.py"], "/utils.py": ["/config.py"], "/dataset.py": ["/config.py"], "/models/flair_classifier.py": ["/config.py"], "/run_rnn.py": ["/config.py", "/dataset.py", "/models/gru_classifier.py", "/utils.py"], "/models/svm_classifier.py": ["/config.py"], "/run_flair.py": ["/dataset.py", "/models/flair_classifier.py"], "/models/gru_classifier.py": ["/config.py"]}
46,838
maciejbiesek/poleval-cyberbullying
refs/heads/master
/dataset.py
import os import pickle import re import string from collections import Counter import numpy as np import pandas as pd from gensim.models.keyedvectors import KeyedVectors from sklearn.model_selection import train_test_split from sklearn.utils import shuffle from spacy.lang.pl import Polish from config import Parser RE_EMOJI = re.compile('[\U00010000-\U0010ffff]', flags=re.UNICODE) class Dataset: def __init__(self, texts_file, tags_file, clean_data=True, remove_stopwords=False, is_train=True): self.args = Parser().get_sections(['GENERAL', 'RNN', 'FLAIR']) self.max_sent_length = int(self.args['max_sent_length']) self.batch_size = int(self.args['batch_size']) self.emb_size = int(self.args['emb_size']) self.clean_data = clean_data self.remove_stopwords = remove_stopwords self.is_train = is_train self.nlp = Polish() self.df = self.build_dataframe(texts_file, tags_file) self.unk_emb = self.get_random_emb(self.emb_size) self.word2idx, self.idx2word = self.build_dict() if self.is_train: self.embeddings = self.get_embeddings(self.args['emb_path']) def build_dataframe(self, texts_file, tags_file): with open(texts_file) as file: lines = [line.strip() for line in file.readlines()] texts = pd.DataFrame(lines, columns=['text']) tags = pd.read_fwf(tags_file, header=None, names=['tag']) df = pd.concat([texts, tags], axis=1) df['tokens'] = df['text'].map(lambda x: self.preprocess_sentence(x)) df['length'] = df['tokens'].map(lambda x: len(x)) df['clean_text'] = df['tokens'].map(lambda x: " ".join(x)) if self.clean_data: df = self.clean(df) return df def preprocess_sentence(self, sentence): sentence = sentence.replace(r"\n", "").replace(r"\r", "").replace(r"\t", "").replace("„", "").replace("”", "") doc = [tok for tok in self.nlp(sentence)] if not self.clean_data and str(doc[0]) == "RT": doc.pop(0) while str(doc[0]) == "@anonymized_account": doc.pop(0) while str(doc[-1]) == "@anonymized_account": doc.pop() if self.remove_stopwords: doc = [tok for tok in doc if not tok.is_stop] doc = [tok.lower_ for tok in doc] doc = ["".join(c for c in tok if not c.isdigit() and c not in string.punctuation) for tok in doc] doc = [RE_EMOJI.sub(r'', tok) for tok in doc] doc = [tok.strip() for tok in doc if tok.strip()] return doc def build_dict(self): if self.is_train: sentences = self.df['tokens'] all_tokens = [token for sentence in sentences for token in sentence] words_counter = Counter(all_tokens).most_common() word2idx = { self.args['pad']: 0, self.args['unk']: 1 } for word, _ in words_counter: word2idx[word] = len(word2idx) with open(self.args['word_dict_path'], 'wb') as dict_file: pickle.dump(word2idx, dict_file) else: with open(self.args['word_dict_path'], 'rb') as dict_file: word2idx = pickle.load(dict_file) idx2word = {idx: word for word, idx in word2idx.items()} return word2idx, idx2word def transform_dataset(self): sentences = self.df['tokens'].values x = [sentence[:self.max_sent_length] for sentence in sentences] x = [sentence + [self.args['pad']] * (self.max_sent_length - len(sentence)) for sentence in x] x = [[self.word2idx.get(word, self.word2idx[self.args['unk']]) for word in sentence] for sentence in x] y = self.df['tag'].values return np.array(x), np.array(y) def parse_dataset(self): x, y = self.transform_dataset() if self.is_train: x, y = shuffle(x, y, random_state=42) train_x, valid_x, train_y, valid_y = train_test_split(x, y, test_size=0.15, random_state=42, stratify=y) return list(self.chunks(train_x, train_y, self.batch_size)), valid_x, valid_y return list(self.chunks(x, y, self.batch_size)) def get_embeddings(self, embeddings_file): emb_list = [] print("Loading vectors...") word_vectors = KeyedVectors.load_word2vec_format(embeddings_file, binary=False) print("Vectors loaded...") for _, word in sorted(self.idx2word.items()): if word == self.args['pad']: word_vec = np.zeros(self.emb_size) elif word == self.args['unk']: word_vec = self.unk_emb else: try: word_vec = word_vectors.word_vec(word) except KeyError: word_vec = self.unk_emb emb_list.append(word_vec) return np.array(emb_list, dtype=np.float32) def get_class_weight(self): y = self.df['tag'].values _, counts = np.unique(y, return_counts=True) return np.array(1 - counts / y.size) def prepare_flair_format(self, column_name): X = self.df[column_name].values y = self.df['tag'].values train_x, val_x, train_y, val_y = train_test_split(X, y, test_size=0.15, random_state=42, stratify=y) train_x, dev_x, train_y, dev_y = train_test_split(train_x, train_y, test_size=0.15, random_state=42, stratify=train_y) train_data = [f"__label__{label} {text}" for text, label in zip(train_x, train_y)] val_data = [f"__label__{label} {text}" for text, label in zip(val_x, val_y)] dev_data = [f"__label__{label} {text}" for text, label in zip(dev_x, dev_y)] flair_dir_path = self.args['flair_data_path'] os.makedirs(flair_dir_path, exist_ok=True) with open(os.path.join(flair_dir_path, f"train_{column_name}.txt"), 'w') as train_file, \ open(os.path.join(flair_dir_path, f"dev_{column_name}.txt"), 'w') as dev_file, \ open(os.path.join(flair_dir_path, f"test_{column_name}.txt"), 'w') as val_file: train_file.write("\n".join(train_data)) dev_file.write("\n".join(dev_data)) val_file.write("\n".join(val_data)) def print_stats(self): print(self.df['length'].describe()) print(self.df['length'].quantile(0.95, interpolation='lower')) print(self.df['length'].quantile(0.99, interpolation='lower')) print(self.df.shape) print(self.df['tag'].value_counts()) @staticmethod def get_random_emb(length): return np.random.uniform(-0.25, 0.25, length) @staticmethod def clean(dataframe): dataframe = dataframe.drop_duplicates('clean_text') return dataframe[(dataframe['tokens'].apply(lambda x: "rt" not in x[:1])) & (dataframe['length'] > 1)] @staticmethod def chunks(inputs, outputs, batch_size): for i in range(0, len(inputs), batch_size): yield inputs[i:i + batch_size], outputs[i:i + batch_size] if __name__ == "__main__": dt = Dataset("../data/task_6-2/training_set_clean_only_text.txt", "../data/task_6-2/training_set_clean_only_tags.txt", True, False, False) # dt.prepare_flair_format("clean_text")
{"/run_svm.py": ["/dataset.py", "/models/svm_classifier.py"], "/utils.py": ["/config.py"], "/dataset.py": ["/config.py"], "/models/flair_classifier.py": ["/config.py"], "/run_rnn.py": ["/config.py", "/dataset.py", "/models/gru_classifier.py", "/utils.py"], "/models/svm_classifier.py": ["/config.py"], "/run_flair.py": ["/dataset.py", "/models/flair_classifier.py"], "/models/gru_classifier.py": ["/config.py"]}
46,839
maciejbiesek/poleval-cyberbullying
refs/heads/master
/models/flair_classifier.py
import os from pathlib import Path from flair.data import Sentence from flair.data_fetcher import NLPTaskDataFetcher from flair.embeddings import WordEmbeddings, FlairEmbeddings, DocumentRNNEmbeddings from flair.models import TextClassifier from flair.trainers import ModelTrainer from flair.training_utils import EvaluationMetric from config import Parser class FlairClassifier: def __init__(self): parser = Parser() args = parser.get_section('FLAIR') self.corpus_path = args['flair_data_path'] self.word_emb_path = args['flair_emb_path'] self.model_path = args['flair_model_path'] self.hidden_size = int(args['flair_num_hidden']) self.epochs = int(args['flair_epochs']) def train(self): corpus = NLPTaskDataFetcher.load_classification_corpus(Path(self.corpus_path), test_file="test_clean_text.txt", dev_file="dev_clean_text.txt", train_file="train_clean_text.txt") embeddings = [WordEmbeddings(self.word_emb_path), FlairEmbeddings('polish-forward'), FlairEmbeddings('polish-backward')] document_embeddings = DocumentRNNEmbeddings(embeddings, hidden_size=self.hidden_size, bidirectional=True) classifier = TextClassifier(document_embeddings, label_dictionary=corpus.make_label_dictionary(), multi_label=False) trainer = ModelTrainer(classifier, corpus) trainer.train(self.model_path, evaluation_metric=EvaluationMetric.MACRO_F1_SCORE, max_epochs=self.epochs) def tagging(self, dataset): classifier = TextClassifier.load_from_file(os.path.join(self.model_path, "best-model.pt")) sentences = dataset.df['clean_text'].values results = [] for sent in sentences: if sent: sentence = Sentence(sent) classifier.predict(sentence) result = sentence.labels[0].value else: result = 0 results.append(result) return results
{"/run_svm.py": ["/dataset.py", "/models/svm_classifier.py"], "/utils.py": ["/config.py"], "/dataset.py": ["/config.py"], "/models/flair_classifier.py": ["/config.py"], "/run_rnn.py": ["/config.py", "/dataset.py", "/models/gru_classifier.py", "/utils.py"], "/models/svm_classifier.py": ["/config.py"], "/run_flair.py": ["/dataset.py", "/models/flair_classifier.py"], "/models/gru_classifier.py": ["/config.py"]}
46,840
maciejbiesek/poleval-cyberbullying
refs/heads/master
/run_rnn.py
import argparse from config import Parser from dataset import Dataset from models.gru_classifier import GRU from utils import evaluate_baselines def parse_args(): parent_parser = argparse.ArgumentParser(add_help=False) parent_parser.add_argument("--text_corpus", type=str, required=True, help="Path to twitter messages in txt file") parent_parser.add_argument("--tag_corpus", type=str, required=True, help="Path to labels in txt file") parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest="mode") # subparser for training subparsers.add_parser("train", parents=[parent_parser]) # subparser for tagging subparsers.add_parser("tagging", parents=[parent_parser]) return parser.parse_args() def train(dataset): model = GRU(dataset) model.train() if __name__ == "__main__": args = parse_args() config_args = Parser().get_section('RNN') if args.mode == "train": dataset = Dataset(args.text_corpus, args.tag_corpus, True, False, True) train(dataset) else: dataset = Dataset(args.text_corpus, args.tag_corpus, False, False, False) model = GRU(None, False) tagged = model.tagging(dataset) tagged = [str(tag) for tag in tagged] with open("results.txt", 'w') as file: file.write("\n".join(tagged))
{"/run_svm.py": ["/dataset.py", "/models/svm_classifier.py"], "/utils.py": ["/config.py"], "/dataset.py": ["/config.py"], "/models/flair_classifier.py": ["/config.py"], "/run_rnn.py": ["/config.py", "/dataset.py", "/models/gru_classifier.py", "/utils.py"], "/models/svm_classifier.py": ["/config.py"], "/run_flair.py": ["/dataset.py", "/models/flair_classifier.py"], "/models/gru_classifier.py": ["/config.py"]}
46,841
maciejbiesek/poleval-cyberbullying
refs/heads/master
/models/svm_classifier.py
import pickle from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.metrics import accuracy_score, f1_score from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline from sklearn.svm import LinearSVC from sklearn.utils import shuffle from config import Parser class SVMClassifier: def __init__(self): parser = Parser() args = parser.get_section('SVM') self.model_path = args['svm_model_path'] self.pipeline = Pipeline( [('vect', CountVectorizer(tokenizer=self.do_nothing, preprocessor=None, lowercase=False)), ('tfidf', TfidfTransformer()), ('clf', LinearSVC(class_weight='balanced'))]) def train(self, dataset): X, y = dataset.df['tokens'].values, dataset.df['tag'].values X, y = shuffle(X, y, random_state=42) train_x, valid_x, train_y, valid_y = train_test_split(X, y, test_size=0.15, random_state=42, stratify=y) self.pipeline.fit(train_x, train_y) with open(self.model_path, 'wb') as file: pickle.dump(self.pipeline, file) y_pred = self.pipeline.predict(valid_x) return accuracy_score(valid_y, y_pred), f1_score(valid_y, y_pred, average='macro') def tagging(self, dataset): X = dataset.df['tokens'].values with open(self.model_path, 'rb') as file: clf = pickle.load(file) return [clf.predict([item])[0] if item else 0 for item in X] @staticmethod # needed to pickle the object def do_nothing(x): return x
{"/run_svm.py": ["/dataset.py", "/models/svm_classifier.py"], "/utils.py": ["/config.py"], "/dataset.py": ["/config.py"], "/models/flair_classifier.py": ["/config.py"], "/run_rnn.py": ["/config.py", "/dataset.py", "/models/gru_classifier.py", "/utils.py"], "/models/svm_classifier.py": ["/config.py"], "/run_flair.py": ["/dataset.py", "/models/flair_classifier.py"], "/models/gru_classifier.py": ["/config.py"]}
46,842
maciejbiesek/poleval-cyberbullying
refs/heads/master
/run_flair.py
import argparse from dataset import Dataset from models.flair_classifier import FlairClassifier def parse_args(): parent_parser = argparse.ArgumentParser(add_help=False) parent_parser.add_argument("--text_corpus", type=str, required=False, help="Path to twitter messages in txt file") parent_parser.add_argument("--tag_corpus", type=str, required=False, help="Path to labels in txt file") parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest="mode") # subparser for training subparsers.add_parser("train", parents=[parent_parser]) # subparser for tagging subparsers.add_parser("tagging", parents=[parent_parser]) return parser.parse_args() if __name__ == "__main__": args = parse_args() model = FlairClassifier() if args.mode == "train": model.train() else: dataset = Dataset(args.text_corpus, args.tag_corpus, False, False, False) tagged = model.tagging(dataset) tagged = [str(tag) for tag in tagged] with open("results.txt", 'w') as file: file.write("\n".join(tagged))
{"/run_svm.py": ["/dataset.py", "/models/svm_classifier.py"], "/utils.py": ["/config.py"], "/dataset.py": ["/config.py"], "/models/flair_classifier.py": ["/config.py"], "/run_rnn.py": ["/config.py", "/dataset.py", "/models/gru_classifier.py", "/utils.py"], "/models/svm_classifier.py": ["/config.py"], "/run_flair.py": ["/dataset.py", "/models/flair_classifier.py"], "/models/gru_classifier.py": ["/config.py"]}
46,843
maciejbiesek/poleval-cyberbullying
refs/heads/master
/models/gru_classifier.py
import os import numpy as np import tensorflow as tf from sklearn.metrics import f1_score from tensorflow.contrib.layers import fully_connected, dropout from tensorflow.contrib.rnn import DropoutWrapper, GRUCell from config import Parser class GRU: def __init__(self, dataset, is_train=True): parser = Parser() args = parser.get_sections(['GENERAL', 'RNN']) self.dataset = dataset self.num_hidden = int(args['num_hidden']) self.hidden_size = int(args['hidden_size']) self.num_classes = int(args['num_classes']) self.num_epochs = int(args['epochs']) self.max_sent_length = int(args['max_sent_length']) self.saved_dir = args['saved_dir'] self.display_freq = int(args['display_frequency']) self.rnn_keep_prob = float(args['rnn_keep_prob']) self.dense_keep_prob = float(args['dense_keep_prob']) self.x = tf.placeholder(tf.int32, [None, self.max_sent_length], name="x") self.y = tf.placeholder(tf.int32, [None], name="y") self.rnn_keep_prob_ph = tf.placeholder(tf.float32, name="rnn_keep_prob") self.dense_keep_prob_ph = tf.placeholder(tf.float32, name="dense_keep_prob") self.class_weight = tf.placeholder(tf.float32, name="class_weight") self.global_step = tf.Variable(0, trainable=False) if is_train: with tf.name_scope("embeddings"): init_embeddings = tf.constant(self.dataset.embeddings, dtype=tf.float32) embeddings = tf.get_variable("embeddings", initializer=init_embeddings, trainable=False) x_emb = tf.nn.embedding_lookup(embeddings, self.x) with tf.name_scope("encoder"): forward_cells = GRUCell(self.num_hidden) backward_cells = GRUCell(self.num_hidden) forward_cells = DropoutWrapper(forward_cells, output_keep_prob=self.rnn_keep_prob_ph) backward_cells = DropoutWrapper(backward_cells, output_keep_prob=self.rnn_keep_prob_ph) (encoder_outputs_fw, encoder_outputs_bw), _ = tf.nn.bidirectional_dynamic_rnn(forward_cells, backward_cells, x_emb, dtype=tf.float32) output = tf.concat([encoder_outputs_fw, encoder_outputs_bw], axis=2)[:, -1, :] with tf.name_scope("dense"): dense = fully_connected(output, self.hidden_size, activation_fn=tf.nn.relu) drop = dropout(dense, self.dense_keep_prob_ph) logits = fully_connected(drop, self.num_classes, activation_fn=tf.nn.relu) self.y_pred = tf.argmax(logits, axis=-1, output_type=tf.int32, name="y_pred") with tf.name_scope("loss"): weights = tf.gather(self.class_weight, self.y) xent = tf.losses.sparse_softmax_cross_entropy(logits=logits, labels=self.y, weights=weights) self.loss = tf.reduce_mean(xent) self.optimizer = tf.train.AdamOptimizer().minimize(self.loss, global_step=self.global_step) with tf.name_scope("accuracy"): correct_predictions = tf.equal(self.y_pred, self.y) self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy") def train(self): train_batches, val_x, val_y = self.dataset.parse_dataset() class_weight = self.dataset.get_class_weight() max_acc, max_f1, min_loss = 0, 0, 100 os.makedirs(self.saved_dir, exist_ok=True) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) saver = tf.train.Saver(tf.global_variables()) for epoch in range(self.num_epochs): print(f"Training epoch: {epoch + 1}") for x_batch, y_batch in train_batches: _, iteration, loss, acc = sess.run([self.optimizer, self.global_step, self.loss, self.accuracy], feed_dict={self.x: x_batch, self.y: y_batch, self.rnn_keep_prob_ph: self.rnn_keep_prob, self.dense_keep_prob_ph: self.dense_keep_prob, self.class_weight: class_weight}) if iteration % self.display_freq == 0: print(f"Global step {iteration:4d}: \t Loss={loss:.2f}, \t Training Accuracy={acc:.01%}") # validation after every epoch step, loss_valid, acc_valid, y_pred = sess.run([self.global_step, self.loss, self.accuracy, self.y_pred], feed_dict={self.x: val_x, self.y: val_y, self.rnn_keep_prob_ph: 1.0, self.dense_keep_prob_ph: 1.0, self.class_weight: class_weight}) f1_valid = f1_score(val_y, y_pred, average='macro') print("-" * 10) print(f"Epoch: {epoch + 1}") print("Model evaluation: \n" f"validation loss: {loss_valid:.2f}, " f"validation accuracy: {acc_valid:.01%}, " f"validation F1: {f1_valid:.01%}") print("-" * 10) if loss_valid <= min_loss and f1_valid > max_f1: min_loss, max_acc, max_f1 = loss_valid, acc_valid, f1_valid filename = os.path.join(self.saved_dir, "saved_model.ckpt") saver.save(sess, filename, global_step=step) print("Model is saved.\n") def tagging(self, dataset): test_batches = dataset.parse_dataset() y_pred = [] checkpoint_file = tf.train.latest_checkpoint(self.saved_dir) graph = tf.Graph() with graph.as_default(): with tf.Session() as sess: saver = tf.train.import_meta_graph(f"{checkpoint_file}.meta") saver.restore(sess, checkpoint_file) x_placeholder = graph.get_operation_by_name("x").outputs[0] y_placeholder = graph.get_operation_by_name("y").outputs[0] rnn_keep_prob_placeholder = graph.get_operation_by_name("rnn_keep_prob").outputs[0] dense_keep_prob_placeholder = graph.get_operation_by_name("dense_keep_prob").outputs[0] class_weight_placeholder = graph.get_operation_by_name("class_weight").outputs[0] y_pred_placeholder = graph.get_operation_by_name("dense/y_pred").outputs[0] for x_batch, y_batch in test_batches: y_pred_batch = sess.run(y_pred_placeholder, feed_dict={x_placeholder: x_batch, y_placeholder: y_batch, rnn_keep_prob_placeholder: 1.0, dense_keep_prob_placeholder: 1.0, class_weight_placeholder: np.array([1.0] * self.num_classes)}) y_pred.extend(y_pred_batch) return y_pred
{"/run_svm.py": ["/dataset.py", "/models/svm_classifier.py"], "/utils.py": ["/config.py"], "/dataset.py": ["/config.py"], "/models/flair_classifier.py": ["/config.py"], "/run_rnn.py": ["/config.py", "/dataset.py", "/models/gru_classifier.py", "/utils.py"], "/models/svm_classifier.py": ["/config.py"], "/run_flair.py": ["/dataset.py", "/models/flair_classifier.py"], "/models/gru_classifier.py": ["/config.py"]}