response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Fuse all `arrays` by simple kronecker addition. Arrays are fused from "right to left", Args: arrays: A list of arrays to be fused. Returns: np.ndarray: The result of fusing `arrays`.
def fuse_ndarrays(arrays: List[Union[List, np.ndarray]]) -> np.ndarray: """ Fuse all `arrays` by simple kronecker addition. Arrays are fused from "right to left", Args: arrays: A list of arrays to be fused. Returns: np.ndarray: The result of fusing `arrays`. """ if len(arrays) == 1: return np...
Fuse degeneracies `degen1` and `degen2` of two leg-charges by simple kronecker product. `degen1` and `degen2` typically belong to two consecutive legs of `BlockSparseTensor`. Given `degen1 = [1, 2, 3]` and `degen2 = [10, 100]`, this returns `[10, 100, 20, 200, 30, 300]`. When using row-major ordering of indices in `Blo...
def fuse_degeneracies(degen1: Union[List, np.ndarray], degen2: Union[List, np.ndarray]) -> np.ndarray: """ Fuse degeneracies `degen1` and `degen2` of two leg-charges by simple kronecker product. `degen1` and `degen2` typically belong to two consecutive legs of `BlockSparseTensor`. Given ...
compute strides of `dims`.
def _get_strides(dims: Union[List[int], np.ndarray]) -> np.ndarray: """ compute strides of `dims`. """ return np.flip(np.append(1, np.cumprod(np.flip(dims[1::]))))
Find the most-levelled partition of `dims`. A levelled partitioning is a partitioning such that np.prod(dim[:partition]) and np.prod(dim[partition:]) are as close as possible. Args: dims: A list or np.ndarray of integers. Returns: int: The best partitioning.
def _find_best_partition(dims: Union[List[int], np.ndarray]) -> int: """ Find the most-levelled partition of `dims`. A levelled partitioning is a partitioning such that np.prod(dim[:partition]) and np.prod(dim[partition:]) are as close as possible. Args: dims: A list or np.ndarray of integers. Returns...
Return the `numpy.dtype` needed to store an element of `itemsize` bytes.
def get_dtype(itemsize: int) -> Type[np.number]: """ Return the `numpy.dtype` needed to store an element of `itemsize` bytes. """ final_dtype = np.int8 if itemsize > 1: final_dtype = np.int16 if itemsize > 2: final_dtype = np.int32 if itemsize > 4: final_dtype = np.int64 return final_d...
If possible, collapse a 2d numpy array `array` along the rows into a 1d array of larger dtype. Args: array: np.ndarray Returns: np.ndarray: The collapsed array.
def collapse(array: np.ndarray) -> np.ndarray: """ If possible, collapse a 2d numpy array `array` along the rows into a 1d array of larger dtype. Args: array: np.ndarray Returns: np.ndarray: The collapsed array. """ if array.ndim <= 1 or array.dtype.itemsize * array.shape[1] > 8: return a...
Reverse operation to `collapse`. Expand a 1d numpy array `array` into a 2d array of dtype `original_dtype` by view-casting. Args: array: The collapsed array. original_dtype: The dtype of the original (uncollapsed) array original_width: The width (the length of the second dimension) of the original (uncollaps...
def expand(array: np.ndarray, original_dtype: Type[np.number], original_width: int, original_ndim: int) -> np.ndarray: """ Reverse operation to `collapse`. Expand a 1d numpy array `array` into a 2d array of dtype `original_dtype` by view-casting. Args: array: The collapsed array. original_...
Compute the unique elements of 1d or 2d `array` along the zero axis of the array. This function performs performs a similar task to `numpy.unique` with `axis=0` argument, but is substantially faster for 2d arrays. Note that for the case of 2d arrays, the ordering of the array of unique elements differs from the orde...
def unique(array: np.ndarray, return_index: bool = False, return_inverse: bool = False, return_counts: bool = False, label_dtype: Type[np.number] = np.int16) -> Any: """ Compute the unique elements of 1d or 2d `array` along the zero axis of the array. This function p...
Extends numpy's intersect1d to find the row or column-wise intersection of two 2d arrays. Takes identical input to numpy intersect1d. Args: A, B (np.ndarray): arrays of matching widths and datatypes Returns: ndarray: sorted 1D array of common rows/cols between the input arrays ndarray: the indices of the first oc...
def intersect(A: np.ndarray, B: np.ndarray, axis=0, assume_unique=False, return_indices=False) -> Any: """ Extends numpy's intersect1d to find the row or column-wise intersection of two 2d arrays. Takes identical input to numpy intersect1d. Args: A, B ...
Extends numpy's intersect1d to find the row or column-wise intersection of two 2d arrays. Takes identical input to numpy intersect1d. Args: A, B (np.ndarray): arrays of matching widths and datatypes Returns: ndarray: sorted 1D array of common rows/cols between the input arrays ndarray: the indices of the first oc...
def _intersect_ndarray(A: np.ndarray, B: np.ndarray, axis=0, assume_unique=False, return_indices=False) -> Any: """ Extends numpy's intersect1d to find the row or column-wise intersection of two 2d arrays. Takes identical ...
Contract given nodes exploiting copy tensors. This is based on the Bucket-Elimination-based algorithm described in `arXiv:quant-ph/1712.05384`_, but avoids explicit construction of the graphical model. Instead, it achieves the efficient contraction of sparse tensors by representing them as subnetworks consisting of ...
def bucket( nodes: Iterable[AbstractNode], contraction_order: Sequence[network_components.CopyNode] ) -> Iterable[AbstractNode]: """Contract given nodes exploiting copy tensors. This is based on the Bucket-Elimination-based algorithm described in `arXiv:quant-ph/1712.05384`_, but avoids explicit construc...
Adds the CNOT quantum gate to tensor network. CNOT consists of two rank-3 tensors: a COPY tensor on the control qubit and a XOR tensor on the target qubit. Args: q0: Input edge for the control qubit. q1: Input edge for the target qubit. backend: backend to use Returns: Tuple with three elements: - copy ten...
def add_cnot( q0: network_components.Edge, q1: network_components.Edge, backend: str = "numpy" ) -> Tuple[network_components.CopyNode, network_components.Edge, network_components.Edge]: """Adds the CNOT quantum gate to tensor network. CNOT consists of two rank-3 tensors: a COPY tensor on the...
Solve for the contraction order of a tensor network (encoded in the `ncon` syntax) that minimizes the computational cost. Args: tensors: list of the tensors in the network. labels: list of the tensor connections (in standard `ncon` format). max_branch: maximum number of contraction paths to search at each step. R...
def ncon_solver(tensors: List[np.ndarray], labels: List[List[int]], max_branch: Optional[int] = None): """ Solve for the contraction order of a tensor network (encoded in the `ncon` syntax) that minimizes the computational cost. Args: tensors: list of the tensors in the netwo...
Create a log-adjacency matrix, where element [i,j] is the log10 of the total dimension of the indices connecting ith and jth tensors, for a network defined in the `ncon` syntax. Args: tensors: list of the tensors in the network. labels: list of the tensor connections (in standard `ncon` format). Returns: np.ndarr...
def ncon_to_adj(tensors: List[np.ndarray], labels: List[List[int]]): """ Create a log-adjacency matrix, where element [i,j] is the log10 of the total dimension of the indices connecting ith and jth tensors, for a network defined in the `ncon` syntax. Args: tensors: list of the tensors in the network. ...
Produces a `ncon` compatible index contraction order from the sequence of pairwise contractions. Args: labels: list of the tensor connections (in standard `ncon` format). orders: array of dim (2,N-1) specifying the set of N-1 pairwise tensor contractions. Returns: np.ndarray: the contraction order (in `ncon` ...
def ord_to_ncon(labels: List[List[int]], orders: np.ndarray): """ Produces a `ncon` compatible index contraction order from the sequence of pairwise contractions. Args: labels: list of the tensor connections (in standard `ncon` format). orders: array of dim (2,N-1) specifying the set of N-1 pairwise ...
Checks the computational cost of an `ncon` contraction (without actually doing the contraction). Ignore the cost contributions from partial traces (which are always sub-leading). Args: tensors: list of the tensors in the network. labels: length-N list of lists (or tuples) specifying the network connections. The...
def ncon_cost_check(tensors: List[np.ndarray], labels: List[Union[List[int], Tuple[int]]], con_order: Optional[Union[List[int], str]] = None): """ Checks the computational cost of an `ncon` contraction (without actually doing the contraction). Ignore the cost contributions ...
Solve for the contraction order of a tensor network (encoded as a log-adjacency matrix) using a greedy algorithm that minimizes the intermediate tensor sizes. Args: log_adj_in: matrix where element [i,j] is the log10 of the total dimension of the indices connecting ith and jth tensors. Returns: np.ndarray: chea...
def greedy_size_solve(log_adj_in: np.ndarray): """ Solve for the contraction order of a tensor network (encoded as a log-adjacency matrix) using a greedy algorithm that minimizes the intermediate tensor sizes. Args: log_adj_in: matrix where element [i,j] is the log10 of the total dimension of the in...
Solve for the contraction order of a tensor network (encoded as a log-adjacency matrix) using a greedy algorithm that minimizes the contraction cost at each step. Args: log_adj_in: matrix where element [i,j] is the log10 of the total dimension of the indices connecting ith and jth tensors. Returns: np.ndarray: ...
def greedy_cost_solve(log_adj_in: np.ndarray): """ Solve for the contraction order of a tensor network (encoded as a log-adjacency matrix) using a greedy algorithm that minimizes the contraction cost at each step. Args: log_adj_in: matrix where element [i,j] is the log10 of the total dimension of th...
Solve for optimal contraction path of a network encoded as a log-adjacency matrix via a full search. Args: log_adj: matrix where element [i,j] is the log10 of the total dimension of the indices connecting ith and jth tensors. cost_bound: upper cost threshold for discarding paths, in log10(FLOPS). max_branch: ...
def full_solve_complete(log_adj: np.ndarray, cost_bound: Optional[int] = None, max_branch: Optional[int] = None): """ Solve for optimal contraction path of a network encoded as a log-adjacency matrix via a full search. Args: log_adj: matrix where element [i,j]...
Solve for the most-likely contraction step given a set of networks encoded as log-adjacency matrices. Uses an algorithm that searches multiple (or, potentially, all viable paths) as to minimize the total contraction cost. Args: log_adj: an np.ndarray of log-adjacency matrices of dim (N,N,m), with `N` the number o...
def _full_solve_single(log_adj: np.ndarray, costs: np.ndarray, groups: np.ndarray, orders: np.ndarray, cost_bound: Optional[int] = None, max_branch: Optional[int] = None, allow_outer...
Reduce from `m` starting paths smaller number of paths by first (i) identifying any equivalent networks then (ii) trimming the most expensive paths. Args: costs: np.ndarray of length `m` detailing to prior cost of each network. groups: np.ndarray of dim (N,m) providing an id-tag for each network, based on a pow...
def _reduce_nets(costs: np.ndarray, groups: np.ndarray, stable: np.ndarray, max_branch: Optional[int] = None): """ Reduce from `m` starting paths smaller number of paths by first (i) identifying any equivalent networks then (ii) trimming the most expensive path...
Creates 'GEMM1' contraction from `opt_einsum` tests.
def gemm_network(): """Creates 'GEMM1' contraction from `opt_einsum` tests.""" x = Node(np.ones([1, 2, 4])) y = Node(np.ones([1, 3])) z = Node(np.ones([2, 4, 3])) # pylint: disable=pointless-statement x[0] ^ y[0] x[1] ^ z[0] x[2] ^ z[1] y[1] ^ z[2] return [x, y, z]
Creates a (modified) `Inner1` contraction from `opt_einsum` tests.
def inner_network(): """Creates a (modified) `Inner1` contraction from `opt_einsum` tests.""" x = Node(np.ones([5, 2, 3, 4])) y = Node(np.ones([5, 3])) z = Node(np.ones([2, 4])) # pylint: disable=pointless-statement x[0] ^ y[0] x[1] ^ z[0] x[2] ^ y[1] x[3] ^ z[1] return [x, y, z]
Creates a contraction of chain of matrices. The `greedy` algorithm does not find the optimal path in this case!
def matrix_chain(): """Creates a contraction of chain of matrices. The `greedy` algorithm does not find the optimal path in this case! """ d = [10, 8, 6, 4, 2] nodes = [Node(np.ones([d1, d2])) for d1, d2 in zip(d[:-1], d[1:])] for a, b in zip(nodes[:-1], nodes[1:]): # pylint: disable=pointless-statemen...
Base method for all `opt_einsum` contractors. Args: nodes: A collection of connected nodes. algorithm: `opt_einsum` contraction method to use. output_edge_order: An optional list of edges. Edges of the final node in `nodes_set` are reordered into `output_edge_order`; if final node has more than one e...
def base(nodes: Iterable[AbstractNode], algorithm: utils.Algorithm, output_edge_order: Optional[Sequence[Edge]] = None, ignore_edge_order: bool = False) -> AbstractNode: """Base method for all `opt_einsum` contractors. Args: nodes: A collection of connected nodes. algorithm: `opt...
Optimal contraction order via `opt_einsum`. This method will find the truly optimal contraction order via `opt_einsum`'s depth first search algorithm. Since this search is exhaustive, if your network is large (n>10), then the search may take longer than just contracting in a suboptimal way. Args: nodes: an iterable...
def optimal(nodes: Iterable[AbstractNode], output_edge_order: Optional[Sequence[Edge]] = None, memory_limit: Optional[int] = None, ignore_edge_order: bool = False) -> AbstractNode: """Optimal contraction order via `opt_einsum`. This method will find the truly optimal contraction...
Branch contraction path via `opt_einsum`. This method uses the DFS approach of `optimal` while sorting potential contractions based on a heuristic cost, in order to reduce time spent in exploring paths which are unlikely to be optimal. More details on `branching path`_. .. _branching path: https://optimized-einsum....
def branch(nodes: Iterable[AbstractNode], output_edge_order: Optional[Sequence[Edge]] = None, memory_limit: Optional[int] = None, nbranch: Optional[int] = None, ignore_edge_order: bool = False) -> AbstractNode: """Branch contraction path via `opt_einsum`. This method use...
Greedy contraction path via `opt_einsum`. This provides a more efficient strategy than `optimal` for finding contraction paths in large networks. First contracts pairs of tensors by finding the pair with the lowest cost at each step. Then it performs the outer products. More details on `greedy path`_. .. _greedy pat...
def greedy(nodes: Iterable[AbstractNode], output_edge_order: Optional[Sequence[Edge]] = None, memory_limit: Optional[int] = None, ignore_edge_order: bool = False) -> AbstractNode: """Greedy contraction path via `opt_einsum`. This provides a more efficient strategy than `optimal` fo...
Chooses one of the above algorithms according to network size. Default behavior is based on `opt_einsum`'s `auto` contractor. Args: nodes: A collection of connected nodes. output_edge_order: An optional list of edges. Edges of the final node in `nodes_set` are reordered into `output_edge_order`; if fi...
def auto(nodes: Iterable[AbstractNode], output_edge_order: Optional[Sequence[Edge]] = None, memory_limit: Optional[int] = None, ignore_edge_order: bool = False) -> AbstractNode: """Chooses one of the above algorithms according to network size. Default behavior is based on `opt_einsum`'s ...
Uses a custom path optimizer created by the user to calculate paths. The custom path optimizer should inherit `opt_einsum`'s `PathOptimizer`. See `custom paths`_. .. _custom paths: https://optimized-einsum.readthedocs.io/en/latest/custom_paths.html Args: nodes: an iterable of Nodes output_edge_order: An option...
def custom(nodes: Iterable[AbstractNode], optimizer: Any, output_edge_order: Sequence[Edge] = None, memory_limit: Optional[int] = None, ignore_edge_order: bool = False) -> AbstractNode: """Uses a custom path optimizer created by the user to calculate paths. The custom pa...
Calculates the contraction paths using `opt_einsum` methods. Args: algorithm: `opt_einsum` method to use for calculating the contraction path. nodes: an iterable of `AbstractNode` objects to contract. memory_limit: Maximum number of elements in an array during contractions. Only relevant for `algorithm in (o...
def path_solver( algorithm: Text, nodes: Iterable[AbstractNode], memory_limit: Optional[int] = None, nbranch: Optional[int] = None ) -> Tuple[List[Tuple[int, int]], List[AbstractNode]]: """Calculates the contraction paths using `opt_einsum` methods. Args: algorithm: `opt_einsum` method to use f...
Contract `nodes` using `path`. Args: path: The contraction path as returned from `path_solver`. nodes: A collection of connected nodes. output_edge_order: A list of edges. Edges of the final node in `nodes` are reordered into `output_edge_order`; Returns: Final node after full contraction.
def contract_path(path: Tuple[List[Tuple[int, int]]], nodes: Iterable[AbstractNode], output_edge_order: Sequence[Edge]) -> AbstractNode: """Contract `nodes` using `path`. Args: path: The contraction path as returned from `path_solver`. nodes: A col...
Remove multiple indicies in a list at once.
def multi_remove(elems: List[Any], indices: List[int]) -> List[Any]: """Remove multiple indicies in a list at once.""" return [i for j, i in enumerate(elems) if j not in indices]
Calculates the contraction paths using `opt_einsum` methods. Args: nodes: An iterable of nodes. algorithm: `opt_einsum` method to use for calculating the contraction path. Returns: The optimal contraction path as returned by `opt_einsum`.
def get_path( nodes: Iterable[AbstractNode], algorithm: Algorithm) -> Tuple[List[Tuple[int, int]], List[AbstractNode]]: """Calculates the contraction paths using `opt_einsum` methods. Args: nodes: An iterable of nodes. algorithm: `opt_einsum` method to use for calculating the contraction path. R...
Return a Tensor wrapping data obtained by an initialization function implemented in a backend. The Tensor will have the same shape as the underlying array that function generates, with all Edges dangling. This function is not intended to be called directly, but doing so should be safe enough. Args: fname: Name of th...
def initialize_tensor(fname: Text, *fargs: Any, backend: Optional[Union[Text, AbstractBackend]] = None, **fkwargs: Any) -> Tensor: """Return a Tensor wrapping data obtained by an initialization function implemented in a backend. The Tensor will hav...
Return a Tensor representing a 2D array with ones on the diagonal and zeros elsewhere. The Tensor has two dangling Edges. Args: N (int): The first dimension of the returned matrix. dtype, optional: dtype of array (default np.float64). M (int, optional): The second dimension of the returned matrix. backend (opti...
def eye(N: int, dtype: Optional[Type[np.number]] = None, M: Optional[int] = None, backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: """Return a Tensor representing a 2D array with ones on the diagonal and zeros elsewhere. The Tensor has two dangling Edges. Args: N (int...
Return a Tensor of shape `shape` of all zeros. The Tensor has one dangling Edge per dimension. Args: shape : Shape of the array. dtype, optional: dtype of array (default np.float64). backend (optional): The backend or its name. Returns: the_tensor : Tensor of shape `shape`. Represents an array of all zeros.
def zeros(shape: Sequence[int], dtype: Optional[Type[np.number]] = None, backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: """Return a Tensor of shape `shape` of all zeros. The Tensor has one dangling Edge per dimension. Args: shape : Shape of the array. dtype, optiona...
Return a Tensor of shape `shape` of all ones. The Tensor has one dangling Edge per dimension. Args: shape : Shape of the array. dtype, optional: dtype of array (default np.float64). backend (optional): The backend or its name. Returns: the_tensor : Tensor of shape `shape` Represents an array of all ones.
def ones(shape: Sequence[int], dtype: Optional[Type[np.number]] = None, backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: """Return a Tensor of shape `shape` of all ones. The Tensor has one dangling Edge per dimension. Args: shape : Shape of the array. dtype, optional: d...
Return a Tensor shape full of ones the same shape as input Args: tensor : Object to recieve shape from dtype (optional) : dtype of object backend(optional): The backend or its name.
def ones_like(tensor: Union[Any], dtype: Optional[Type[Any]] = None, backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: """Return a Tensor shape full of ones the same shape as input Args: tensor : Object to recieve shape from dtype (optional) : dtype of object ...
Return a Tensor shape full of zeros the same shape as input Args: tensor : Object to recieve shape from dtype (optional) : dtype of object backend(optional): The backend or its name.
def zeros_like(tensor: Union[Any], dtype: Optional[Any] = None, backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: """Return a Tensor shape full of zeros the same shape as input Args: tensor : Object to recieve shape from ...
Return a Tensor of shape `shape` of Gaussian random floats. The Tensor has one dangling Edge per dimension. Args: shape : Shape of the array. dtype, optional: dtype of array (default np.float64). seed, optional: Seed for the RNG. backend (optional): The backend or its name. Returns: the_tensor : Tensor of sha...
def randn(shape: Sequence[int], dtype: Optional[Type[np.number]] = None, seed: Optional[int] = None, backend: Optional[Union[Text, AbstractBackend]] = None) -> Tensor: """Return a Tensor of shape `shape` of Gaussian random floats. The Tensor has one dangling Edge per dimension. Args:...
Return a Tensor of shape `shape` of uniform random floats. The Tensor has one dangling Edge per dimension. Args: shape : Shape of the array. dtype, optional: dtype of array (default np.float64). seed, optional: Seed for the RNG. boundaries : Values lie in [boundaries[0], boundaries[1]). backend (optional): Th...
def random_uniform(shape: Sequence[int], dtype: Optional[Type[np.number]] = None, seed: Optional[int] = None, boundaries: Optional[Tuple[float, float]] = (0.0, 1.0), backend: Optional[Union[Text, AbstractBackend]] = None) -> ...
Checks that at least one of backend and x0 are not None; that backend and x0.backend agree; that if args is not None its elements are Tensors whose backends also agree. Creates a backend object from backend and returns the arrays housed by x0 and args. Args: backend: A backend, text specifying one, or None. x0: A ...
def krylov_error_checks(backend: Union[Text, AbstractBackend, None], x0: Union[Tensor, None], args: Union[List[Tensor], None]): """ Checks that at least one of backend and x0 are not None; that backend and x0.backend agree; that if args is not None its elements are ...
Lanczos method for finding the lowest eigenvector-eigenvalue pairs of `A`. Args: A: A (sparse) implementation of a linear operator. Call signature of `A` is `res = A(vector, *args)`, where `vector` can be an arbitrary `Array`, and `res.shape` has to be `vector.shape`. backend: A backend, text specifying ...
def eigsh_lanczos(A: Callable, backend: Optional[Union[Text, AbstractBackend]] = None, args: Optional[List[Tensor]] = None, x0: Optional[Tensor] = None, shape: Optional[Tuple[int, ...]] = None, dtype: Optional[Type[np.number]] = N...
Implicitly restarted Arnoldi method for finding the lowest eigenvector-eigenvalue pairs of a linear operator `A`. `A` is a function implementing the matrix-vector product. WARNING: This routine uses jax.jit to reduce runtimes. jitting is triggered at the first invocation of `eigs`, and on any subsequent calls if the p...
def eigs(A: Callable, backend: Optional[Union[Text, AbstractBackend]] = None, args: Optional[List[Tensor]] = None, x0: Optional[Tensor] = None, shape: Optional[Tuple[int, ...]] = None, dtype: Optional[Type[np.number]] = None, num_krylov_vecs: int = 20, nume...
GMRES solves the linear system A @ x = b for x given a vector `b` and a general (not necessarily symmetric/Hermitian) linear operator `A`. As a Krylov method, GMRES does not require a concrete matrix representation of the n by n `A`, but only a function `vector1 = A_mv(vector0, *A_args, **A_kwargs)` prescribing a one-...
def gmres(A_mv: Callable, b: Tensor, A_args: Optional[List] = None, x0: Optional[Tensor] = None, tol: float = 1E-05, atol: Optional[float] = None, num_krylov_vectors: Optional[int] = None, maxiter: Optional[int] = 1, M: Optional[Callable] =...
Computes the singular value decomposition (SVD) of a tensor. The SVD is performed by treating the tensor as a matrix, with an effective left (row) index resulting from combining the axes `tensor.shape[:pivot_axis]` and an effective right (column) index resulting from combining the axes `tensor.shape[pivot_axis:]`. Fo...
def svd( tensor: Tensor, pivot_axis: int = -1, max_singular_values: Optional[int] = None, max_truncation_error: Optional[float] = None, relative: Optional[bool] = False ) -> Tuple[Tensor, Tensor, Tensor, Tensor]: """Computes the singular value decomposition (SVD) of a tensor. The SVD is perform...
QR reshapes tensor into a matrix and then decomposes that matrix into the product of unitary and upper triangular matrices Q and R. Q is reshaped into a tensor depending on the input shape and the choice of pivot_axis. Computes the reduced QR decomposition of the matrix formed by concatenating tensor about pivot_axis,...
def qr( tensor: Tensor, pivot_axis: int = -1, non_negative_diagonal: bool = False ) -> Tuple[Tensor, Tensor]: """ QR reshapes tensor into a matrix and then decomposes that matrix into the product of unitary and upper triangular matrices Q and R. Q is reshaped into a tensor depending on the input sha...
RQ reshapes tensor into a matrix and then decomposes that matrix into the product of upper triangular and unitary matrices R and Q. Q is reshaped into a tensor depending on the input shape and the choice of pivot_axis. Computes the reduced RQ decomposition of the matrix formed by concatenating tensor about pivot_axis,...
def rq( tensor: Tensor, pivot_axis: int = -1, non_negative_diagonal: bool = False ) -> Tuple[Tensor, Tensor]: """ RQ reshapes tensor into a matrix and then decomposes that matrix into the product of upper triangular and unitary matrices R and Q. Q is reshaped into a tensor depending on the input sha...
Compute eigenvectors and eigenvalues of a hermitian matrix. Args: matrix: A symetric matrix. Returns: Tensor: The eigenvalues in ascending order. Tensor: The eigenvectors.
def eigh(matrix: Tensor) -> Tuple[Tensor, Tensor]: """Compute eigenvectors and eigenvalues of a hermitian matrix. Args: matrix: A symetric matrix. Returns: Tensor: The eigenvalues in ascending order. Tensor: The eigenvectors. """ backend = matrix.backend out = backend.eigh(matrix.array) tenso...
Calculate the L2-norm of the elements of `tensor`
def norm(tensor: Tensor) -> Tensor: """Calculate the L2-norm of the elements of `tensor` """ backend = tensor.backend out = backend.norm(tensor.array) return out
Compute the matrix inverse of `matrix`. Args: matrix: A matrix. Returns: Tensor: The inverse of `matrix`
def inv(matrix: Tensor) -> Tensor: """Compute the matrix inverse of `matrix`. Args: matrix: A matrix. Returns: Tensor: The inverse of `matrix` """ backend = matrix.backend out = backend.inv(matrix.array) tensor = Tensor(out, backend=backend) return tensor
Return expm log of `matrix`, matrix exponential. Args: matrix: A tensor. Returns: Tensor
def expm(matrix: Tensor) -> Tensor: """ Return expm log of `matrix`, matrix exponential. Args: matrix: A tensor. Returns: Tensor """ backend = matrix.backend out = backend.expm(matrix.array) tensor = Tensor(out, backend=backend) return tensor
Return a Node wrapping data obtained by an initialization function implemented in a backend. The Node will have the same shape as the underlying array that function generates, with all Edges dangling. This function is not intended to be called directly, but doing so should be safe enough. Args: fname: Name of the m...
def initialize_node(fname: Text, *fargs: Any, name: Optional[Text] = None, axis_names: Optional[List[Text]] = None, backend: Optional[Union[Text, BaseBackend]] = None, **fkwargs: Any) -> Tensor: """Return a Node wrappi...
Return a Node representing a 2D array with ones on the diagonal and zeros elsewhere. The Node has two dangling Edges. Args: N (int): The first dimension of the returned matrix. dtype, optional: dtype of array (default np.float64). M (int, optional): The second dimension of the returned matrix. name (text, optio...
def eye(N: int, dtype: Optional[Type[np.number]] = None, M: Optional[int] = None, name: Optional[Text] = None, axis_names: Optional[List[Text]] = None, backend: Optional[Union[Text, BaseBackend]] = None) -> Tensor: """Return a Node representing a 2D array with ones on the diago...
Return a Node of shape `shape` of all zeros. The Node has one dangling Edge per dimension. Args: shape : Shape of the array. dtype, optional: dtype of array (default np.float64). name (text, optional): Name of the Node. axis_names (optional): List of names of the edges. backend (optional): The backend or its ...
def zeros(shape: Sequence[int], dtype: Optional[Type[np.number]] = None, name: Optional[Text] = None, axis_names: Optional[List[Text]] = None, backend: Optional[Union[Text, BaseBackend]] = None) -> Tensor: """Return a Node of shape `shape` of all zeros. The Node has one dangl...
Return a Node of shape `shape` of all ones. The Node has one dangling Edge per dimension. Args: shape : Shape of the array. dtype, optional: dtype of array (default np.float64). name (text, optional): Name of the Node. axis_names (optional): List of names of the edges. backend (optional): The backend or its n...
def ones(shape: Sequence[int], dtype: Optional[Type[np.number]] = None, name: Optional[Text] = None, axis_names: Optional[List[Text]] = None, backend: Optional[Union[Text, BaseBackend]] = None) -> Tensor: """Return a Node of shape `shape` of all ones. The Node has one dangling Ed...
Return a Node of shape `shape` of Gaussian random floats. The Node has one dangling Edge per dimension. Args: shape : Shape of the array. dtype, optional: dtype of array (default np.float64). seed, optional: Seed for the RNG. name (text, optional): Name of the Node. axis_names (optional): List of names of the...
def randn(shape: Sequence[int], dtype: Optional[Type[np.number]] = None, seed: Optional[int] = None, name: Optional[Text] = None, axis_names: Optional[List[Text]] = None, backend: Optional[Union[Text, BaseBackend]] = None) -> Tensor: """Return a Node of shape `shape` ...
Return a Node of shape `shape` of uniform random floats. The Node has one dangling Edge per dimension. Args: shape : Shape of the array. dtype, optional: dtype of array (default np.float64). seed, optional: Seed for the RNG. boundaries : Values lie in [boundaries[0], boundaries[1]). name (text, optional): Nam...
def random_uniform( shape: Sequence[int], dtype: Optional[Type[np.number]] = None, seed: Optional[int] = None, boundaries: Optional[Tuple[float, float]] = (0.0, 1.0), name: Optional[Text] = None, axis_names: Optional[List[Text]] = None, backend: Optional[Union[Text, BaseBackend]] = None) -> ...
The L2 norm of `node` Args: node: A `AbstractNode`. Returns: The L2 norm. Raises: AttributeError: If `node` has no `backend` attribute.
def norm(node: AbstractNode) -> Tensor: """The L2 norm of `node` Args: node: A `AbstractNode`. Returns: The L2 norm. Raises: AttributeError: If `node` has no `backend` attribute. """ if not hasattr(node, 'backend'): raise AttributeError('Node {} of type {} has no `backend`'.format( ...
Conjugate a `node`. Args: node: A `AbstractNode`. name: Optional name to give the new node. axis_names: Optional list of names for the axis. Returns: A new node. The complex conjugate of `node`. Raises: AttributeError: If `node` has no `backend` attribute.
def conj(node: AbstractNode, name: Optional[Text] = None, axis_names: Optional[List[Text]] = None) -> AbstractNode: """Conjugate a `node`. Args: node: A `AbstractNode`. name: Optional name to give the new node. axis_names: Optional list of names for the axis. Returns: A new nod...
Transpose `node` Args: node: A `AbstractNode`. permutation: A list of int or str. The permutation of the axis. name: Optional name to give the new node. axis_names: Optional list of names for the axis. Returns: A new node. The transpose of `node`. Raises: AttributeError: If `node` has no `backend` attrib...
def transpose(node: AbstractNode, permutation: Sequence[Union[Text, int]], name: Optional[Text] = None, axis_names: Optional[List[Text]] = None) -> AbstractNode: """Transpose `node` Args: node: A `AbstractNode`. permutation: A list of int or str. The permutation of...
Kronecker product of the given nodes. Kronecker products of nodes is the same as the outer product, but the order of the axes is different. The first half of edges of all of the nodes will appear first half of edges in the resulting node, and the second half ot the edges in each node will be in the second half of the ...
def kron(nodes: Sequence[AbstractNode]) -> AbstractNode: """Kronecker product of the given nodes. Kronecker products of nodes is the same as the outer product, but the order of the axes is different. The first half of edges of all of the nodes will appear first half of edges in the resulting node, and the seco...
Checks that each of tensors has the same backend, returning True and an empty string if so, or False and an error string if not. Args: tensors: The list of tensors whose backends to check. fname: The name of the calling function, which will go into the errstring. Returns: (flag, errstr): Whether all backends ...
def _check_backends(tensors: Sequence[Tensor], fname: str) -> Tuple[bool, str]: """ Checks that each of tensors has the same backend, returning True and an empty string if so, or False and an error string if not. Args: tensors: The list of tensors whose backends to check. fname: The name of the callin...
Do a tensordot (contraction) of Tensors `a` and `b` over the given axes. The behaviour of this function largely matches that of np.tensordot. Args: a: A Tensor. b: Another Tensor. axes: Two lists of integers. These values are the contraction axes. A single integer may also be supplied, in which case both...
def tensordot(a: Tensor, b: Tensor, axes: Union[int, Sequence[Sequence[int]]]) -> Tensor: """Do a tensordot (contraction) of Tensors `a` and `b` over the given axes. The behaviour of this function largely matches that of np.tensordot. Args: a: A Tensor. b: Another Tensor. axes: Two list...
Reshape Tensor to the given shape. Args: tensor: Tensor to reshape. new_shape: The new shape. Returns: The reshaped Tensor.
def reshape(tensor: Tensor, new_shape: Sequence[int]) -> Tensor: """Reshape Tensor to the given shape. Args: tensor: Tensor to reshape. new_shape: The new shape. Returns: The reshaped Tensor. """ return tensor.reshape(new_shape)
Return a new `Tensor` transposed according to the permutation set by `axes`. By default the axes are reversed. Args: axes: The permutation. If None (default) the index order is reversed. Returns: The transposed `Tensor`.
def transpose(tensor: Tensor, perm: Optional[Sequence[int]] = None) -> Tensor: """ Return a new `Tensor` transposed according to the permutation set by `axes`. By default the axes are reversed. Args: axes: The permutation. If None (default) the index order is reversed. Returns: The transposed `Tensor`. ...
Obtains a slice of a Tensor based on start_indices and slice_sizes. Args: Tensor: A Tensor. start_indices: Tuple of integers denoting start indices of slice. slice_sizes: Tuple of integers denoting size of slice along each axis. Returns: The slice, a Tensor.
def take_slice(tensor: Tensor, start_indices: Tuple[int, ...], slice_sizes: Tuple[int, ...]) -> Tensor: """Obtains a slice of a Tensor based on start_indices and slice_sizes. Args: Tensor: A Tensor. start_indices: Tuple of integers denoting start indices of slice. slice_sizes: Tuple of i...
Get the shape of a Tensor as a tuple of integers. Args: Tensor: A Tensor. Returns: The shape of the input Tensor.
def shape(tensor: Tensor) -> Tuple[int, ...]: """Get the shape of a Tensor as a tuple of integers. Args: Tensor: A Tensor. Returns: The shape of the input Tensor. """ return tensor.shape
Take the square root (element wise) of a given Tensor.
def sqrt(tensor: Tensor) -> Tensor: """Take the square root (element wise) of a given Tensor.""" out_array = tensor.backend.sqrt(tensor.array) return Tensor(out_array, backend=tensor.backend)
Calculate the outer product of the two given Tensors.
def outer(tensor1: Tensor, tensor2: Tensor) -> Tensor: """Calculate the outer product of the two given Tensors.""" tensors = [tensor1, tensor2] all_backends_same, errstr = _check_backends(tensors, "outer") if not all_backends_same: raise ValueError(errstr) out_data = tensor1.backend.outer_product(tensor1....
Calculate sum of products of Tensors according to expression.
def einsum(expression: Text, *tensors: Tensor, optimize: bool) -> Tensor: """Calculate sum of products of Tensors according to expression.""" all_backends_same, errstr = _check_backends(tensors, "einsum") if not all_backends_same: raise ValueError(errstr) backend = tensors[0].backend arrays = [tensor.arra...
Return the complex conjugate of `Tensor` Args: Tensor: A Tensor. Returns: The complex conjugated Tensor.
def conj(tensor: Tensor) -> Tensor: """ Return the complex conjugate of `Tensor` Args: Tensor: A Tensor. Returns: The complex conjugated Tensor. """ return tensor.conj()
The Hermitian conjugated tensor; e.g. the complex conjugate tranposed by the permutation set be `axes`. By default the axes are reversed. Args: tensor: The Tensor to conjugate. axes: The permutation. If None (default) the index order is reversed. Returns: The Hermitian conjugated `Tensor`.
def hconj(tensor: Tensor, perm: Optional[Sequence[int]] = None) -> Tensor: """ The Hermitian conjugated tensor; e.g. the complex conjugate tranposed by the permutation set be `axes`. By default the axes are reversed. Args: tensor: The Tensor to conjugate. axes: The permutation. If None (default) the index...
Return sin of `Tensor`. Args: Tensor: A Tensor. Returns: Tensor
def sin(tensor: Tensor) -> Tensor: """ Return sin of `Tensor`. Args: Tensor: A Tensor. Returns: Tensor """ out_array = tensor.backend.sin(tensor.array) return Tensor(out_array, backend=tensor.backend)
Return cos of `Tensor`. Args: Tensor: A Tensor. Returns: Tensor
def cos(tensor: Tensor) -> Tensor: """ Return cos of `Tensor`. Args: Tensor: A Tensor. Returns: Tensor """ out_array = tensor.backend.cos(tensor.array) return Tensor(out_array, backend=tensor.backend)
Return elementwise exp of `Tensor`. Args: Tensor: A Tensor. Returns: Tensor
def exp(tensor: Tensor) -> Tensor: """ Return elementwise exp of `Tensor`. Args: Tensor: A Tensor. Returns: Tensor """ out_array = tensor.backend.exp(tensor.array) return Tensor(out_array, backend=tensor.backend)
Return elementwise natural logarithm of `Tensor`. Args: Tensor: A Tensor. Returns: Tensor
def log(tensor: Tensor) -> Tensor: """ Return elementwise natural logarithm of `Tensor`. Args: Tensor: A Tensor. Returns: Tensor """ out_array = tensor.backend.log(tensor.array) return Tensor(out_array, backend=tensor.backend)
Extracts the offset'th diagonal from the matrix slice of tensor indexed by (axis1, axis2). Args: tensor: A Tensor. offset: Offset of the diagonal from the main diagonal. axis1, axis2: Indices of the matrix slice to extract from. Returns: out : A 1D Tensor storing the elements of the selected diagonal.
def diagonal(tensor: Tensor, offset: int = 0, axis1: int = -2, axis2: int = -1) -> Tensor: """ Extracts the offset'th diagonal from the matrix slice of tensor indexed by (axis1, axis2). Args: tensor: A Tensor. offset: Offset of the diagonal from the main diagonal. axis1, axis2: Indices...
Flattens tensor and places its elements at the k'th diagonal of a new (tensor.size + k, tensor.size + k) `Tensor` of zeros. Args: tensor: A Tensor. k : The elements of tensor will be stored at this diagonal. Returns: out : A (tensor.size + k, tensor.size + k) `Tensor` with the elements of tensor ...
def diagflat(tensor: Tensor, k: int = 0) -> Tensor: """ Flattens tensor and places its elements at the k'th diagonal of a new (tensor.size + k, tensor.size + k) `Tensor` of zeros. Args: tensor: A Tensor. k : The elements of tensor will be stored at this diagonal. Returns: out : A (tensor.si...
Calculate the sum along diagonal entries of the given Tensor. The entries of the offset`th diagonal of the matrix slice of tensor indexed by (axis1, axis2) are summed. Args: tensor: A Tensor. offset: Offset of the diagonal from the main diagonal. axis1, axis2: Indices of the matrix slice to extract from. ...
def trace(tensor: Tensor, offset: int = 0, axis1: int = -2, axis2: int = -1) -> Tensor: """Calculate the sum along diagonal entries of the given Tensor. The entries of the offset`th diagonal of the matrix slice of tensor indexed by (axis1, axis2) are summed. Args: tensor: A Tensor. offs...
Returns the sign of the elements of Tensor.
def sign(tensor: Tensor) -> Tensor: """ Returns the sign of the elements of Tensor. """ backend = tensor.backend result = backend.sign(tensor.array) return Tensor(result, backend=backend)
Returns the absolute value of the elements of Tensor.
def abs(tensor: Tensor) -> Tensor: """ Returns the absolute value of the elements of Tensor. """ backend = tensor.backend result = backend.abs(tensor.array) return Tensor(result, backend=backend)
Reshapes tensor into a matrix about the pivot_axis. Equivalent to tensor.reshape(prod(tensor.shape[:pivot_axis]), prod(tensor.shape[pivot_axis:])). Args: tensor: The input tensor. pivot_axis: Axis to pivot around.
def pivot(tensor: Tensor, pivot_axis: int = -1) -> Tensor: """ Reshapes tensor into a matrix about the pivot_axis. Equivalent to tensor.reshape(prod(tensor.shape[:pivot_axis]), prod(tensor.shape[pivot_axis:])). Args: tensor: The input tensor. pivot_axis: Axis to pivot around...
Compute the (tensor) kronecker product between `tensorA` and `tensorB`. `tensorA` and `tensorB` can be tensors of any even order (i.e. `tensorA.ndim % 2 == 0`, `tensorB.ndim % 2 == 0`). The returned tensor has index ordering such that when reshaped into a matrix with `pivot =t ensorA.ndim//2 + tensorB.ndim//2`, the ...
def kron(tensorA: Tensor, tensorB: Tensor) -> Tensor: """ Compute the (tensor) kronecker product between `tensorA` and `tensorB`. `tensorA` and `tensorB` can be tensors of any even order (i.e. `tensorA.ndim % 2 == 0`, `tensorB.ndim % 2 == 0`). The returned tensor has index ordering such that when reshaped in...
Tests tensornetwork.eye against np.eye.
def test_eye(backend): """ Tests tensornetwork.eye against np.eye. """ N = 4 M = 6 backend_obj = backends.backend_factory.get_backend(backend) for dtype in dtypes[backend]["all"]: tnI = tensornetwork.eye(N, dtype=dtype, M=M, backend=backend) npI = backend_obj.eye(N, dtype=dtype, M=M) np.testin...
Tests tensornetwork.zeros against np.zeros.
def test_zeros(backend): """ Tests tensornetwork.zeros against np.zeros. """ shape = (5, 10, 3) backend_obj = backends.backend_factory.get_backend(backend) for dtype in dtypes[backend]["all"]: tnI = tensornetwork.zeros(shape, dtype=dtype, backend=backend) npI = backend_obj.zeros(shape, dtype=dtype) ...
Tests tensornetwork.ones against np.ones.
def test_ones(backend): """ Tests tensornetwork.ones against np.ones. """ shape = (5, 10, 3) backend_obj = backends.backend_factory.get_backend(backend) for dtype in dtypes[backend]["all"]: tnI = tensornetwork.ones(shape, dtype=dtype, backend=backend) npI = backend_obj.ones(shape, dtype=dtype) n...
Tests tensornetwork.randn against the backend code.
def test_randn(backend): """ Tests tensornetwork.randn against the backend code. """ shape = (5, 10, 3, 2) seed = int(time.time()) np.random.seed(seed=seed) backend_obj = backends.backend_factory.get_backend(backend) for dtype in dtypes[backend]["rand"]: tnI = tensornetwork.randn( shape, ...
Tests tensornetwork.ones against np.ones.
def test_random_uniform(backend): """ Tests tensornetwork.ones against np.ones. """ shape = (5, 10, 3, 2) seed = int(time.time()) np.random.seed(seed=seed) boundaries = (-0.3, 10.5) backend_obj = backends.backend_factory.get_backend(backend) for dtype in dtypes[backend]["rand"]: tnI = tensornetwor...
Tests tensornetwork.ones_like against np.zeros_like
def test_ones_like(backend, shape, n): """Tests tensornetwork.ones_like against np.zeros_like""" backend_obj = backends.backend_factory.get_backend(backend) @pytest.mark.parametrize("dtype,expected", (dtypes[backend]["all"])) def inner_ones_test(dtype): objTensor = tensornetwork.ones(shape, dty...
Tests tensornetwork.zeros_like against np.zeros_like
def test_zeros_like(backend, shape, n): """Tests tensornetwork.zeros_like against np.zeros_like""" backend_obj = backends.backend_factory.get_backend(backend) @pytest.mark.parametrize("dtype,expected", (dtypes[backend]["all"])) def inner_zero_test(dtype): objTensor = tensornetwork.zeros(shape, ...
Tests node_linalg.eye against np.eye.
def test_eye(backend): """ Tests node_linalg.eye against np.eye. """ N = 4 M = 6 name = "Jeffrey" axis_names = ["Sam", "Blinkey"] backend_obj = backends.backend_factory.get_backend(backend) for dtype in dtypes[backend]["all"]: tnI = node_linalg.eye( N, dtype=dtype, M=M, name=name, axis_nam...
Tests node_linalg.zeros against np.zeros.
def test_zeros(backend): """ Tests node_linalg.zeros against np.zeros. """ shape = (5, 10, 3) name = "Jeffrey" axis_names = ["Sam", "Blinkey", "Renaldo"] backend_obj = backends.backend_factory.get_backend(backend) for dtype in dtypes[backend]["all"]: tnI = node_linalg.zeros( shape, dtype=dty...
Tests node_linalg.ones against np.ones.
def test_ones(backend): """ Tests node_linalg.ones against np.ones. """ shape = (5, 10, 3) name = "Jeffrey" axis_names = ["Sam", "Blinkey", "Renaldo"] backend_obj = backends.backend_factory.get_backend(backend) for dtype in dtypes[backend]["all"]: tnI = node_linalg.ones( shape, dtype=dtype, ...
Tests node_linalg.randn against the backend code.
def test_randn(backend): """ Tests node_linalg.randn against the backend code. """ shape = (5, 10, 3, 2) seed = int(time.time()) np.random.seed(seed=seed) name = "Jeffrey" axis_names = ["Sam", "Blinkey", "Renaldo", "Jarvis"] backend_obj = backends.backend_factory.get_backend(backend) for dtype in dt...
Tests node_linalg.ones against np.ones.
def test_random_uniform(backend): """ Tests node_linalg.ones against np.ones. """ shape = (5, 10, 3, 2) seed = int(time.time()) np.random.seed(seed=seed) boundaries = (-0.3, 10.5) name = "Jeffrey" axis_names = ["Sam", "Blinkey", "Renaldo", "Jarvis"] backend_obj = backends.backend_factory.get_backend...
Compares linalg.krylov.eigsh_lanczos with backend.eigsh_lanczos.
def test_eigsh_lanczos(sparse_backend, dtype): """ Compares linalg.krylov.eigsh_lanczos with backend.eigsh_lanczos. """ n = 2 shape = (n, n) dtype = testing_utils.np_dtype_to_backend(sparse_backend, dtype) A = tensornetwork.linalg.initialization.ones(shape, b...
Compares linalg.krylov.eigsh_lanczos with backend.eigsh_lanczos.
def test_eigsh_lanczos_with_args(sparse_backend, dtype): """ Compares linalg.krylov.eigsh_lanczos with backend.eigsh_lanczos. """ n = 2 shape = (n, n) dtype = testing_utils.np_dtype_to_backend(sparse_backend, dtype) A = tensornetwork.linalg.initialization.ones(shape, ...
Tests that tensordot raises ValueError when fed Tensors with different backends. Other failure modes are tested at the backend level.
def test_tensordot_invalid_backend_raises_value_error(backend, dtype): """ Tests that tensordot raises ValueError when fed Tensors with different backends. Other failure modes are tested at the backend level. """ backend_names = set(["jax", "numpy", "tensorflow", "pytorch"]) this_name = set([backend]) oth...