Skip to content

binsparse

from_binsparse(array)

Convert a Binsparse tensor from the reference binsparse package into a Finch tensor which shares its buffers wherever possible.

Dense levels become one Finch DenseLevel per dimension, rank-1 sparse levels become SparseListLevel, and higher-rank sparse levels become SparseCOOLevel.

Source code in src/finch/fileio/binsparse.py
21
22
23
24
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
def from_binsparse(array: bsp.BinsparseTensor) -> FiberTensor:
    """
    Convert a Binsparse tensor from the reference `binsparse` package into a
    Finch tensor which shares its buffers wherever possible.

    Dense levels become one Finch `DenseLevel` per dimension, rank-1 sparse
    levels become `SparseListLevel`, and higher-rank sparse levels become
    `SparseCOOLevel`.
    """
    if not isinstance(array, bsp.CustomTensor):
        container = bsp.InMemoryBinsparseContainer()
        array.serialize(container, alias=False)
        array = bsp.CustomTensor.parse(container)
    match array:
        case bsp.CustomTensor(
            shape=shape, transpose=None, level=bsp.BinsparseLevel() as level
        ):
            values = _element_values(level)
            fill_value = array.fill_value if array.fill is True else 0
            element_format = element(
                fill_type=StaticFillFType(values.dtype.type(fill_value)),
                element_type=ftype(values.dtype),
                position_type=ftype(_position_dtype(level)),
            )
            return FiberTensor(_from_level(level, shape, element_format, 0))
        case _:
            raise NotImplementedError(
                "Finch does not support transposed Binsparse tensors."
            )

to_binsparse(tns)

Convert a Finch tensor to a Binsparse tensor which shares its buffers.

Source code in src/finch/fileio/binsparse.py
52
53
54
55
56
57
58
59
60
61
def to_binsparse(tns: FiberTensor) -> bsp.CustomTensor:
    """Convert a Finch tensor to a Binsparse tensor which shares its buffers."""
    level, shape = _to_level(tns.lvl, 0)
    return bsp.CustomTensor(
        shape=shape,
        number_of_stored_values=_element_values(level).size,
        fill=True,
        fill_value=tns.fill_value,
        level=level,
    )