Skip to content

constants

A collection of generic physical constants, conversions, and miscellaneous constants.

ANGLE = <Unit('degree')> module-attribute

CURRENT = <Unit('ampere')> module-attribute

C_LIGHT = 299792458.0 module-attribute

Convert a string or number to a floating point number, if possible.

DENSITY = <Unit('kilogram / meter ** 3')> module-attribute

D_MOLAR_MASS = 2.01410177784 module-attribute

Convert a string or number to a floating point number, if possible.

ELECTRON_MASS = 9.1093837139e-31 module-attribute

Convert a string or number to a floating point number, if possible.

ELECTRON_MOLAR_MASS = 0.0005485799096195737 module-attribute

Convert a string or number to a floating point number, if possible.

ELEMENTARY_CHARGE = 1.602176634e-19 module-attribute

Convert a string or number to a floating point number, if possible.

E_CHARGE = 1.602176634e-19 module-attribute

Convert a string or number to a floating point number, if possible.

E_DD_HE3N_FUSION = 5.237367559215132e-13 module-attribute

Convert a string or number to a floating point number, if possible.

E_DD_NEUTRON = 3.924425728571561e-13 module-attribute

Convert a string or number to a floating point number, if possible.

E_DD_TP_FUSION = 6.461016407480568e-13 module-attribute

Convert a string or number to a floating point number, if possible.

E_DHE3_FUSION = 2.940668400408501e-12 module-attribute

Convert a string or number to a floating point number, if possible.

E_DT_FUSION = 2.8183035155819573e-12 module-attribute

Convert a string or number to a floating point number, if possible.

E_DT_NEUTRON = 2.250912784396904e-12 module-attribute

Convert a string or number to a floating point number, if possible.

E_TT_FUSION = 1.8157845541890245e-12 module-attribute

Convert a string or number to a floating point number, if possible.

E_TT_NEUTRON = 7.546109313264398e-13 module-attribute

Convert a string or number to a floating point number, if possible.

FLUX_DENSITY = <Unit('1 / meter ** 2 / second')> module-attribute

HE3_MOLAR_MASS = 3.01602932197 module-attribute

Convert a string or number to a floating point number, if possible.

HE_MOLAR_MASS = 4.002602 module-attribute

Convert a string or number to a floating point number, if possible.

H_PLANCK = 1.0545718176461565e-34 module-attribute

Convert a string or number to a floating point number, if possible.

K_BOLTZMANN = 1.380649e-23 module-attribute

Convert a string or number to a floating point number, if possible.

LENGTH = <Unit('meter')> module-attribute

MASS = <Unit('kilogram')> module-attribute

MOLAR_MASSES = {'D': 2.01410177784, 'T': 3.01604928132, 'He': 4.002602, 'He3': 3.01602932197, 'n': 1.0086649171167301, 'p': 1.0072764676333197, 'e': 0.0005485799096195737} module-attribute

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

NEUTRON_MOLAR_MASS = 1.0086649171167301 module-attribute

Convert a string or number to a floating point number, if possible.

N_AVOGADRO = 6.02214076e+23 module-attribute

Convert a string or number to a floating point number, if possible.

PART_DENSITY = <Unit('1 / meter ** 3')> module-attribute

PROTON_MASS = 1.67262192595e-27 module-attribute

Convert a string or number to a floating point number, if possible.

PROTON_MOLAR_MASS = 1.0072764676333197 module-attribute

Convert a string or number to a floating point number, if possible.

QUANTITY = <Unit('mole')> module-attribute

SIGMA_BOLTZMANN = 5.670374419184431e-08 module-attribute

Convert a string or number to a floating point number, if possible.

TEMP = <Unit('kelvin')> module-attribute

TIME = <Unit('second')> module-attribute

TYPE_CHECKING = False module-attribute

bool(x) -> bool

Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

T_MOLAR_MASS = 3.01604928132 module-attribute

Convert a string or number to a floating point number, if possible.

ValueLikeT = ~ValueLikeT module-attribute

Type variable.

Usage::

T = TypeVar('T') # Can be anything A = TypeVar('A', str, bytes) # Must be str or bytes

Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function definitions. See class Generic for more information on generic types. Generic functions work as follows:

def repeat(x: T, n: int) -> List[T]: '''Return a list containing n references to x.''' return [x]*n

def longest(x: A, y: A) -> A: '''Return the longest of two strings.''' return x if len(x) >= len(y) else y

The latter example's signature is essentially the overloading of (str, str) -> str and (bytes, bytes) -> bytes. Also note that if the arguments are instances of some subclass of str, the return type is still plain str.

At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.

Type variables defined with covariant=True or contravariant=True can be used to declare covariant or contravariant generic types. See PEP 484 for more details. By default generic types are invariant in all type variables.

Type variables can be introspected. e.g.:

T.name == 'T' T.constraints == () T.covariant == False T.contravariant = False A.constraints == (str, bytes)

Note that only type variables defined in global scope can be pickled.

annotations = _Feature((3, 7, 0, 'beta', 1), None, 16777216) module-attribute

elements = <periodictable.core.PeriodicTable object at 0x7ff200ce0f50> module-attribute

Defines the periodic table of the elements with isotopes. Individidual elements are accessed by name, symbol or atomic number. Individual isotopes are addressable by element[mass_number] or elements.isotope(element name), elements.isotope(element symbol).

For example, the following all retrieve iron:

.. doctest::

>>> from periodictable import *
>>> print(elements[26])
Fe
>>> print(elements.Fe)
Fe
>>> print(elements.symbol('Fe'))
Fe
>>> print(elements.name('iron'))
Fe
>>> print(elements.isotope('Fe'))
Fe

To get iron-56, use:

.. doctest::

>>> print(elements[26][56])
56-Fe
>>> print(elements.Fe[56])
56-Fe
>>> print(elements.isotope('56-Fe'))
56-Fe

Deuterium and tritium are defined as 'D' and 'T'.

To show all the elements in the table, use the iterator:

.. doctest::

>>> from periodictable import *
>>> for el in elements:  # lists the element symbols
...     print("%s %s"%(el.symbol, el.name))  # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
H hydrogen
He helium
...
Og oganesson

.. Note:: Properties can be added to the elements as needed, including mass, nuclear and X-ray scattering cross sections. See section :ref:Adding properties <extending> for details.

TNSUnitRegistry

Bases: pint.registry.UnitRegistry

TNS UnitRegistry Extra conversions: eV <-> Kelvin

Source code in tokamak_neutron_source/constants.py
class TNSUnitRegistry(UnitRegistry):
    """
    TNS UnitRegistry
    Extra conversions:
    eV <-> Kelvin
    """

    def __init__(self):
        # Preprocessor replacements have spaces so
        # the units dont become prefixes or get prefixed
        # M$ makes sense if a bit non-standard
        super().__init__(
            fmt_locale="en_GB",
            preprocessors=[
                lambda x: x.replace("$", "USD "),
            ],
        )

        self._contexts_added = False

    def _add_contexts(self, contexts: list[Context] | None = None):
        """
        Add new contexts to registry
        """
        if not self._contexts_added:
            self.contexts = [
                self._energy_temperature_context(),
                self._mass_energy_context(),
            ]

            for c in self.contexts:
                self.add_context(c)

            self._contexts_added = True

        if contexts:
            for c in contexts:
                self.add_context(c)

    def enable_contexts(self, *contexts: Context, **kwargs):
        """
        Enable contexts
        """
        self._add_contexts(contexts)

        super().enable_contexts(*[*self.contexts, *contexts], **kwargs)

    def _energy_temperature_context(self):
        """
        Converter between energy and temperature
        temperature = energy / k_B

        Returns
        -------
        :
            pint context
        """
        e_to_t = Context("Energy_to_Temperature")

        t_units = "[temperature]"
        ev_units = "[energy]"

        conversion = self.Quantity("k_B")

        return self._transform(
            e_to_t,
            t_units,
            ev_units,
            lambda _, x: x * conversion,
            lambda _, x: x / conversion,
        )

    def _mass_energy_context(self):
        """
        Converter between mass and energy
        energy = mass * speed-of-light^2

        Returns
        -------
        :
            pint context
        """
        m_to_e = Context("Mass_to_Energy")

        m_units = "[mass]"
        e_units = "[energy]"

        conversion = self.Quantity("c^2")

        return self._transform(
            m_to_e,
            m_units,
            e_units,
            lambda _, x: x * conversion,
            lambda _, x: x / conversion,
        )

    @staticmethod
    def _transform(
        context: Context,
        units_from: str,
        units_to: str,
        forward_transform: Callable[[UnitRegistry, complex | Quantity], float],
        reverse_transform: Callable[[UnitRegistry, complex | Quantity], float],
    ) -> Context:
        formatters = ["{}", "{} / [time]"]

        for form in formatters:
            context.add_transformation(
                form.format(units_from),
                form.format(units_to),
                forward_transform,
            )
            context.add_transformation(
                form.format(units_to),
                form.format(units_from),
                reverse_transform,
            )

        return context

enable_contexts(*contexts, **kwargs)

Enable contexts

Source code in tokamak_neutron_source/constants.py
def enable_contexts(self, *contexts: Context, **kwargs):
    """
    Enable contexts
    """
    self._add_contexts(contexts)

    super().enable_contexts(*[*self.contexts, *contexts], **kwargs)

units_compatible(unit_1, unit_2)

Test if units are compatible.

Parameters:

Name Type Description Default
unit_1 str

unit 1 string

required
unit_2 str

unit 2 string

required

Returns:

Type Description
bool

True if compatible, False otherwise

Source code in tokamak_neutron_source/constants.py
def units_compatible(unit_1: str, unit_2: str) -> bool:
    """
    Test if units are compatible.

    Parameters
    ----------
    unit_1:
        unit 1 string
    unit_2:
        unit 2 string

    Returns
    -------
    :
        True if compatible, False otherwise
    """
    try:
        raw_uc(1, unit_1, unit_2)
    except PintError:
        return False
    else:
        return True

raw_uc(value, unit_from, unit_to)

Raw unit converter Converts a value from one unit to another

Parameters:

Name Type Description Default
value ValueLikeT

value to convert

required
unit_from str | Unit

unit to convert from

required
unit_to str | Unit

unit to convert to

required

Returns:

Type Description
ValueLikeT

converted value

Source code in tokamak_neutron_source/constants.py
def raw_uc(
    value: ValueLikeT,
    unit_from: str | ureg.Unit,
    unit_to: str | ureg.Unit,
) -> ValueLikeT:
    """
    Raw unit converter
    Converts a value from one unit to another

    Parameters
    ----------
    value:
        value to convert
    unit_from:
        unit to convert from
    unit_to:
        unit to convert to

    Returns
    -------
    :
        converted value
    """
    try:
        return (
            ureg.Quantity(value, ureg.Unit(unit_from)).to(ureg.Unit(unit_to)).magnitude
        )
    except ValueError:
        # Catch scales on units eg the ridculousness of this unit: 10^19/m^3
        unit_from_q = ureg.Quantity(unit_from)
        unit_to_q = ureg.Quantity(unit_to)
        return (
            ureg.Quantity(value * unit_from_q).to(unit_to_q.units).magnitude
            / unit_to_q.magnitude
        )

ureg(input_string, case_sensitive=None, **values)

TNS UnitRegistry Extra conversions: eV <-> Kelvin