Skip to content

independent

Conditions of a Material

UnVerifiedPhysicalProperty

Bases: NDArrayOperatorsMixin

Source code in matproplib/properties/independent.py
class UnVerifiedPhysicalProperty(np.lib.mixins.NDArrayOperatorsMixin):
    def __init__(self, value, unit):
        self.value = value
        self.unit = unit

    def __eq__(self, other: PhysicalProperty | UnVerifiedPhysicalProperty) -> bool:
        """
        Returns
        -------
        :
            The boolean of equality

        Raises
        ------
        TypeError
            Unable to complete equality check
        """
        if type(self) is not type(other):
            try:
                return not np.allclose(self.value, other)
            except TypeError:
                if hasattr(other, "__eq__"):
                    return other.__eq__(self.value)
                raise
        else:
            return not (
                not np.allclose(self.value, other.value) or not self.unit == other.unit
            )

    def __hash__(self):
        """
        Returns
        -------
        :
            hash of object
        """
        return hash((self.value, self.unit))

    def __abs__(self):
        return np.abs(self.value)

    def __array_ufunc__(  # noqa: PLW3201
        self, ufunc: np.ufunc, method: str, *inputs: Any, **kwargs: Any
    ) -> float | tuple[float, ...]:
        """Array options for physical properties"""  # noqa: DOC201
        out = kwargs.get("out", ())
        for x in inputs + out:
            if not isinstance(
                x, np.ndarray | Number | PhysicalProperty | UnVerifiedPhysicalProperty
            ):
                return NotImplemented

        inputs = tuple(
            x.value
            if isinstance(x, PhysicalProperty | UnVerifiedPhysicalProperty)
            else x
            for x in inputs
        )
        if out:
            kwargs["out"] = tuple(
                x.value
                if isinstance(x, PhysicalProperty | UnVerifiedPhysicalProperty)
                else x
                for x in out
            )

        result = getattr(ufunc, method)(*inputs, **kwargs)

        if isinstance(result, tuple):
            return tuple(
                x.value
                if isinstance(x, PhysicalProperty | UnVerifiedPhysicalProperty)
                else x
                for x in result
            )
        if isinstance(result, type(self)):
            return result.value
        return result

    def __array_function__(self, func, types: tuple[type, ...], args, kwargs) -> float:  # noqa: PLW3201
        """Array options for physical properties"""  # noqa: DOC201
        if not all(
            issubclass(
                t, PhysicalProperty | UnVerifiedPhysicalProperty | Number | np.ndarray
            )
            for t in types
        ):
            return NotImplemented

        args = tuple(
            x.value
            if isinstance(x, PhysicalProperty | UnVerifiedPhysicalProperty)
            else x
            for x in args
        )
        return func(*args, **kwargs)

value = value instance-attribute

unit = unit instance-attribute

PhysicalProperty

Bases: BasePhysicalProperty, UnVerifiedPhysicalProperty

Independent Physical Property model

Source code in matproplib/properties/independent.py
class PhysicalProperty(BasePhysicalProperty, UnVerifiedPhysicalProperty):
    """Independent Physical Property model"""

    @model_validator(mode="before")
    def _value_entry(self):
        """Validate value"""  # noqa: DOC201
        if isinstance(self, float | int | np.ndarray | list):
            return {"value": self}

        if isinstance(self, Quantity):
            return {"value": self.magnitude, "unit": self.units}

        if isinstance(self, tuple) and len(self) == 2:  # noqa: PLR2004
            return {"value": self[0], "unit": self[1]}

        if isinstance(self, dict):
            val = self.get("value", None)
            if isinstance(val, Quantity):
                return {"value": val.magnitude, "unit": val.units}
            if isinstance(val, tuple) and len(val) == 2:  # noqa: PLR2004
                return {"value": val[0], "unit": val[1]}

        return self

    @model_validator(mode="after")
    def _unitify(self):
        """Convert value and unit to default

        Raises
        ------
        ValueError
            Failed unit conversion

        Returns
        -------
        :
            The property instance
        """
        dunit = type(self).model_fields["unit"].default
        if isinstance(dunit, Unit) and self.unit == dunit:
            return self

        unit_val, default = super()._unitify()

        if unit_val.units != default or not (
            unit_val.magnitude == 1 or np.isclose(unit_val.magnitude, 1)
        ):
            object.__setattr__(  # noqa: PLC2801
                self, "value", unit_conversion(unit_val * self.value, default)
            )
        object.__setattr__(self, "unit", default)  # noqa: PLC2801
        return self

    def value_as(self, unit: str | Unit) -> float:
        """
        Returns
        -------
        :
            value in another unit

        Raises
        ------
        ValueError
            Failed unit conversion
        """
        try:
            return ureg.Quantity(self.value, self.unit).to(unit).magnitude
        except DimensionalityError as de:
            raise ValueError(
                f"Cannot convert from '{de.args[0]}' "
                f"({de.args[2]}) to '{de.args[1]}' ({de.args[3]})"
            ) from None

value_as(unit)

Returns:

Type Description
float

value in another unit

Raises:

Type Description
ValueError

Failed unit conversion

Source code in matproplib/properties/independent.py
def value_as(self, unit: str | Unit) -> float:
    """
    Returns
    -------
    :
        value in another unit

    Raises
    ------
    ValueError
        Failed unit conversion
    """
    try:
        return ureg.Quantity(self.value, self.unit).to(unit).magnitude
    except DimensionalityError as de:
        raise ValueError(
            f"Cannot convert from '{de.args[0]}' "
            f"({de.args[2]}) to '{de.args[1]}' ({de.args[3]})"
        ) from None

Temperature

Bases: PhysicalProperty

Temperature of a material

Source code in matproplib/properties/independent.py
class Temperature(PhysicalProperty):
    """Temperature of a material"""

    unit: Unit | str = ureg.Unit("K")

    @model_validator(mode="after")
    def _k_below_0(self):
        """Validate negative temperature

        Raises
        ------
        ValueError
            Less than 0K
        """  # noqa: DOC201
        value = (
            ureg.Quantity(self.value, self.unit).to("K")
            if self.unit != ureg.Unit("K")
            else self.value
        )
        if any(np.atleast_1d(np.less(value, 0))):
            raise ValueError("Temperature cannot be below 0 K")
        return self

unit = ureg.Unit('K') class-attribute instance-attribute

Pressure

Bases: PhysicalProperty

Pressure on a material

Source code in matproplib/properties/independent.py
class Pressure(PhysicalProperty):
    """Pressure on a material"""

    unit: Unit | str = ureg.Unit("Pa")

unit = ureg.Unit('Pa') class-attribute instance-attribute

MagneticField

Bases: PhysicalProperty

Magnetic field on a material

Source code in matproplib/properties/independent.py
class MagneticField(PhysicalProperty):
    """Magnetic field on a material"""

    unit: Unit | str = ureg.Unit("T")

unit = ureg.Unit('T') class-attribute instance-attribute

Strain

Bases: PhysicalProperty

Strain on a material

Source code in matproplib/properties/independent.py
class Strain(PhysicalProperty):
    """Strain on a material"""

    unit: Unit | str = ""

unit = '' class-attribute instance-attribute

NeutronDamage

Bases: PhysicalProperty

Neutron damage of a material

Source code in matproplib/properties/independent.py
class NeutronDamage(PhysicalProperty):
    """Neutron damage of a material"""

    unit: Unit | str = "dpa"

unit = 'dpa' class-attribute instance-attribute

NeutronFluence

Bases: PhysicalProperty

Neutron damage of a material

Source code in matproplib/properties/independent.py
class NeutronFluence(PhysicalProperty):
    """Neutron damage of a material"""

    unit: Unit | str = "1/m^2"

unit = '1/m^2' class-attribute instance-attribute

CurrentDensity

Bases: PhysicalProperty

Current density of a material

Source code in matproplib/properties/independent.py
class CurrentDensity(PhysicalProperty):
    """Current density of a material"""

    unit: Unit | str = "A/m^2"

unit = 'A/m^2' class-attribute instance-attribute

Volume

Bases: PhysicalProperty

Volume of a material

Source code in matproplib/properties/independent.py
class Volume(PhysicalProperty):
    """Volume of a material"""

    unit: Unit | str = "m^3"

unit = 'm^3' class-attribute instance-attribute

pp(name, unit)

Source code in matproplib/properties/independent.py
def pp(name: str, unit: str | Unit) -> PhysicalProperty:
    return create_model(
        name,
        __base__=PhysicalProperty,
        unit=(Unit | str, Field(default=unit, validate_default=True)),
    )