예제 #1
0
def test_isnuclide():
    are = [922350, "U235"]
    arent = ["U3", -30060000]
    for nuc in are:
        yield assert_true, nucname.isnuclide(nuc)
    for nuc in arent:
        yield assert_false, nucname.isnuclide(nuc)
예제 #2
0
def test_isnuclide():
    are = [922350, "U235"]
    arent = ["U3", -30060000]
    for nuc in are:
        yield assert_true, nucname.isnuclide(nuc)
    for nuc in arent:
        yield assert_false, nucname.isnuclide(nuc)
예제 #3
0
def test_isnuclide():
    are = [922350, 'U235']
    arent = ['U3', -30060000]
    for nuc in are:
        yield assert_true, nucname.isnuclide(nuc)
    for nuc in arent:
        yield assert_false, nucname.isnuclide(nuc)
예제 #4
0
def test_isnuclide():
    are = [922350, 'U235']
    arent = ['U3', -30060000]
    for nuc in are:
        yield assert_true, nucname.isnuclide(nuc)
    for nuc in arent:
        yield assert_false, nucname.isnuclide(nuc)
예제 #5
0
def _is_data(line):
    """
    This function is used to check whether a line of alara output file contains
    wanted data. The line contains data is conposed of:
        - nuc : nuc name (total or total)
        - data for each decay time (including 'shutdown': floats

    Parameters
    ----------
    line : string
        A line from ALARA output.txt

    Returns
    -------
    True : if this line contains results data
    False : if this line doesn't contain results data
    """
    # check the list from the second value, if they are float, then return True
    tokens = line.strip().split()
    if len(tokens) < 2:
        return False
    # first block should be a valid nucname or 'total'
    if not (nucname.isnuclide(tokens[0]) or tokens[0] == "TOTAL".lower()):
        return False
    try:
        np.array(tokens[1:]).astype(float)
        return True
    except:
        return False
예제 #6
0
 def __add_recipe(self,constraints,root):
     for constraint in constraints:
         if nucname.isnuclide(constraint[0]):
             eliso = etree.SubElement(root,"isotope")
             elid = etree.SubElement(eliso,"id")
             elid.text = self.__get_nuclide(constraint[0])
             elval = etree.SubElement(eliso,"comp")
             elval.text = str(constraint[1])
예제 #7
0
파일: openmc_utils.py 프로젝트: pyne/pyne
    def __init__(
        self,
        alias=None,
        awr=None,
        location=None,
        metastable=None,
        name=None,
        path=None,
        temperature=None,
        zaid=None,
        cross_sections_path=None,
    ):
        """Parameters
        ----------
        alias : str, optional
            ace_table attribute.
        awr : str, optional
            ace_table attribute.
        location : str, optional
            ace_table attribute.
        metastable : str, optional
            ace_table attribute.
        name : str, optional
            ace_table attribute.
        path : str, optional
            ace_table attribute.
        temperature : str, optional
            ace_table attribute.
        zaid : str, optional
            ace_table attribute. If set or non-zero then the nucid attribute
            will be set.
        cross_sections_path : str, optional
            If this and path are both present then the abspath attribute will be
            set.
        """

        super(AceTable, self).__init__()
        nuc = None
        if zaid is not None or zaid != "0":
            meta = "0" if metastable is None else metastable
            nuc = nucname.zzaaam_to_id(zaid + meta)
            if nuc == 0:
                pass
            elif not nucname.isnuclide(
                    nuc):  # then it's in MCNP metastable form
                nuc = nucname.mcnp_to_id(zaid)
        self.nucid = nuc
        abspath = None
        if path is not None and cross_sections_path is not None:
            if os.path.isdir(cross_sections_path):
                d = cross_sections_path
            else:
                d = os.path.dirname(cross_sections_path)
            abspath = os.path.abspath(os.path.join(d, path))
        self.abspath = abspath
예제 #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
예제 #9
0
파일: openmc.py 프로젝트: FlanFlanagan/pyne
 def __init__(self, alias=None, awr=None, location=None, metastable=None,
              name=None, path=None, temperature=None, zaid=None,
              cross_sections_path=None):
     """Parameters
     ----------
     alias : str, optional
         ace_table attribute.
     awr : str, optional
         ace_table attribute.
     location : str, optional
         ace_table attribute.
     metastable : str, optional
         ace_table attribute.
     name : str, optional
         ace_table attribute.
     path : str, optional
         ace_table attribute.
     temperature : str, optional
         ace_table attribute.
     zaid : str, optional
         ace_table attribute. If set or non-zero then the nucid attribute
         will be set.
     cross_sections_path : str, optional
         If this and path are both present then the abspath attribute will be
         set.
     """
     super(AceTable, self).__init__()
     nuc = None
     if zaid is not None or zaid != '0':
         meta = "0" if metastable is None else metastable
         nuc = nucname.zzaaam_to_id(zaid + meta)
         if nuc == 0:
             pass
         elif not nucname.isnuclide(nuc):  # then it's in MCNP metastable form
             nuc = nucname.mcnp_to_id(zaid)
     self.nucid = nuc
     abspath = None
     if path is not None and cross_sections_path is not None:
         if os.path.isdir(cross_sections_path):
             d = cross_sections_path
         else:
             d = os.path.dirname(cross_sections_path)
         abspath = os.path.abspath(os.path.join(d, path))
     self.abspath = abspath
예제 #10
0
파일: base.py 프로젝트: tardis-sn/nuclear
def make_energy_injection_model(cutoff_em_energy=20*u.keV, **kwargs):
    """
    Make a bolometric lightcurve model
    :param kwargs:
    :return:
    """
    class_dict = {}
    class_dict['__init__'] = BaseEnergyInjection.__init__
    #class_dict['evaluate'] = BaseBolometricLightCurve.evaluate_specific

    init_kwargs = {}
    for isotope_name in kwargs:
        if not nucname.isnuclide(isotope_name):
            raise ValueError('{0} is not a nuclide name')
        class_dict[isotope_name.lower()] = Parameter()
        init_kwargs[isotope_name.lower()] = kwargs[isotope_name]

    EnergyInjection = type('EnergyInjection',
                                (BaseEnergyInjection,), class_dict)

    return EnergyInjection(cutoff_em_energy, **init_kwargs)
예제 #11
0
    def from_csvy(cls, config):
        """
        Create a new Radial1DModel instance from a Configuration object.

        Parameters
        ----------
        config : tardis.io.config_reader.Configuration

        Returns
        -------
        Radial1DModel

        """
        CSVY_SUPPORTED_COLUMNS = {
            'velocity', 'density', 't_rad', 'dilution_factor'
        }

        if os.path.isabs(config.csvy_model):
            csvy_model_fname = config.csvy_model
        else:
            csvy_model_fname = os.path.join(config.config_dirname,
                                            config.csvy_model)
        csvy_model_config, csvy_model_data = load_csvy(csvy_model_fname)
        base_dir = os.path.abspath(os.path.dirname(__file__))
        schema_dir = os.path.join(base_dir, '..', 'io', 'schemas')
        csvy_schema_file = os.path.join(schema_dir, 'csvy_model.yml')
        csvy_model_config = Configuration(
            validate_dict(csvy_model_config, schemapath=csvy_schema_file))

        if hasattr(csvy_model_data, 'columns'):
            abund_names = set([
                name for name in csvy_model_data.columns
                if nucname.iselement(name) or nucname.isnuclide(name)
            ])
            unsupported_columns = set(
                csvy_model_data.columns) - abund_names - CSVY_SUPPORTED_COLUMNS

            field_names = set(
                [field['name'] for field in csvy_model_config.datatype.fields])
            assert set(csvy_model_data.columns) - field_names == set(),\
                'CSVY columns exist without field descriptions'
            assert field_names - set(csvy_model_data.columns) == set(),\
                'CSVY field descriptions exist without corresponding csv data'
            if unsupported_columns != set():
                logger.warning(
                    "The following columns are specified in the csvy"
                    "model file, but are IGNORED by TARDIS: %s" %
                    (str(unsupported_columns)))

        time_explosion = config.supernova.time_explosion.cgs

        electron_densities = None
        temperature = None

        #if hasattr(csvy_model_config, 'v_inner_boundary'):
        #    v_boundary_inner = csvy_model_config.v_inner_boundary
        #else:
        #    v_boundary_inner = None

        #if hasattr(csvy_model_config, 'v_outer_boundary'):
        #    v_boundary_outer = csvy_model_config.v_outer_boundary
        #else:
        #    v_boundary_outer = None

        if hasattr(config, 'model'):
            if hasattr(config.model, 'v_inner_boundary'):
                v_boundary_inner = config.model.v_inner_boundary
            else:
                v_boundary_inner = None

            if hasattr(config.model, 'v_outer_boundary'):
                v_boundary_outer = config.model.v_outer_boundary
            else:
                v_boundary_outer = None
        else:
            v_boundary_inner = None
            v_boundary_outer = None

        if hasattr(csvy_model_config, 'velocity'):
            velocity = quantity_linspace(csvy_model_config.velocity.start,
                                         csvy_model_config.velocity.stop,
                                         csvy_model_config.velocity.num +
                                         1).cgs
        else:
            velocity_field_index = [
                field['name'] for field in csvy_model_config.datatype.fields
            ].index('velocity')
            velocity_unit = u.Unit(
                csvy_model_config.datatype.fields[velocity_field_index]
                ['unit'])
            velocity = csvy_model_data['velocity'].values * velocity_unit
            velocity = velocity.to('cm/s')

        if hasattr(csvy_model_config, 'density'):
            homologous_density = HomologousDensity.from_csvy(
                config, csvy_model_config)
        else:
            time_0 = csvy_model_config.model_density_time_0
            density_field_index = [
                field['name'] for field in csvy_model_config.datatype.fields
            ].index('density')
            density_unit = u.Unit(
                csvy_model_config.datatype.fields[density_field_index]['unit'])
            density_0 = csvy_model_data['density'].values * density_unit
            density_0 = density_0.to('g/cm^3')[1:]
            density_0 = density_0.insert(0, 0)
            homologous_density = HomologousDensity(density_0, time_0)

        no_of_shells = len(velocity) - 1

        # TODO -- implement t_radiative
        #t_radiative = None
        if temperature:
            t_radiative = temperature
        elif hasattr(csvy_model_data, 'columns'):
            if 't_rad' in csvy_model_data.columns:
                t_rad_field_index = [
                    field['name']
                    for field in csvy_model_config.datatype.fields
                ].index('t_rad')
                t_rad_unit = u.Unit(
                    csvy_model_config.datatype.fields[t_rad_field_index]
                    ['unit'])
                t_radiative = csvy_model_data['t_rad'].iloc[
                    0:].values * t_rad_unit
            else:
                t_radiative = None

        dilution_factor = None
        if hasattr(csvy_model_data, 'columns'):
            if 'dilution_factor' in csvy_model_data.columns:
                dilution_factor = csvy_model_data['dilution_factor'].iloc[
                    0:].to_numpy()

        elif config.plasma.initial_t_rad > 0 * u.K:
            t_radiative = np.ones(no_of_shells) * config.plasma.initial_t_rad
        else:
            t_radiative = None

        if config.plasma.initial_t_inner < 0.0 * u.K:
            luminosity_requested = config.supernova.luminosity_requested
            t_inner = None
        else:
            luminosity_requested = None
            t_inner = config.plasma.initial_t_inner

        if hasattr(csvy_model_config, 'abundance'):
            abundances_section = csvy_model_config.abundance
            abundance, isotope_abundance = read_uniform_abundances(
                abundances_section, no_of_shells)
        else:
            index, abundance, isotope_abundance = parse_csv_abundances(
                csvy_model_data)

        abundance = abundance.replace(np.nan, 0.0)
        abundance = abundance[abundance.sum(axis=1) > 0]
        abundance = abundance.loc[:, 1:]
        abundance.columns = np.arange(abundance.shape[1])

        norm_factor = abundance.sum(axis=0) + isotope_abundance.sum(axis=0)

        if np.any(np.abs(norm_factor - 1) > 1e-12):
            logger.warning("Abundances have not been normalized to 1."
                           " - normalizing")
            abundance /= norm_factor
            isotope_abundance /= norm_factor

        #isotope_abundance = IsotopeAbundances(isotope_abundance)
        isotope_abundance = IsotopeAbundances(
            isotope_abundance, time_0=csvy_model_config.model_isotope_time_0)
        #isotope_abundance.time_0 = csvy_model_config.model_isotope_time_0

        return cls(velocity=velocity,
                   homologous_density=homologous_density,
                   abundance=abundance,
                   isotope_abundance=isotope_abundance,
                   time_explosion=time_explosion,
                   t_radiative=t_radiative,
                   t_inner=t_inner,
                   luminosity_requested=luminosity_requested,
                   dilution_factor=dilution_factor,
                   v_boundary_inner=v_boundary_inner,
                   v_boundary_outer=v_boundary_outer,
                   electron_densities=electron_densities)