def run_nuclide(nuc): bateman = defaultdict(emptytime) bateman[nuc][0] = 1 crammed = defaultdict(emptytime) crammed[nuc][0] = 1 diagexp = defaultdict(emptytime) diagexp[nuc][0] = 1 n0 = Material({nuc: 1.0}, mass=1.0, atoms_per_molecule=1.0) for i, t in enumerate(TIMES[1:], 1): # compute Bateman try: b1 = n0.decay(t).to_atom_frac() except RuntimeError: # decay can't handle all of the same nuclides CRAM can b1 = {} for key, val in b1.items(): n = nucname.name(key) bateman[n][i] = val # compute CRAM c1 = n0.cram(DECAY_MATS[t], order=16).to_atom_frac() for key, val in c1.items(): n = nucname.name(key) crammed[n][i] = val # compute e^x of the diagonal of the decay matrix, ie the nuc itself nuc_idx = cram.NUCS_IDX[nuc] mat_idx = cram.IJ[nuc_idx, nuc_idx] diagexp[nuc][i] = exp(-DECAY_MATS[t][mat_idx]).evalf(n=30) return bateman, crammed, diagexp
def graph(nuc): """Returns a graphviz Digraph object for the decay chain starting from nuc.""" i = nucname.name(nuc) name = nucname.name(nuc) dot = Digraph(comment='Decay chain for ' + nuc) dot.node(name) nodes_seen = {name} kids = data.decay_children(i) from_to = {(i, j) for j in kids} edges_seen = set() while len(from_to) != 0: new_from_to = set() for ft in from_to: i, j = ft jname = nucname.name(j) if jname not in nodes_seen: dot.node(jname) nodes_seen.add(jname) if ft not in edges_seen: iname = nucname.name(i) try: label = rxname.name(i, j, 'decay') except RuntimeError: label = 'sf' label = PRETTY_RX.get(label, label) br = data.branch_ratio(i, j) if br < 1.0: label += ', br={0:.3}'.format(br) dot.edge(iname, jname, label=label) edges_seen.add(ft) kids = data.decay_children(j) new_from_to |= {(j, k) for k in kids} from_to = new_from_to return dot
def generate_run(self, run, fname): """Generate transmutation tables, neutron production/destruction rates, and burnup statistics for a sequence of states with the same initial conditions. Parameters ---------- run : list of States A list of States that has the same initial conditions at increasing burnup times. Returns ------- libs : list of dicts Libraries to write out - one for the full fuel and one for each tracked nuclide. """ self.libs = {'xs': [], 'phi_g': { 'E_g': {'EAF': self.eafds.src_group_struct, 'OpenMC': self.omcds.src_group_struct}, 'phi_g': []}, "fuel": { "TIME": [0], "NEUT_PROD": [0], "NEUT_DEST": [0], "BUd": [0], "material": [self.rc.fuel_material], "tracked_nucs": {nucname.name(n): [self.rc.fuel_material.comp.get(n, 0) * 1000] for n in self.rc.track_nucs}, "phi_tot": [0] }} for nuc in self.rc.track_nucs: self.libs[nuc] = { "TIME": [0], "NEUT_PROD": [0], "NEUT_DEST": [0], "BUd": [0], "material": [Material({nuc: 1}, 1000)], "tracked_nucs": {nucname.name(n): [0] for n in self.rc.track_nucs}, "phi_tot": [0] } self.libs[nuc]["tracked_nucs"][nucname.name(nuc)] = [1000] print([state.burn_times for state in run]) for i, state in enumerate(run): if i > 0: transmute_time = state.burn_times - run[i-1].burn_times results = self.generate(state, transmute_time) self.libs = self._update_libs_with_results(self.libs, results) self.rc.writers[0].write(self.libs, fname) return self.libs
def __getitem__(self, item): try: isotope = item.title() except AttributeError: try: nucname.name(item) except RuntimeError: raise ValueError('item is neither a integer or string that ' 'identifies an isotope') else: isotope = nucname.name(item) return self.data[isotope]
def parse_atomic_abund(build_dir=""): """Builds and returns a dictionary from nuclides to atomic abundence fractions.""" build_dir = os.path.join(build_dir, 'KAERI') # Grab and parse elemental summary files. natural_nuclides = set() for element in nucname.name_zz.keys(): htmlfile = element + '.html' natural_nuclides = natural_nuclides | parse_for_natural_isotopes( os.path.join(build_dir, htmlfile)) atomic_abund = {} for nuc in natural_nuclides: nuc_name = nucname.name(nuc) htmlfile = os.path.join(build_dir, nuc_name + '.html') with open(htmlfile, 'r') as f: for line in f: m = atomic_abund_regex.search(line) if m is not None: val = float(m.group(1)) * 0.01 atomic_abund[nuc] = val break return atomic_abund
def grab_kaeri_atomic_abund(build_dir=""): """Grabs the KAERI files needed for the atomic abundance calculation, if not already present. Parameters ---------- build_dir : str Major directory to place html files in. 'KAERI/' will be appended. """ # Add kaeri to build_dir build_dir = os.path.join(build_dir, 'KAERI') try: os.makedirs(build_dir) except OSError: pass already_grabbed = set(os.listdir(build_dir)) # Grab and parse elemental summary files. natural_nuclides = set() for element in nucname.name_zz.keys(): htmlfile = element + '.html' if htmlfile not in already_grabbed: grab_kaeri_nuclide(element, build_dir) natural_nuclides = natural_nuclides | parse_for_natural_isotopes( os.path.join(build_dir, htmlfile)) # Grab natural nuclide files for nuc in natural_nuclides: nuc = nucname.name(nuc) htmlfile = nuc + '.html' if htmlfile not in already_grabbed: grab_kaeri_nuclide(nuc, build_dir)
def parse_scattering_lengths(build_dir): """Converts to scattering lenth data to a numpy array.""" build_filename = os.path.join(build_dir, "scattering_lengths.html") # Read in cinder data file with open(build_filename, 'r') as f: raw_data = f.read() sl_data = [] # Iterate over all isotopes in the table for m in re.finditer(scat_len_pattern, raw_data): md = m.groupdict() slrow = (nucname.name(md['iso']), nucname.zzaaam(md['iso']), nist_num(md['b_coherent']) * (1E-13), nist_num(md['b_incoherent']) * (1E-13), nist_num(md['xs_coherent']), nist_num(md['xs_incoherent']), nist_num(md['xs'])) sl_data.append(slrow) sl_array = np.array(sl_data, dtype=sl_dtype) return sl_array
def parse_atomic_abund(build_dir=""): """Builds and returns a dictionary from nuclides to atomic abundence fractions.""" build_dir = os.path.join(build_dir, 'KAERI') # Grab and parse elemental summary files. natural_nuclides = set() for element in nucname.name_zz.keys(): htmlfile = element + '.html' natural_nuclides = natural_nuclides | parse_for_natural_isotopes(os.path.join(build_dir, htmlfile)) atomic_abund = {} for nuc in natural_nuclides: nuc_name = nucname.name(nuc) htmlfile = os.path.join(build_dir, nuc_name + '.html') with open(htmlfile, 'r') as f: for line in f: m = atomic_abund_regex.search(line) if m is not None: val = float(m.group(1)) * 0.01 atomic_abund[nuc] = val break return atomic_abund
def grab_kaeri_simple_xs(build_dir=""): """Grabs the KAERI files needed for the simple cross sections table, if not already present. Parameters ---------- build_dir : str Major directory to place html files in. 'KAERI/' will be appended. """ # Add kaeri to build_dir build_dir = os.path.join(build_dir, 'KAERI') try: os.makedirs(build_dir) except OSError: pass already_grabbed = set(os.listdir(build_dir)) # Grab and parse elemental summary files. all_nuclides = set() for element in nucname.name_zz.keys(): htmlfile = element + '.html' if htmlfile not in already_grabbed: grab_kaeri_nuclide(element, build_dir) all_nuclides = all_nuclides | parse_for_all_isotopes( os.path.join(build_dir, htmlfile)) # Grab nuclide XS summary files for nuc in sorted(all_nuclides): nuc = nucname.name(nuc) htmlfile = nuc + '_2.html' if htmlfile not in already_grabbed: grab_kaeri_nuclide(nuc, build_dir, 2)
def main(): # get list of nuclides data.atomic_mass('U235') nucs = set(data.atomic_mass_map.keys()) for nuc in data.atomic_mass_map: nucm = nuc + 1 if nucname.anum(nuc) == 0 or data.decay_const(nucm) < 1e-16 or \ data.decay_const(nuc) == data.decay_const(nucm): continue nucs.add(nucm) nucs = [nuc for nuc in nucs if nucname.anum(nuc) > 0] #and # not np.isnan(data.decay_const(nuc)) and # nuc < 200000000] nucs.sort() # get symbols symbols = {} channels = {} for nuc in nucs: add_child_decays(nuc, symbols) add_child_xss(nuc, channels, nucs) # print symbols ns = [] for nuc in nucs: try: nname = nucname.name(nuc) except RuntimeError: continue ns.append(nname) nucs = ns d = {'symbols': symbols, 'nucs': nucs, 'channels': channels} s = json.dumps(d, indent=4, sort_keys=True) print(s)
def convert_abundances_format(fname, delimiter='\s+'): df = pd.read_csv(fname, delimiter=delimiter, comment='#', header=None) #Drop shell index column df.drop(df.columns[0], axis=1, inplace=True) #Assign header row df.columns = [nucname.name(i) for i in range(1, df.shape[1] + 1)] return df
def add_child_decays(nuc, symbols): try: childname = nucname.name(nuc) except RuntimeError: return for rx in DECAY_RXS: try: parent = rxname.parent(nuc, rx, b'decay') except RuntimeError: continue if data.branch_ratio(parent, nuc) < 1e-16: continue parname = nucname.name(parent) symbols['lambda_' + parname] = data.decay_const(parent) gamma = 'gamma_{0}_{1}_{2}'.format(parname, childname, rx) symbols[gamma] = data.branch_ratio(parent, nuc)
def genelemfuncs( nucs, short=1e-16, small=1e-16, sf=False, debug=False, ): idx = dict(zip(nucs, range(len(nucs)))) cases = {i: [-1, []] for i in elems(nucs)} for nuc in nucs: z = nucname.znum(nuc) case, cases[z][0] = gencase(nuc, idx, cases[z][0], short=short, sf=sf, debug=debug, small=small) cases[z][1] += case funcs = [] for i, (b, kases) in cases.items(): kases[0] = kases[0][2:] ctx = dict(nucs=nucs, elem=nucname.name(i), cases='\n'.join(kases)) funcs.append(ELEM_FUNC.render(ctx)) return "\n\n".join(funcs)
def _update_libs_with_results(self, matlibs, newlibs): """Update a set of libraries with results from a single timestep in-place. Parameters ---------- matlibs : dict A set of libraries with nuclides as keys. newlibs: dict A set of libraries for a single timestep, with nuclides as keys. Returns ------- libs : dict The updated library. """ for mat, newlib in newlibs.items(): if mat == 'xs': matlibs[mat].append(newlib) continue elif mat == 'phi_g': matlibs[mat][mat].append(newlib) continue oldlib = matlibs[mat] for nuc in self.rc.track_nucs: name = nucname.name(nuc) nuc_frac = newlib["material"].comp.get(nuc, 0) mass = newlib["material"].mass oldlib["tracked_nucs"][name].append(nuc_frac * mass) for key, value in newlib.items(): if isinstance(key, int): continue else: oldlib[key].append(value) return matlibs
def _update_material(self): self.comp_dicts = [dict() for i in range(len(self.columns))] for (atomic_number, mass_number), abundances in self.iterrows(): nuclear_symbol = '%s%d'.format(nucname.name(atomic_number), mass_number) for i in range(len(self.columns)): self.comp_dicts[i][nuclear_symbol] = abundances[i]
def _generate_xs(self, e_g, phi_g): """Grab xs data from cache depending on group flux. Parameters ---------- e_g : list of floats Group structure. phi_g : list of floats Group flux. Returns ------- data : list of tuples A list of tuples of the format (nuc, rx, xs). """ rc = self.rc verbose = rc.verbose xscache = self.xscache xscache['E_g'] = e_g xscache['phi_g'] = phi_g G = len(phi_g) temp = rc.temperature rxs = self.reactions nucs = rc.track_nucs dt = np.dtype([('nuc', 'i4'), ('rx', np.uint32), ('xs', 'f8', G)]) data = np.empty(len(nucs)*len(rxs), dtype=dt) i = 0 for nuc in nucs: for rx in rxs: xs = xscache[nuc, rx, temp] if verbose: print("OpenMC XS:", nucname.name(nuc), rxname.name(rx), xs, temp) data[i] = nuc, rx, xs i += 1 return data
def grab_kaeri_atomic_abund(build_dir=""): """Grabs the KAERI files needed for the atomic abundance calculation, if not already present. Parameters ---------- build_dir : str Major directory to place html files in. 'KAERI/' will be appended. """ # Add kaeri to build_dir build_dir = os.path.join(build_dir, 'KAERI') try: os.makedirs(build_dir) except OSError: pass already_grabbed = set(os.listdir(build_dir)) # Grab and parse elemental summary files. natural_nuclides = set() for element in nucname.name_zz.keys(): htmlfile = element + '.html' if htmlfile not in already_grabbed: grab_kaeri_nuclide(element, build_dir) natural_nuclides = natural_nuclides | parse_for_natural_isotopes(os.path.join(build_dir, htmlfile)) # Grab natural nuclide files for nuc in natural_nuclides: nuc = nucname.name(nuc) htmlfile = nuc + '.html' if htmlfile not in already_grabbed: grab_kaeri_nuclide(nuc, build_dir)
def get_sigma_f_n(nuc): """Grabs a nuclide's fission cross-section from the nuc_data library. Parameters ---------- nuc : int nuclide in zzaaam form. Returns ------- sigma_f_n : numpy array This nuclide's fission cross-section pulled from the nuc_data library file. If not present in the library, a zero-array is returned. """ nuc_data = pyne_conf.NUC_DATA_PATH with tb.openFile(nuc_data, 'r') as f: N = f.root.neutron.cinder_xs.fission.coldescrs['xs'].shape[0] cond = 'nuc_zz == {0}'.format(nuc) rows = [np.array(row['xs']) for row in f.root.neutron.cinder_xs.fission.where(cond)] if len(rows) == 0: # Not fissionable, return zero-array sigma_f_n = np.zeros(N, dtype=float) elif len(rows) == 1: # Return cross-section from file sigma_f_n = rows[0] else: nuc_name = nucname.name(nuc) err_str = "The database contains multiple entries for the fission cross-section for {0}!".format(nuc_name) raise ValueError(err_str) return sigma_f_n
def _nucid_to_xs(mat_lib, **kwargs): """Replace nucids with xs library names. """ if 'nuc_names' in kwargs: nuc_names = kwargs['nuc_names'] names_tf = True else: names_tf = False mat_xs_names = {} for mat in mat_lib: mat_name = strip_mat_name(mat) mat_xs_names[mat_name] = {} for nucid in mat_lib[mat]: if names_tf: if nucid in nuc_names: name = nuc_names[nucid] mat_xs_names[mat_name][name] = mat_lib[mat][nucid] else: warn("Nucid {0} does not exist in the provided nuc_names dictionary.".format(nucid)) mat_xs_names[mat_name]["{0}".format(nucid)] = mat_lib[mat][nucid] else: mat_xs_names[mat_name][nucname.name(nucid)] = mat_lib[mat][nucid] return mat_xs_names
def _nucid_to_xs(mat_lib, **kwargs): """Replace nucids with xs library names.""" if "nuc_names" in kwargs: nuc_names = kwargs["nuc_names"] names_tf = True else: names_tf = False mat_xs_names = {} for mat in mat_lib: mat_xs_names[mat] = {} for nucid in mat_lib[mat]: if names_tf: if nucid in nuc_names: name = nuc_names[nucid] mat_xs_names[mat][name] = mat_lib[mat][nucid] else: warn( "Nucid {0} does not exist in the provided nuc_names dictionary." .format(nucid)) mat_xs_names[mat]["{0}".format( nucid)] = mat_lib[mat][nucid] else: mat_xs_names[mat][nucname.name(nucid)] = mat_lib[mat][nucid] return mat_xs_names
def grab_kaeri_simple_xs(build_dir=""): """Grabs the KAERI files needed for the simple cross sections table, if not already present. Parameters ---------- build_dir : str Major directory to place html files in. 'KAERI/' will be appended. """ # Add kaeri to build_dir build_dir = os.path.join(build_dir, 'KAERI') try: os.makedirs(build_dir) except OSError: pass already_grabbed = set(os.listdir(build_dir)) # Grab and parse elemental summary files. all_nuclides = set() for element in nucname.name_zz.keys(): htmlfile = element + '.html' if htmlfile not in already_grabbed: grab_kaeri_nuclide(element, build_dir) all_nuclides = all_nuclides | parse_for_all_isotopes(os.path.join(build_dir, htmlfile)) # Grab nuclide XS summary files for nuc in sorted(all_nuclides): nuc = nucname.name(nuc) htmlfile = nuc + '_2.html' if htmlfile not in already_grabbed: grab_kaeri_nuclide(nuc, build_dir, 2)
def make_atomic_weight_table(nuc_data, build_dir=""): """Makes an atomic weight table in the nuc_data library. Parameters ---------- nuc_data : str Path to nuclide data file. build_dir : str Directory to place html files in. """ # Grab raw data atomic_abund = parse_atomic_abund(build_dir) atomic_masses = parse_atmoic_mass_adjustment(build_dir) A = {} # Add normal isotopes to A for nuc_zz, mass, error in atomic_masses: try: nuc_name = nucname.name(nuc_zz) except RuntimeError: continue if nuc_zz in atomic_abund: A[nuc_zz] = nuc_name, nuc_zz, mass, error, atomic_abund[nuc_zz] else: A[nuc_zz] = nuc_name, nuc_zz, mass, error, 0.0 # Add naturally occuring elements for element in nucname.name_zz: nuc_zz = nucname.zzaaam(element) A[nuc_zz] = element, nuc_zz, 0.0, 0.0, 0.0 for nuc, abund in atomic_abund.items(): zz = nuc / 10000 element_zz = zz * 10000 element = nucname.zz_name[zz] nuc_name, nuc_zz, nuc_mass, _error, _abund = A[nuc] elem_name, elem_zz, elem_mass, _error, _abund = A[element_zz] new_elem_mass = elem_mass + (nuc_mass * abund) A[element_zz] = element, element_zz, new_elem_mass, 0.0, 0.0 A = sorted(A.values(), key=lambda x: x[1]) # A = np.array(A, dtype=atomic_weight_dtype) # Open the HDF5 File kdb = tb.openFile(nuc_data, "a", filters=BASIC_FILTERS) # Make a new the table Atable = kdb.createTable("/", "atomic_weight", atomic_weight_desc, "Atomic Weight Data [amu]", expectedrows=len(A)) Atable.append(A) # Ensure that data was written to table Atable.flush() # Close the hdf5 file kdb.close()
def get_nuc_name(self, nuc_code): """Returns nuclide name in human-readable notation: chemical symbol (one or two characters), dash, and the atomic weight. Lastly, if the nuclide is in metastable state, the letter `m` is concatenated with number of excited state. For example, `Am-242m1`. Parameters ---------- nuc_code : str Name of nuclide in Serpent2 form. For instance, `Am-242m`. Returns ------- nuc_name : str Name of nuclide in human-readable notation (`Am-242m1`). nuc_zzaaam : str Name of nuclide in `zzaaam` form (`952421`). """ if '.' in str(nuc_code): nuc_code = pyname.zzzaaa_to_id(int(nuc_code.split('.')[0])) zz = pyname.znum(nuc_code) aa = pyname.anum(nuc_code) aa_str = str(aa) # at_mass = pydata.atomic_mass(nuc_code_id) if aa > 300: if zz > 76: aa_str = str(aa - 100) + 'm1' aa = aa - 100 else: aa_str = str(aa - 200) + 'm1' aa = aa - 200 nuc_zzaaam = str(zz) + str(aa) + '1' elif aa == 0: aa_str = 'nat' nuc_name = pyname.zz_name[zz] + aa_str else: meta_flag = pyname.snum(nuc_code) if meta_flag: nuc_name = pyname.name(nuc_code)[:-1] + 'm' + str(meta_flag) else: nuc_name = pyname.name(nuc_code) nuc_zzaaam = \ self.convert_nuclide_name_serpent_to_zam(pyname.zzaaam(nuc_code)) return nuc_name, nuc_zzaaam
def gencases(nucs): switches = [] for i in elems(nucs): c = ['case {0}:'.format(i), ' decay_{0}(t, it, outcomp, out);'.format(nucname.name(i).lower()), ' break;'] switches.append('\n'.join(c)) return '\n'.join(switches)
def gencases(nucs): switches = [] for i in elems(nucs): c = [ 'case {0}:'.format(i), ' decay_{0}(t, it, outcomp, out);'.format( nucname.name(i).lower()), ' break;' ] switches.append('\n'.join(c)) return '\n'.join(switches)
def add_child_xss(nuc, channels, parents): try: childname = nucname.name(nuc) except RuntimeError: return channels[childname] = rxs = {} for rx in XS_RXS: try: parent = rxname.parent(nuc, rx) except RuntimeError: continue if parent not in parents: continue try: parname = nucname.name(parent) except RuntimeError: continue rxs[rx] = parname
def parse_decay(build_dir=""): """Builds and returns a list of nuclide decay data. """ build_dir = os.path.join(build_dir, 'ENSDF') decay_data = [] files = sorted([f for f in glob.glob(os.path.join(build_dir, 'ensdf.*'))]) for f in files: print " parsing decay data from {0}".format(f) decay_data += ensdf.half_life(f) ln2 = np.log(2.0) decay_data = [(nucname.name(fn), fn, lvl, nucname.name(tn), tn, hl, ln2/hl, br) for fn, lvl, tn, hl, br in decay_data] decay_array = np.array(decay_data, dtype=atomic_decay_dtype) da, mask = np.unique(decay_array, return_index=True) mask.sort() decay_array = decay_array[mask] return decay_array
def MC2_3MaterialWriter(heu_atom): temperature=800.0 print"\n\n" print"\$material" print"i_externalspectrum(1)= 1 ! Spectrum file for composition: I_FUEL" print "t_composition(:, 1)=" for iso in heu_atom: # NA23_7 NA23I 8.04935E-03 740.5 print " {iso}_7 {iso}I {wt_pt:.5E} {temp:.1f}".format(iso=nucname.name(iso), wt_pt=heu_atom[iso],temp=temperature) print "/"
def gencases(nucs, debug=False): switches = [] for i in elems(nucs): c = [ "case {0}:".format(i), " decay_{0}(t, it, outcomp, out);".format(nucname.name(i).lower()), " break;", ] switches.append("\n".join(c)) return "\n".join(switches)
def elemental_row(row): if re.match('[A-Z][a-z]?-?(\d{1,3})?$', row[0]): element = nucname.zzaaam(row[0]) weight_frac = row[3] if nucname.name(element) in elemental_mats: composition.update(elemental_mats[row[0].upper()]) else: composition[element] = float(weight_frac) nuc_zz.add(element) else: pass
def convert_zaids_to_names(zaids): names = [] for item in zaids: item_id = nucname.mcnp_to_id(item) name = nucname.name(item_id) # print(item, name) if name not in [ 'C12', 'C13', 'O18', 'Pt190', 'Pt192', 'Pt194', 'Pt195', 'Pt196', 'Pt198' ]: # I don't have these cross section names.append(name) return names
def genelemfuncs(nucs, short=1e-8, sf=False): idx = dict(zip(nucs, range(len(nucs)))) cases = {i: [-1, []] for i in elems(nucs)} for nuc in nucs: z = nucname.znum(nuc) case, cases[z][0] = gencase(nuc, idx, cases[z][0], short=short, sf=sf) cases[z][1] += case funcs = [] for i, (b, kases) in cases.items(): kases[0] = kases[0][2:] ctx = dict(nucs=nucs, elem=nucname.name(i), cases='\n'.join(kases)) funcs.append(ELEM_FUNC.render(ctx)) return "\n\n".join(funcs)
def grab_photon_fp_info(raw_data): """Grabs the photon fission product info. Parameters ---------- raw_data : str string of the cinder.dat data file. Returns ------- info_table : array Structured array with the form "(index, nuc_name, nuc_zz, type, mass)". """ # Get group sizes N_n, N_g = get_fp_sizes(raw_data) # Grab the part of the file that is a neutron fission product yield info m_info = re.search(gfp_info_pattern, raw_data, re.DOTALL) gfp_info_raw = m_info.group(0) # Grab the index, nuctope, and type iits = re.findall(iit_pattern, gfp_info_raw) # Grab the masses masses = re.findall(mass_pattern, gfp_info_raw) # Make sure data is the right size assert N_g == len(iits) assert N_g == len(masses) # Make info table rows info_table = [] for m in range(N_g): iit = iits[m] index = int(iit[0]) nuc_zz = nucname.zzaaam(iit[1]) # Correct for metastable flag if 0 != nuc_zz%10: nuc_zz = nuc_zz + 2000 nuc_name = nucname.name(nuc_zz) type = fp_type_flag[iit[2]] mass = float(masses[m]) info_row = (index, nuc_name, nuc_zz, type, mass) info_table.append(info_row) info_table = np.array(info_table, dtype=fp_info_dtype) return info_table
def facility_commodity_flux_isotopics(cur, agent_ids, commod_list, is_outflux, is_cum=True): """ Returns timeseries isotoptics of commodity in/outflux from agents Parameters ---------- cur: sqlite cursor sqlite cursor agent_ids: list list of agentids commod_list: list list of commodities is_outflux: bool gets outflux if True, influx if False is_cum: bool gets cumulative timeseris if True, monthly value if False Returns ------- iso_dict: dictionary dictionary with "key=isotope, and value=timeseries list of masses in kg" """ init_year, init_month, duration, timestep = get_timesteps(cur) iso_dict = collections.defaultdict(list) for comm in commod_list: query = ('SELECT time, sum(quantity)*massfrac, nucid ' 'FROM transactions INNER JOIN resources ' 'ON resources.resourceid = transactions.resourceid ' 'LEFT OUTER JOIN compositions ' 'ON compositions.qualid = resources.qualid ' 'WHERE (receiverid = ' + ' OR receiverid = '.join(agent_ids) + ') AND (commodity = "' + str(comm) + '") GROUP BY time, nucid') # outflux changes receiverid to senderid if is_outflux: query = query.replace('receiverid', 'senderid') res = cur.execute(query).fetchall() for time, amount, nucid in res: iso_dict[nucname.name(nucid)].append((time, amount)) for key in iso_dict: if is_cum: iso_dict[key] = get_timeseries_cum(iso_dict[key], duration, True) else: iso_dict[key] = get_timeseries(iso_dict[key], duration, True) return iso_dict
def parse_simple_xs(build_dir=""): """Builds and returns a dictionary from cross-section types to nuclides.""" build_dir = os.path.join(build_dir, "KAERI") # Grab and parse elemental summary files. all_nuclides = set() for element in nucname.name_zz.keys(): htmlfile = element + ".html" all_nuclides = all_nuclides | parse_for_all_isotopes(os.path.join(build_dir, htmlfile)) all_nuclides = sorted([nucname.zzaaam(nuc) for nuc in all_nuclides]) energy_tables = {eng: np.zeros(len(all_nuclides), dtype=simple_xs_dtype) for eng in simple_xs_energy.keys()} # Loop through species for i, nuc_zz in enumerate(all_nuclides): nuc_name = nucname.name(nuc_zz) filename = os.path.join(build_dir, nuc_name + "_2.html") # Loop through all energy types for eng in simple_xs_energy: energy_tables[eng]["nuc_name"][i] = nuc_name energy_tables[eng]["nuc_zz"][i] = nuc_zz # Loop trhough reactions for chan in simple_xs_channels: energy_tables[eng][chan][i] = get_xs_from_file(filename, eng, chan) for eng in simple_xs_energy: # Store only non-trivial entries mask = ( energy_tables[eng][simple_xs_channels.keys()] != np.zeros(1, dtype=simple_xs_dtype)[simple_xs_channels.keys()] ) energy_tables[eng] = energy_tables[eng][mask] # Calculate some xs energy_tables[eng]["sigma_s"] = energy_tables[eng]["sigma_e"] + energy_tables[eng]["sigma_i"] energy_tables[eng]["sigma_a"] = ( energy_tables[eng]["sigma_gamma"] + energy_tables[eng]["sigma_f"] + energy_tables[eng]["sigma_alpha"] + energy_tables[eng]["sigma_proton"] + energy_tables[eng]["sigma_deut"] + energy_tables[eng]["sigma_trit"] + energy_tables[eng]["sigma_2n"] + energy_tables[eng]["sigma_3n"] + energy_tables[eng]["sigma_4n"] ) return energy_tables
def grab_kaeri_nuclide(nuc, build_dir="", n=None): """Grabs a nuclide file from KAERI from the web and places it a {nuc}.html file in the build directory. Parameters ---------- nuc : str, int nuclide, preferably in name form. build_dir : str, optional Directory to place html files in. n : None or int Optional flag on data to grab. None = basic data, 2 = cross section summary, 3 = cross section graphs. """ if not isinstance(nuc, basestring): nuc = nucname.name(nuc).upper() if n is None: filename = os.path.join(build_dir, nuc + ".html") kaeri_url = "http://atom.kaeri.re.kr/cgi-bin/nuclide?nuc={0}".format(nuc) else: filename = os.path.join(build_dir, "{nuc}_{n}.html".format(nuc=nuc, n=n)) kaeri_url = "http://atom.kaeri.re.kr/cgi-bin/nuclide?nuc={0}&n={n}".format( nuc, n=n ) print(" getting {0} and placing in {1}".format(nuc, filename)) # Get the url req = urllib2.Request(kaeri_url, headers={"User-Agent": "Mozilla/5.0"}) hdl = urllib2.urlopen(req, timeout=30.0) i = 1 # try reading in the data until it works or ten times read_in = False while (not read_in) and (i <= 10): try: kaeri_html = hdl.read() read_in = True except URLError: hdl.close() i += 1 print( " getting {0} and placing in {1}, attempt {2}".format( nuc, filename, i ) ) hdl = urllib2.urlopen(req, timeout=30.0) # Write out to the file with open(filename, "w") as f: f.write(kaeri_html)
def parse_simple_xs(build_dir=""): """Builds and returns a dictionary from cross-section types to nuclides.""" build_dir = os.path.join(build_dir, 'KAERI') # Grab and parse elemental summary files. all_nuclides = set() for element in nucname.name_zz.keys(): htmlfile = element + '.html' all_nuclides = all_nuclides | parse_for_all_isotopes( os.path.join(build_dir, htmlfile)) all_nuclides = sorted([nucname.zzaaam(nuc) for nuc in all_nuclides]) energy_tables = dict([(eng, np.zeros(len(all_nuclides), dtype=simple_xs_dtype)) \ for eng in simple_xs_energy.keys()]) # Loop through species for i, nuc in enumerate(all_nuclides): nuc_name = nucname.name(nuc) filename = os.path.join(build_dir, nuc_name + '_2.html') # Loop through all energy types for eng in simple_xs_energy: energy_tables[eng]['nuc'][i] = nuc # Loop trhough reactions for chan in simple_xs_channels: energy_tables[eng][chan][i] = get_xs_from_file( filename, eng, chan) for eng in simple_xs_energy: # Store only non-trivial entries mask = (energy_tables[eng][simple_xs_channels.keys()] != np.zeros( 1, dtype=simple_xs_dtype)[simple_xs_channels.keys()]) energy_tables[eng] = energy_tables[eng][mask] # Calculate some xs energy_tables[eng]['sigma_s'] = energy_tables[eng][ 'sigma_e'] + energy_tables[eng]['sigma_i'] energy_tables[eng]['sigma_a'] = energy_tables[eng]['sigma_gamma'] + \ energy_tables[eng]['sigma_f'] + \ energy_tables[eng]['sigma_alpha'] + \ energy_tables[eng]['sigma_proton'] + \ energy_tables[eng]['sigma_deut'] + \ energy_tables[eng]['sigma_trit'] + \ energy_tables[eng]['sigma_2n'] + \ energy_tables[eng]['sigma_3n'] + \ energy_tables[eng]['sigma_4n'] return energy_tables
def parent_decay_to_gammas(self, total_ions, decay_parent, decay_to_gammas): tm = Transmuter(tol=1e-10, log=sys.stdout) inp = Material({decay_parent: 1.0}, mass=1.0) decay_chain = tm.transmute(inp, t=self.time_in_trap_per_cycle, tol=1e-5) for decay_product in decay_chain: decay_name = nucname.name(decay_product) if decay_name in decay_to_gammas: self.write_gammas( decay_chain[decay_product], total_ions, decay_to_gammas[decay_name], "gammas_" + decay_to_gammas[decay_name] + ".csv") return
def parse_simple_xs(build_dir=""): """Builds and returns a dictionary from cross-section types to nuclides.""" build_dir = os.path.join(build_dir, 'KAERI') # Grab and parse elemental summary files. all_nuclides = set() for element in nucname.name_zz.keys(): htmlfile = element + '.html' all_nuclides = all_nuclides | parse_for_all_isotopes(os.path.join(build_dir, htmlfile)) all_nuclides = sorted([nucname.zzaaam(nuc) for nuc in all_nuclides]) energy_tables = dict([(eng, np.zeros(len(all_nuclides), dtype=simple_xs_dtype)) \ for eng in simple_xs_energy.keys()]) # Loop through species for i, nuc in enumerate(all_nuclides): nuc_name = nucname.name(nuc) filename = os.path.join(build_dir, nuc_name + '_2.html') # Loop through all energy types for eng in simple_xs_energy: energy_tables[eng]['nuc'][i] = nuc # Loop trhough reactions for chan in simple_xs_channels: energy_tables[eng][chan][i] = get_xs_from_file(filename, eng, chan) for eng in simple_xs_energy: # Store only non-trivial entries mask = (energy_tables[eng][simple_xs_channels.keys()] != np.zeros(1, dtype=simple_xs_dtype)[simple_xs_channels.keys()]) energy_tables[eng] = energy_tables[eng][mask] # Calculate some xs energy_tables[eng]['sigma_s'] = energy_tables[eng]['sigma_e'] + energy_tables[eng]['sigma_i'] energy_tables[eng]['sigma_a'] = energy_tables[eng]['sigma_gamma'] + \ energy_tables[eng]['sigma_f'] + \ energy_tables[eng]['sigma_alpha'] + \ energy_tables[eng]['sigma_proton'] + \ energy_tables[eng]['sigma_deut'] + \ energy_tables[eng]['sigma_trit'] + \ energy_tables[eng]['sigma_2n'] + \ energy_tables[eng]['sigma_3n'] + \ energy_tables[eng]['sigma_4n'] return energy_tables
def write(self, libs, dirname): """Write out libraries to a directory. Parameters ---------- libs : dict The reactor libraries gleaned from buk. dirname : str The output directory. """ if not os.path.isdir(dirname): os.makedirs(dirname) rownames = ["TIME", "phi_tot", "NEUT_PROD", "NEUT_DEST", "BUd"] for mat, matlib in libs.items(): if isinstance(mat, int): fname = str(nucname.zzaaam(mat)) elif mat == 'fuel': fname = mat else: continue trans_matrix = {} if os.path.isdir(os.path.join(dirname, fname + ".txt")): libs, trans_matrix = self.update(libs, dirname, fname) else: i = 0 while i < len(matlib['material']): for temp_nuc in matlib['material'][i].comp: nuc_name = str(nucname.name(temp_nuc)) try: trans_matrix[nuc_name].append(matlib['material'][i].comp[temp_nuc]*1000) except KeyError: if matlib['material'][i].comp[temp_nuc] > self.rc.track_nuc_threshold: zero_array = [0.]*i trans_matrix[nuc_name] = zero_array trans_matrix[nuc_name].append(matlib['material'][i].comp[temp_nuc]*1000) i+=1 lines = [row + " " + " ".join(map(str, matlib[row])) for row in rownames] lines.extend(sorted([n + " " + " ". join(["{:.4g}".format(f) for f in trans_matrix[n]]) for n in trans_matrix])) with open(os.path.join(dirname, fname + ".txt"), "w") as f: f.write("\n".join(lines)) nucs = matlib["tracked_nucs"] if not os.path.isfile(os.path.join(dirname, "manifest.txt")): self.write_metadata(nucs, libs, dirname)
def grab_kaeri_nuclide(nuc, build_dir="", n=None): """Grabs a nuclide file from KAERI from the web and places it a {nuc}.html file in the build directory. Parameters ---------- nuc : str, int nuclide, preferably in name form. build_dir : str, optional Directory to place html files in. n : None or int Optional flag on data to grab. None = basic data, 2 = cross section summary, 3 = cross section graphs. """ if not isinstance(nuc, basestring): nuc = nucname.name(nuc) if n is None: filename = os.path.join(build_dir, nuc + '.html') kaeri_url = 'http://atom.kaeri.re.kr/cgi-bin/nuclide?nuc={0}'.format(nuc) else: filename = os.path.join(build_dir, '{nuc}_{n}.html'.format(nuc=nuc, n=n)) kaeri_url = 'http://atom.kaeri.re.kr/cgi-bin/nuclide?nuc={0}&n={n}'.format(nuc, n=n) print " getting {0} and placing in {1}".format(nuc, filename) # Get the url req = urllib2.Request(kaeri_url, headers={'User-Agent': 'Mozilla/5.0'}) hdl = urllib2.urlopen(req, timeout=30.0) i = 1 # try reading in the data until it works or ten times read_in = False while (not read_in) and (i <= 10): try: kaeri_html = hdl.read() read_in = True except urllib2.URLError: hdl.close() i += 1 print " getting {0} and placing in {1}, attempt {2}".format(nuc, filename, i) hdl = urllib2.urlopen(req, timeout=30.0) # Write out to the file with open(filename, 'w') as f: f.write(kaeri_html)
def to_materials(self): """ Convert DataFrame to a list of materials interpreting the MultiIndex as atomic_number and mass_number Returns ------- list list of pyne Materials """ comp_dicts = [dict() for i in range(len(self.columns))] for (atomic_number, mass_number), abundances in self.iterrows(): nuclear_symbol = "{0:s}{1:d}".format(nucname.name(atomic_number), mass_number) for i in range(len(self.columns)): comp_dicts[i][nuclear_symbol] = abundances[i] return [material.Material(comp_dict) for comp_dict in comp_dicts]
def _sanitize_isotope_string(isotope_string): """ Checks if the string given is a valid isotope_string Parameters ---------- isotope_string: str Returns ------- sanitized_isotope_string: str """ try: sanitized_isotope_string = nucname.name(isotope_string) except RuntimeError: raise ValueError(f'{isotope_string} not a valid isotope string') else: return sanitized_isotope_string
def to_materials(self): """ Convert DataFrame to a list of materials interpreting the MultiIndex as atomic_number and mass_number Returns ------- : ~list list of pyne Materialss :return: """ comp_dicts = [dict() for i in range(len(self.columns))] for (atomic_number, mass_number), abundances in self.iterrows(): nuclear_symbol = '{0:s}{1:d}'.format(nucname.name(atomic_number), mass_number) for i in range(len(self.columns)): comp_dicts[i][nuclear_symbol] = abundances[i] return [material.Material(comp_dict) for comp_dict in comp_dicts]
def make_materials_compendium(nuc_data): """Adds materials compendium to nuc_data.h5.""" # open nuc_data, make nuc_zz an array with tb.openFile(nuc_data, 'r+', filters=tb.Filters(complevel=5, complib='zlib', shuffle=True, fletcher32=False)) as f: f.createGroup('/', 'materials_library') f.createArray('/materials_library', 'nuc_zz', np.array(list(nuc_zz))) # Writes elements for which we have compositional data to file for zz in elemental_mats: if 0 == len(elemental_mats[zz]): continue element = Material(elemental_mats[zz], mass = 1.0, attrs = {'name':nucname.name(zz)}) element.write_hdf5(nuc_data, datapath="/materials_library/materials", nucpath="/materials_library/nuc_zz", chunksize=70) # Writes materials from mats to file, and names them. for i in range(len(mats)): mats[i].mass = 1.0 mats[i].density = float(densities[i]) mats[i].attrs = {'name': names[i]} mats[i].write_hdf5(nuc_data, datapath="/materials_library/materials", nucpath="/materials_library/nuc_zz", chunksize=70)
def make_elements(): """Make natural elemental materials based on isotopic abundances. Returns ------- eltsdict : dict from str to pyne.material.Material Natural elements as materials. """ natural_abund("H1") # initialize natural_abund_map # get rid of elemental total abundances and empty isotopic abundances abunds_no_trivial = [abund for abund in natural_abund_map.items() if nucname.anum(abund[0]) != 0 and abund[1] != 0] sorted_abunds = sorted(abunds_no_trivial) grouped_abunds = groupby(sorted_abunds, lambda abund: nucname.znum(abund[0])) # filter out 111, 113, 115, 117, 118 - the ones with no names elts = (Material(dict(abunds), metadata={"name": nucname.name(zz)}) for zz, abunds in grouped_abunds if zz in nucname.zz_name.keys()) eltsdict = dict(((elt.metadata["name"], elt) for elt in elts)) return eltsdict
def _generate_xs(self, phi_g): rc = self.rc verbose = rc.verbose xscache = self.xscache xscache['E_g'] = rc.group_structure xscache['phi_g'] = phi_g G = len(phi_g) temp = rc.temperature rxs = self.reactions nucs = rc.core_transmute dt = np.dtype([('nuc', 'i4'), ('rx', np.uint32), ('xs', 'f8', G)]) data = np.empty(len(nucs)*len(rxs), dtype=dt) i = 0 for nuc in nucs: for rx in rxs: xs = xscache[nuc, rx, temp] if verbose: print("OpenMC XS:", nucname.name(nuc), rxname.name(rx), xs) data[i] = nuc, rx, xs i += 1 return data
def convert_abundances_format(fname, delimiter=r"\s+"): """ Changes format of file containing abundances into data frame Parameters ---------- fname : file, str File or file name that contains abundance info delimiter : str, optional(default = '\\s+') Determines the separator for splitting file Returns ------- DataFrame Corresponding data frame """ df = pd.read_csv(fname, delimiter=delimiter, comment="#", header=None) # Drop shell index column df.drop(df.columns[0], axis=1, inplace=True) # Assign header row df.columns = [nucname.name(i) for i in range(1, df.shape[1] + 1)] return df
def adens_to_mass(fuel_vol, array, iso_names): shape = array.shape mass_array = np.zeros(shape) for num, row in enumerate(array): mat_dict = {} mass_comp = np.zeros(len(row)) for indx, val in enumerate(row): mat_dict[iso_names[indx]] = val mat = Material() mat.from_atom_frac(mat_dict) # mat.comp is mass density for key, val in mat.comp.items(): key = nucname.name(key) iso_indx = list(iso_names).index(key) # mass = mass density * volume * unit(barns) mass_comp[indx] = val * fuel_vol * 1e24 mass_array[num] = mass_comp # you still there? if num == (len(array) // 2): print('halfway there') return mass_array
def _log_tree(self, depth, nuc, numdens): """Logging method to track path of _traversal. Parameters ---------- depth : integer Current depth of traversal (root at 0). nuc : nucname Current nuclide in traversal. numdens : float Current number density of nuc. tree : File File to write tree log to. """ # Don't print a zero density. if numdens == 0.0: return space = ' |' entry = "{spacing}--> {name} {numdens}\n".format( spacing=depth * space, numdens=numdens, name=nucname.name(nuc)) self.log.write(entry) self.log.flush()
def _log_tree(self, depth, nuc, numdens): """Logging method to track path of _traversal. Parameters ---------- depth : integer Current depth of traversal (root at 0). nuc : nucname Current nuclide in traversal. numdens : float Current number density of nuc. tree : File File to write tree log to. """ # Don't print a zero density. if numdens == 0.0: return space = ' |' entry = "{spacing}--> {name} {numdens}\n".format(spacing=depth*space, numdens=numdens, name=nucname.name(nuc)) self.log.write(entry) self.log.flush()
def findPeaks(energyList=[], energyUncertainty=[], intensityList=[], intensityUncertainty=[]): """Finds relevant 'peak' elements in a spectra. Args: energyList: energies associated with an intensity peak in our dataset. energyUncertainty: uncertainties of energy values (in order). intensityList: The spectrum of intensities in our dataset. intensityUncertainty: The uncertainties of intensity peaks (in order) of dataset """ #initialize posEl = [] counts = 0 bestCount = 0 bestElement = 'FirstRun' abundance = 0.0 bCE = [] bAE = [] bA = [] bC = [] bCEN = [] bAEN = [] bAN = [] bCN = [] #for each energy, find the parents associated with that energy posEl = findParents(energyList, energyUncertainty) for element in posEl: counts = 0 #find all intensities associated with this element intensities = data.gamma_photon_intensity(element) #find unicode name of element name = nucname.name(element) #count number of intensity peaks that this set has in common #with this element counts = countIntensityPeaks(intensities, intensityList, intensityUncertainty) #calculate relative counts and natural abundance counts = 1.0 * counts / len(intensities) abundance = data.natural_abund(element) #update lists addToLists(bC, bA, bCE, bAE, bCN, bAN, bCEN, bAEN, counts, abundance, name, element) checkAbundanceLists(abundance, name, bA, bAE, bAN, element, bAEN) checkCountsLists(abundance, name, element, bCE, bC, bCN, bCEN, counts) if (counts > bestCount and abundance > 0.0 and abundance < 1.0 and name[-1] != 'M'): num = getNum(name) if bestElement == 'FirstRun': bestCount = counts bestElement = name counts = 0 elif num < getNum(bestElement): bestCount = counts bestElement = name counts = 0 elif data.natural_abund(bestElement) < abundance: bestCount = counts bestElement = name counts = 0 presentInfo(bestElement, bAN, bAEN)
def test_name(): assert_equal(nucname.name(942390), "Pu239") assert_equal(nucname.name(952421), "Am242M") assert_equal(nucname.name("PU239"), "Pu239") assert_equal(nucname.name(94239), "Pu239") assert_equal(nucname.name(95242), "Am242M") assert_equal(nucname.name(95642), "Am242") assert_equal(nucname.name(92636), "U236M") assert_equal(nucname.name("Am-242m"), "Am242M") assert_equal(nucname.name(40020), "He4") assert_equal(nucname.name(2440961), "Cm244M") assert_equal(nucname.name(2390940), "Pu239") assert_equal(nucname.name(2420950), "Am242")
if t_term_i: term += "*t" terms.append(term) terms = " + ".join(terms) return CHAIN_EXPR.format(terms), b, bt def gencase(nuc, idx, b, short=1e-16, small=1e-16, sf=False, debug=False): case = ["}} case {0}: {{".format(nuc)] dc = decay_const(nuc, False) if dc == 0.0: # stable nuclide case.append(CHAIN_STMT.format(idx[nuc], "it->second")) else: chains = genchains([(nuc,)], sf=sf) print("{} has {} chains".format(nucname.name(nuc), len(set(chains)))) cse = {} # common sub-expression exponents to elimnate bt = 0 for c in chains: if c[-1] not in idx: continue cexpr, b, bt = chainexpr(c, cse, b, bt, short=short, small=small) if cexpr is None: continue if debug: case.append(" // " + " -> ".join(map(nucname.name, c))) case.append(CHAIN_STMT.format(idx[c[-1]], cexpr)) bstmts = [ " " + B_STMT.format(exp=exp, b=bval) for exp, bval in sorted(cse.items(), key=lambda x: x[1]) ]
def get_trade_dict(cur, sender, receiver, is_prototype, do_isotopic, is_cum=True): """ Returns trade timeseries between two prototypes' or facilities with or without isotopics Parameters ---------- cur: sqlite cursor sqlite cursor sender: str name of sender as facility type or prototype name receiver: str name of receiver as facility type or prototype name is_prototype: bool if True, search sender and receiver as prototype, if False, as facility type from spec. do_isotopic: bool if True, perform isotopics (takes significantly longer) is_cum: bool gets cumulative timeseris if True, monthly value if False Returns: -------- return_dict: dictionary if do_isotopic: dictionary with "key=isotope, and value=timeseries list of mass traded between two prototypes" else: dictionary with "key=string, sender to receiver, value=timeseries list of mass traded between two prototypes" """ init_year, init_month, duration, timestep = get_timesteps(cur) iso_dict = collections.defaultdict(list) return_dict = collections.defaultdict() if is_prototype: sender_id = get_prototype_id(cur, sender) receiver_id = get_prototype_id(cur, receiver) else: sender_id = get_agent_ids(cur, sender) receiver_id = get_agent_ids(cur, receiver) if do_isotopic: trade = cur.execute('SELECT time, sum(quantity)*massfrac, nucid ' 'FROM transactions INNER JOIN resources ON ' 'resources.resourceid = transactions.resourceid ' 'LEFT OUTER JOIN compositions ' 'ON compositions.qualid = resources.qualid ' 'WHERE (senderid = ' + ' OR senderid = '.join(sender_id) + ') AND (receiverid = ' + ' OR receiverid = '.join(receiver_id) + ') GROUP BY time, nucid').fetchall() else: trade = cur.execute('SELECT time, sum(quantity), qualid ' 'FROM transactions INNER JOIN resources ON ' 'resources.resourceid = transactions.resourceid' ' WHERE (senderid = ' + ' OR senderid = '.join(sender_id) + ') AND (receiverid = ' + ' OR receiverid = '.join(receiver_id) + ') GROUP BY time').fetchall() if do_isotopic: for time, amount, nucid in trade: iso_dict[nucname.name(nucid)].append((time, amount)) for key in iso_dict: if is_cum: iso_dict[key] = get_timeseries_cum(iso_dict[key], duration, True) else: iso_dict[key] = get_timeseries(iso_dict[key], duration, True) return iso_dict else: key_name = str(sender)[:5] + ' to ' + str(receiver)[:5] if is_cum: return_dict[key_name] = get_timeseries_cum(trade, duration, True) else: return_dict[key_name] = get_timeseries(trade, duration, True) return return_dict
@author: tyler """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 24 08:28:02 2018 @author: tyler """ from pyne import data from pyne import nucname from pyne.gui import decaychain import numpy as np import matplotlib.pyplot as plt U235 = nucname.id('U-235') unk = nucname.name(902310000) ######### Decay chain U235 = nucname.id('U-235') decay_graph = decaychain.graph('922350000') IDS = [922350000] gens = 7 generation = [0] parent_to_child = [] parent_text = [] j = 0 for i in range(gens): iso = IDS[i] child = data.decay_data_children(iso) nums = len(child) if nums == 1: