torchbox.base package

Submodules

torchbox.base.arrayops module

torchbox.base.arrayops.arraycomb(arrays, out=None)

compute the elemnts combination of several lists.

Parameters
  • arrays (list or tensor) – The lists or tensors.

  • out (tensor, optional) – The combination results (defaults is None).

Returns

The combination results.

Return type

tensor

Examples:

Compute the combination of three lists: \([1,2,3]\), \([4, 5]\), \([6,7]\), this will produce a \(12\times 3\) array.

x = arraycomb(([1, 2, 3], [4, 5], [6, 7]))
print(x, x.shape)

# output:
[[1 4 6]
[1 4 7]
[1 5 6]
[1 5 7]
[2 4 6]
[2 4 7]
[2 5 6]
[2 5 7]
[3 4 6]
[3 4 7]
[3 5 6]
[3 5 7]] (12, 3)
torchbox.base.arrayops.cut(x, pos, axis=None, **kwargs)

Cut array at given position.

Cut array at given position.

Parameters
  • x (array or tensor) – a tensor to be cut

  • pos (tuple or list) – cut positions: ((cpstart, cpend), (cpstart, cpend), …)

  • axis (int, tuple or list, optional) – cut axis (the default is None, which means nothing)

torchbox.base.arrayops.merge(x, dim, keepdim=False)

merge tensor’s dimensions

Parameters
  • x (Tensor) – the input

  • dim (int, list or tuple) – dimensions indexes for merging, putting the dimensions specified by second and subsequent elements of dim after the dimension specified by the specified by the first element of dim)

  • keepdim (bool, optional) – keep the dimensions?, by default False

Returns

merged tensor.

Return type

tensor

torchbox.base.arrayops.permute(X, dim, mode=None, dir='f')

permutes axes of tensor

Parameters
  • X (Tensor) – the input tensor

  • dim (list or tuple) – the order of new dimensions (mode is None) or multiplication dimensions ('matmul')

  • mode (str or None, optional) – permution mode, 'matmul' for matrix multiplication, 'merge' for dimension merging (putting the dimensions specified by second and subsequent elements of dim after the dimension specified by the specified by the first element of dim), None for regular permute, such as torch.permute, by default None.

  • dir (str, optional) – the direction, 'f' or 'b' (reverse process of 'f'), default is 'f'.

torchbox.base.arrayops.reduce(X, dim, keepdim, reduction)

reduce tensor in speciffied dimensions

Parameters
  • X (Tensor) – the input tensor

  • dim (int, list or tuple) – the dimensions for reduction

  • keepdim (bool) – whether keep dimensions

  • reduction (str or None) – The mode of reduction, None, 'mean' or 'sum'

Returns

the reduced tensor

Return type

tensor

Raises

ValueError – reduction mode

torchbox.base.arrayops.roll(x, dim, shifts)

cyclic shift along specified dimension

Roll the tensor x along the given dimension. Elements that are shifted beyond the last position are re-introduced at the first position.

see How to shift columns (or rows) in a tensor with different offsets in PyTorch?

Parameters
  • x (Tensor) – the input

  • dim (int or None) – if dim is None, the tensor will be flattened before rolling and then restored to the original shape.

  • shifts (int or Tensor) – the number of shifts, if shifts is an integer, all the data will be shifted with the same shifts, otherwise, will be shifted with different shifts which are specified by shifts.

Returns

the shifted tensor.

Return type

Tensor

Examples

print('-------roll-------')
x = th.rand(5, 7)
print(x.shape)
print(x)
print('-------roll with the same shifts-------')
print(roll(x, 1, 2))
print('-------roll with different shifts-------')
print(roll(x, 1, th.arange(1, 6)))

print('-------roll a three-dimensional tensor-------')
x = th.rand(5, 7, 3)
y = roll(x, 1, th.arange(1, 6).view(5, 1).repeat(1, 3))
print(x.shape)
print(y.shape)
print(x[..., 1])
print(y[..., 1])
torchbox.base.arrayops.sl(dims, axis, idx=None, **kwargs)

Slice any axis

generates slice in specified axis.

Parameters
  • dims (int) – total dimensions

  • axis (int or list) – select axis list.

  • idx (list or None, optional) – slice lists of the specified axis, if None, does nothing (the default)

  • dim (int or list) – (kwargs) if specified, will overwrite axis

Returns

slice for specified axis elements.

Return type

tuple of slice

Examples

import numpy as np

np.random.seed(2020)
X = np.random.randint(0, 100, (9, 10))
print(X, 'X)
print(X[sl(2, -1, [0, 1])], 'Xsl')

# output:

[[96  8 67 67 91  3 71 56 29 48]
[32 24 74  9 51 11 55 62 67 69]
[48 28 20  8 38 84 65  1 79 69]
[74 73 62 21 29 90  6 38 22 63]
[21 68  6 98  3 20 55  1 52  9]
[83 82 65 42 66 55 33 80 82 72]
[94 91 14 14 75  5 38 83 99 10]
[80 64 79 30 84 22 46 26 60 13]
[24 63 25 89  9 69 47 89 55 75]] X
[[96  8]
[32 24]
[48 28]
[74 73]
[21 68]
[83 82]
[94 91]
[80 64]
[24 63]] Xsl
torchbox.base.arrayops.swap(x, dim1, dim2)

swap dimensions of input

Parameters
  • x (Tensor) – the input

  • dim1 (int, list or tuple) – the first dimension

  • dim2 (int, list or tuple) – the first dimension

Returns

the result

Return type

tensor

Raises

TypeErrordim1 and dim2 must be integer, list or tuple.

torchbox.base.baseops module

torchbox.base.baseops.argsort(x, reverse=False)

returns index of sorted array

Parameters
  • x (list, ndarray or tensor) – the input

  • reverse (bool, optional) – sort in reversed order?, by default False

Returns

the index

Return type

list, ndarray or tensor

torchbox.base.baseops.cat(shapes, axis=0)

Concatenates

Concatenates the given sequence of seq shapes in the given dimension. All tensors must either have the same shape (except in the concatenating dimension) or be empty.

Parameters
  • shapes (tuples or lists) – (shape1, shape2, …)

  • axis (int, optional) – specify the concatenated axis (the default is 0)

Returns

concatenated shape

Return type

tuple or list

Raises

ValueError – Shapes are not consistent in axises except the specified one.

torchbox.base.baseops.dimmerge(ndim, mdim, dim, keepdim=False)

obtain new dimension indexes after merging

Parameters
  • ndim (int) – the number of dimensions

  • mdim (int, list or tuple) – the dimension indexes for merging

  • dim (int, list or tuple) – the dimension indexes that are not merged

  • keepdim (bool) – keep the dimensions when merging?

torchbox.base.baseops.dimpermute(ndim, dim, mode=None, dir='f')

permutes dimensions

Parameters
  • ndim (int) – the number of dimensions

  • dim (list or tuple) – the order of new dimensions (mode is None) or multiplication dimensions ('matmul')

  • mode (str or None, optional) – permution mode, 'matmul' for matrix multiplication, 'merge' for dimension merging (putting the dimensions specified by second and subsequent elements of dim after the dimension specified by the specified by the first element of dim), None for regular permute, such as torch.permute, by default None.

  • dir (str, optional) – the direction, 'f' or 'b' (reverse process of 'f'), default is 'f'.

torchbox.base.baseops.dimpos(ndim, dim)

make positive dimensions

Parameters
  • ndim (int) – the number of dimensions

  • dim (int, list or tuple) – the dimension index to be converted

torchbox.base.baseops.dimreduce(ndim, cdim, dim, keepcdim=False, reduction=None)

get dimensions for reduction operation

Parameters
  • ndim (int) – the number of dimensions

  • cdim (int, optional) – if the data is complex-valued but represented as real tensors, you should specify the dimension. Otherwise, set it to None

  • dim (int, list, tuple or None) – dimensions for processing, None means all

  • keepcdim (bool) – keep the complex dimension? The default is False

  • reduction (str or None, optional) – The operation in other dimensions except the dimensions specified by dim, None, 'mean' or 'sum' (the default is None)

torchbox.base.baseops.dmka(D, Ds)

Multiple key-value assign to a dict

Parameters
  • D (dict) – main dict

  • Ds (dict) – sub dict

Returns

after assign

Return type

dict

torchbox.base.baseops.dreplace(d, fv=None, rv='None', new=False)

replace dict value

Parameters
  • d (dict) – the dict

  • fv (any, optional) – to be replaced, by default None

  • rv (any, optional) – replaced with, by default ‘None’

  • new (bool, optional) – if true, deep copy dict, will not change input, by default False

Returns

dict with replaced value

Return type

dict

torchbox.base.baseops.rmcdim(ndim, cdim, dim, keepdim)

get dimension indexes after removing cdim

Parameters
  • ndim (int) – the number of dimensions

  • cdim (int, optional) – If data is complex-valued but represented as real tensors, you should specify the dimension. Otherwise, set it to None

  • dim (int, None, tuple or list) – dimensions to be re-defined

  • keepdim (bool) – keep dimensions? (include complex dim, defalut is False)

Returns

re-defined dimensions

Return type

int, tuple or list

torchbox.base.baseops.upkeys(D, mode='-', k='module.')

update keys of a dictionary

Parameters
  • D (dict) – the input dictionary

  • mode (str, optional) – '-' for remove key string which is specified by k, by default ‘-’ '+' for add key string which is specified by k, by default ‘-’

  • k (str, optional) – key string pattern, by default ‘module.’

Returns

new dictionary with keys updated

Return type

dict

torchbox.base.mathops module

torchbox.base.mathops.abs(X, cdim=None, keepdim=False)

obtain amplitude of a tensor

Both complex and real representation are supported.

\[{\rm abs}({\bf X}) = |x| = \sqrt{u^2 + v^2}, x\in {\bf X} \]

where, \(u, v\) are the real and imaginary part of x, respectively.

Parameters
  • X (Tensor) – input

  • cdim (int or None) – If X is complex-valued, cdim is ignored. If X is real-valued and cdim is integer then X will be treated as complex-valued, in this case, cdim specifies the complex axis; otherwise (None), X will be treated as real-valued

  • keepdim (bool, optional) – keep dimensions? (include complex dim, defalut is False) (only work when the dimension at cdim equals 2)

Returns

the inputs’s amplitude.

Return type

tensor

Examples

th.manual_seed(2020)
X = th.rand((2, 3, 3))

print('---abs')
print(abs(X))  # real
print(abs(X, cdim=0))  # complex in real
print(abs(X[0] + 1j * X[1]))  # complex in complex

# ---output
---abs
tensor([[0.7968, 0.5504, 0.9957],
        [0.7868, 0.7011, 0.9326],
        [0.8113, 1.0793, 0.2535]])
tensor([[0.7968, 0.5504, 0.9957],
        [0.7868, 0.7011, 0.9326],
        [0.8113, 1.0793, 0.2535]])
torchbox.base.mathops.angle(X, cdim=None, keepdim=False)

obtain angle of a tensor

Both complex and real representation are supported.

\[{\rm angle}(x) = {\rm atan}(\frac{v}{u}), x\in {\bf X} \]

where, \(u, v\) are the real and imaginary part of x, respectively.

Parameters
  • X (Tensor) – input

  • cdim (int or None) – If X is complex-valued, cdim is ignored. If X is real-valued and cdim is integer then X will be treated as complex-valued, in this case, cdim specifies the complex axis; otherwise (None), X will be treated as real-valued

  • keepdim (bool, optional) – keep dimensions? (include complex dim, defalut is False) (only work when the dimension at cdim equals 2)

Returns

the inputs’s amplitude.

Return type

tensor

Examples

th.manual_seed(2020)
X = th.rand((2, 3, 3))

print('---angle')
print(angle(X))  # real
print(angle(X, cdim=0))  # complex in real
print(angle(X[0] + 1j * X[1]))  # complex in complex
torchbox.base.mathops.c2r(X, cdim=- 1, keepdim=False)

complex representaion to real representaion

Parameters
  • X (Tensor) – input in complex representaion

  • cdim (int, optional) – real and imag dimension in real format, by default -1

  • keepdim (bool, optional) – keep dimension, if False, stacks (make a new axis) at dimension cdim, otherwise concatenates the real and imag part at exist dimension cdim, (Default is False).

Returns

  • tensor – output in real representaion

  • see also r2c()

Examples

th.manual_seed(2020)
Xr = th.randint(0, 30, (3, 3, 2))
Xc = Xr[..., 0] + 1j * Xr[..., 1]
Yr = c2r(Xc, cdim=0)
Yc = r2c(Yr, cdim=0)
print(Xr, Xr.shape, 'Xr')
print(Xc, Xc.shape, 'Xc')
print(Yr, Yr.shape, 'Yr')
print(Yc, Yc.shape, 'Yc')

# ---output
tensor([[[20,  6],
        [27, 12],
        [25, 21]],

        [[21, 19],
        [29, 24],
        [25, 10]],

        [[16, 14],
        [ 6,  9],
        [ 5, 29]]]) torch.Size([3, 3, 2]) Xr
tensor([[20.+6.j, 27.+12.j, 25.+21.j],
        [21.+19.j, 29.+24.j, 25.+10.j],
        [16.+14.j,  6.+9.j,  5.+29.j]]) torch.Size([3, 3]) Xc
tensor([[[20., 27., 25.],
        [21., 29., 25.],
        [16.,  6.,  5.]],

        [[ 6., 12., 21.],
        [19., 24., 10.],
        [14.,  9., 29.]]]) torch.Size([2, 3, 3]) Yr
tensor([[20.+6.j, 27.+12.j, 25.+21.j],
        [21.+19.j, 29.+24.j, 25.+10.j],
        [16.+14.j,  6.+9.j,  5.+29.j]]) torch.Size([3, 3]) Yc
torchbox.base.mathops.conj(X, cdim=None)

conjugates a tensor

Both complex and real representation are supported.

Parameters
  • X (Tensor) – input

  • cdim (int or None) – If X is complex-valued, cdim is ignored. If X is real-valued and cdim is integer then X will be treated as complex-valued, in this case, cdim specifies the complex axis; otherwise (None), X will be treated as real-valued

Returns

the inputs’s conjugate matrix.

Return type

tensor

Examples

th.manual_seed(2020)
X = th.rand((2, 3, 3))

print('---conj')
print(conj(X, cdim=0))
print(conj(X[0] + 1j * X[1]))

# ---output
---conj
tensor([[[ 0.4869,  0.1052,  0.5883],
        [ 0.1161,  0.4949,  0.2824],
        [ 0.5899,  0.8105,  0.2512]],

        [[-0.6307, -0.5403, -0.8033],
        [-0.7781, -0.4966, -0.8888],
        [-0.5570, -0.7127, -0.0339]]])
tensor([[0.4869-0.6307j, 0.1052-0.5403j, 0.5883-0.8033j],
        [0.1161-0.7781j, 0.4949-0.4966j, 0.2824-0.8888j],
        [0.5899-0.5570j, 0.8105-0.7127j, 0.2512-0.0339j]])
torchbox.base.mathops.cov(X, Y, biased=False, cdim=None, dim=None, keepdim=False)

Calculates the covariance over the specified dimensions

\[\operatorname{cov}_w(x, y)=\frac{\sum_{i=1}^N\left(x_i-\bar{x}\right)\left(y_i-\bar{y}\right)}{N-\delta} \]

where \(\delta = 0\) for biased estimation, \(\delta = 1\) for unbiased estimation.

Parameters
  • X (Tensor) – the first input tensor

  • Y (Tensor) – the second input tensor

  • biased (bool, optional) – True for N, False for N-1, by default False

  • cdim (int or None) – If X is complex-valued, cdim is ignored. If X is real-valued and cdim is integer then X will be treated as complex-valued, in this case, cdim specifies the complex axis; otherwise (None), X will be treated as real-valued

  • dim (int, list or None, optional) – the dimensions for calculation, by default None (all dims)

  • keepdim (bool, optional) – keep dimensions? (include complex dim, defalut is False)

Returns

the result

Return type

tensor

Examples

th.manual_seed(2020)
X = th.rand((2, 3, 3))
Y = th.rand((2, 3, 3))

print(cov(X, Y))  # real
print(cov(X, Y, cdim=0))  # complex in real
print(cov(X[0] + 1j * X[1], Y[0] + 1j * Y[1]))  # complex in complex
torchbox.base.mathops.db2mag(db, s=20.0)

Converts decibel values to magnitudes

\[{\rm mag} = 10^{db / s} \]
Parameters
  • db (int, float, tuple, list, ndarray, tensor) – The decibel values.

  • s (int or float) – The scale values, default is 20.

Returns

The magnitudes of inputs with the same type.

Return type

int, float, tuple, list, ndarray, tensor

torchbox.base.mathops.dot(X, Y, mode='xyh', cdim=None, dim=None, keepdim=False)

dot product or inner product

\[ = xy^H \]

Note

the dot() function in numpy and pytorch compute the inner product by \(<x,y> = xy\).

Parameters
  • X (Tensor) – the left input

  • Y (Tensor) – the right input

  • mode (str) – 'xyh' for \(<x,y> = xy^H\) (default), 'xy' for \(<x,y> = xy\), where \(y^H\) is the complex conjection of \(y\)

  • cdim (int or None) – If X is complex-valued, cdim is ignored. If X is real-valued and cdim is integer then X will be treated as complex-valued, in this case, cdim specifies the complex axis; otherwise (None), X will be treated as real-valued

  • dim (tuple, None, optional) – The dimension axis for computing dot product. The default is None, which means all.

  • keepdim (bool) – keep dimensions? (include complex dim, defalut is False)

Examples

th.manual_seed(2020)
X = th.rand((2, 3, 3))

print(dot(X, X))  # real
print(dot(X, X, cdim=0))  # complex in real
print(dot(X[0] + 1j * X[1], X[0] + 1j * X[1]))  # complex in complex
torchbox.base.mathops.ebeo(a, b, op='+')

element by element operation

Element by element operation.

Parameters
  • a (list, tuple, tensor or array) – The first list/tuple/nparray/tensor.

  • b (list, tuple, tensor or array) – The second list/tuple/nparray/tensor.

  • op (str, optional) – Supported operations are: - '+' or 'add' for addition (default) - '-' or 'sub' for substraction - '*' or 'mul' for multiplication - '/' or 'div' for division - '**' or pow for power - '<', or 'lt' for less than - '<=', or 'le' for less than or equal to - '>', or 'gt' for greater than - '>=', or 'ge' for greater than or equal to - '&' for bitwise and - '|' for bitwise or - '^' for bitwise xor - function for custom operation.

Raises

TypeError – If the specified operator not in the above list, raise a TypeError.

torchbox.base.mathops.ematmul(A, B, **kwargs)

Element-by-element complex multiplication

like A .* B in matlab

Parameters
  • A (Tensor) – any size tensor, both complex and real representation are supported. For real representation, the real and imaginary dimension is specified by cdim or caxis.

  • B (Tensor) – any size tensor, both complex and real representation are supported. For real representation, the real and imaginary dimension is specified by cdim or caxis.

  • cdim (int or None, optional) – if A and B are complex tensors but represented in real format, cdim or caxis should be specified (Default is None).

Returns

result of element-by-element complex multiplication with the same repesentation as A and B.

Return type

tensor

Examples

th.manual_seed(2020)
Ar = th.randn((3, 3, 2))
Br = th.randn((3, 3, 2))

Ac = th.view_as_complex(Ar)
Bc = th.view_as_complex(Br)

Mr = th.view_as_real(Ac * Bc)
print(th.sum(Mr - ematmul(Ar, Br, cdim=-1)))
print(th.sum(Ac * Bc - ematmul(Ac, Bc)))

# output
tensor(-1.1921e-07)
tensor(0.+0.j)
torchbox.base.mathops.fnab(n)

gives the closest two integer number factor of a number

Parameters

n (int or float) – the number

Returns

  • a (int)

  • b (int) – the factor number

Examples

print(fnab(5))
print(fnab(6))
print(fnab(7))
print(fnab(8))
print(fnab(9))

# ---output
(2, 3)
(2, 3)
(2, 4)
(2, 4)
(3, 3)
torchbox.base.mathops.imag(X, cdim=None, keepdim=False)

obtain imaginary part of a tensor

Both complex and real representation are supported.

Parameters
  • X (Tensor) – input

  • cdim (int or None) – If X is complex-valued, cdim is ignored. If X is real-valued and cdim is integer then X will be treated as complex-valued, in this case, cdim specifies the complex axis; otherwise (None), X will be treated as real-valued

  • keepdim (bool, optional) – keep dimensions? (include complex dim, defalut is False) (only work when the dimension at cdim equals 2)

Returns

the inputs’s imaginary part tensor.

Return type

tensor

Examples

th.manual_seed(2020)
X = th.rand((2, 3, 3))

print('---imag')
print(imag(X, cdim=0))
print(imag(X[0] + 1j * X[1]))

# ---output
---imag
tensor([[0.6307, 0.5403, 0.8033],
        [0.7781, 0.4966, 0.8888],
        [0.5570, 0.7127, 0.0339]])
tensor([[0.6307, 0.5403, 0.8033],
        [0.7781, 0.4966, 0.8888],
        [0.5570, 0.7127, 0.0339]])
torchbox.base.mathops.mag2db(mag, s=20.0)

Converts decibel values to magnitudes

\[{\rm db} = s*{\rm log10}{\rm mag} \]
Parameters
  • mag (int, float, tuple, list, ndarray, tensor) – The magnitude values.

  • s (int or float) – The scale values, default is 20.

Returns

The decibel of inputs with the same type.

Return type

int, float, tuple, list, ndarray, tensor

torchbox.base.mathops.matmul(A, B, cdim=None, dim=(- 2, - 1))

Complex matrix multiplication

like A * B in matlab

Parameters
  • A (Tensor) – any size tensor, both complex and real representation are supported. For real representation, the real and imaginary dimension is specified by cdim or caxis.

  • B (Tensor) – any size tensor, both complex and real representation are supported. For real representation, the real and imaginary dimension is specified by cdim or caxis.

  • cdim (int or None, optional) – if A and B are complex tensors but represented in real format, cdim or caxis should be specified (Default is None).

  • dim (tulpe or list) – dimensions for multiplication (default is (-2, -1))

Returns

result of complex multiplication with the same repesentation as A and B.

Return type

tensor

Examples

th.manual_seed(2020)
Ar = th.randn((3, 3, 2))
Br = th.randn((3, 3, 2))

Ac = th.view_as_complex(Ar)
Bc = th.view_as_complex(Br)

print(th.sum(th.matmul(Ac, Bc) - matmul(Ac, Bc)))
Mr = matmul(Ar, Br, cdim=-1, dim=( 0, 1))
Mc = th.view_as_real(th.matmul(Ac, Bc))
print(th.sum(Mr - Mc))

# output
tensor(0.+0.j)
tensor(1.0729e-06)
torchbox.base.mathops.mean(X, cdim=None, dim=None, keepdim=False)
Parameters
  • X (Tensor) – the input tensor

  • cdim (int or None) – If X is complex-valued, cdim is ignored. If X is real-valued and cdim is integer then X will be treated as complex-valued, in this case, cdim specifies the complex axis; otherwise (None), X will be treated as real-valued

  • dim (int, list or None, optional) – the dimensions for calculation, by default None (all dims)

  • keepdim (bool, optional) – keep dimensions? (include complex dim, defalut is False)

Examples

th.manual_seed(2020)
X = th.rand((2, 3, 3))

print(mean(X))  # real
print(mean(X, cdim=0))  # complex in real
print(mean(X[0] + 1j * X[1]))  # complex in complex
torchbox.base.mathops.nextpow2(x)

get the next higher power of 2.

Given an number \(x\), returns the first p such that \(2^p >=|x|\).

Parameters

x (int or float) – an number.

Returns

Next higher power of 2.

Return type

int

Examples

print(prevpow2(-5), nextpow2(-5))
print(prevpow2(5), nextpow2(5))
print(prevpow2(0.3), nextpow2(0.3))
print(prevpow2(7.3), nextpow2(7.3))
print(prevpow2(-3.5), nextpow2(-3.5))

# output
2 3
2 3
-2 -1
2 3
1 2
torchbox.base.mathops.pow(X, cdim=None, keepdim=False)

obtain power of a tensor

Both complex and real representation are supported.

\[{\rm pow}({\bf X}) = |x|^2 = u^2 + v^2, x\in {\bf X} \]

where, \(u, v\) are the real and imaginary part of x, respectively.

Parameters
  • X (Tensor) – input

  • cdim (int or None) – If X is complex-valued, cdim is ignored. If X is real-valued and cdim is integer then X will be treated as complex-valued, in this case, cdim specifies the complex axis; otherwise (None), X will be treated as real-valued

  • keepdim (bool, optional) – keep dimensions? (include complex dim, defalut is False) (only work when the dimension at cdim equals 2)

Returns

the inputs’s power.

Return type

tensor

Examples

th.manual_seed(2020)
X = th.rand((2, 3, 3))

print('---pow')
print(pow(X))  # real
print(pow(X, cdim=0))  # complex in real
print(pow(X[0] + 1j * X[1]))  # complex in complex

# ---output
---pow
tensor([[0.6349, 0.3030, 0.9914],
        [0.6190, 0.4915, 0.8697],
        [0.6583, 1.1649, 0.0643]])
tensor([[0.6349, 0.3030, 0.9914],
        [0.6190, 0.4915, 0.8697],
        [0.6583, 1.1649, 0.0643]])
torchbox.base.mathops.prevpow2(x)

get the previous lower power of 2.

Given an number \(x\), returns the first p such that \(2^p <=|x|\).

Parameters

x (int or float) – an number.

Returns

Next higher power of 2.

Return type

int

Examples

print(prevpow2(-5), nextpow2(-5))
print(prevpow2(5), nextpow2(5))
print(prevpow2(0.3), nextpow2(0.3))
print(prevpow2(7.3), nextpow2(7.3))
print(prevpow2(-3.5), nextpow2(-3.5))

# output
2 3
2 3
-2 -1
2 3
1 2
torchbox.base.mathops.r2c(X, cdim=- 1, keepdim=False)

real representaion to complex representaion

Parameters
  • X (Tensor) – input in real representaion

  • cdim (int, optional) – real and imag dimension in real format, by default -1

  • keepdim (bool, optional) – keep dimension, if False, discards axis cdim, otherwise preserves the axis cdim, (Default is False). (only work when the dimension at cdim equals 2)

Returns

  • tensor – output in complex representaion

  • see also c2r()

Examples

th.manual_seed(2020)
Xr = th.randint(0, 30, (3, 3, 2))
Xc = Xr[..., 0] + 1j * Xr[..., 1]
Yr = c2r(Xc, cdim=0)
Yc = r2c(Yr, cdim=0)
print(Xr, Xr.shape, 'Xr')
print(Xc, Xc.shape, 'Xc')
print(Yr, Yr.shape, 'Yr')
print(Yc, Yc.shape, 'Yc')

# ---output
tensor([[[20,  6],
        [27, 12],
        [25, 21]],

        [[21, 19],
        [29, 24],
        [25, 10]],

        [[16, 14],
        [ 6,  9],
        [ 5, 29]]]) torch.Size([3, 3, 2]) Xr
tensor([[20.+6.j, 27.+12.j, 25.+21.j],
        [21.+19.j, 29.+24.j, 25.+10.j],
        [16.+14.j,  6.+9.j,  5.+29.j]]) torch.Size([3, 3]) Xc
tensor([[[20., 27., 25.],
        [21., 29., 25.],
        [16.,  6.,  5.]],

        [[ 6., 12., 21.],
        [19., 24., 10.],
        [14.,  9., 29.]]]) torch.Size([2, 3, 3]) Yr
tensor([[20.+6.j, 27.+12.j, 25.+21.j],
        [21.+19.j, 29.+24.j, 25.+10.j],
        [16.+14.j,  6.+9.j,  5.+29.j]]) torch.Size([3, 3]) Yc
torchbox.base.mathops.real(X, cdim=None, keepdim=False)

obtain real part of a tensor

Both complex and real representation are supported.

Parameters
  • X (Tensor) – input

  • cdim (int or None) – If X is complex-valued, cdim is ignored. If X is real-valued and cdim is integer then X will be treated as complex-valued, in this case, cdim specifies the complex axis; otherwise (None), X will be treated as real-valued

  • keepdim (bool, optional) – keep dimensions? (include complex dim, defalut is False) (only work when the dimension at cdim equals 2)

Returns

the inputs’s real part tensor.

Return type

tensor

Examples

th.manual_seed(2020)
X = th.rand((2, 3, 3))

print('---real')
print(real(X, cdim=0))
print(real(X[0] + 1j * X[1]))

# ---output
---real
tensor([[0.4869, 0.1052, 0.5883],
        [0.1161, 0.4949, 0.2824],
        [0.5899, 0.8105, 0.2512]])
tensor([[0.4869, 0.1052, 0.5883],
        [0.1161, 0.4949, 0.2824],
        [0.5899, 0.8105, 0.2512]])
torchbox.base.mathops.sinc(x)

Applies sinc function to a tensor

Parameters

x (Tensor) – input tensor

Returns

after sinc transformation.

Return type

Tensor

torchbox.base.mathops.std(X, biased=False, cdim=None, dim=None, keepdim=False)

Calculates the standard deviation over the specified dimensions

Parameters
  • X (Tensor) – the input tensor

  • biased (bool, optional) – True for N, False for N-1, by default False

  • cdim (int or None) – If X is complex-valued, cdim is ignored. If X is real-valued and cdim is integer then X will be treated as complex-valued, in this case, cdim specifies the complex axis; otherwise (None), X will be treated as real-valued

  • dim (int, list or None, optional) – the dimensions for calculation, by default None (all dims)

  • keepdim (bool, optional) – keep dimensions? (include complex dim, defalut is False)

Returns

the result

Return type

tensor

Examples

th.manual_seed(2020)
X = th.rand((2, 3, 3))

print(std(X))  # real
print(std(X, cdim=0))  # complex in real
print(std(X[0] + 1j * X[1]))  # complex in complex
torchbox.base.mathops.var(X, biased=False, cdim=None, dim=None, keepdim=False)

Calculates the variance over the specified dimensions

\[\sigma^2=\frac{1}{N-\delta} \sum_{i=0}^{N-1}\left(x_i-\bar{x}\right)^2 \]

where \(\delta = 0\) for biased estimation, \(\delta = 1\) for unbiased estimation.

Parameters
  • X (Tensor) – the input tensor

  • biased (bool, optional) – True for N, False for N-1, by default False

  • cdim (int or None) – If X is complex-valued, cdim is ignored. If X is real-valued and cdim is integer then X will be treated as complex-valued, in this case, cdim specifies the complex axis; otherwise (None), X will be treated as real-valued

  • dim (int, list or None, optional) – the dimensions for calculation, by default None (all dims)

  • keepdim (bool, optional) – keep dimensions? (include complex dim, defalut is False)

Returns

the result

Return type

tensor

Examples

th.manual_seed(2020)
X = th.rand((2, 3, 3))

print(var(X))  # real
print(var(X, cdim=0))  # complex in real
print(var(X[0] + 1j * X[1]))  # complex in complex

torchbox.base.randomfunc module

torchbox.base.randomfunc.permutation(x)

permutation function like numpy.random.permutation

permutation function like numpy.random.permutation

Parameters

x (Tensor) – inputs, can have any dimensions.

Returns

x – permutated tensor

Return type

Tensor

torchbox.base.randomfunc.randgrid(start, stop, step, shake=0, n=None)

generates non-repeated uniform stepped random ints

Generates n non-repeated random ints from start to stop with step size step.

When step is 1 and shake is 0, it works similar to randperm,

Parameters
  • start (int or list) – start sampling point

  • stop (int or list) – stop sampling point

  • step (int or list) – sampling stepsize

  • shake (float) – the shake rate, if shake is 0, no shake, (default), if positive, add a positive shake, if negative, add a negative.

  • n (int or None) – the number of samples (default None, int((stop0 - start0) / step0) * int((stop1 - start1) / step1)…).

Return type

for multi-dimension, return a 2-d tensor, for 1-dimension, return a 1d-tensor.

Example

import matplotlib.pyplot as plt

setseed(2021)
print(randperm(2, 40, 8), ", randperm(2, 40, 8)")
print(randgrid(2, 40, 1, -1., 8), ", randgrid(2, 40, 1, 8, -1.)")
print(randgrid(2, 40, 6, -1, 8), ", randgrid(2, 40, 6, 8)")
print(randgrid(2, 40, 6, 0.5, 8), ", randgrid(2, 40, 6, 8, 0.5)")
print(randgrid(2, 40, 6, -1, 12), ", randgrid(2, 40, 6, 12)")
print(randgrid(2, 40, 6, 0.5, 12), ", randgrid(2, 40, 6, 12, 0.5)")

mask = th.zeros((5, 6))
mask[3, 4] = 0
mask[2, 5] = 0

Rh, Rw = randperm2d(5, 6, 4, mask=mask)

print(Rh)
print(Rw)

y = randperm(0, 8192, 800)
x = randperm(0, 8192, 800)

y, x = randgrid([0, 0], [512, 512], [64, 64], [0.0, 0.], 32)
print(len(y), len(x))

plt.figure()
plt.plot(x, y, 'o')
plt.show()

y, x = randgrid([0, 0], [8192, 8192], [256, 256], [0., 0.], 400)
print(len(y), len(x))

plt.figure()
plt.plot(x, y, '*')
plt.show()

see also randperm().

torchbox.base.randomfunc.randperm(start, stop, n)

randperm function like matlab

genarates diffrent random interges in range [start, stop)

Parameters
  • start (int or list) – start sampling point

  • stop (int or list) – stop sampling point

  • n (int, list or None) – the number of samples (default None, int((stop - start)))

:param see also randgrid().:

torchbox.base.randomfunc.randperm2d(H, W, number, population=None, mask=None)

randperm 2d function

genarates diffrent random interges in range [start, end)

Parameters
  • H (int) – height

  • W (int) – width

  • number (int) – random numbers

  • population ({list or numpy array(1d or 2d)}) – part of population in range(0, H*W)

torchbox.base.randomfunc.setseed(seed=None, target='torch')

set seed

Set numpy / random / torch / torch.random / torch.cuda seed.

Parameters
  • seed (int or None, optional) – seed for random number generator (the default is None)

  • target (str, optional) –

    • 'numpy': np.random.seed(seed)

    • 'random': random.seed(seed)

    • 'torch': torch.manual_seed(seed) (default)

    • 'torch.random': torch.random.manual_seed(seed)

    • 'cuda': torch.cuda.manual_seed(seed)

    • 'cudaall': torch.cuda.manual_seed_all(seed)

torchbox.base.typevalue module

torchbox.base.typevalue.dtypes(t='int')
torchbox.base.typevalue.peakvalue(A)

Compute the peak value of the input.

Find peak value in matrix

Parameters

A (numpy array) – Data for finding peak value

Returns

Peak value.

Return type

number

Module contents