# ctf package¶

## ctf.core module¶

ctf.core.MPI_Stop()

Kill all working nodes.

ctf.core.TTTP(A, mat_list) Compute updates to entries in tensor A based on matrices in mat_list (tensor times tensor products)

Compute updates to entries in tensor A based on matrices in mat_list (tensor times tensor products)

Parameters
A: tensor_like

Input tensor of arbitrary ndim

mat_list: list of size A.ndim

Contains either None or matrix of dimensions m-by-k or vector, where m matches the corresponding mode length of A and k is the same for all given matrices (or all are vectors)

Returns
B: tensor

A tensor of the same ndim as A, updating by taking products of entries of A with multilinear dot products of columns of given matrices. For ndim=3 and mat_list=[X,Y,Z], this operation is equivalent to einsum(“ijk,ia,ja,ka->ijk”,A,X,Y,Z)

ctf.core.abs()

Calculate the elementwise absolute value of a tensor.

Parameters
A: tensor_like

Input tensor.

Returns
output: tensor

A tensor containing the absolute value of each element in input tensor. For complex number $$a + bi$$, the absolute value is calculated as $$\sqrt{a^2 + b^2}$$

Examples

>>> import ctf
>>> a = ctf.astensor([-2, 3])
array([-2,  3])
>>> abs(a)
array([2, 3])

ctf.core.all()

Return whether given an axis elements are True.

Parameters
A: tensor_like

Input tensor.

axis: None or int, optional

Currently not supported in CTF Python.

out: tensor, optional

Currently not supported in CTF Python.

keepdimsbool, optional

Currently not supported in CTF Python.

Returns
output: tensor_like

Output tensor or scalar.

Examples

>>> import ctf
>>> a = ctf.astensor([[0, 1], [1, 1]])
>>> ctf.all(a)
False

ctf.core.any()

Return whether given an axis any elements are True.

Parameters
A: tensor_like

Input tensor.

axis: None or int, optional

Axis along which logical OR is applied.

out: tensor_like, optional

Objects which will place the result.

keepdims: bool, optional

If keepdims is set to True, the reduced axis will remain 1 in shape.

Returns
output: tensor_like

Output tensor or scalar.

Examples

>>> import ctf
>>> a = ctf.astensor([[0, 0], [1, 1]])
>>> ctf.any(a)
True
>>> ctf.any(a, axis=0)
array([ True,  True])
>>> ctf.any(a, axis=1)
array([False,  True])

ctf.core.arange()

Generate CTF vector with values from start to stop (inclusive) in increments of step

Parameters
start: scalar

first element value

stop: scalar

bound on last element value

step: scalar

increment between values (default 1)

dtype: type

datatype (default None, uses type of start)

Returns
——-
output: tensor (CTF vector)

A vector of length ceil((stop-start)/step) containing values start, start+step, start+2*step, etc.

References

numpy.arange

ctf.core.array()

Create a tensor.

Parameters
A: tensor_like

Input tensor like object.

dtype: data-type, optional

The desired data-type for the tensor. If the dtype is not specified, the dtype will be determined as np.array().

copy: bool, optional

If copy is true, the object is copied.

order: {‘K’, ‘A’, ‘C’, ‘F’}, optional

Specify the memory layout for the tensor.

subok: bool, optional

Currently subok is not supported in ctf.array().

ndmin: int, optional

Currently ndmin is not supported in ctf.array().

Returns
output: tensor

A tensor object with specified requirements.

ctf

ctf.astensor()

Notes

The input of ctf.array() should be tensor or numpy.ndarray

Examples

>>> import ctf
>>> import numpy as np
>>> a = np.array([1, 2, 3.])
array([1., 2., 3.])
>>> b = ctf.array(a)
array([1., 2., 3.])

ctf.core.astensor()

Convert the input data to tensor.

Parameters
A: tensor_like

Input data.

dtype: data-type, optional

Numpy data-type, if it is not specified, the function will return the tensor with same type as np.asarray returned ndarray.

order: {‘C’, ‘F’}, optional

C or Fortran memory order, default is ‘F’.

Returns
output: tensor

A tensor representation of A.

numpy

numpy.asarray()

Examples

>>> import ctf
>>> a = ctf.astensor([1,2,3])
>>> a
array([1, 2, 3])

ctf.core.ceil(x, out=None) Elementwise ceiling to integer (output as floating point type)

Elementwise ceiling to integer (output as floating point type)

Parameters
x: tensor_like

Input tensor.

Returns
out: tensor

A tensor of same structure and dtype as x with values ceil(f)

ctf.core.cholesky()

Compute Cholesky factorization of tensor A.

Parameters
A: tensor_like

Input matrix

Returns
L: tensor

A CTF tensor with 2 dimensions corresponding to lower triangular Cholesky factor of A

class ctf.core.comm

Bases: object

Methods

 np rank
np()
rank()
ctf.core.conj()

Return the conjugate tensor A element-wisely.

Parameters
A: tensor_like

Input tensor.

Returns
output: tensor

The element-wise complex conjugate of input tensor A. If tensor A is not complex, just return a copy of A.

Examples

>>> import ctf
>>> a = ctf.astensor([2+3j, 3-2j])
array([2.+3.j, 3.-2.j])
>>> ctf.conj(a)
array([2.-3.j, 3.+2.j])

class ctf.core.contract_term

Bases: ctf.core.term

Attributes
dtype

Methods

 conv_type scale
conv_type()
ctf.core.copy()

Return a copy of tensor A.

Parameters
A: tensor

Input tensor.

Returns
output: tensor

A tensor representation of A.

Examples

>>> a = ctf.astensor([1,2,3])
>>> a
array([1, 2, 3])
>>> b = ctf.copy(a)
>>> b
array([1, 2, 3])
>>> id(a) == id(b)
False

ctf.core.diag()

Return the diagonal tensor of A.

Parameters
A: tensor_like

Input tensor with 1 or 2 dimensions. If A is 1-D tensor, return a 2-D tensor with A on diagonal.

k: int, optional

k=0 is the diagonal. k<0, diagnals below the main diagonal. k>0, diagonals above the main diagonal.

sp: bool, optional

If sp is true, the returned tensor is sparse.

Returns
output: tensor

Diagonal tensor of A.

ctf

ctf.diagonal() ctf.triu() ctf.tril() ctf.trace() ctf.spdiag()

Notes

When the input tensor is sparse, returned tensor will also be sparse.

Examples

>>> import ctf
>>> a = ctf.ones([3,])
>>> ctf.diag(a, k=1)
array([[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])
>>> b = ctf.zeros([4,4])
>>> ctf.diag(b)
array([0., 0., 0., 0.])

ctf.core.diagonal()

Return the diagonal of tensor A if A is 2D. If A is a higher order square tensor (same shape for every dimension), return diagonal of tensor determined by axis1=0, axis2=1.

Parameters
A: tensor_like

Input tensor.

offset: int, optional

Default is 0 which indicates the main diagonal.

axis1: int, optional

Default is 0 which indicates the first axis of 2-D tensor where diagonal is taken.

axis2: int, optional

Default is 1 which indicates the second axis of 2-D tensor where diagonal is taken.

Returns
output: tensor

Diagonal of input tensor.

Notes

ctf.diagonal only supports diagonal of square tensor with order more than 2.

Examples

>>> import ctf
>>> a = ctf.astensor([[1,2,3], [4,5,6], [7,8,9]])
>>> ctf.diagonal(a)
array([1, 5, 9])

ctf.core.dot()

Return the dot product of two tensors A and B.

Parameters
A: tensor_like

First input tensor.

B: tensor_like

Second input tensor.

out: tensor

Currently not supported in CTF Python.

Returns
output: tensor

Dot product of two tensors.

numpy

numpy.dot()

Examples

>>> import ctf
>>> a = ctf.astensor([[1,2,3], [4,5,6], [7,8,9]])
>>> b = ctf.astensor([1,1,1])
>>> ctf.dot(a, b)
array([ 6, 15, 24])

ctf.core.eigh()

Compute eigenvalues of eigenvectors of A, assuming that it is symmetric or Hermitian

Parameters
A: tensor_like

Input matrix

Returns
D: tensor

CTF vector containing eigenvalues of A

X: tensor

CTF matrix containing all eigenvectors of A

ctf.core.einsum()

Einstein summation on operands.

Parameters
subscripts: str

Subscripts for summation.

operands: list of tensor

List of tensors.

out: tensor or None

If the out is not None, calculated result will stored into out tensor.

dtype: data-type, optional

Numpy data-type of returned tensor, dtype of returned tensor will be specified by operand tensors.

order: {‘C’, ‘F’, ‘A’, ‘K’}, optional

Currently not supported by CTF Python.

casting: {‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional

Currently not supported by CTF Python.

out_scale: scalar, optional

Scales output prior to accumulation of contraction, by default is zero (as in numpy)

Returns
output: tensor

numpy

numpy.einsum()

Examples

>>> import ctf
>>> a = ctf.astensor([[1,2,3], [4,5,6], [7,8,9]])
>>> ctf.einsum("ii->i", a)
array([1, 5, 9])

ctf.core.empty()

Return the tensor with specified shape and dtype without initialization. Currently not supported by CTF Python, this function same with the ctf.zeros().

Parameters
shape: int or tuple of int

Shape of the empty tensor.

dtype: data-type, optional

Output data-type for the empty tensor.

order: {‘C’, ‘F’}, optional, default: ‘F’

Currently not supported by CTF Python.

sp: {True, False}, optional, default: ‘False’

Whether to represent tensor in a sparse format.

Returns
output: tensor_like

Output tensor.

Examples

>>> import ctf
>>> import numpy as np
>>> a = ctf.empty([3,4], dtype=np.int64)
>>> a
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])

ctf.core.empty_like()

Return uninitialized tensor of with same shape and dtype of tensor A. Currently in CTF Python is same with ctf.zero_like.

Parameters
A: tensor_like

Input tensor where the output tensor shape and dtype defined as.

dtype: data-type, optional

Output data-type for the empty tensor.

Returns
output: tensor_like

Output tensor.

ctf

ctf.zeros_like()

Examples

>>> import ctf
>>> a = ctf.zeros([3,4], dtype=np.int64)
>>> b = ctf.empty_like(a)
>>> b
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])

ctf.core.exp()

Exponential of all elements in input tensor A.

Parameters
A: tensor_like

Input tensor or tensor like array.

out: tensor, optional

Crrently not supported by CTF Python.

where: array_like, optional

Crrently not supported by CTF Python.

casting: same_kind or unsafe

Default same_kind.

order: optional

Crrently not supported by CTF Python.

dtype: data-type, optional

Output data-type for the exp result.

subok: bool

Crrently not supported by CTF Python.

Returns
output: tensor_like

Output tensor for the exponential.

numpy

numpy.exp()

Examples

>>> import ctf
>>> a = ctf.astensor([1,2,3])
>>> ctf.exp(a)
array([ 2.71828183,  7.3890561 , 20.08553692])

ctf.core.eye()

Return a 2D tensor with ones on the diagonal and zeros elsewhere.

Parameters
n: int

Number of rows.

m: int, optional

Number of columns, default set to n.

k: int, optional

Diagonal index, specify ones on main diagonal, upper diagonal or lower diagonal.

dtype: data-type, optional

Numpy data-type of returned tensor, default np.float64.

sp: bool, optional

If true the returned tensor will be sparse, default sp=False.

Returns
output: tensor

Examples

>>> import ctf
>>> e = ctf.eye(3,m=4,k=-1)
>>> e
array([[0., 0., 0., 0.],
[1., 0., 0., 0.],
[0., 1., 0., 0.]])

ctf.core.floor()

Elementwise round to integer by dropping decimal fraction (output as floating point type). Uses c-style round-to-greatest rule to break-tiies as opposed to numpy’s round to nearest even

Parameters
x: tensor_like

Input tensor.

Returns
out: tensor

A tensor of same structure and dtype as x with values rounded C-style to int

ctf.core.from_nparray()

Convert the numpy array to tensor.

Parameters
A: ndarray

Input numpy array.

Returns
output: tensor

Tensor representation of input numpy array.

ctf

ctf.astensor()

Examples

>>> import ctf
>>> import numpy as np
>>> a = np.array([1,2,3])
>>> b = ctf.from_nparray(a)
>>> b
array([1, 2, 3])
>>> type(b)
<class 'ctf.core.tensor'>

ctf.core.hstack()

Stack the tensor in column-wise.

Parameters
in_tup: tuple of tensors

Input tensor.

Returns
output: tensor_like

Output horizontally stacked tensor.

Examples

>>> import ctf
>>> a = ctf.astensor([1,2,3])
>>> b = ctf.astensor([4,5,6])
>>> ctf.hstack((a, b))
array([1, 2, 3, 4, 5, 6])

ctf.core.identity()

Return a squared 2-D tensor where the main diagonal contains ones and elsewhere zeros.

Parameters
n: int

Number of rows.

dtype: data-type, optional

Numpy data-type of returned tensor, default np.float64.

Returns
output: tensor

ctf

ctf.eye()

Examples

>>> import ctf
>>> a = ctf.identity(3)
>>> a
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])

ctf.core.imag()

Return the image part of the tensor elementwisely.

Parameters
A: tensor_like

Input tensor.

Returns
output: tensor

A tensor with real part of the input tensor.

numpy

numpy.imag()

Notes

The input should be a CTF tensor.

Examples

>>> import ctf
>>> a = ctf.astensor([1+2j, 3+4j, 5+6j, 7+8j])
>>> a
array([1.+2.j, 3.+4.j, 5.+6.j, 7.+8.j])
>>> ctf.imag(a)
array([2., 4., 6., 8.])

class ctf.core.itensor

Bases: ctf.core.term

Attributes
dtype
string
tsr

Methods

 Compute Single Value Decomposition of a given transposition/matricization of tensor A.
 conv_type scale scl
conv_type()
scl()
string
svd()

Compute Single Value Decomposition of a given transposition/matricization of tensor A.

Parameters
U_string: char string

Indices indexing left singular vectors, should be subset of the string of this itensor plus an auxiliary index

VT_string: char string

Indices indexing right singular vectors, should be subset of the string of this itensor, plus same auxiliary index as in U

threshold: real double precision or None, optional

threshold for truncating singular values of the SVD, determines rank, if threshold ia also used, rank will be set to minimum of rank and number of singular values above threshold

niter: int or None, optional, default 1

number of orthogonal iterations to perform (higher gives better accuracy)

oversamp: int or None, optional, default 5

oversampling parameter

Returns
U: tensor

A unitary CTF tensor with dimensions len(U_string).

S: tensor

A 1-D tensor with singular values.

VT: tensor

A unitary CTF tensor with dimensions len(VT_string)+1.

tsr
ctf.core.kron()

Kronecker product of A and B, generalized to arbitrary order by taking Kronecker product along all modes Tensor of lesser order is padded with lengths of dimension 1.

Parameters
A: tensor_like

Input tensor or tensor like array.

B: tensor_like

Input tensor or tensor like array.

Returns
output: tensor_like

Output tensor with size being the product of sizes of A and B

numpy

numpy.kron()

ctf.core.norm()

Return vector or matrix norm of tensor A. If A a matrix, compute induced (1/2/infinity)-matrix norms or Frobenius norm, if A has one or more than three dimensions, treat as vector

Parameters
A: tensor_like

Input tensor with 1, 2, or more dimensions.

ord: {int 1, 2, inf}, optional

Order of the norm.

Returns
output: tensor

Norm of tensor A.

Examples

>>> import ctf
>>> import ctf.linalg as la
>>> a = ctf.astensor([3,4.])
>>> la.vecnorm(a)
5.0

ctf.core.ones()

Return a tensor filled with ones with specified shape and dtype.

Parameters
shape: int or sequence of ints

Shape of the returned tensor.

dtype: numpy data-type, optional

The data-type for the tensor.

order: {‘C’, ‘F’}, optional

Not support by current CTF Python.

Returns
output: tensor

Tensor with specified shape and dtype.

Examples

>>> import ctf
>>> a = ctf.ones([2, 2])
>>> a
array([[1., 1.],
[1., 1.]])

ctf.core.power()

Elementwisely raise tensor A to powers from the tensor B.

Parameters
A: tensor_like

Bases tensor.

B: tensor_like

Exponents tensor

Returns
output: tensor

The output tensor containing elementwise bases A raise to exponents of B.

Examples

>>> import ctf
>>> a = ctf.astensor([2., 3])
array([2., 3.])
>>> b = ctf.astensor([2., 3])
array([2., 3.])
>>> ctf.power(a, b)
array([ 4., 27.])

ctf.core.qr()

Compute QR factorization of matrix A.

Parameters
A: tensor_like

Input matrix

Returns
Q: tensor

A CTF tensor with 2 dimensions and orthonormal columns.

R: tensor

An upper triangular 2-D CTF tensor.

ctf.core.ravel()

Return flattened CTF tensor of input tensor A.

Parameters
A: tensor_like

Input tensor.

order: {‘C’,’F’, ‘A’, ‘K’}, optional

Currently not supported by current CTF Python.

Returns
output: tensor_like

Flattened tensor.

Examples

>>> import ctf
>>> a = ctf.astensor([1,2,3,4,5,6,7,8]).reshape(2,2,2)
>>> a
array([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])
>>> ctf.ravel(a)
array([1, 2, 3, 4, 5, 6, 7, 8])

ctf.core.real()

Return the real part of the tensor elementwisely.

Parameters
A: tensor_like

Input tensor.

Returns
output: tensor

A tensor with real part of the input tensor.

numpy

numpy.real()

Notes

The input should be a CTF tensor.

Examples

>>> import ctf
>>> a = ctf.astensor([1+2j, 3+4j, 5+6j, 7+8j])
>>> a
array([1.+2.j, 3.+4.j, 5.+6.j, 7.+8.j])
>>> ctf.real(a)
array([1., 3., 5., 7.])

ctf.core.reshape()

Reshape the input tensor A to new shape.

Parameters
A: tensor_like

Input tensor.

newshape: tuple of ints or int

New shape where the input tensor is shaped to.

order: {‘C’, ‘F’}, optional

Currently not supported by CTF Python.

Returns
output: tensor

Tensor with new shape of A.

ctf

ctf.tensor.reshape()

Examples

>>> import ctf
a = ctf.astensor([1,2,3,4])
>>> ctf.reshape(a, (2, 2))
array([[1, 2],
[3, 4]])

ctf.core.rint(x, out=None) Elementwise round to nearest integer (output as floating point type)

Elementwise round to nearest integer (output as floating point type)

Parameters
x: tensor_like

Input tensor.

Returns
out: tensor

A tensor of same structure and dtype as x with values rounded to nearest integer

ctf.core.solve_tri(L, B, lower, from_left, transp_L)
Parameters
L: tensor_like

Triangular matrix encoding equations

B: tensor_like

Right or left hand sides

lower: bool

if true L is lower triangular, if false upper

from_left: bool

if true solve LX = B, if false, solve XL=B

transp_L: bool

if true solve L^TX = B or XL^T=B

Returns
X: tensor

CTF matrix containing solutions to triangular equations, same shape as B

ctf.core.spdiag()

Return the sparse diagonal tensor of A.

Parameters
A: tensor_like

Input tensor with 1 or 2 dimensions. If A is 1-D tensor, return a 2-D tensor with A on diagonal.

k: int, optional

k=0 is the diagonal. k<0, diagnals below the main diagonal. k>0, diagonals above the main diagonal.

Returns
output: tensor

Sparse diagonal tensor of A.

Notes

Same with ctf.diag(A,k,sp=True)

Examples

>>> import ctf
>>> a = ctf.astensor([[1,2,3], [4,5,6], [7,8,9]])
>>> ctf.spdiag(a)
array([1, 5, 9])

ctf.core.speye()

Return a sparse 2D tensor with ones on the diagonal and zeros elsewhere.

Parameters
n: int

Number of rows.

m: int, optional

Number of columns, default set to n.

k: int, optional

Diagonal index, specify ones on main diagonal, upper diagonal or lower diagonal.

dtype: data-type, optional

Numpy data-type of returned tensor, default np.float64.

Returns
output: tensor

ctf

ctf.eye()

Examples

>>> import ctf
>>> e = ctf.speye(3,m=4,k=-1)
>>> e
array([[0., 0., 0., 0.],
[1., 0., 0., 0.],
[0., 1., 0., 0.]])

ctf.core.sum()

Sum of elements in tensor or along specified axis.

Parameters
A: tensor_like

Input tensor.

axis: None, int or tuple of ints

Axis or axes where the sum of elements is performed.

dtype: data-type, optional

Data-type for the output tensor.

out: tensor, optional

Alternative output tensor.

keepdims: None, bool, optional

If set to true, axes summed over will remain size one.

Returns
output: tensor_like

Output tensor.

numpy

numpy.sum()

Examples

>>> import ctf
>>> a = ctf.ones([3,4], dtype=np.int64)
>>> ctf.sum(a)
12

class ctf.core.sum_term

Bases: ctf.core.term

Attributes
dtype

Methods

 conv_type scale
conv_type()
ctf.core.svd()

Compute Single Value Decomposition of matrix A.

Parameters
A: tensor_like

Input tensor 2 dimensions.

rank: int or None, optional

Target rank for SVD, default rank=None, implying full rank.

threshold: real double precision or None, optional

Threshold for truncation of singular values. Either rank or threshold must be set to None.

Returns
U: tensor

A unitary CTF tensor with 2 dimensions.

S: tensor

A 1-D tensor with singular values.

VT: tensor

A unitary CTF tensor with 2 dimensions.

ctf.core.svd_rand()

Uses randomized method (orthogonal iteration) to calculate a low-rank singular value decomposition, M = U x S x VT. Is faster, especially for low-rank, but less robust than typical svd.

Parameters
A: tensor_like

Input matrix

rank: int

Target SVD rank

niter: int or None, optional, default 1

number of orthogonal iterations to perform (higher gives better accuracy)

oversamp: int or None, optional, default 5

oversampling parameter

VT_guess: initial guess for first rank+oversamp singular vectors (matrix with orthogonal columns is also good), on output is final iterate (with oversamp more columns than VT)
Returns
U: tensor

A unitary CTF tensor with 2 dimensions.

S: tensor

A 1-D tensor with singular values.

VT: tensor

A unitary CTF tensor with 2 dimensions.

ctf.core.take()

Take elements from a tensor along axis.

Parameters
A: tensor_like

Input tensor.

indices: tensor_like

Indices of the values wnat to be extracted.

axis: int, optional

Select values from which axis, default None.

out: tensor

Currently not supported in CTF Python take().

mode: {‘raise’, ‘wrap’, ‘clip’}, optional

Currently not supported in CTF Python take().

Returns
output: tensor or scalar

Elements extracted from the input tensor.

numpy

numpy.take()

Examples

>>> import ctf
>>> a = ctf.astensor([[1,2,3], [4,5,6], [7,8,9]])
>>> ctf.take(a, [0, 1, 2])
array([1, 2, 3])

class ctf.core.tensor

Bases: object

The class for CTF Python tensor.

Attributes
nbytes: int

The number of bytes for the tensor.

size: int

Total number of elements in the tensor.

ndim: int

Number of dimensions.

sp: int

0 indicates the tensor is not sparse tensor, 1 means the tensor is CTF sparse tensor.

strides: tuple

Tuple of bytes for each dimension to traverse the tensor.

shape: tuple

Tuple of each dimension.

dtype: data-type

Numpy data-type, indicating the type of tensor.

itemsize: int

One element in bytes.

order: {‘F’,’C’}

Bytes memory order for the tensor.

sym: ndarray

Symmetry description of the tensor, sym[i] describes symmetry relation SY/AS/SH of mode i to mode i+1 NS (0) is nonsymmetric, SY (1) is symmetric, AS (2) is antisymmetric, SH (3) is symmetric with zero diagonal

Methods

 T: Transpose of tensor. all: Whether all elements give an axis for a tensor is true. astype: Copy the tensor to specified type. conj: Return the self conjugate tensor element-wisely. copy: Copy the tensor to a new tensor. diagonal: Return the diagonal of the tensor if it is 2D. If the tensor is a higher order square tensor (same shape for every dimension), return diagonal of tensor determined by axis1=0, axis2=1. dot: Return the dot product with tensor other. fill_random: Fill random elements to the tensor. fill_sp_random: Fill random elements to a sparse tensor. from_nparray: Convert numpy ndarray to CTF tensor. get_dims: Return the dims/shape of tensor. get_type: Return the dtype of tensor. i: Core function on summing the ctensor. imag: Return imaginary part of a tensor or set its imaginary part to new value. norm1: 1-norm of the tensor. norm2: 2-norm of the tensor. norm_infty: Infinity-norm of the tensor. permute: Permute the tensor. prnt: Function to print the non-zero elements and their indices of a tensor. ravel: Return the flattened tensor. read: Helper function on reading a tensor. read_all: Helper function on reading a tensor. read_local: Helper function on reading a tensor. read_local_nnz: Helper function on reading a tensor. real: Return real part of a tensor or set its real part to new value. reshape: Return a new tensor with reshaped shape. sample: Extract a sample of the entries (if sparse of the current nonzeros) by keeping each entry with probability p. Also transforms tensor into sparse format if not already. set_all: Set all elements in a tensor to a value. set_zero: Set all elements in a tensor to 0. sum: Sum of elements in tensor or along specified axis. take: Take elements from a tensor along axis. tensordot: Return the tensor dot product of two tensors along axes. to_nparray: Convert the tensor to numpy array. trace: Return the sum over the diagonal of the tensor. transpose: Return the transposed tensor with specified order of axes. write: Helper function on writing a tensor. write_all: Helper function on writing a tensor.
T()

Permute the dimensions of the input tensor.

Returns
output: tensor

Tensor with permuted axes.

ctf

ctf.transpose

Examples

>>> import ctf
>>> a = ctf.zeros([3,4,5])
>>> a.shape
(3, 4, 5)
>>> a.T().shape
(5, 4, 3)

all()

Return whether given an axis elements are True.

Parameters
axis: None or int, optional

Currently not supported in CTF Python.

out: tensor, optional

Currently not supported in CTF Python.

keepdimsbool, optional

Currently not supported in CTF Python.

Returns
output: tensor_like

Output tensor or scalar.

ctf

ctf.all

Examples

>>> import ctf
>>> a = ctf.astensor([[0, 1], [1, 1]])
>>> a.all()
False

astype()

Copy the tensor to specified type.

Parameters
dtype: data-type

Numpy data-type.

order: {‘F’, ‘C’}

Bytes order for the tensor.

casting: {‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional

Returns
output: tensor

Copied tensor with specified data-type.

numpy

numpy.ndarray.astype

Examples

>>> import ctf
>>> a = ctf.astensor([[1,2,3], [4,5,6], [7,8,9]])
>>> a.dtype
<class 'numpy.int64'>
>>> a.astype(np.float64).dtype
<class 'numpy.float64'>

conj()

Return the self conjugate tensor element-wisely.

Returns
output: tensor

The element-wise complex conjugate of the tensor. If the tensor is not complex, just return a copy.

Examples

>>> import ctf
>>> a = ctf.astensor([2+3j, 3-2j])
>>> a
array([2.+3.j, 3.-2.j])
>>> a.conj()
array([2.-3.j, 3.+2.j])

copy()

Copy the tensor to a new tensor.

Returns
output: tensor_like

Output copied tensor.

Examples

>>> import ctf
>>> a = ctf.astensor([[1,2,3],[4,5,6]])
>>> b = a.copy()
>>> id(a) == id(b)
False
>>> a == b
array([[ True,  True,  True],
[ True,  True,  True]])

diagonal()

Return the diagonal of the tensor if it is 2D. If the tensor is a higher order square tensor (same shape for every dimension), return diagonal of tensor determined by axis1=0, axis2=1.

Parameters
offset: int, optional

Default is 0 which indicates the main diagonal.

axis1: int, optional

Default is 0 which indicates the first axis of 2-D tensor where diagonal is taken.

axis2: int, optional

Default is 1 which indicates the second axis of 2-D tensor where diagonal is taken.

Returns
output: tensor

Diagonal of input tensor.

Notes

ctf.diagonal only supports diagonal of square tensor with order more than 2.

Examples

>>> import ctf
>>> a = ctf.astensor([[1,2,3], [4,5,6], [7,8,9]])
>>> a.diagonal()
array([1, 5, 9])

dot()

Return the dot product with tensor other.

Parameters
other: tensor_like

The other input tensor.

out: tensor

Currently not supported in CTF Python.

Returns
output: tensor

Dot product of two tensors.

numpy

numpy.dot()

ctf

ctf.dot()

Examples

>>> import ctf
>>> a = ctf.astensor([[1,2,3], [4,5,6], [7,8,9]])
>>> b = ctf.astensor([1,1,1])
>>> a.dot(b)
array([ 6, 15, 24])

dtype

Attribute dtype. Numpy data-type, indicating the type of tensor.

fill_random()

Fill random elements to the tensor.

Parameters
mn: int or float

The range of random number from, default 0.

mx: int or float

The range of random number to, default 1.

ctf

ctf.tensor.fill_sp_random()

Examples

>>> import ctf
>>> a = ctf.zeros([2, 2])
>>> a
array([[0., 0.],
[0., 0.]])
>>> a.fill_random(3,5)
>>> a
array([[3.31908598, 4.34013067],
[4.5355426 , 4.6763659 ]])

fill_sp_random()

Fill random elements to a sparse tensor.

Parameters
mn: int or float

The range of random number from, default 0.

mx: int or float

The range of random number to, default 1.

frac_sp: float

The percent of non-zero elements.

ctf

ctf.tensor.fill_random()

Examples

>>> import ctf
>>> a = ctf.tensor([3, 3], sp=1)
>>> a.fill_sp_random(frac_sp=0.2)
>>> a
array([[0.96985989, 0.        , 0.        ],
[0.        , 0.        , 0.10310342],
[0.        , 0.        , 0.        ]])

from_nparray()

Convert numpy ndarray to CTF tensor.

Returns
output: tensor

CTF tensor of the numpy ndarray.

Examples

>>> import ctf
>>> import numpy as np
>>> a = np.asarray([1.,2.,3.])
>>> b = ctf.zeros([3, ])
>>> b.from_nparray(a)
>>> b
array([1., 2., 3.])

get_dims()

Return the dims/shape of tensor.

Returns
output: tuple

Dims or shape of the tensor.

get_type()

Return the dtype of tensor.

Returns
output: data-type

Dtype of the tensor.

i()

Core function on summing the ctensor.

Parameters
string: string

Dimensions for summation.

Returns
output: tensor_like

Output tensor or scalar.

Examples

>>> import ctf
>>> a = ctf.astensor([[1,2,3],[4,5,6]])
>>> a.i("ij") << a.i("ij")
>>> a
array([[ 2,  4,  6],
[ 8, 10, 12]])

imag()

Return imaginary part of a tensor or set its imaginary part to new value.

Returns
value: tensor_like

The value tensor set imaginary to the original tensor, current only support value tensor with dtype np.float64 or np.complex128. Default is none.

ctf

ctf.reshape()

Examples

>>> import ctf
>>> a = ctf.astensor([1+2j, 3+4j])
>>> b = ctf.astensor([5,6], dtype=np.float64)
>>> a.imag(value = b)
>>> a
array([5.+2.j, 6.+4.j])

item()

get value of scalar stored in size 1 tensor

Returns
output: scalar
itemsize

Attribute itemsize. One element in bytes.

nbytes

Attribute nbytes. The number of bytes for the tensor.

ndim

Attribute ndim. Number of dimensions.

nnz_tot

Total number of nonzeros in tensor

norm1()

1-norm of the tensor.

Returns
output: scalar

1-norm of the tensor.

Examples

>>> import ctf
>>> a = ctf.ones([3,4], dtype=np.float64)
>>> a.norm1()
12.0

norm2()

2-norm of the tensor.

Returns
output: scalar np.float64

2-norm of the tensor.

Examples

>>> import ctf
>>> a = ctf.ones([3,4], dtype=np.float64)
>>> a.norm2()
3.4641016151377544

norm_infty()

Infinity norm of the tensor.

Returns
output: scalar

Infinity norm of the tensor.

Examples

>>> import ctf
>>> a = ctf.ones([3,4], dtype=np.float64)
>>> a.norm_infty()
1.0

order

Attribute order. Bytes memory order for the tensor.

permute(self, tensor A, p_A=None, p_B=None, a=None, b=None)
Permute the tensor along each mode, so that

self[p_B[0,i_1],….,p_B[self.ndim-1,i_ndim]] = A[i_1,….,i_ndim]

or

B[i_1,….,i_ndim] = A[p_A[0,i_1],….,p_A[self.ndim-1,i_ndim]]

exactly one of p_A or p_B should be provided.

Parameters
A: CTF tensor

Tensor whose data will be permuted.

p_A: list of arrays

List of length A.ndim, the ith item of which is an array of slength A.shape[i], with values specifying the permutation target of that index or -1 to denote that this index should be projected away.

p_B: list of arrays

List of length self.ndim, the ith item of which is an array of slength Aselfshape[i], with values specifying the permutation target of that index or -1 to denote that this index should not be permuted to.

a: scalar

Scaling for values in a (default 1)

b: scalar

Scaling for values in self (default 0)

prnt()

Function to print the non-zero elements and their indices of a tensor.

Examples

>>> import ctf
>>> a = ctf.astensor([0,1,2,3,0])
>>> a.prnt()
Printing tensor ZYTP01
(1, <1>)
(2, <2>)
(3, <3>)

ravel()

Return the flattened tensor.

Returns
output: tensor_like

Output flattened tensor.

Examples

>>> import ctf
>>> a = ctf.astensor([[1,2,3],[4,5,6]])
>>> a.ravel()
array([1, 2, 3, 4, 5, 6])

read(inds, vals=None, a=None, b=None)

Retrieves and accumulates a set of values to a corresponding set of specified indices (a is scaling for vals and b is scaling for old vlaues in tensor). vals[i] = b*vals[i] + a*T[inds[i]] Each MPI process is expected to read a different subset of values and all MPI processes must participate (even if reading nothing). However, the set of values read may overlap.

Parameters
inds: array (1D or 2D)

If 1D array, each index specifies global index, e.g. access T[i,j,k] via i+n*j+n^2*k, if 2D array, a corresponding row would be [i,j,k]

vals: array

A 1D array specifying values to be accumulated to for each index, if None, this array will be returned

a: scalar

Scaling factor to apply to data in tensor (default is 1)

b: scalar

Scaling factor to apply to vals (default is 0)

read_all()

reads all values in the tensor

Parameters
arr: array (optional, default: None)

preallocated storage for data, of size equal to number of elements in tensor

unpack: bool (default: True)

whether to read symmetrically-equivallent values or only unique values

Returns
——-
output: tensor if arr is None, otherwise nothing
———-
read_all_nnz()

reads all nonzero values in the tensor as key-value pairs where key is the global index

Parameters
unpack: bool (default: True)

whether to read symmetrically-equivallent values or only unique values

Returns
inds: global indices of each nonzero values
vals: the nonzero values
read_from_file()
read_local()

Obtains tensor values stored on this MPI process

Parameters
unpack_sym: if true retrieves symmetrically equivalent entries, if alse only the ones unique up to symmetry
Returns
inds: array of global indices of nonzeros
vals: array of values of nonzeros
——-
read_local_nnz()

Obtains nonzeros of tensor stored on this MPI process

Parameters
unpack_sym: if true retrieves symmetrically equivalent entries, if alse only the ones unique up to symmetry
Returns
inds: array of global indices of nonzeros
vals: array of values of nonzeros
——-
real()

Return real part of a tensor or set its real part to new value.

Returns
value: tensor_like

The value tensor set real to the original tensor, current only support value tensor with dtype np.float64 or np.complex128. Default is none.

ctf

ctf.reshape()

Examples

>>> import ctf
>>> a = ctf.astensor([1+2j, 3+4j])
>>> b = ctf.astensor([5,6], dtype=np.float64)
>>> a.real(value = b)
>>> a
array([5.+2.j, 6.+4.j])

reshape()

Return a new tensor with reshaped shape.

Returns
output: tensor_like

Output reshaped tensor.

ctf

ctf.reshape()

Examples

>>> import ctf
>>> a = ctf.astensor([[1,2,3],[4,5,6]])
>>> a.reshape(6,1)
array([,
,
,
,
,
])

sample()

Extract a sample of the entries (if sparse of the current nonzeros) by keeping each entry with probability p. Also transforms tensor into sparse format if not already.

Parameters
p: float

Probability that keep each entry.

Returns
output: tensor or scalar

Elements extracted from the input tensor.

Examples

>>> import ctf
>>> a = ctf.astensor([[1,2,3], [4,5,6], [7,8,9]])
>>> a.sample(0.1)
>>> a
array([[0, 0, 3],
[0, 0, 6],
[0, 0, 0]])

set_all()

Set all elements in a tensor to a value.

Parameters
value: scalar

Value set to a tensor.

Examples

>>> import ctf
>>> a = ctf.astensor([1,2,3])
>>> a.set_all(3)
>>> a
array([3, 3, 3])

set_zero()
shape

Attribute shape. Tuple of each dimension.

size

Attribute size. Total number of elements in the tensor.

sp

Attribute sp. 0 indicates the tensor is not sparse tensor, 1 means the tensor is CTF sparse tensor.

sparsify()

Make tensor sparse and remove all values with value or absolute value if take_abs=True below threshold.

Returns
output: tensor

Sparsified version of the tensor

strides

Attribute strides. Tuple of bytes for each dimension to traverse the tensor.

sum()

Sum of elements in tensor or along specified axis.

Parameters
axis: None, int or tuple of ints

Axis or axes where the sum of elements is performed.

dtype: data-type, optional

Data-type for the output tensor.

out: tensor, optional

Alternative output tensor.

keepdims: None, bool, optional

If set to true, axes summed over will remain size one.

Returns
output: tensor_like

Output tensor.

numpy

numpy.sum()

Examples

>>> import ctf
>>> a = ctf.ones([3,4], dtype=np.int64)
>>> a.sum()
12

sym

Attribute sym. ?

take()

Take elements from a tensor along axis.

Parameters
indices: tensor_like

Indices of the values wnat to be extracted.

axis: int, optional

Select values from which axis, default None.

out: tensor

Currently not supported in CTF Python take().

mode: {‘raise’, ‘wrap’, ‘clip’}, optional

Currently not supported in CTF Python take().

Returns
output: tensor or scalar

Elements extracted from the input tensor.

numpy

numpy.take()

Examples

>>> import ctf
>>> a = ctf.astensor([[1,2,3], [4,5,6], [7,8,9]])
>>> a.take([0, 1, 2])
array([1, 2, 3])

tensordot()

Return the tensor dot product of two tensors along axes.

Parameters
other: tensor_like

Second input tensor.

axes: int or array_like

Sum over which axes.

Returns
output: tensor

Tensor dot product of two tensors.

numpy

numpy.tensordot()

Examples

>>> import ctf
>>> import numpy as np
>>> a = np.arange(60.).reshape(3,4,5)
>>> b = np.arange(24.).reshape(4,3,2)
>>> a = ctf.astensor(a)
>>> b = ctf.astensor(b)
>>> a.tensordot(b, axes=([1,0],[0,1]))
array([[4400., 4730.],
[4532., 4874.],
[4664., 5018.],
[4796., 5162.],
[4928., 5306.]])

to_nparray()

Convert tensor to numpy ndarray.

Returns
output: ndarray

Numpy ndarray of the tensor.

Examples

>>> import ctf
>>> a = ctf.ones([3,4], dtype=np.float64)
>>> a = ctf.ones([3,4])
>>> a.to_nparray()
array([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])

tot_size()
trace()

Return the sum over the diagonal of input tensor.

Parameters
offset: int, optional

Default is 0 which indicates the main diagonal.

axis1: int, optional

Default is 0 which indicates the first axis of 2-D tensor where diagonal is taken.

axis2: int, optional

Default is 1 which indicates the second axis of 2-D tensor where diagonal is taken.

dtype: data-type, optional

Numpy data-type, currently not supported in CTF Python trace().

out: tensor

Currently not supported in CTF Python trace().

Returns
output: tensor or scalar

Sum along diagonal of input tensor.

ctf

ctf.trace()

Examples

>>> import ctf
>>> a = ctf.astensor([[1,2,3], [4,5,6], [7,8,9]])
>>> a.trace()
15

transpose()

Return the transposed tensor with specified order of axes.

Returns
output: tensor

Tensor with permuted axes.

ctf

ctf.transpose

Examples

>>> import ctf
>>> a = ctf.zeros([3,4,5])
>>> a.shape
(3, 4, 5)
>>> a.transpose([2,1,0]).shape
(5, 4, 3)

write(inds, vals, a=None, b=None)

Accumulates a set of values to a corresponding set of specified indices (a is scaling for vals and b is scaling for old vlaues in tensor). T[inds[i]] = b*T[inds[i]] + a*vals[i]. Each MPI process is expected to write a different subset of values and all MPI processes must participate (even if writing nothing). However, the set of values written may overlap, in which case they will be accumulated.

Parameters
inds: array (1D or 2D)

If 1D array, each index specifies global index, e.g. access T[i,j,k] via i+n*j+n^2*k, if 2D array, a corresponding row would be [i,j,k]

vals: array

A 1D array specifying values to write for each index

a: scalar

Scaling factor to apply to vals (default is 1)

b: scalar

Scaling factor to apply to existing data (default is 0)

write_all()

Helper function on writing a tensor.

write_to_file()
ctf.core.tensordot()

Return the tensor dot product of two tensors A and B along axes.

Parameters
A: tensor_like

First input tensor.

B: tensor_like

Second input tensor.

axes: int or array_like

Sum over which axes.

Returns
output: tensor

Tensor dot product of two tensors.

numpy

numpy.tensordot()

Examples

>>> import ctf
>>> import numpy as np
>>> a = np.arange(60.).reshape(3,4,5)
>>> b = np.arange(24.).reshape(4,3,2)
>>> a = ctf.astensor(a)
>>> b = ctf.astensor(b)
>>> c = ctf.tensordot(a,b, axes=([1,0],[0,1]))
>>> c
array([[4400., 4730.],
[4532., 4874.],
[4664., 5018.],
[4796., 5162.],
[4928., 5306.]])

class ctf.core.term

Bases: object

Attributes
dtype

Methods

 conv_type scale
conv_type()
dtype
scale()
class ctf.core.timer

Bases: object

Methods

 exit start stop
exit()
start()
stop()
class ctf.core.timer_epoch

Bases: object

Methods

 begin end exit
begin()
end()
exit()
ctf.core.to_nparray()

Convert the tensor to numpy array.

Parameters
A: tensor_like

Input tensor or tensor like array.

Returns
output: ndarray

Numpy ndarray representation of tensor like input A.

numpy

numpy.asarray()

Examples

>>> import ctf
>>> import numpy as np
>>> a = ctf.zeros([3,4])
>>> b = ctf.to_nparray(a)
>>> b
array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
>>> type(b)
<class 'numpy.ndarray'>

ctf.core.trace()

Return the sum over the diagonal of input tensor.

Parameters
A: tensor_like

Input tensor.

offset: int, optional

Default is 0 which indicates the main diagonal.

axis1: int, optional

Default is 0 which indicates the first axis of 2-D tensor where diagonal is taken.

axis2: int, optional

Default is 1 which indicates the second axis of 2-D tensor where diagonal is taken.

dtype: data-type, optional

Numpy data-type, currently not supported in CTF Python trace().

out: tensor

Currently not supported in CTF Python trace().

Returns
output: tensor or scalar

Sum along diagonal of input tensor.

Examples

>>> import ctf
>>> a = ctf.astensor([[1,2,3], [4,5,6], [7,8,9]])
>>> ctf.trace(a)
15

ctf.core.transpose()

Permute the dimensions of the input tensor.

Parameters
A: tensor_like

Input tensor.

axes: list of ints, optional

If axes is None, the dimensions are inversed, otherwise permute the dimensions according to the axes value.

Returns
output: tensor

Tensor with permuted axes of A.

Examples

>>> import ctf
>>> a = ctf.zeros([3,4,5])
>>> a.shape
(3, 4, 5)
>>> ctf.transpose(a, axes=[0, 2, 1]).shape
(3, 5, 4)
>>> ctf.transpose(a).shape
(5, 4, 3)

ctf.core.tril()

Return lower triangle of a CTF tensor.

Parameters
A: tensor_like

2-D input tensor.

k: int

Specify last diagonal not zeroed. Default k=0 which indicates elements under the main diagonal are zeroed.

Returns
output: tensor

Lower triangular 2-d tensor of input tensor.

Examples

>>> import ctf
>>> a = ctf.astensor([[1,2,3],[4,5,6],[7,8,9]])
>>> ctf.tril(a, k=1)
array([[1, 2, 0],
[4, 5, 6],
[7, 8, 9]])

ctf.core.triu()

Return upper triangle of a CTF tensor.

Parameters
A: tensor_like

2-D input tensor.

k: int

Specify last diagonal not zeroed. Default k=0 which indicates elements under the main diagonal are zeroed.

Returns
output: tensor

Upper triangular 2-d tensor of input tensor.

Examples

>>> import ctf
>>> a = ctf.astensor([[1,2,3],[4,5,6],[7,8,9]])
>>> ctf.triu(a, k=-1)
array([[1, 2, 3],
[4, 5, 6],
[0, 8, 9]])

ctf.core.vecnorm()

Return vector (elementwise) norm of tensor A.

Parameters
A: tensor_like

Input tensor with 1, 2 or more dimensions.

ord: {int 1, 2, inf}, optional

Type the norm, 2=Frobenius.

Returns
output: tensor

Norm of tensor A.

Examples

>>> import ctf
>>> import ctf.linalg as la
>>> a = ctf.astensor([3,4.])
>>> la.vecnorm(a)
5.0

ctf.core.vstack()

Stack the tensor in row-wise.

Parameters
in_tup: tuple of tensors

Input tensor.

Returns
output: tensor_like

Output vertically stacked tensor.

Examples

>>> import ctf
>>> a = ctf.astensor([1,2,3])
>>> b = ctf.astensor([4,5,6])
>>> ctf.vstack((a, b))
array([[1, 2, 3],
[4, 5, 6]])

ctf.core.zeros()

Return the tensor with specified shape and dtype with all elements filled as zeros.

Parameters
shape: int or tuple of int

Shape of the empty tensor.

dtype: data-type, optional

Output data-type for the empty tensor.

order: {‘C’, ‘F’}, optional, default: ‘F’

Currently not supported by CTF Python.

sp: {True, False}, optional, default: ‘False’

Whether to represent tensor in a sparse format.

Returns
output: tensor_like

Output tensor.

Examples

>>> import ctf
>>> import numpy as np
>>> a = ctf.zeros([3,4], dtype=np.int64)
>>> a
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])

ctf.core.zeros_like()

Return the tensor of zeros with same shape and dtype of tensor A.

Parameters
A: tensor_like

Input tensor where the output tensor shape and dtype defined as.

dtype: data-type, optional

Output data-type for the empty tensor.

order: {‘C’, ‘F’}, optional, default: ‘F’

Currently not supported by CTF Python.

Returns
output: tensor_like

Output tensor.

Examples

>>> import ctf
>>> import numpy as np
>>> a = ctf.zeros([3,4], dtype=np.int64)
>>> b = ctf.zeros_like(a)
>>> b
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])


## ctf.random module¶

ctf.random.all_seed()

Seed the random tensor generator with the same seed in all processes.

Parameters
seed: int

Seed for random.

ctf.random.random()

Return random float (in half-open interval [0.0, 1.0)) tensor with specified parameters. Result tensor is from the continuous uniform distribution over the interval.

Parameters
shape: tensor_like

Input tensor with 1-D or 2-D dimensions. If A is 1-D tensor, return a 2-D tensor with A on diagonal.

sp: bool, optional

When sp is specified True, the output tensor will be sparse.

p: float, optional

When sp is True, p specifies the fraction of sparsity for the sparse tensor.

dtype: data-type, optional

Not supportted in current CTF Python.

Returns
output: tensor

Random float tensor.

Examples

>>> import ctf
>>> import ctf.random as random
>>> random.random([2, 2])
array([[0.95027513, 0.79755613],
[0.27834548, 0.55310684]])

ctf.random.seed()

Seed the random tensor generator.

Parameters
seed: int

Seed for random. Each process has the seed with seed + get_universe().rank.