Skip to content

ftypes

FDType

Bases: FType

Source code in src/finch/algebra/ftypes.py
class FDType(FType):
    @property
    @abstractmethod
    def dtype(self) -> np.dtype:
        """The NumPy dtype used to store values of this data type."""
        ...

    def __promote__(self, other):
        """
        Return the result of promoting this type with another type.
        """
        return

dtype abstractmethod property

The NumPy dtype used to store values of this data type.

__promote__(other)

Return the result of promoting this type with another type.

Source code in src/finch/algebra/ftypes.py
def __promote__(self, other):
    """
    Return the result of promoting this type with another type.
    """
    return

FDTypeBuiltin

Bases: FDType

Source code in src/finch/algebra/ftypes.py
class FDTypeBuiltin(FDType):
    @property
    def dtype(self) -> np.dtype:
        return np.dtype(self.type)

    @property
    @abstractmethod
    def type(self):
        """
        The corresponding Python built-in type for this ftype.
        """
        ...

    def __eq__(self, other):
        return isinstance(other, FDTypeBuiltin) and self.type == other.type

    def __hash__(self):
        return hash(self.type)

    def __call__(self, val):
        """
        Create an instance of this ftype with the given value.
        """
        return self.type(val)

type abstractmethod property

The corresponding Python built-in type for this ftype.

__call__(val)

Create an instance of this ftype with the given value.

Source code in src/finch/algebra/ftypes.py
def __call__(self, val):
    """
    Create an instance of this ftype with the given value.
    """
    return self.type(val)

FDTypeFloat

Bases: FDTypeNumeric

Source code in src/finch/algebra/ftypes.py
class FDTypeFloat(FDTypeNumeric):
    @property
    @abstractmethod
    def finfo(self):
        """
        The finfo object for this float type.
        """
        ...

finfo abstractmethod property

The finfo object for this float type.

FDTypeInteger

Bases: FDTypeNumeric

Source code in src/finch/algebra/ftypes.py
class FDTypeInteger(FDTypeNumeric):
    @property
    @abstractmethod
    def iinfo(self):
        """
        The iinfo object for this integer type.
        """
        ...

iinfo abstractmethod property

The iinfo object for this integer type.

FDTypeNumpy

Bases: FDType

Source code in src/finch/algebra/ftypes.py
class FDTypeNumpy(FDType):
    def __eq__(self, other):
        return isinstance(other, FDTypeNumpy) and self.dtype == other.dtype

    def __hash__(self):
        return hash(self.dtype)

    def __call__(self, val):
        """
        Create an instance of this ftype with the given value.
        """
        return self.dtype.type(val)

    def __promote__(self, other):
        if isinstance(other, FDTypeNumpy):
            return _promote_numpy_dtypes(self, other)
        return None

__call__(val)

Create an instance of this ftype with the given value.

Source code in src/finch/algebra/ftypes.py
def __call__(self, val):
    """
    Create an instance of this ftype with the given value.
    """
    return self.dtype.type(val)

FDTypeNumpyFloat

Bases: FDTypeFloat, FDTypeNumpy

Source code in src/finch/algebra/ftypes.py
class FDTypeNumpyFloat(FDTypeFloat, FDTypeNumpy):
    def __promote__(self, other):
        if isinstance(other, FDTypeBuiltin):
            if other in (bool_, int_, float_):
                return self
            if other == complex_:
                return _promote_numpy_dtypes(self, complex64)
        return super().__promote__(other)

    @property
    def finfo(self):
        """
        The finfo object for this float type.
        """
        return _finfo(self, np.finfo(self.dtype))

    @property
    def type_min(self):
        """
        The minimum value for this type.
        """
        return self.dtype.type(-np.inf)

    @property
    def type_max(self):
        """
        The maximum value for this type.
        """
        return self.dtype.type(np.inf)

finfo property

The finfo object for this float type.

type_max property

The maximum value for this type.

type_min property

The minimum value for this type.

FDTypeNumpyInteger

Bases: FDTypeInteger, FDTypeNumpy

Source code in src/finch/algebra/ftypes.py
class FDTypeNumpyInteger(FDTypeInteger, FDTypeNumpy):
    def __promote__(self, other):
        if isinstance(other, FDTypeBuiltin):
            if other in (bool_, int_):
                return self
            if other == float_:
                return _promote_numpy_dtypes(self, float32)
            if other == complex_:
                return _promote_numpy_dtypes(self, complex64)
        return super().__promote__(other)

    @property
    def iinfo(self):
        """
        The iinfo object for this integer type.
        """
        return _iinfo(self, np.iinfo(self.dtype))

    @property
    def type_min(self):
        """
        The minimum value for this type.
        """
        return self.dtype.type(self.iinfo.min)

    @property
    def type_max(self):
        """
        The maximum value for this type.
        """
        return self.dtype.type(self.iinfo.max)

iinfo property

The iinfo object for this integer type.

type_max property

The maximum value for this type.

type_min property

The minimum value for this type.

FDTypeOrdered

Bases: FDType

Source code in src/finch/algebra/ftypes.py
class FDTypeOrdered(FDType):
    @property
    @abstractmethod
    def type_min(self):
        """
        The minimum value for this type.
        """
        ...

    @property
    @abstractmethod
    def type_max(self):
        """
        The maximum value for this type.
        """
        ...

type_max abstractmethod property

The maximum value for this type.

type_min abstractmethod property

The minimum value for this type.

FType

Bases: ABC

Source code in src/finch/algebra/ftypes.py
class FType(ABC):
    @abstractmethod
    def __eq__(self, other) -> builtins.bool: ...

    @abstractmethod
    def __hash__(self) -> builtins.int: ...

    @abstractmethod
    def __call__(self, val: Any, /) -> Any:
        """
        Perform type conversion or construction with the given value.

        For numeric/scalar types, this converts the value to this type.
        For composite types, this may construct an instance of this type.

        Args:
            val: The value to convert or use for construction

        Returns:
            The converted/constructed value
        """
        ...

    def fisinstance(self, other) -> builtins.bool:
        """
        Check if `other` is an instance of this ftype.
        """
        return ftype(other) == self

__call__(val) abstractmethod

Perform type conversion or construction with the given value.

For numeric/scalar types, this converts the value to this type. For composite types, this may construct an instance of this type.

Parameters:

Name Type Description Default
val Any

The value to convert or use for construction

required

Returns:

Type Description
Any

The converted/constructed value

Source code in src/finch/algebra/ftypes.py
@abstractmethod
def __call__(self, val: Any, /) -> Any:
    """
    Perform type conversion or construction with the given value.

    For numeric/scalar types, this converts the value to this type.
    For composite types, this may construct an instance of this type.

    Args:
        val: The value to convert or use for construction

    Returns:
        The converted/constructed value
    """
    ...

fisinstance(other)

Check if other is an instance of this ftype.

Source code in src/finch/algebra/ftypes.py
def fisinstance(self, other) -> builtins.bool:
    """
    Check if `other` is an instance of this ftype.
    """
    return ftype(other) == self

FTyped

Bases: Generic[FT]

Abstract base class for objects that can be formatted.

Source code in src/finch/algebra/ftypes.py
class FTyped(Generic[FT]):
    """
    Abstract base class for objects that can be formatted.
    """

    @property
    @abstractmethod
    def ftype(self) -> FT:
        """
        The ftype of the object.
        """
        ...

ftype abstractmethod property

The ftype of the object.

StructFType

Bases: FType, ABC

Source code in src/finch/algebra/ftypes.py
class StructFType(FType, ABC):
    def __eq__(self, other):
        return (
            type(other) is type(self)
            and self.struct_name == other.struct_name
            and self.struct_fields == other.struct_fields
        )

    def __hash__(self):
        return hash((type(self), self.struct_name, tuple(self.struct_fields)))

    def __repr__(self):
        fields_str = ", ".join(f"{name}: {type_}" for name, type_ in self.struct_fields)
        return f"{self.struct_name}({fields_str})"

    def __call__(self, *args, **kwargs):
        """
        Construct a struct instance from the given fields.

        Can be called with positional arguments matching struct_fields order,
        or keyword arguments matching field names.
        """
        if args and kwargs:
            raise TypeError("Cannot use both positional and keyword arguments")
        if args:
            return self.from_fields(*args)
        if kwargs:
            # Convert kwargs to positional args in field order
            field_values = [kwargs[name] for name, _ in self.struct_fields]
            return self.from_fields(*field_values)
        raise TypeError("__call__ requires at least one argument")

    @property
    @abstractmethod
    def struct_name(self) -> str: ...

    @property
    @abstractmethod
    def struct_fields(self) -> list[tuple[str, FType]]: ...

    @abstractmethod
    def from_fields(self, *args): ...

    @property
    @abstractmethod
    def is_mutable(self) -> builtins.bool: ...

    def struct_getattr(self, obj, attr) -> Any:
        return getattr(obj, attr)

    def struct_setattr(self, obj, attr, value) -> None:
        setattr(obj, attr, value)
        return

    @property
    def struct_fieldnames(self) -> list[str]:
        return [name for (name, _) in self.struct_fields]

    @property
    def struct_fieldtypes(self) -> list[FType]:
        return [type_ for (_, type_) in self.struct_fields]

    def struct_hasattr(self, attr: str) -> builtins.bool:
        return attr in dict(self.struct_fields)

    def struct_attrtype(self, attr: str) -> FType:
        return dict(self.struct_fields)[attr]

__call__(*args, **kwargs)

Construct a struct instance from the given fields.

Can be called with positional arguments matching struct_fields order, or keyword arguments matching field names.

Source code in src/finch/algebra/ftypes.py
def __call__(self, *args, **kwargs):
    """
    Construct a struct instance from the given fields.

    Can be called with positional arguments matching struct_fields order,
    or keyword arguments matching field names.
    """
    if args and kwargs:
        raise TypeError("Cannot use both positional and keyword arguments")
    if args:
        return self.from_fields(*args)
    if kwargs:
        # Convert kwargs to positional args in field order
        field_values = [kwargs[name] for name, _ in self.struct_fields]
        return self.from_fields(*field_values)
    raise TypeError("__call__ requires at least one argument")

TupleFType

Bases: ImmutableStructFType, FDType

FType for Python tuples, with a struct-compatible interface.

Source code in src/finch/algebra/ftypes.py
class TupleFType(ImmutableStructFType, FDType):
    """FType for Python tuples, with a struct-compatible interface."""

    def __init__(self, struct_types):
        self._struct_types = struct_types

    @property
    def dtype(self) -> np.dtype:
        return np.dtype(
            [(name, np_dtype(field_type)) for name, field_type in self.struct_fields]
        )

    def __repr__(self):
        return f"TupleFType(({', '.join(map(repr, self._struct_types))},))"

    def __str__(self):
        fields_str = ", ".join(f"{name}: {type_}" for name, type_ in self.struct_fields)
        return f"{self.struct_name}({fields_str})"

    @property
    def struct_name(self):
        return "tuple"

    @property
    def struct_fields(self):
        return [(f"element_{i}", fmt) for i, fmt in enumerate(self._struct_types)]

    @property
    def struct_fieldnames(self) -> list[str]:
        return [name for (name, _) in self.struct_fields]

    @property
    def struct_fieldtypes(self) -> list[Any]:
        return [type_ for (_, type_) in self.struct_fields]

    def __promote__(self, other):
        if not isinstance(other, TupleFType):
            return None
        if len(self.struct_fieldtypes) != len(other.struct_fieldtypes):
            raise TypeError("Tuple operands must have the same length.")
        return TupleFType.from_tuple(
            tuple(
                promote_type(type_, other_type)
                for type_, other_type in zip(
                    self.struct_fieldtypes,
                    other.struct_fieldtypes,
                    strict=True,
                )
            )
        )

    def struct_hasattr(self, attr: str) -> builtins.bool:
        return attr in dict(self.struct_fields)

    def struct_attrtype(self, attr: str) -> Any:
        return dict(self.struct_fields)[attr]

    def struct_getattr(self, obj, attr):
        index = list(self.struct_fieldnames).index(attr)
        field_type = self.struct_fieldtypes[index]
        return field_type(obj[index])

    def struct_setattr(self, obj, attr, value):
        index = list(self.struct_fieldnames).index(attr)
        obj[index] = value

    def fisinstance(self, other):
        if not isinstance(other, tuple) or len(other) != len(self.struct_fieldtypes):
            return False
        return all(
            fisinstance(elt, fmt)
            for elt, fmt in zip(other, self.struct_fieldtypes, strict=False)
        )

    def from_fields(self, *args):
        assert all(
            fisinstance(a, f)
            for a, f in zip(args, self.struct_fieldtypes, strict=False)
        )
        return tuple(args)

    def __call__(self, arg):
        return tuple([T(x) for T, x in zip(self._struct_types, arg, strict=False)])

    @staticmethod
    @lru_cache
    def from_tuple(types: tuple[FType, ...]) -> TupleFType:
        if not isinstance(types, tuple):
            raise TypeError("TupleFType.from_tuple expects tuple[FType, ...]")
        if not all(isinstance(type_, FType) for type_ in types):
            raise TypeError("TupleFType.from_tuple expects tuple[FType, ...]")
        return TupleFType(types)

fisinstance(x, f)

Check if x is an instance of f.

Source code in src/finch/algebra/ftypes.py
def fisinstance(x, f: FType):
    """
    Check if `x` is an instance of `f`.
    """
    return f.fisinstance(x)

ftype(x)

ftype(x: FinchOperator) -> FinchOperatorFType
ftype(x: Tensor) -> TensorFType
ftype(x: tuple) -> TupleFType
ftype(x: NumpyBuffer) -> NumpyBufferFType
ftype(x: np.integer) -> FDTypeInteger
ftype(x: FT) -> FT
ftype(x: FTyped[FT]) -> FT
ftype(x: Any) -> FType

Return the corresponding FType for a given object. Recognizes numpy, Python builtins, and Python tuples. Sometimes recognizes types. Override .ftype to customize the ftype of an object.

Source code in src/finch/algebra/ftypes.py
def ftype(x: Any) -> FType:
    """Return the corresponding FType for a given object.  Recognizes numpy,
    Python builtins, and Python tuples.  Sometimes recognizes types.
    Override .ftype to customize the ftype of an object.
    """
    if isinstance(x, FType):
        return x
    if isinstance(x, FTyped):
        return x.ftype
    dtype: Any = None
    if isinstance(x, np.dtype):
        if x.fields is not None:
            assert x.names is not None
            return TupleFType.from_tuple(
                tuple(ftype(x.fields[name][0]) for name in x.names)
            )
        dtype = x
    elif isinstance(x, np.void) and x.dtype.fields is not None:
        assert x.dtype.names is not None
        return TupleFType.from_tuple(
            tuple(ftype(x.dtype.fields[name][0]) for name in x.dtype.names)
        )
    elif isinstance(x, np.generic):
        dtype = x.dtype
    elif isinstance(x, type) and issubclass(x, np.generic):
        dtype = np.dtype(x)
    if dtype is not None:
        if dtype == np.dtype(np.bool_):
            return bool
        if dtype == np.dtype(np.int8):
            return int8
        if dtype == np.dtype(np.int16):
            return int16
        if dtype == np.dtype(np.int32):
            return int32
        if dtype == np.dtype(np.int64):
            return int64
        if dtype == np.dtype(np.uint8):
            return uint8
        if dtype == np.dtype(np.uint16):
            return uint16
        if dtype == np.dtype(np.uint32):
            return uint32
        if dtype == np.dtype(np.uint64):
            return uint64
        if dtype == np.dtype(np.float16):
            return float16
        if dtype == np.dtype(np.float32):
            return float32
        if dtype == np.dtype(np.float64):
            return float64
        if dtype == np.dtype(np.complex64):
            return complex64
        if dtype == np.dtype(np.complex128):
            return complex128
        raise NotImplementedError
    if type(x) is builtins.bool or x is builtins.bool:
        return bool_
    if type(x) is builtins.int or x is builtins.int:
        return int_
    if type(x) is builtins.float or x is builtins.float:
        return float_
    if type(x) is builtins.complex or x is builtins.complex:
        return complex_
    if type(x) is builtins.str or x is builtins.str:
        return str_
    if x is None:
        return none_
    if isinstance(x, tuple):
        T = type(x)
        if hasattr(T, "_fields") and all(isinstance(field, str) for field in T._fields):
            return NamedTupleFType(
                T.__name__,
                [(fieldname, ftype(getattr(x, fieldname))) for fieldname in T._fields],
            )
        return TupleFType.from_tuple(tuple(ftype(elem) for elem in x))
    raise NotImplementedError(
        f"finch.ftype cannot be constructed from instance of: {type(x)}"
    )

isdtype(dtype, kind)

Check if a dtype belongs to an Array API dtype kind.

Source code in src/finch/algebra/ftypes.py
def isdtype(dtype, kind):
    """
    Check if a dtype belongs to an Array API dtype kind.
    """
    dtype = ftype(dtype)
    if isinstance(kind, tuple):
        return any(isdtype(dtype, k) for k in kind)
    if isinstance(kind, str):
        match kind:
            case "bool":
                return builtins.bool(dtype == bool)
            case "signed integer":
                return isinstance(dtype, FDTypeSignedInteger)
            case "unsigned integer":
                return isinstance(dtype, FDTypeUnsignedInteger)
            case "integral":
                return isinstance(dtype, FDTypeInteger)
            case "real floating":
                return isinstance(dtype, FDTypeFloat) and not isinstance(
                    dtype, FDTypeComplex
                )
            case "complex floating":
                return isinstance(dtype, FDTypeComplex)
            case "numeric":
                return isinstance(dtype, FDTypeNumeric)
            case _:
                raise ValueError(f"Unrecognized dtype kind: {kind!r}")
    return builtins.bool(dtype == ftype(kind))

promote_type(T1, T2)

Returns the data type with the smallest size and smallest scalar kind to which both type1 and type2 may be safely cast.

Parameters:

Name Type Description Default
T1 FDType

The first type to promote.

required
T2 FDType

The second type to promote.

required

Returns:

Type Description
FDType

The common type of the given arguments.

Source code in src/finch/algebra/ftypes.py
def promote_type(T1: FDType, T2: FDType) -> FDType:
    """
    Returns the data type with the smallest size and smallest scalar kind to
    which both type1 and type2 may be safely cast.

    Args:
        T1: The first type to promote.
        T2: The second type to promote.

    Returns:
        The common type of the given arguments.
    """
    if T1 == T2:
        return T1
    S1 = T1.__promote__(T2)
    S2 = T2.__promote__(T1)
    if S1 is not None:
        assert S1 == S2, f"Promotion of {T1} and {T2} is not consistent: {S1} vs {S2}"
        return S1
    if S2 is not None:
        return S2
    raise TypeError(f"Cannot promote types {T1} and {T2}")