How to use the plasmapy.particles.exceptions.InvalidParticleError function in plasmapy

To help you get started, we’ve selected a few plasmapy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github PlasmaPy / PlasmaPy / plasmapy / particles / particle_class.py View on Github external
if particle in particle_taxonomy[category]:
                    categories.add(category)

            if attributes["name"] in _specific_particle_categories:
                categories.add(attributes["name"])

            if particle == "p+":
                categories.update({"element", "isotope", "ion"})

            if mass_numb is not None or Z is not None:
                if particle == "p+" and (mass_numb == 1 or Z == 1):
                    warnings.warn(
                        "Redundant mass number or charge information.", AtomicWarning
                    )
                else:
                    raise InvalidParticleError(
                        "The keywords 'mass_numb' and 'Z' cannot be used when "
                        "creating Particle objects for special particles. To "
                        f"create a Particle object for {attributes['name']}s, "
                        f"use:  Particle({repr(attributes['particle'])})"
                    )

        else:  # elements, isotopes, and ions (besides protons)
            try:
                nomenclature = _parse_and_check_atomic_input(
                    argument, mass_numb=mass_numb, Z=Z
                )
            except Exception as exc:
                errmsg = _invalid_particle_errmsg(argument, mass_numb=mass_numb, Z=Z)
                raise InvalidParticleError(errmsg) from exc

            for key in nomenclature.keys():
github PlasmaPy / PlasmaPy / plasmapy / particles / particle_class.py View on Github external
Examples
        --------
        >>> electron = Particle('e-')
        >>> positron = Particle('e+')
        >>> electron == positron
        False
        >>> electron == 'e-'
        True

        """
        if isinstance(other, str):
            try:
                other_particle = Particle(other)
                return self.particle == other_particle.particle
            except InvalidParticleError as exc:
                raise InvalidParticleError(
                    f"{other} is not a particle and cannot be compared to {self}."
                ) from exc

        if not isinstance(other, self.__class__):
            raise TypeError(
                f"The equality of a Particle object with a {type(other)} is undefined."
            )

        no_particle_attr = "particle" not in dir(self) or "particle" not in dir(other)
        no_attributes_attr = "_attributes" not in dir(self) or "_attributes" not in dir(
            other
        )

        if no_particle_attr or no_attributes_attr:  # coverage: ignore
            raise TypeError(f"The equality of {self} with {other} is undefined.")
github PlasmaPy / PlasmaPy / plasmapy / particles / ionization_state.py View on Github external
"""Return information for a single ionization level."""
        if isinstance(value, slice):
            raise TypeError("IonizationState instances cannot be sliced.")

        if isinstance(value, Integral) and 0 <= value <= self.atomic_number:
            result = State(
                value,
                self.ionic_fractions[value],
                self.ionic_symbols[value],
                self.number_densities[value],
            )
        else:
            if not isinstance(value, Particle):
                try:
                    value = Particle(value)
                except InvalidParticleError as exc:
                    raise InvalidParticleError(
                        f"{value} is not a valid integer charge or " f"particle."
                    ) from exc

            same_element = value.element == self.element
            same_isotope = value.isotope == self.isotope
            has_charge_info = value.is_category(any_of=["charged", "uncharged"])

            if same_element and same_isotope and has_charge_info:
                Z = value.integer_charge
                result = State(
                    Z,
                    self.ionic_fractions[Z],
                    self.ionic_symbols[Z],
                    self.number_densities[Z],
                )
github PlasmaPy / PlasmaPy / plasmapy / particles / particle_class.py View on Github external
elif isinstance(q, Real):
            self._charge = q * const.e.si
            warnings.warn(
                f"CustomParticle charge set to {q} times the elementary charge."
            )
        elif isinstance(q, u.Quantity):
            if not isinstance(q.value, Real):
                raise InvalidParticleError(
                    "The charge of a custom particle can only be a real "
                    "number or a quantity representing a real number with "
                    "units of charge."
                )
            try:
                self._charge = q.to(u.C)
            except u.UnitsError as exc:
                raise InvalidParticleError(
                    "The charge of a custom particle can only have units "
                    "that are compatible with coulombs."
                ) from exc
        else:
            raise TypeError(
                "The charge of a custom particle must be provided either "
                "as a Quantity with units compatible with coulombs or as "
github PlasmaPy / PlasmaPy / plasmapy / particles / particle_class.py View on Github external
Examples
        --------
        >>> electron = Particle('e-')
        >>> positron = Particle('e+')
        >>> electron == positron
        False
        >>> electron == 'e-'
        True

        """
        if isinstance(other, str):
            try:
                other_particle = Particle(other)
                return self.particle == other_particle.particle
            except InvalidParticleError as exc:
                raise InvalidParticleError(
                    f"{other} is not a particle and cannot be compared to {self}."
                ) from exc

        if not isinstance(other, self.__class__):
            raise TypeError(
                f"The equality of a Particle object with a {type(other)} is undefined."
            )

        no_particle_attr = "particle" not in dir(self) or "particle" not in dir(other)
        no_attributes_attr = "_attributes" not in dir(self) or "_attributes" not in dir(
            other
        )

        if no_particle_attr or no_attributes_attr:  # coverage: ignore
            raise TypeError(f"The equality of {self} with {other} is undefined.")
github PlasmaPy / PlasmaPy / plasmapy / particles / particle_class.py View on Github external
def charge(self, q: Optional[Union[Real, u.Quantity]]):
        try:
            self._charge = self._validate_parameter(q, can_be_negative=True)
        except (TypeError, ValueError):
            raise InvalidParticleError(
                f"The charge of a dimensionless particle must be a real "
                f"number, not: {q}"
            ) from None
        if self._charge is np.nan:
            warnings.warn(
                "DimensionlessParticle charge set to NaN", MissingAtomicDataWarning
            )
github PlasmaPy / PlasmaPy / plasmapy / particles / particle_input.py View on Github external
# Convert the argument to a Particle object if it is not
        # already one.

        if not already_particle:

            if not isinstance(argval, (numbers.Integral, str, tuple, list)):
                raise TypeError(
                    f"The argument {argname} to {funcname} must be "
                    f"a string, an integer or a tuple or list of them "
                    f"corresponding to an atomic number, or a "
                    f"Particle object."
                )

            try:
                particle = Particle(argval, Z=Z, mass_numb=mass_numb)
            except InvalidParticleError as e:
                raise InvalidParticleError(
                    _particle_errmsg(argname, argval, Z, mass_numb, funcname)
                ) from e

        # We will need to do the same error checks whether or not the
        # argument is already an instance of the Particle class.

        if already_particle:
            particle = argval

        # If the name of the argument annotated with Particle in the
        # decorated function is element, isotope, or ion; then this
        # decorator should raise the appropriate exception when the
        # particle ends up not being an element, isotope, or ion.

        cat_table = [
github PlasmaPy / PlasmaPy / plasmapy / particles / particle_input.py View on Github external
# already one.

        if not already_particle:

            if not isinstance(argval, (numbers.Integral, str, tuple, list)):
                raise TypeError(
                    f"The argument {argname} to {funcname} must be "
                    f"a string, an integer or a tuple or list of them "
                    f"corresponding to an atomic number, or a "
                    f"Particle object."
                )

            try:
                particle = Particle(argval, Z=Z, mass_numb=mass_numb)
            except InvalidParticleError as e:
                raise InvalidParticleError(
                    _particle_errmsg(argname, argval, Z, mass_numb, funcname)
                ) from e

        # We will need to do the same error checks whether or not the
        # argument is already an instance of the Particle class.

        if already_particle:
            particle = argval

        # If the name of the argument annotated with Particle in the
        # decorated function is element, isotope, or ion; then this
        # decorator should raise the appropriate exception when the
        # particle ends up not being an element, isotope, or ion.

        cat_table = [
            ("element", particle.element, InvalidElementError),
github PlasmaPy / PlasmaPy / plasmapy / particles / parsing.py View on Github external
`int` representing a mass number.  Return the isotope symbol
        or `None` if no mass number information is available.  Raises an
        `~plasmapy.utils.InvalidParticleError` for isotopes that have
        not yet been discovered.
        """

        if mass_numb is not None:
            isotope = f"{element}-{mass_numb}"

            if isotope == "H-2":
                isotope = "D"
            elif isotope == "H-3":
                isotope = "T"

            if isotope not in _Isotopes.keys():
                raise InvalidParticleError(
                    f"The string '{isotope}' does not correspond to "
                    f"a valid isotope."
                )

        else:
            isotope = None

        return isotope
github PlasmaPy / PlasmaPy / plasmapy / particles / atomic.py View on Github external
mass_number
            for (isotope, mass_number) in sorted(zip(mass_numbers, isotopes))
        ]
        return sorted_isotopes

    if argument is not None:
        try:
            element = atomic_symbol(argument)
            isotopes_list = known_isotopes_for_element(element)
        except InvalidElementError:
            raise InvalidElementError(
                "known_isotopes is unable to get "
                f"isotopes from an input of: {argument}"
            )
        except InvalidParticleError:
            raise InvalidParticleError("Invalid particle in known_isotopes.")
    elif argument is None:
        isotopes_list = []
        for atomic_numb in range(1, len(_Elements.keys()) + 1):
            isotopes_list += known_isotopes_for_element(atomic_numb)

    return isotopes_list