Package: tensora
TensoraA fast and easy-to-use dense/sparse tensor library for Python. Evaluate arbitrary tensor expressions with tensors in a variety of sparsity formats.Tensors are n-dimensional generalizations of matrices. Instead of being confined to 1 or 2 dimensions, tensors may have 3, 4, or more dimensions. They are useful in a variety of applications. NumPy is the best known tensor library in Python; its centralndarrayobject is an example of a dense tensor.In a dense tensor, each element is explicitly stored in memory. If the vast majority of elements are zero, then this is an inefficient layout, taking far more memory to store and far more time to operate on. There are many different sparse tensor formats, each one better or worse depending on which elements of the tensor are nonzero.Many tensor kernels (functions that perform a specific algebraic calculation between tensors with specific sparse formats) have been written to solve specific problems. Recently, theTensor Algebra Compiler(TACO) was invented to automate the construction and optimization of tensor kernels for arbitrary algebraic expressions for arbitrary sparse formats. TACO takes an algebraic expression and description of the format of each tensor in the expression and returns a C function that efficiently evaluates the given expression for those tensor arguments.Tensora is a Python wrapper around two tensor algebra compilers: the original TACO library and an independent Python implementation in Tensora. Tensora has a central classTensorthat simply has a pointer to a taco tensor held in C memory, managed by thecffipackage. Tensora exposes functions that take a string of an algebraic expression and return a Python function the performs that operation in fast C code. In order to do that, the string is parsed and passed to the tensor algebra compiler; the C code generated by the tensor algebra compiler is compiled "on the fly" bycffiand then wrapped by code that provides good error handling.Tensora comes with a command line tooltensora, which provides the C code to the user for given algebraic expressions and tensor formats.Getting startedTensora can be installed withpipfrom PyPI:pipinstalltensoraThe classTensorand the functionevaluatetogether provide the porcelain interface for Tensora.Here is an example of multiplying a sparse matrix in CSR format with a dense vector:fromtensoraimportTensor,evaluateelements={(1,0):2.0,(0,1):-2.0,(1,2):4.0,}A=Tensor.from_dok(elements,dimensions=(2,3),format='ds')x=Tensor.from_lol([0,-1,2])y=evaluate('y(i) = A(i,j) * x(j)','d',A=A,x=x)asserty==Tensor.from_lol([2,8])CreatingTensorsCreating aTensoris best done via theTensor.from_*methods. These methods convert a variety of data types into aTensor. Most of the conversion methods optionally take bothdimensionsandformatto determine the dimensions and format of the resulting tensor.from_lol: list of listsTensor.from_lol(lol,*,dimensions:tuple[int,...]=None,format:Format|str=None)Convert a dense list of lists to aTensor.lolis a list of lists, possibly deeply nested. That is,lolis afloat, alist[float], alist[list[float]], etc. to an arbitrary depth oflists. The values are read in row-major format, meaning the top-level list is the first dimension and the deepest list (the one containing actual scalars) is the last dimension. All lists at the same level must have the same length. For those familiar, this is identical to the NumPy behavior when constructing an array from lists of lists vianumpy.array.dimensionshas a default value that is inferred from the structure oflol. If provided, it must be consistent with the structure oflol. Providing the dimensions is typically only useful when one or more non-final dimensions may have size zero. For example,Tensor.from_lol([[], []])has dimensions of(2,0), whileTensor.from_lol([[], []], dimensions=(2,0,3))has dimensions of(2,0,3).formathas a default value of all dense dimensions.from_dok: dictionary of keysTensor.from_dok(dok:dict[tuple[int,...],float],*,dimensions:tuple[int,...]=None,format:Format|str=None)Convert a dictionary of keys to aTensor.dokis a Python dictionary where each key is the coordinate of one non-zero value and the value of the entry is the value of the tensor at that coordinate. All coordinates not mentioned are implicitly zero.dimensionshas a default value that is the largest size in each dimension found among the coordinates.formathas a default value of dense dimensions as long as the number of nonzeros is larger than the product of those dimensions and then sparse dimensions after that. The default value is subject to change with experience.from_aos: array of structsTensor.from_aos(aos:Iterable[tuple[int,...]],values:Iterable[float],*,dimensions:tuple[int,...]=None,format:Format|str=None)Convert a list of coordinates and a corresponding list of values to aTensor.aosis an iterable of the coordinates of the non-zero values.valuesmust be the same length asaosand each value is the non-zero value at the corresponding coordinate.dimensionshas the same default asTensor.from_dok, the largest size in each dimension.formathas the same default asTensor.from_dok, dense for an many dimensions as needed to fit the non-zeros.from_soa: struct of arraysTensor.from_soa(soa:tuple[Iterable[int],...],values:Iterable[float],*,dimensions:tuple[int,...]=None,format:Format|str=None)Convert lists of indexes for each dimension and a corresponding list of values to aTensor.soais a tuple of iterables, where each iterable is all the indexes of the corresponding dimension. All iterables must be the same length.valuesmust be the same length as the iterables in coordinates and each value is the non-zero value at the corresponding coordinate.dimensionshas the same default asTensor.from_dok, the largest size in each dimension.formathas the same default asTensor.from_dok, dense for an many dimensions as needed to fit the non-zeros.from_numpy: convert a NumPy arrayTensor.from_numpy(array:numpy.ndarray,*,format:Format|str=None)Convert a NumPy array to aTensor.arrayis anyNumPy.ndarray. The resultingTensorwill have the same order, dimensions, and values of this array.formathas a default value of all dense dimensions.from_scipy_sparse: convert a SciPy sparse matrixTensor.from_scipy_sparse(data:scipy.sparse.spmatrix,*,format:Format|str=None)Convert a SciPy sparse matrix to aTensor.matrixis anySciPy.sparse.spmatrix. The resultingTensorwill have the same order, dimensions, and values of this matrix. The tensor will always have order 2.formathas a default value ofdsforcsr_matrixandd1s0forcsc_matrixand alsodsfor the other sparse matrix types, though that is subject to changes as Tensora adds new format mode types.Evaluating expressionsTensora generates kernels for algebraic expressions of tensor kernels and wraps them in theevaluatefunction.evaluate(assignment:str,output_format:str,**inputs:Tensor)assignmentis parsable as an algebraic tensor assignment.output_formatis the desired format of the output tensor.inputsis all the inputs to the expression. There must be one named argument for each variable name inassignment. The dimensions of the tensors ininputsmust be consistent withassignmentand with each other.There is alsoevaluate_tensoraandevaluate_tacothat have identical interfaces, but use different tensor algebra compilers.evaluateis an alias for the default, which is currentlyevaluate_tensora.Getting the C codeThetensoraCLI tool emits the C code for a given algebraic expression, tensor formats, and kernel type. It can emit the C code it generates itself, or the C code generated by TACO. It comes installed with Tensora and can be run like:tensora'y(i) = A(i,j) * x(j)'-fA:ds-tcompute-okernel.cHere is the output oftensora --helpfor reference:Usage: tensora [OPTIONS] ASSIGNMENT

╭─ Arguments ──────────────────────────────────────────────────────────────────────────────╮
│ *    assignment      TEXT  The assignment for which to generate code, e.g. y(i) = A(i,j) │
│                            * x(j).                                                       │
│                            [required]                                                    │
╰──────────────────────────────────────────────────────────────────────────────────────────╯
╭─ Options ────────────────────────────────────────────────────────────────────────────────╮
│ --format              -f      TEXT                         A tensor and its format       │
│                                                            separated by a colon, e.g.    │
│                                                            A:d1s0 for CSC matrix.        │
│                                                            Unmentioned tensors are be    │
│                                                            assumed to be all dense.      │
│ --type                -t      [assemble|compute|evaluate]  The type of kernel that will  │
│                                                            be generated. Can be          │
│                                                            mentioned multiple times.     │
│                                                            [default: compute]            │
│ --compiler            -c      [tensora|taco]               The tensor algebra compiler   │
│                                                            to use to generate the        │
│                                                            kernel.                       │
│                                                            [default: tensora]            │
│ --output              -o      PATH                         The file to which the kernel  │
│                                                            will be written. If not       │
│                                                            specified, prints to standard │
│                                                            out.                          │
│                                                            [default: None]               │
│ --install-completion          [bash|zsh|fish|powershell|p  Install completion for the    │
│                               wsh]                         specified shell.              │
│                                                            [default: None]               │
│ --show-completion             [bash|zsh|fish|powershell|p  Show completion for the       │
│                               wsh]                         specified shell, to copy it   │
│                                                            or customize the              │
│                                                            installation.                 │
│                                                            [default: None]               │
│ --help                                                     Show this message and exit.   │
╰──────────────────────────────────────────────────────────────────────────────────────────╯