Exemple #1
0
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)
Exemple #2
0
def evaluate_flux(isotopes, conc, DATA, fixed=False):
    if fixed:
        flux = 0
        return flux

    # Assume power/mass
    power_per_mass = 35  # W/g or J/s/g
    fission_E = 200 * 1e6 * EV2JOULE  # J/fission
    # macro_per_density = 0 # cm^2/g
    macro = 0  # cm^-1
    for i, iso in enumerate(isotopes):
        try:
            fis_xs = DATA[iso]['fis'] * 1e-24
            # macro_per_density += fis_xs*MOL/nucname.anum(iso)
            macro += fis_xs * conc[i] / nucname.anum(iso) * MOL
        except:
            fis_xs = 0
    if macro > 0:
        flux = power_per_mass / (fission_E * macro)
    else:
        flux = 0

    # print('Flux!')
    # print(flux)
    # print(type(flux))
    # print("{:.2e}".format(flux))
    return flux
Exemple #3
0
    def sss_meta_zzz(self, nuc_code):
        """Checks Serpent-specific meta stable-flag for zzaaam. For instance,
        47310 instead of 471101 for `Ag-110m1`. Metastable isotopes represented
        with `aaa` started with ``3``.

        Parameters
        ----------
        nuc_code : str
            Name of nuclide in Serpent form. For instance, `47310`.

        Returns
        -------
        int
            Name of nuclide in `zzaaam` form (`471101`).

        """
        zz = pyname.znum(nuc_code)
        aa = pyname.anum(nuc_code)
        if aa > 300:
            if zz > 76:
                aa_new = aa - 100
            else:
                aa_new = aa - 200
            zzaaam = str(zz) + str(aa_new) + '1'
        else:
            zzaaam = nuc_code
        return int(zzaaam)
Exemple #4
0
def ScaleMaterialWriter(heu):
    print "{matName} {materialNum} {mass} {numIso}".format(matName=heu.metadata['materialName'],
                                    materialNum=heu.metadata['materialNumber'],
                                    mass=heu.metadata['density_g_per_cc'],
                                    numIso=len(heu))
    for iso in heu:
        print "             %s%s  %s"%(nucname.znum(iso),nucname.anum(iso), heu[iso]*100)
    print "             1  300 end"
Exemple #5
0
    def convertF0(self):
        onlyfiles = [ f for f in os.listdir(self.csdir) if (os.path.isfile(os.path.join(self.csdir,f)) & f.endswith(self.ending)) ]
        for datafile in onlyfiles:
            print "====== Loading JENDL (alpha,n) File: " + datafile
            endfeval = eva(os.path.join(self.csdir, datafile), verbose = False)
            endfeval.read()
            nuc = nucname.zzzaaa_to_id(endfeval.target['ZA'])
            elname = elements[nucname.znum(nuc)].name
            elname = elname.capitalize()
            nuclidefilename = str(nucname.znum(nuc)) + "_" + str(nucname.anum(nuc)) + "_" + elname
            if (endfeval.target['isomeric_state'] != 0):
                print "Found nuclide in exited state, will add _<state> to filename"
                nuclidefilename = nuclidefilename + "_" + str(endfeval.target['isomeric_state'])

            mf3data = {}
            fullfilename = "Inelastic/F01/" + nuclidefilename
            fullfilename = self.outputdir + fullfilename
            if not os.path.exists(os.path.dirname(fullfilename)):
                os.makedirs(os.path.dirname(fullfilename))
                print os.path.dirname(fullfilename) + " has been created (did not exist before)."
            outf = open(fullfilename, 'w')
            for mt in [4] + range(50, 92):
                if(mt in endfeval.reactions):
                    mf3data[mt] = endfeval.reactions[mt]
                    if(mf3data[mt].xs.nbt[0] != len(mf3data[mt].xs.x)):
                       print("Problem with interpolation")
                    #print mf3data[mt].xs.interp
                    outf.write("  {:12d}".format(1))
                    outf.write("\n")
                    outf.write("  {:12d}".format(3))
                    outf.write("\n")
                    outf.write("  {:12d}".format(mt)) 
                    outf.write("  {:12d}".format(0))
                    outf.write("\n")
                    outf.write("  {:12d}".format(int(mf3data[mt].Q_reaction)))
                    outf.write("  {:12d}".format(0))
                    outf.write("  {:12d}".format(len(mf3data[mt].xs.x)))
                    outf.write("\n")
                    writeline = ""
                    zippedxs = zip(mf3data[mt].xs.x, mf3data[mt].xs.y)
                    count = 0
                    for se, sxs in zippedxs:
                        count += 1
                        writeline += "  {:8.6e}  {:8.6e}".format(se, sxs)
                        if (count == 3):
                            writeline += "\n"
                            count = 0
                    if(count != 0):
                        writeline += "\n"
                    outf.write(writeline)

            outf.close()
Exemple #6
0
def evaluate_kinf(isotopes, conc, DATA, reactor_type):
    numerator = 0
    denom = 0
    for i, iso in enumerate(isotopes):
        try:
            fis_xs = DATA[iso]['fis'] * 1e-24
            abs_xs = DATA[iso]['cap'] * 1e-24 + fis_xs
            macro_abs = abs_xs * conc[i] / nucname.anum(iso) * MOL
            denom += macro_abs
        except:
            continue

        try:
            fis_xs = DATA[iso]['fis'] * 1e-24
            nubar = DATA[iso]['nubar']
            macro_fis = fis_xs * conc[i] / nucname.anum(iso) * MOL
            numerator += nubar * macro_fis
        except:
            continue

    kinf = numerator / denom
    return kinf
Exemple #7
0
def read_simple_isotope_abundances(fname, delimiter='\s+'):
    """
    Reading an abundance file of the following structure (example; lines starting with hash will be ignored):
    The first line of abundances describe the abundances in the center of the model and are not used.
    First 4 columns contain values related to velocity, density, electron_density and temperature.
    From 5th column onwards, abundances of elements and isotopes begin.
    The file consists of a header row and next row contains unit of the respective attributes
    Since abundance fractions are unitless , its unit row is filled with ones
    Example 
    velocity...temperature C O Ni56
    km/s.........K         1 1 1
    ...................... 0.4 0.3 0.2

    Parameters
    ----------

    fname: str
        filename or path with filename

    Returns
    -------

    index: ~np.ndarray
    abundances: ~pandas.DataFrame
    isotope_abundance: ~pandas.MultiIndex    
    """
    df = pd.read_csv(fname, comment='#', delimiter=delimiter, skiprows=[0, 2])
    df = df.transpose()

    abundance = pd.DataFrame(columns=np.arange(df.shape[1] - 1),
                             index=pd.Index([], name='atomic_number'),
                             dtype=np.float64)

    isotope_index = pd.MultiIndex([[]] * 2, [[]] * 2,
                                  names=['atomic_number', 'mass_number'])
    isotope_abundance = pd.DataFrame(columns=np.arange(df.shape[1] - 1),
                                     index=isotope_index,
                                     dtype=np.float64)

    #First 4 columns related to density parser (e.g. velocity)
    for element_symbol_string in df.index[4:]:
        if element_symbol_string in nucname.name_zz:
            z = nucname.name_zz[element_symbol_string]
            abundance.loc[z, :] = df.loc[element_symbol_string].tolist()[1:]
        else:
            z = nucname.znum(element_symbol_string)
            mass_no = nucname.anum(element_symbol_string)
            isotope_abundance.loc[(
                z, mass_no), :] = df.loc[element_symbol_string].tolist()[1:]

    return abundance.index, abundance, isotope_abundance
Exemple #8
0
def parse_csv_abundances(csvy_data):
    """
    A parser for the csv data part of a csvy model file. This function filters out columns that are not abundances.

    Parameters
    ----------

    csvy_data : pandas.DataFrame

    Returns
    -------

    index : ~np.ndarray
    abundances : ~pandas.DataFrame
    isotope_abundance : ~pandas.MultiIndex
    """

    abundance_col_names = [
        name for name in csvy_data.columns
        if nucname.iselement(name) or nucname.isnuclide(name)
    ]
    df = csvy_data.loc[:, abundance_col_names]

    df = df.transpose()

    abundance = pd.DataFrame(
        columns=np.arange(df.shape[1]),
        index=pd.Index([], name="atomic_number"),
        dtype=np.float64,
    )

    isotope_index = pd.MultiIndex([[]] * 2, [[]] * 2,
                                  names=["atomic_number", "mass_number"])
    isotope_abundance = pd.DataFrame(columns=np.arange(df.shape[1]),
                                     index=isotope_index,
                                     dtype=np.float64)

    for element_symbol_string in df.index[0:]:
        if element_symbol_string in nucname.name_zz:
            z = nucname.name_zz[element_symbol_string]
            abundance.loc[z, :] = df.loc[element_symbol_string].tolist()
        else:
            z = nucname.znum(element_symbol_string)
            mass_no = nucname.anum(element_symbol_string)
            isotope_abundance.loc[(
                z, mass_no), :] = df.loc[element_symbol_string].tolist()

    return abundance.index, abundance, isotope_abundance
Exemple #9
0
    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
Exemple #10
0
def read_uniform_abundances(abundances_section, no_of_shells):
    """
    Parameters
    ----------

    abundances_section: ~config.model.abundances
    no_of_shells: int

    Returns
    -------
    abundance: ~pandas.DataFrame
    isotope_abundance: ~pandas.DataFrame
    """
    abundance = pd.DataFrame(
        columns=np.arange(no_of_shells),
        index=pd.Index(np.arange(1, 120), name="atomic_number"),
        dtype=np.float64,
    )

    isotope_index = pd.MultiIndex([[]] * 2, [[]] * 2,
                                  names=["atomic_number", "mass_number"])
    isotope_abundance = pd.DataFrame(columns=np.arange(no_of_shells),
                                     index=isotope_index,
                                     dtype=np.float64)

    for element_symbol_string in abundances_section:
        if element_symbol_string == "type":
            continue
        try:
            if element_symbol_string in nucname.name_zz:
                z = nucname.name_zz[element_symbol_string]
                abundance.loc[z] = float(
                    abundances_section[element_symbol_string])
            else:
                mass_no = nucname.anum(element_symbol_string)
                z = nucname.znum(element_symbol_string)
                isotope_abundance.loc[(z, mass_no), :] = float(
                    abundances_section[element_symbol_string])

        except RuntimeError as err:
            raise RuntimeError(
                "Abundances are not defined properly in config file : {}".
                format(err.args))

    return abundance, isotope_abundance
Exemple #11
0
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
Exemple #12
0
def plot_inv_para(fo, ts, param, low_limit=1e-10, save=False, sfile=""):
    """plots parameter as table of nuclides for a timestep 
       this is for stable parameters only
    """

    atom_grid = np.zeros((113,173))

    for nuc in fo.timestep_data[ts-1].inventory:
         if nuc[0][-1] == "n":
             nuc[0] = nuc[0][:-1]
         
         a = nucname.anum(nuc[0])
         z = nucname.znum(nuc[0])
         n=a-z
         atom_grid[z,n] = np.log10(float(nuc[param]))

    atom_grid = np.ma.masked_array(atom_grid, atom_grid<low_limit)
    title = fo.sumdat[0][ts-1]
    make_plot(atom_grid, title, save, sfile)
Exemple #13
0
def read_uniform_abundances(abundances_section, no_of_shells):
    """
    Parameters
    ----------

    abundances_section: ~config.model.abundances
    no_of_shells: int

    Returns
    -------
    abundance: ~pandas.DataFrame
    isotope_abundance: ~pandas.DataFrame
    """
    abundance = pd.DataFrame(columns=np.arange(no_of_shells),
                             index=pd.Index(np.arange(1, 120),
                                            name='atomic_number'),
                             dtype=np.float64)

    isotope_index = pd.MultiIndex(
        [[]] * 2, [[]] * 2, names=['atomic_number', 'mass_number'])
    isotope_abundance = pd.DataFrame(columns=np.arange(no_of_shells),
                                     index=isotope_index,
                                     dtype=np.float64)

    for element_symbol_string in abundances_section:
        if element_symbol_string == 'type':
            continue
        try:
            if element_symbol_string in nucname.name_zz:
                z = nucname.name_zz[element_symbol_string]
                abundance.loc[z] = float(
                    abundances_section[element_symbol_string])
            else:
                mass_no = nucname.anum(element_symbol_string)
                z = nucname.znum(element_symbol_string)
                isotope_abundance.loc[(z, mass_no), :] = float(
                    abundances_section[element_symbol_string])

        except RuntimeError as err:
            raise RuntimeError(
                "Abundances are not defined properly in config file : {}".format(err.args))

    return abundance, isotope_abundance
Exemple #14
0
def plot_inv_act_para(fo, ts, para, low_limit=1e-5, save=False, sfile=""):
    """plots parameter as table of nuclides form for a timestep
       this is for active parameters
    """
    
    act_grid = np.zeros((113,173))

    for nuc in fo.timestep_data[ts-1].inventory:
         if float(nuc[para]) > 0:
            if nuc[0][-1] == "n":
                nuc[0] = nuc[0][:-1]
            
            a = nucname.anum(nuc[0])
            z = nucname.znum(nuc[0])
            n=a-z
            act_grid[z,n] = np.log10(float(nuc[para]))

    act_grid = np.ma.masked_array(act_grid, act_grid<low_limit)
    make_plot(act_grid, save, sfile)
Exemple #15
0
def read_csv_isotope_abundances(fname, delimiter='\s+', skip_columns=0,
                                skip_rows=[1]):
    """
    A generic parser for a TARDIS composition stored as a CSV file

    The parser can read in both elemental and isotopic abundances. The first
    column is always expected to contain a running index, labelling the grid
    cells. The parser also allows for additional information to be stored in
    the first skip_columns columns. These will be ignored if skip_columns > 0.
    Note that the first column, containing the cell index is not taken into
    account here.

    Specific header lines can be skipped by the skip_rows keyword argument

    It is expected that the first row of the date block (after skipping the
    rows specified in skip_rows) specifies the different elements and isotopes.
    Each row after contains the composition in the corresponding grid shell.
    The first composition row describes the composition of the photosphere and
    is essentially ignored (for the default value of skip_rows).

    Example:

    Index C   O   Ni56
    0     1   1   1
    1     0.4 0.3 0.2

    Parameters
    ----------

    fname: str
        filename or path with filename

    Returns
    -------

    index: ~np.ndarray
    abundances: ~pandas.DataFrame
    isotope_abundance: ~pandas.MultiIndex
    """

    df = pd.read_csv(fname, comment='#',
                     sep=delimiter, skiprows=skip_rows, index_col=0)
    df = df.transpose()

    abundance = pd.DataFrame(columns=np.arange(df.shape[1]),
                             index=pd.Index([],
                                            name='atomic_number'),
                             dtype=np.float64)

    isotope_index = pd.MultiIndex(
        [[]] * 2, [[]] * 2, names=['atomic_number', 'mass_number'])
    isotope_abundance = pd.DataFrame(columns=np.arange(df.shape[1]),
                                     index=isotope_index,
                                     dtype=np.float64)

    for element_symbol_string in df.index[skip_columns:]:
        if element_symbol_string in nucname.name_zz:
            z = nucname.name_zz[element_symbol_string]
            abundance.loc[z, :] = df.loc[element_symbol_string].tolist()
        else:
            z = nucname.znum(element_symbol_string)
            mass_no = nucname.anum(element_symbol_string)
            isotope_abundance.loc[(
                z, mass_no), :] = df.loc[element_symbol_string].tolist()

    return abundance.index, abundance, isotope_abundance
Exemple #16
0
print(np.log(2)/data.decay_const('922340000')/3.15e7)

print('-------Np-239 to Pu-239 test--------')
print(data.decay_const('932390'))
print(data.decay_children('932390'))

print(data.decay_const('932390'))
print(data.decay_children('932390'))
print(data.branch_ratio(932390,942390))

print('-------U-240 decay test--------')
print(np.log(2)/data.decay_const('922400')/3600)
print(data.branch_ratio('922400','932400', use_metastable=False))

print('-----U234 Capture Test-----')
print(float('922350')-float('922340') == 10)

print('-----Mass Test-----')
print(nucname.anum('922350'))
print('-----Name Test-----')
print(nucname.serpent('922350'))

print('-------U-236 test--------')
print(data.decay_const('922360'))
print(data.half_life('922360')/(3.15e7))

print('-------Np-234 to U-234 test--------')
print(data.decay_const('932340'))
print(data.decay_children('932340'))
print(data.branch_ratio(932340,922340))
Exemple #17
0
    def readendf(self, datafile):
        endfds = ENDFDataSource(os.path.join(self.csdir, datafile))
        endfds.load()

        #    print endfds.library.intdict
        print "++++ The File contains data for the following nuclides:"
        self.lines = {}
        for nuc, value in endfds.library.mat_dict.iteritems() :
            cname = nucname.name(nuc)
            print "+++ Data for nuclide " + cname
            elname = elements[nucname.znum(nuc)].name
            elname = elname.capitalize()
            nuclidefilename = str(nucname.znum(nuc)) + "_" + str(nucname.anum(nuc)) + "_" + elname
            if (nucname.snum(nuc) != 0):
                print "Found nuclide in exited state, will add _<state> to filename"
                nuclidefilename = nuclidefilename + "_" + str(nucname.snum(nuc))
            for keyb, valueb in value['mfs'].iteritems() :
                print "+++ The nuclide has data for MF=", keyb[0], " and MT=", keyb[1]
                # MF=3 (cs)            
                if(keyb[0] == 3) :
                    print "Convert to geant compatible lines for MF=3"
                    reactiondata = endfds.reaction(nuc, keyb[1])
                    if (len(reactiondata['intschemes']) == 1):
                        if (reactiondata['intschemes'] == 2) :
                            writeline = ""
                            writeline += "  {:12d}".format(len(reactiondata['xs']))
                            writeline += "\n"
                            zippedxs = zip(reactiondata['xs'], reactiondata['e_int'])
                            count = 0
                            for sxs, se in zippedxs:
                                count += 1
                                writeline += "  {:8.6e}  {:8.6e}".format(se, sxs)
                                if (count == 3):
                                    writeline += "\n"
                                    count = 0
                            if(count != 0):
                                writeline += "\n"
                            if(not keyb[1] in self.lines):
                                self.lines.update({keyb[1]: {}})
                            self.lines[keyb[1]].update({keyb[0]: writeline})

                        else:
                            print "Non-linear interpolation scheme (Type {}) is currently not supported.".format(reactiondata['intschemes'])
                    else:
                        print "Multiple interpolation schemes are currently not supprted."
                        #print reactiondata
                        #exit()
                if(keyb[0] == 1) :
                    #                xsdata =  endfds.library.get_rx(key, 1, keyb[1]).reshape(-1,6)
                    #                print xsdata
                    print "Conversion for MF=1 not yet possible"
                if(keyb[0] == 6) :
                    print "Convert to geant compatible lines for MF=6"
                    mf6data = newmf.mf6()
                    mf6data.setdatasource(endfds)
                    mf6data.loadmtenangdata(nuc, keyb[1])
                    enangdist = mf6data.getdata()

                    gdata = geantdata.geantdata()
                    gdata.importenangdist(enangdist)
                    gdata.writesection(6, keyb[1])

                    if(not gdata.producterror):
                        if(not keyb[1] in self.lines):
                            self.lines.update({keyb[1]: {}})
                        self.lines[keyb[1]].update({keyb[0]: gdata.getline()})
                    else:
                        print("No output for MT/MF combination because of errors")
        return nuclidefilename
Exemple #18
0
def num_density_to_mesh(lines, time, m):
    """num_density_to_mesh(lines, time, m)
    This function reads ALARA output containing number density information and 
    creates material objects which are then added to a supplied PyNE Mesh object. 
    The volumes within ALARA are assummed to appear in the same order as the 
    idx on the Mesh object.

    Parameters
    ----------
    lines : list or str
        ALARA output from ALARA run with 'number_density' in the 'output' block
        of the input file. Lines can either be a filename or the equivalent to
        calling readlines() on an ALARA output file. If reading in ALARA output
        from stdout, call split('\n') before passing it in as the lines parameter.
    time : str
        The decay time for which number densities are requested (e.g. '1 h',
        'shutdown', etc.)
    m : PyNE Mesh
        Mesh object for which mats will be applied to.
    """
    if isinstance(lines, basestring):
        with open(lines) as f:
            lines = f.readlines()
    elif not isinstance(lines, collections.Sequence):
        raise TypeError("Lines argument not a file or sequence.")
    # Advance file to number density portion.
    header = 'Number Density [atoms/cm3]'
    line = ""
    while line.rstrip() != header:
        line = lines.pop(0)

    # Get decay time index from next line (the column the decay time answers
    # appear in.
    line_strs = lines.pop(0).replace('\t', '  ')
    time_index = [s.strip() for s in line_strs.split('  ')
                  if s.strip()].index(time)

    # Create a dict of mats for the mesh.
    mats = {}
    count = 0
    # Read through file until enough material objects are create to fill mesh.
    while count != len(m):
        # Pop lines to the start of the next material.
        while (lines.pop(0) + " ")[0] != '=':
            pass

        # Create a new material object and add to mats dict.
        line = lines.pop(0)
        nucvec = {}
        density = 0.0
        # Read lines until '=' delimiter at the end of a material.
        while line[0] != '=':
            nuc = line.split()[0]
            n = float(line.split()[time_index])
            if n != 0.0:
                nucvec[nuc] = n
                density += n * anum(nuc) / N_A

            line = lines.pop(0)
        mat = from_atom_frac(nucvec, density=density, mass=0)
        mats[count] = mat
        count += 1

    m.mats = mats
Exemple #19
0
def num_density_to_mesh(lines, time, m):
    """num_density_to_mesh(lines, time, m)
    This function reads ALARA output containing number density information and 
    creates material objects which are then added to a supplied PyNE Mesh object. 
    The volumes within ALARA are assummed to appear in the same order as the 
    idx on the Mesh object.

    Parameters
    ----------
    lines : list or str
        ALARA output from ALARA run with 'number_density' in the 'output' block
        of the input file. Lines can either be a filename or the equivalent to
        calling readlines() on an ALARA output file. If reading in ALARA output
        from stdout, call split('\n') before passing it in as the lines parameter.
    time : str
        The decay time for which number densities are requested (e.g. '1 h',
        'shutdown', etc.)
    m : PyNE Mesh
        Mesh object for which mats will be applied to.
    """
    if isinstance(lines, basestring):
        with open(lines) as f:
            lines = f.readlines()
    elif not isinstance(lines, collections.Sequence):
        raise TypeError("Lines argument not a file or sequence.")
    # Advance file to number density portion.
    header = 'Number Density [atoms/cm3]'
    line = ""
    while line.rstrip() != header:
        line = lines.pop(0)

    # Get decay time index from next line (the column the decay time answers
    # appear in.
    line_strs = lines.pop(0).replace('\t', '  ')
    time_index = [s.strip() for s in line_strs.split('  ') 
                  if s.strip()].index(time)

    # Create a dict of mats for the mesh.
    mats = {}
    count = 0
    # Read through file until enough material objects are create to fill mesh.
    while count != len(m):
        # Pop lines to the start of the next material.
        while (lines.pop(0) + " " )[0] != '=':
            pass

        # Create a new material object and add to mats dict.
        line = lines.pop(0)
        nucvec = {}
        density = 0.0
        # Read lines until '=' delimiter at the end of a material.
        while line[0] != '=':
            nuc = line.split()[0]
            n = float(line.split()[time_index])
            if n != 0.0:
                nucvec[nuc] = n
                density += n * anum(nuc)/N_A

            line = lines.pop(0)
        mat = from_atom_frac(nucvec, density=density, mass=0)
        mats[count] = mat
        count += 1

    m.mats = mats
Exemple #20
0
 def id_to_tuple(atomic_id):
     return nucname.znum(atomic_id), nucname.anum(atomic_id)
Exemple #21
0
 def id_to_tuple(atomic_id):
     return nucname.znum(atomic_id), nucname.anum(atomic_id)