Skip to content

ftypes

FDType

Bases: FType

Source code in src/finch/algebra/ftypes.py
63
64
65
66
67
68
69
70
71
72
73
74
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
70
71
72
73
74
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
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
214
215
216
217
218
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
144
145
146
147
148
149
150
151
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
128
129
130
131
132
133
134
135
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
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
376
377
378
379
380
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
@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
48
49
50
51
52
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
708
709
710
711
712
713
714
715
716
717
718
719
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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
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
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
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
945
946
947
948
949
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
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
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

isdtype(dtype, kind)

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

Source code in src/finch/algebra/ftypes.py
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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}")