Example #1
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()
    def _copy_radio_abundances(self):
        """Copies the radioactive isotopes onto the corresponding stable
        elements. This routine is intended for uses of the mapper during which
        the decay is neglected

        Notes
        -----
        Must be called after _remap_abundances.

        Raises
        ------
        AttributeError if called before _remap_abundances
        """
        try:
            self.radio_abundances_interp
        except AttributeError:
            logger.critical("Abundances must be remapped before radioactive:"
                            " isotopes are copied onto the stable elements")
            raise AttributeError("no radio_abundances_interp; call"
                                 " _remap_abundances first")

        for ident in self.radio_abundances_interp.keys():
            elemid = nucname.id(ident)
            z = nucname.znum(elemid)
            self.abundances_interp[z] = \
                self.abundances_interp[z] + self.radio_abundances_interp[ident]
    def _decay_abundances(self):
        """Determines the decay of all radioactive isotopes. Afterwards their
        mass fractions are added to the stable elements.

        Notes
        -----
        Must be called after _remap_abundances.

        Raises
        ------
        AttributeError if called before _remap_abundances
        """
        try:
            self.radio_abundances_interp
        except AttributeError:
            logger.critical("Abundances must be remapped before decay is"
                            " handled")
            raise AttributeError("no radio_abundances_interp; call "
                                 "_remap_abundances first")

        for i in xrange(self.N_interp):
            comp = {}
            mass = 0
            for ident in self.radio_abundances_interp.keys():
                Xi = self.radio_abundances_interp[ident][i]
                mass += Xi
                comp[nucname.id(ident)] = Xi
            inp = material.Material(comp, mass=mass)
            res = inp.decay(
                (self.t - self.orig.t).to("s").value).mult_by_mass()

            for item in res.items():
                z = nucname.znum(item[0])
                self.abundances_interp[z][i] = \
                    self.abundances_interp[z][i] + item[1]
    def _copy_radio_abundances(self):
        """Copies the radioactive isotopes onto the corresponding stable
        elements. This routine is intended for uses of the mapper during which
        the decay is neglected

        Notes
        -----
        Must be called after _remap_abundances.

        Raises
        ------
        AttributeError if called before _remap_abundances
        """
        try:
            self.radio_abundances_interp
        except AttributeError:
            logger.critical("Abundances must be remapped before radioactive:"
                            " isotopes are copied onto the stable elements")
            raise AttributeError("no radio_abundances_interp; call"
                                 " _remap_abundances first")

        for ident in self.radio_abundances_interp.keys():
            elemid = nucname.id(ident)
            z = nucname.znum(elemid)
            self.abundances_interp[z] = \
                self.abundances_interp[z] + self.radio_abundances_interp[ident]
Example #5
0
def make_atomic_mass_table(nuc_data, build_dir=""):
    """Makes an atomic mass 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 = get_isotopic_abundances()
    atomic_masses = parse_atomic_mass_adjustment(build_dir)

    A = {}

    # Add normal isotopes to A
    for nuc, mass, error in atomic_masses:
        if nuc in atomic_abund:
            A[nuc] = nuc, mass, error, atomic_abund[nuc]
        else:
            A[nuc] = nuc, mass, error, 0.0

    # Add naturally occuring elements
    for element in nucname.name_zz:
        nuc = nucname.id(element)
        A[nuc] = nuc, 0.0, 0.0, 0.0

    for nuc, abund in atomic_abund.items():
        zz = nucname.znum(nuc)
        element_zz = nucname.id(zz)
        element = nucname.zz_name[zz]

        _nuc, nuc_mass, _error, _abund = A[nuc]
        elem_zz, elem_mass, _error, _abund = A[element_zz]

        new_elem_mass = elem_mass + (nuc_mass * abund)
        A[element_zz] = element_zz, new_elem_mass, 0.0, float(
            0.0 < new_elem_mass)

    A = sorted(A.values(), key=lambda x: x[0])

    # Open the HDF5 File
    kdb = tb.open_file(nuc_data, "a", filters=BASIC_FILTERS)

    # Make a new the table
    Atable = kdb.create_table(
        "/",
        "atomic_mass",
        atomic_mass_desc,
        "Atomic Mass Data [amu]",
        expectedrows=len(A),
    )
    Atable.append(A)

    # Ensure that data was written to table
    Atable.flush()

    # Close the hdf5 file
    kdb.close()
Example #6
0
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 _decay_abundances(self):
        """Determines the decay of all radioactive isotopes. Afterwards their
        mass fractions are added to the stable elements.

        Notes
        -----
        Must be called after _remap_abundances.

        Raises
        ------
        AttributeError if called before _remap_abundances
        """
        try:
            self.radio_abundances_interp
        except AttributeError:
            logger.critical("Abundances must be remapped before decay is"
                            " handled")
            raise AttributeError("no radio_abundances_interp; call "
                                 "_remap_abundances first")

        for i in xrange(self.N_interp):
            comp = {}
            mass = 0
            for ident in self.radio_abundances_interp.keys():
                Xi = self.radio_abundances_interp[ident][i]
                mass += Xi
                comp[nucname.id(ident)] = Xi
            inp = material.Material(comp, mass=mass)
            res = inp.decay(
                (self.t - self.orig.t).to("s").value).mult_by_mass()

            for item in res.items():
                z = nucname.znum(item[0])
                self.abundances_interp[z][i] = \
                    self.abundances_interp[z][i] + item[1]
Example #8
0
 def write_metadata(self, nucs, libs, dirname):
     track_actinides = [n for n in nucs if nucname.znum(n) in nucname.act]
     with open(os.path.join(dirname, "manifest.txt"), "w") as f:
         f.write("\n".join([str(nucname.zzaaam(act)) for act in track_actinides]))
         f.write("\n")
     with open(os.path.join(dirname, "params.txt"), "w") as f:
         if self.rc.get("enrichment") is None:
             enrichment = self.rc.initial_heavy_metal.get(922350)
         else:
             enrichment = self.rc.enrichment
         if enrichment is not None:
             f.write("ENRICHMENT {}\n".format(enrichment))
         if self.rc.get("batches") is not None:
             f.write("BATCHES {}\n".format(self.rc.batches))
         if self.rc.get("pnl") is not None:
             f.write("PNL {}\n".format(self.rc.pnl))
         f.write("BURNUP {}\n".format(sum(libs["fuel"]["BUd"])))
         f.write("FLUX {:.0E}\n".format(np.mean(libs["fuel"]["phi_tot"][1:])))
     with open(os.path.join(dirname, "structural.txt"), "w") as f:
         clad_linear_density = pi * self.rc.clad_density * \
             (self.rc.clad_cell_radius ** 2 - self.rc.void_cell_radius ** 2)
         fuel_linear_density = pi * self.rc.fuel_density * \
             self.rc.fuel_cell_radius ** 2
         clad_frac = float(clad_linear_density / fuel_linear_density)
         cladrows = ["{} {:.8f}".format(nucname.zzaaam(n), f*clad_frac)
                     for n, f in self.rc.clad_material.comp.items()]
         f.write("\n".join(cladrows))
         f.write("\n")
     shutil.copyfile("TAPE9.INP", os.path.join(dirname, "TAPE9.INP"))
Example #9
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)
Example #10
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"
Example #11
0
def make_atomic_mass_table(nuc_data, build_dir=""):
    """Makes an atomic mass 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 = get_isotopic_abundances()
    atomic_masses = parse_atomic_mass_adjustment(build_dir)

    A = {}

    # Add normal isotopes to A
    for nuc, mass, error in atomic_masses:
        if nuc in atomic_abund:
            A[nuc] = nuc, mass, error, atomic_abund[nuc]
        else:
            A[nuc] = nuc, mass, error, 0.0

    # Add naturally occuring elements
    for element in nucname.name_zz:
        nuc = nucname.id(element)
        A[nuc] = nuc, 0.0, 0.0, 0.0

    for nuc, abund in atomic_abund.items():
        zz = nucname.znum(nuc)
        element_zz = nucname.id(zz)
        element = nucname.zz_name[zz]

        _nuc, nuc_mass, _error, _abund = A[nuc]
        elem_zz, elem_mass, _error, _abund = A[element_zz]

        new_elem_mass = elem_mass + (nuc_mass * abund)
        A[element_zz] = element_zz, new_elem_mass, 0.0, float(0.0 < new_elem_mass)

    A = sorted(A.values(), key=lambda x: x[0])

    # Open the HDF5 File
    kdb = tb.openFile(nuc_data, 'a', filters=BASIC_FILTERS)

    # Make a new the table
    Atable = kdb.createTable("/", "atomic_mass", atomic_mass_desc,
                             "Atomic Mass Data [amu]", expectedrows=len(A))
    Atable.append(A)

    # Ensure that data was written to table
    Atable.flush()

    # Close the hdf5 file
    kdb.close()
Example #12
0
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)
Example #13
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
Example #14
0
def mesh_to_geom(mesh, geom_file, matlib_file):
    """This function reads the materials of a PyNE mesh object and prints the
    geometry and materials portion of an ALARA input file, as well as a
    corresponding matlib file. If the mesh is structured, xyz ordering is used
    (z changing fastest). If the mesh is unstructured the mesh_iterate order is
    used.

    Parameters
    ----------
    mesh : PyNE Mesh object
        The Mesh object containing the materials to be printed.
    geom_file : str
        The name of the file to print the geometry and material blocks.
    matlib_file : str
        The name of the file to print the matlib.
    """
    # Create geometry information header. Note that the shape of the geometry
    # (rectangular) is actually inconsequential to the ALARA calculation so
    # unstructured meshes are not adversely affected.
    geometry = u"geometry rectangular\n\n"

    # Create three strings in order to create all ALARA input blocks in a
    # single mesh iteration.
    volume = u"volume\n"  # volume input block
    mat_loading = u"mat_loading\n"  # material loading input block
    mixture = u""  # mixture blocks
    matlib = u""  # ALARA material library string

    for i, mat, ve in mesh:
        volume += u"    {0: 1.6E}    zone_{1}\n".format(
            mesh.elem_volume(ve), i)
        mat_loading += u"    zone_{0}    mix_{0}\n".format(i)
        matlib += u"mat_{0}    {1: 1.6E}    {2}\n".format(
            i, mesh.density[i], len(mesh.comp[i]))
        mixture += (u"mixture mix_{0}\n"
                    u"    material mat_{0} 1 1\nend\n\n".format(i))

        for nuc, comp in mesh.comp[i].items():
            matlib += u"{0}    {1: 1.6E}    {2}\n".format(
                alara(nuc), comp * 100.0, znum(nuc))
        matlib += u"\n"

    volume += u"end\n\n"
    mat_loading += u"end\n\n"

    with open(geom_file, 'w') as f:
        f.write(geometry + volume + mat_loading + mixture)

    with open(matlib_file, 'w') as f:
        f.write(matlib)
Example #15
0
def mesh_to_geom(mesh, geom_file, matlib_file):
    """This function reads the materials of a PyNE mesh object and prints the
    geometry and materials portion of an ALARA input file, as well as a
    corresponding matlib file. If the mesh is structured, xyz ordering is used
    (z changing fastest). If the mesh is unstructured iMesh.iterate order is
    used. 

    Parameters
    ----------
    mesh : PyNE Mesh object
        The Mesh object containing the materials to be printed.
    geom_file : str
        The name of the file to print the geometry and material blocks.
    matlib_file : str
        The name of the file to print the matlib.
    """
    # Create geometry information header. Note that the shape of the geometry
    # (rectangular) is actually inconsequential to the ALARA calculation so
    # unstructured meshes are not adversely affected. 
    geometry = "geometry rectangular\n\n"

    # Create three strings in order to create all ALARA input blocks in a
    # single mesh iteration.
    volume = "volume\n" # volume input block
    mat_loading = "mat_loading\n" # material loading input block
    mixture = "" # mixture blocks
    matlib = "" # ALARA material library string

    for i, mat, ve in mesh:
        volume += "    {0: 1.6E}    zone_{1}\n".format(mesh.elem_volume(ve), i)
        mat_loading += "    zone_{0}    mix_{0}\n".format(i)
        matlib += "mat_{0}    {1: 1.6E}    {2}\n".format(i, mesh.density[i], 
                                                         len(mesh.comp[i]))
        mixture += ("mixture mix_{0}\n"
                    "    material mat_{0} 1 1\nend\n\n".format(i))

        for nuc, comp in mesh.comp[i].iteritems():
            matlib += "{0}    {1: 1.6E}    {2}\n".format(alara(nuc), comp*100.0, 
                                                         znum(nuc))
        matlib += "\n"

    volume += "end\n\n"
    mat_loading += "end\n\n"

    with open(geom_file, 'w') as f:
        f.write(geometry + volume + mat_loading + mixture)
    
    with open(matlib_file, 'w') as f:
        f.write(matlib)
Example #16
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
Example #17
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
Example #18
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
Example #19
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)
Example #20
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
Example #21
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
Example #22
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)
Example #23
0
 def write(self, libs, dirname):
     if not os.path.isdir(dirname):
         os.makedirs(dirname)
     rownames = ["TIME", "NEUT_PROD", "NEUT_DEST", "BUd"]
     for mat, matlib in libs.items():
         if isinstance(mat, int):
             fname = str(nucname.zzaaam(mat))
         else:
             fname = mat
         lines = [row + "   " + "   ".join(map(str, matlib[row]))
                  for row in rownames]
         nucs = matlib["tracked_nucs"]
         lines.extend(sorted([n + "   " + "   ".
                              join(["{:.4g}".format(f) for f in nucs[n]])
                              for n in nucs]))
         with open(os.path.join(dirname, fname + ".txt"), "w") as f:
             f.write("\n".join(lines))
     track_actinides = [n for n in nucs if nucname.znum(n) in nucname.act]
     with open(os.path.join(dirname, "manifest.txt"), "w") as f:
         f.write("\n".join([str(nucname.zzaaam(act)) for act in track_actinides]))
         f.write("\n")
     with open(os.path.join(dirname, "params.txt"), "w") as f:
         f.write("ENRICHMENT {}\n".format(self.rc.enrichment))
         f.write("BATCHES {}\n".format(self.rc.batches))
         f.write("PNL {}\n".format(self.rc.pnl))
         f.write("BURNUP {}\n".format(sum(libs["fuel"]["BUd"])))
         f.write("FLUX {:.0E}\n".format(np.mean(libs["fuel"]["phi_tot"][1:])))
     with open(os.path.join(dirname, "structural.txt"), "w") as f:
         clad_linear_density = pi * self.rc.clad_density * \
             (self.rc.clad_cell_radius ** 2 - self.rc.void_cell_radius ** 2)
         fuel_linear_density = pi * self.rc.fuel_density * \
             self.rc.fuel_cell_radius ** 2
         clad_frac = float(clad_linear_density / fuel_linear_density)
         cladrows = ["{} {:.8f}".format(nucname.zzaaam(n), f*clad_frac)
                     for n, f in self.rc.clad_material.comp.items()]
         f.write("\n".join(cladrows))
         f.write("\n")
     shutil.copyfile("TAPE9.INP", os.path.join(dirname, "TAPE9.INP"))
Example #24
0
def record_to_geom(mesh,
                   cell_fracs,
                   cell_mats,
                   geom_file,
                   matlib_file,
                   sig_figs=6,
                   sub_voxel=False):
    """This function preforms the same task as alara.mesh_to_geom, except the
    geometry is on the basis of the stuctured array output of
    dagmc.discretize_geom rather than a PyNE material object with materials.
    This allows for more efficient ALARA runs by minimizing the number of
    materials in the ALARA matlib. This is done by treating mixtures that are
    equal up to <sig_figs> digits to be the same mixture within ALARA.

    Parameters
    ----------
    mesh : PyNE Mesh object
        The Mesh object for which the geometry is discretized.
    cell_fracs : structured array
        The output from dagmc.discretize_geom(). A sorted, one dimensional
        array, each entry containing the following fields:

            :idx: int
                The volume element index.
            :cell: int
                The geometry cell number.
            :vol_frac: float
                The volume fraction of the cell withing the mesh ve.
            :rel_error: float
                The relative error associated with the volume fraction.

    cell_mats : dict
        Maps geometry cell numbers to PyNE Material objects. Each PyNE material
        object must have 'name' specified in Material.metadata.
    geom_file : str
        The name of the file to print the geometry and material blocks.
    matlib_file : str
        The name of the file to print the matlib.
    sig_figs : int
        The number of significant figures that two mixtures must have in common
        to be treated as the same mixture within ALARA.
    sub_voxel : bool
        If sub_voxel is True, the sub-voxel r2s will be used.
    """
    # Create geometry information header. Note that the shape of the geometry
    # (rectangular) is actually inconsequential to the ALARA calculation so
    # unstructured meshes are not adversely affected.
    geometry = "geometry rectangular\n\n"

    # Create three strings in order to create all ALARA input blocks in a
    # single mesh iteration.
    volume = "volume\n"  # volume input block
    mat_loading = "mat_loading\n"  # material loading input block
    mixture = ""  # mixture blocks

    unique_mixtures = []
    if not sub_voxel:
        for i, mat, ve in mesh:
            volume += "    {0: 1.6E}    zone_{1}\n".format(
                mesh.elem_volume(ve), i)

            ve_mixture = {}
            for row in cell_fracs[cell_fracs["idx"] == i]:
                cell_mat = cell_mats[row["cell"]]
                name = cell_mat.metadata["name"]
                if _is_void(name):
                    name = "mat_void"
                if name not in ve_mixture.keys():
                    ve_mixture[name] = np.round(row["vol_frac"], sig_figs)
                else:
                    ve_mixture[name] += np.round(row["vol_frac"], sig_figs)

            if ve_mixture not in unique_mixtures:
                unique_mixtures.append(ve_mixture)
                mixture += "mixture mix_{0}\n".format(
                    unique_mixtures.index(ve_mixture))
                for key, value in ve_mixture.items():
                    mixture += "    material {0} 1 {1}\n".format(key, value)

                mixture += "end\n\n"

            mat_loading += "    zone_{0}    mix_{1}\n".format(
                i, unique_mixtures.index(ve_mixture))
    else:
        ves = list(mesh.iter_ve())
        sve_count = 0
        for row in cell_fracs:
            if len(cell_mats[row["cell"]].comp) != 0:
                volume += "    {0: 1.6E}    zone_{1}\n".format(
                    mesh.elem_volume(ves[row["idx"]]) * row["vol_frac"],
                    sve_count)
                cell_mat = cell_mats[row["cell"]]
                name = cell_mat.metadata["name"]
                if name not in unique_mixtures:
                    unique_mixtures.append(name)
                    mixture += "mixture {0}\n".format(name)
                    mixture += "    material {0} 1 1\n".format(name)
                    mixture += "end\n\n"
                mat_loading += "    zone_{0}    {1}\n".format(sve_count, name)
                sve_count += 1

    volume += "end\n\n"
    mat_loading += "end\n\n"

    with open(geom_file, "w") as f:
        f.write(geometry + volume + mat_loading + mixture)

    matlib = ""  # ALARA material library string

    printed_mats = []
    print_void = False
    for mat in cell_mats.values():
        name = mat.metadata["name"]
        if _is_void(name):
            print_void = True
            continue
        if name not in printed_mats:
            printed_mats.append(name)
            matlib += "{0}    {1: 1.6E}    {2}\n".format(
                name, mat.density, len(mat.comp))
            for nuc, comp in mat.comp.items():
                matlib += "{0}    {1: 1.6E}    {2}\n".format(
                    alara(nuc), comp * 100.0, znum(nuc))
            matlib += "\n"

    if print_void:
        matlib += "# void material\nmat_void 0.0 1\nhe 1 2\n"

    with open(matlib_file, "w") as f:
        f.write(matlib)
Example #25
0
 def id_to_tuple(atomic_id):
     return nucname.znum(atomic_id), nucname.anum(atomic_id)
Example #26
0
    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
            lines = [row + "   " + "   ".join(map(str, matlib[row]))
                     for row in rownames]
            trans_matrix = {}
            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
            #for nuc in trans_matrix:
            #    if len(trans_matrix[nuc]) < len(matlib['TIME']):
            #        zero_array = [0.]*(len(matlib['TIME'])-len(trans_matrix[nuc])) 
            #        trans_matrix[nuc].append(zero_array)
            nucs = matlib["tracked_nucs"]
            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))
        track_actinides = [n for n in nucs if nucname.znum(n) in nucname.act]
        with open(os.path.join(dirname, "manifest.txt"), "w") as f:
            f.write("\n".join([str(nucname.zzaaam(act)) for act in track_actinides]))
            f.write("\n")
        with open(os.path.join(dirname, "params.txt"), "w") as f:
            if self.rc.get("enrichment") is None:
                enrichment = self.rc.initial_heavy_metal.get(922350)
            else:
                enrichment = self.rc.enrichment
            if enrichment is not None:
                f.write("ENRICHMENT {}\n".format(enrichment))
            if self.rc.get("batches") is not None:
                f.write("BATCHES {}\n".format(self.rc.batches))
            if self.rc.get("pnl") is not None:
                f.write("PNL {}\n".format(self.rc.pnl))
            f.write("BURNUP {}\n".format(sum(libs["fuel"]["BUd"])))
            f.write("FLUX {:.0E}\n".format(np.mean(libs["fuel"]["phi_tot"][1:])))
        with open(os.path.join(dirname, "structural.txt"), "w") as f:
            clad_linear_density = pi * self.rc.clad_density * \
                (self.rc.clad_cell_radius ** 2 - self.rc.void_cell_radius ** 2)
            fuel_linear_density = pi * self.rc.fuel_density * \
                self.rc.fuel_cell_radius ** 2
            clad_frac = float(clad_linear_density / fuel_linear_density)
            cladrows = ["{} {:.8f}".format(nucname.zzaaam(n), f*clad_frac)
                        for n, f in self.rc.clad_material.comp.items()]
            f.write("\n".join(cladrows))
            f.write("\n")
        shutil.copyfile("TAPE9.INP", os.path.join(dirname, "TAPE9.INP"))
Example #27
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
Example #28
0
    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", "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
            lines = [row + "   " + "   ".join(map(str, matlib[row]))
                     for row in rownames]
            nucs = matlib["tracked_nucs"]
            lines.extend(sorted([n + "   " + "   ".
                                 join(["{:.4g}".format(f) for f in nucs[n]])
                                 for n in nucs]))
            with open(os.path.join(dirname, fname + ".txt"), "w") as f:
                f.write("\n".join(lines))
        track_actinides = [n for n in nucs if nucname.znum(n) in nucname.act]
        with open(os.path.join(dirname, "manifest.txt"), "w") as f:
            f.write("\n".join([str(nucname.zzaaam(act)) for act in track_actinides]))
            f.write("\n")
        with open(os.path.join(dirname, "params.txt"), "w") as f:
            if self.rc.get("enrichment") is None:
                enrichment = self.rc.initial_heavy_metal.get(922350)
            else:
                enrichment = self.rc.enrichment
            if enrichment is not None:
                f.write("ENRICHMENT {}\n".format(enrichment))
            if self.rc.get("batches") is not None:
                f.write("BATCHES {}\n".format(self.rc.batches))
            if self.rc.get("pnl") is not None:
                f.write("PNL {}\n".format(self.rc.pnl))
            f.write("BURNUP {}\n".format(sum(libs["fuel"]["BUd"])))
            f.write("FLUX {:.0E}\n".format(np.mean(libs["fuel"]["phi_tot"][1:])))
        with open(os.path.join(dirname, "structural.txt"), "w") as f:
            clad_linear_density = pi * self.rc.clad_density * \
                (self.rc.clad_cell_radius ** 2 - self.rc.void_cell_radius ** 2)
            fuel_linear_density = pi * self.rc.fuel_density * \
                self.rc.fuel_cell_radius ** 2
            clad_frac = float(clad_linear_density / fuel_linear_density)
            cladrows = ["{} {:.8f}".format(nucname.zzaaam(n), f*clad_frac)
                        for n, f in self.rc.clad_material.comp.items()]
            f.write("\n".join(cladrows))
            f.write("\n")
        shutil.copyfile("TAPE9.INP", os.path.join(dirname, "TAPE9.INP"))
        # write cross section json file
        xsdata = [[[nucname.name(int(n)), rxname.name(int(r)), float(x)] 
                  for n, r, x in lib] for lib in libs['xs']]
        with open(os.path.join(dirname, 'xs.json'), 'w') as f:
            json.dump(xsdata, f, sort_keys=True, indent=1, 
                      separators=(', ', ': '))
        # write flux json file
        with open(os.path.join(dirname, 'phi_g.json'), 'w') as f:
            json.dump(libs['phi_g'], f, sort_keys=True, indent=1, 
                      separators=(', ', ': '))
Example #29
0
def record_to_geom(mesh,
                   cell_fracs,
                   cell_mats,
                   geom_file,
                   matlib_file,
                   sig_figs=6):
    """This function preforms the same task as alara.mesh_to_geom, except the
    geometry is on the basis of the stuctured array output of
    dagmc.discretize_geom rather than a PyNE material object with materials.
    This allows for more efficient ALARA runs by minimizing the number of
    materials in the ALARA matlib. This is done by treating mixtures that are
    equal up to <sig_figs> digits to be the same mixture within ALARA.

    Parameters
    ----------
    mesh : PyNE Mesh object
        The Mesh object for which the geometry is discretized.
     cell_fracs : structured array
        The output from dagmc.discretize_geom(). A sorted, one dimensional
        array, each entry containing the following fields:

            :idx: int 
                The volume element index.
            :cell: int
                The geometry cell number.
            :vol_frac: float
                The volume fraction of the cell withing the mesh ve.
            :rel_error: float
                The relative error associated with the volume fraction.

     cell_mats : dict
        Maps geometry cell numbers to PyNE Material objects. Each PyNE material
        object must have the 'mat_number' in Material.metadata.
    geom_file : str
        The name of the file to print the geometry and material blocks.
    matlib_file : str
        The name of the file to print the matlib.
    sig_figs : int
        The number of significant figures that two mixtures must have in common
        to be treated as the same mixture within ALARA.
    """
    # Create geometry information header. Note that the shape of the geometry
    # (rectangular) is actually inconsequential to the ALARA calculation so
    # unstructured meshes are not adversely affected.
    geometry = "geometry rectangular\n\n"

    # Create three strings in order to create all ALARA input blocks in a
    # single mesh iteration.
    volume = "volume\n"  # volume input block
    mat_loading = "mat_loading\n"  # material loading input block
    mixture = ""  # mixture blocks

    unique_mixtures = []
    for i, mat, ve in mesh:
        volume += "    {0: 1.6E}    zone_{1}\n".format(mesh.elem_volume(ve), i)

        ve_mixture = {}
        for row in cell_fracs[cell_fracs['idx'] == i]:
            if cell_mats[row['cell']].metadata['mat_number'] \
                not in ve_mixture.keys():
                ve_mixture[cell_mats[row['cell']].metadata['mat_number']] = \
                    round(row['vol_frac'], sig_figs)
            else:
                ve_mixture[cell_mats[row['cell']].metadata['mat_number']] += \
                    round(row['vol_frac'], sig_figs)

        if ve_mixture not in unique_mixtures:
            unique_mixtures.append(ve_mixture)
            mixture += "mixture mix_{0}\n".format(
                unique_mixtures.index(ve_mixture))
            for key, value in ve_mixture.items():
                mixture += "    material mat_{0} 1 {1}\n".format(key, value)

            mixture += "end\n\n"

        mat_loading += "    zone_{0}    mix_{1}\n".format(
            i, unique_mixtures.index(ve_mixture))

    volume += "end\n\n"
    mat_loading += "end\n\n"

    with open(geom_file, 'w') as f:
        f.write(geometry + volume + mat_loading + mixture)

    matlib = ""  # ALARA material library string

    printed_mats = []
    for mat in cell_mats.values():
        mat_num = mat.metadata['mat_number']
        if mat_num not in printed_mats:
            printed_mats.append(mat_num)
            matlib += "mat_{0}    {1: 1.6E}    {2}\n".format(
                mat.metadata['mat_number'], mat.density, len(mat.comp))
            for nuc, comp in mat.comp.iteritems():
                matlib += "{0}    {1: 1.6E}    {2}\n".format(
                    alara(nuc), comp * 100.0, znum(nuc))
            matlib += "\n"

    with open(matlib_file, 'w') as f:
        f.write(matlib)
Example #30
0
 def id_to_tuple(atomic_id):
     return nucname.znum(atomic_id), nucname.anum(atomic_id)
Example #31
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
Example #32
0
File: alara.py Project: mzweig/pyne
def record_to_geom(mesh, cell_fracs, cell_mats, geom_file, matlib_file, 
                   sig_figs=6):
    """This function preforms the same task as alara.mesh_to_geom, except the
    geometry is on the basis of the stuctured array output of
    dagmc.discretize_geom rather than a PyNE material object with materials.
    This allows for more efficient ALARA runs by minimizing the number of
    materials in the ALARA matlib. This is done by treating mixtures that are
    equal up to <sig_figs> digits to be the same mixture within ALARA.

    Parameters
    ----------
    mesh : PyNE Mesh object
        The Mesh object for which the geometry is discretized.
     cell_fracs : structured array
        The output from dagmc.discretize_geom(). A sorted, one dimensional
        array, each entry containing the following fields:

            :idx: int 
                The volume element index.
            :cell: int
                The geometry cell number.
            :vol_frac: float
                The volume fraction of the cell withing the mesh ve.
            :rel_error: float
                The relative error associated with the volume fraction.

     cell_mats : dict
        Maps geometry cell numbers to PyNE Material objects. Each PyNE material
        object must have the 'mat_number' in Material.metadata.
    geom_file : str
        The name of the file to print the geometry and material blocks.
    matlib_file : str
        The name of the file to print the matlib.
    sig_figs : int
        The number of significant figures that two mixtures must have in common
        to be treated as the same mixture within ALARA.
    """
    # Create geometry information header. Note that the shape of the geometry
    # (rectangular) is actually inconsequential to the ALARA calculation so
    # unstructured meshes are not adversely affected. 
    geometry = "geometry rectangular\n\n"

    # Create three strings in order to create all ALARA input blocks in a
    # single mesh iteration.
    volume = "volume\n" # volume input block
    mat_loading = "mat_loading\n" # material loading input block
    mixture = "" # mixture blocks

    unique_mixtures = []
    for i, mat, ve in mesh:
        volume += "    {0: 1.6E}    zone_{1}\n".format(mesh.elem_volume(ve), i)

        ve_mixture = {}
        for row in cell_fracs[cell_fracs['idx'] == i]:
            if cell_mats[row['cell']].metadata['mat_number'] \
                not in ve_mixture.keys():
                ve_mixture[cell_mats[row['cell']].metadata['mat_number']] = \
                    round(row['vol_frac'], sig_figs)
            else:
                ve_mixture[cell_mats[row['cell']].metadata['mat_number']] += \
                    round(row['vol_frac'], sig_figs)

        if ve_mixture not in unique_mixtures:
            unique_mixtures.append(ve_mixture)
            mixture += "mixture mix_{0}\n".format(
                                           unique_mixtures.index(ve_mixture))
            for key, value in ve_mixture.items():
                mixture += "    material mat_{0} 1 {1}\n".format(key, value)

            mixture += "end\n\n"

        mat_loading += "    zone_{0}    mix_{1}\n".format(i, 
                        unique_mixtures.index(ve_mixture))

    volume += "end\n\n"
    mat_loading += "end\n\n"

    with open(geom_file, 'w') as f:
        f.write(geometry + volume + mat_loading + mixture)
    
    matlib = "" # ALARA material library string

    printed_mats = []
    for mat in cell_mats.values():
        mat_num = mat.metadata['mat_number']
        if mat_num not in printed_mats:
            printed_mats.append(mat_num)
            matlib += "mat_{0}    {1: 1.6E}    {2}\n".format(
                       mat.metadata['mat_number'], mat.density, len(mat.comp))
            for nuc, comp in mat.comp.iteritems():
                matlib += "{0}    {1: 1.6E}    {2}\n".format(alara(nuc), 
                                                      comp*100.0, znum(nuc))
            matlib += "\n"

    with open(matlib_file, 'w') as f:
        f.write(matlib)