torchbox.base package
Submodules
torchbox.base.arrayops module
- torchbox.base.arrayops.arraycomb(arrays, out=None)
compute the elemnts combination of several lists.
- Parameters:
- 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.
- torchbox.base.arrayops.merge(x, dim, keepdim=False)
merge tensor’s dimensions
- Parameters:
- 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 (
modeisNone) or multiplication dimensions ('matmul')mode (str or None, optional) – permution mode,
'matmul'for matrix multiplication;'swap'for swapping two dimensions;'merge'for dimension merging (putting the dimensions specified by second and subsequent elements ofdimafter the dimension specified by the specified by the first element ofdim),'gather0': the specified dims are gathered at begin;'gather-1': the specified dims are gathered at end.Nonefor regular permute, such as torch.permute, by defaultNone.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
- torchbox.base.arrayops.roll(x, dim, shifts)
cyclic shift along specified dimension
Roll the tensor
xalong 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
dimisNone, the tensor will be flattened before rolling and then restored to the original shape.shifts (int or Tensor) – the number of shifts, if
shiftsis 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(ndim, axis=None, idx=None, **kwargs)
Slice any axis
generates slice in specified axis.
- Parameters:
- Returns:
slice for specified axis elements.
- Return type:
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
- torchbox.base.arrayops.ta(shape, axis=None, idx=None, **kwargs)
returns take/put along dimension indexes
- Parameters:
- Returns:
slice for specified axis elements.
- Return type:
Examples
import torch as th import torchbox as tb tb.setseed(2025) print("---three dimensional") x = th.rand(3, 4, 5) print(x, x.shape) y = x.argmax(dim=1, keepdim=True) print(y, y.shape) print(th.take_along_dim(x, y, 1)) print(x[tb.ta(x.shape, dim=1, idx=y)]) print("---two dimensional") x = th.rand(3, 4) print(x, x.shape) y = x.argmax(dim=1, keepdim=True) print(y, y.shape) print(th.take_along_dim(x, y, 1)) print(x[tb.ta(x.shape, dim=1, idx=y)]) # outputs: ---three dimensional tensor([[[0.6850, 0.9355, 0.2900, 0.3991, 0.7470], [0.0215, 0.0654, 0.7855, 0.3883, 0.6340], [0.9447, 0.4773, 0.2861, 0.3887, 0.1099], [0.3606, 0.8450, 0.8059, 0.0520, 0.3438]], [[0.5326, 0.5318, 0.0709, 0.8716, 0.6798], [0.2956, 0.9812, 0.9813, 0.8118, 0.0463], [0.9592, 0.5132, 0.3941, 0.6953, 0.7350], [0.0309, 0.8294, 0.3368, 0.6413, 0.6471]], [[0.5964, 0.9792, 0.8084, 0.9328, 0.8772], [0.1945, 0.5616, 0.6019, 0.5040, 0.0028], [0.2127, 0.0655, 0.0905, 0.2134, 0.0313], [0.6896, 0.6147, 0.6534, 0.7446, 0.0566]]]) torch.Size([3, 4, 5]) tensor([[[2, 0, 3, 0, 0]], [[2, 1, 1, 0, 2]], [[3, 0, 0, 0, 0]]]) torch.Size([3, 1, 5]) tensor([[[0.9447, 0.9355, 0.8059, 0.3991, 0.7470]], [[0.9592, 0.9812, 0.9813, 0.8716, 0.7350]], [[0.6896, 0.9792, 0.8084, 0.9328, 0.8772]]]) tensor([[[0.9447, 0.9355, 0.8059, 0.3991, 0.7470]], [[0.9592, 0.9812, 0.9813, 0.8716, 0.7350]], [[0.6896, 0.9792, 0.8084, 0.9328, 0.8772]]]) ---two dimensional tensor([[0.0063, 0.8315, 0.6700, 0.5649], [0.3642, 0.8325, 0.3829, 0.1168], [0.2533, 0.3268, 0.7434, 0.9798]]) torch.Size([3, 4]) tensor([[1], [1], [3]]) torch.Size([3, 1]) tensor([[0.8315], [0.8325], [0.9798]]) tensor([[0.8315], [0.8325], [0.9798]])
torchbox.base.baseops module
- torchbox.base.baseops.argmax(X, cdim=None, dim=None, keepdim=False)
return index of maximum values
- Parameters:
X (tensor) – the input data
cdim (int or None) – If
Xis complex-valued,cdimis ignored. IfXis real-valued andcdimis integer thenXwill be treated as complex-valued, in this case,cdimspecifies the complex axis; otherwise (None),Xwill be treated as real-valueddim (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)
- torchbox.base.baseops.argmin(X, cdim=None, dim=None, keepdim=False)
return index of minimum values
- Parameters:
X (tensor) – the input data
cdim (int or None) – If
Xis complex-valued,cdimis ignored. IfXis real-valued andcdimis integer thenXwill be treated as complex-valued, in this case,cdimspecifies the complex axis; otherwise (None),Xwill be treated as real-valueddim (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)
- torchbox.base.baseops.argsort(x, reverse=False)
returns index of sorted array
- 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:
- 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
- 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 (
modeisNone) or multiplication dimensions ('matmul')mode (str or None, optional) – permution mode,
'matmul'for matrix multiplication;'swap'for swapping two dimensions;'merge'for dimension merging (putting the dimensions specified by second and subsequent elements ofdimafter the dimension specified by the specified by the first element ofdim);'gather0': the specified dims are gathered at begin;'gather-1': the specified dims are gathered at end.Nonefor regular permute, such as torch.permute, by defaultNone.dir (str, optional) – the direction,
'f'or'b'(reverse process of'f'), default is'f'.
- torchbox.base.baseops.dimpos(ndim, dim)
make positive dimensions
- 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
Nonedim (int, list, tuple or None) – dimensions for processing,
Nonemeans allkeepcdim (bool) – keep the complex dimension? The default is
Falsereduction (str or None, optional) – The operation in other dimensions except the dimensions specified by
dim,None,'mean'or'sum'(the default isNone)
- torchbox.base.baseops.dmka(D, Ds)
Multiple key-value assign to a dict
- torchbox.base.baseops.dreplace(d, fv=None, rv='None', new=False)
replace dict value
- torchbox.base.baseops.ind2sub(siz, ind)
returns multiple subscripts from linear index
- Parameters:
See also
Examples
conversion between subscripts and linear index of one, two and three dimensional data.
print('---sub2ind([12], [1, 10])') print(sub2ind([12], [1, 10])) print('---ind2sub([12], [1, 10])') print(ind2sub([12], [1, 10])) print('---sub2ind([3, 4], [[1, 2], [2, 3], [0, 2]])') print(sub2ind([3, 4], [[1, 2], [2, 3], [0, 2]])) print('---ind2sub([3, 4], [6, 11, 2])') print(ind2sub([3, 4], [6, 11, 2])) print('---sub2ind([3, 4, 5], [[0, 3, 0], [1, 1, 1]])') print(sub2ind([3, 4, 5], [[0, 3, 0], [1, 1, 1]])) print('---ind2sub([3, 4, 5], [15, 26])') print(ind2sub([3, 4, 5], [15, 26]))
- torchbox.base.baseops.max(X, cdim=None, dim=None, keepdim=False)
return maximum values
- Parameters:
X (tensor) – the input data
cdim (int or None) – If
Xis complex-valued,cdimis ignored. IfXis real-valued andcdimis integer thenXwill be treated as complex-valued, in this case,cdimspecifies the complex axis; otherwise (None),Xwill be treated as real-valueddim (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, 4)) print(X) print((X[[0]]+1j*X[[1]]).abs()) print('---argmax') print(argmax(X, cdim=None, dim=[-2, -1], keepdim=True)) print(argmax(X, cdim=0, dim=[-2, -1], keepdim=True)) print(argmax(X[[0]]+1j*X[[1]], cdim=None, dim=[-1, -2], keepdim=True)) print('---max') print(max(X, cdim=None, dim=[-2, -1], keepdim=True)) print(max(X, cdim=0, dim=[-2, -1], keepdim=True)) print(max(X[[0]]+1j*X[[1]], cdim=None, dim=[-1, -2], keepdim=True)) # outputs: 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, 0.1151, 0.8780], [0.0671, 0.5173, 0.8126, 0.3861]]]) tensor([[[0.9179, 0.5077, 1.0659, 0.5690], [0.8676, 0.2844, 0.6011, 1.1949], [0.2600, 0.8158, 0.9758, 0.8912]]]) ---argmax [tensor([[[1]], [[0]]]), tensor([[[3]], [[2]]])] [tensor([[[1]]]), tensor([[[3]]])] [tensor([[[3]]]), tensor([[[1]]])] ---max tensor([[[0.8105]], [[0.8888]]]) tensor([[[0.8105]], [[0.8780]]]) tensor([[[0.8105+0.8780j]]])
- torchbox.base.baseops.min(X, cdim=None, dim=None, keepdim=False)
return minimum values
- Parameters:
X (tensor) – the input data
cdim (int or None) – If
Xis complex-valued,cdimis ignored. IfXis real-valued andcdimis integer thenXwill be treated as complex-valued, in this case,cdimspecifies the complex axis; otherwise (None),Xwill be treated as real-valueddim (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, 4)) print(X) print(min(X, cdim=None, dim=[-2, -1], keepdim=False)) print((X[[0]]+1j*X[[1]]).abs()) print('---argmin') print(argmin(X, cdim=None, dim=[-1, -2], keepdim=False)) print(argmin(X, cdim=0, dim=[-2, -1], keepdim=False)) print(argmin(X[[0]]+1j*X[[1]], cdim=None, dim=[-1, -2], keepdim=False)) print('---min') print(min(X, cdim=None, dim=[-2, -1], keepdim=False)) print(min(X, cdim=0, dim=[-2, -1], keepdim=False)) print(min(X[[0]]+1j*X[[1]], cdim=None, dim=[-1, -2], keepdim=False)) 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, 0.1151, 0.8780], [0.0671, 0.5173, 0.8126, 0.3861]]]) tensor([0.1052, 0.0339]) tensor([[[0.9179, 0.5077, 1.0659, 0.5690], [0.8676, 0.2844, 0.6011, 1.1949], [0.2600, 0.8158, 0.9758, 0.8912]]]) ---argmin [tensor([1, 1]), tensor([0, 1])] [tensor(2), tensor(0)] [tensor([0]), tensor([2])] ---min tensor([0.1052, 0.0339]) tensor([0.2512, 0.0671]) tensor([0.2512+0.0671j])
- 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
Nonedim (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:
- torchbox.base.baseops.sub2ind(siz, sub)
returns linear index from multiple subscripts
- Parameters:
Examples
conversion between subscripts and linear index of one, two and three dimensional data.
print('---sub2ind([12], [1, 10])') print(sub2ind([12], [1, 10])) print('---ind2sub([12], [1, 10])') print(ind2sub([12], [1, 10])) print('---sub2ind([3, 4], [[1, 2], [2, 3], [0, 2]])') print(sub2ind([3, 4], [[1, 2], [2, 3], [0, 2]])) print('---ind2sub([3, 4], [6, 11, 2])') print(ind2sub([3, 4], [6, 11, 2])) print('---sub2ind([3, 4, 5], [[0, 3, 0], [1, 1, 1]])') print(sub2ind([3, 4, 5], [[0, 3, 0], [1, 1, 1]])) print('---ind2sub([3, 4, 5], [15, 26])') print(ind2sub([3, 4, 5], [15, 26]))
- torchbox.base.baseops.upkeys(D, mode='-', k='module.')
update keys of a dictionary
- Parameters:
- Returns:
new dictionary with keys updated
- Return type:
torchbox.base.geometry module
- torchbox.base.geometry.car2pol(x, y, unita='rad')
Cartesian coordinate –> Spherical coordinate
- Parameters:
- Returns:
tensor – radius in Polar
tensor – angle in Polar
Examples
r, a = 10, 30 x, y = pol2car(r, a, 'deg') print(x, y) r, a = car2pol(x, y, 'deg') print(r, a)
- torchbox.base.geometry.car2sph(x, y, z, unita='rad')
Cartesian coordinate –> Spherical coordinate
\[\begin{aligned} r &= \sqrt{x^2+y^2+z^2}\\ a &= \arctan{(\sqrt{x^2+y^2}/z)}\\ e &= \arctan{(y/x)} \end{aligned} \]- Parameters:
- Returns:
tensor – radius in Spherical
tensor – azimuth in Spherical
tensor – elevation in Spherical
Examples
r, a, e = 10, 30, 60 x, y, z = sph2car(r, a, e, 'deg') print(x, y, z) r, a, e = car2sph(x, y, z, 'deg') print(r, a, e)
- torchbox.base.geometry.deg2rad(deg)
degree –> radian
- torchbox.base.geometry.pol2car(r, a, unita='rad')
Polar coordinate –> Cartesian coordinate
\[\begin{aligned} x &= r \cos(a) \\ y &= r \sin(a) \end{aligned} \]- Parameters:
- Returns:
tensor – x coordinates in Cartesian
tensor – y coordinates in Cartesian
Examples
r, a = 10, 30 x, y = pol2car(r, a, 'deg') print(x, y) r, a = car2pol(x, y, 'deg') print(r, a)
- torchbox.base.geometry.rad2deg(rad)
radian –> degree
- torchbox.base.geometry.sph2car(r, a, e, unita='rad')
Spherical coordinate –> Cartesian coordinate
\[\begin{aligned} x &= r \cos(e) \cos(a) \\ y &= r \cos(e) \sin(a) \\ z &= r \sin(e) \end{aligned} \]- Parameters:
- Returns:
tensor – x coordinates in Cartesian
tensor – y coordinates in Cartesian
tensor – z coordinates in Cartesian
Examples
r, a, e = 10, 30, 60 x, y, z = sph2car(r, a, e, 'deg') print(x, y, z) r, a, e = car2sph(x, y, z, 'deg') print(r, a, e)
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
Xis complex-valued,cdimis ignored. IfXis real-valued andcdimis integer thenXwill be treated as complex-valued, in this case,cdimspecifies the complex axis; otherwise (None),Xwill be treated as real-valuedkeepdim (bool, optional) – keep dimensions? (include complex dim, defalut is
False) (only work when the dimension atcdimequals 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
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
Xis complex-valued,cdimis ignored. IfXis real-valued andcdimis integer thenXwill be treated as complex-valued, in this case,cdimspecifies the complex axis; otherwise (None),Xwill be treated as real-valuedkeepdim (bool, optional) – keep dimensions? (include complex dim, defalut is
False) (only work when the dimension atcdimequals 2)
- Returns:
the angles of inputs.
- 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 dimensioncdim, otherwise concatenates the real and imag part at exist dimensioncdim, (Default isFalse).
- 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
Xis complex-valued,cdimis ignored. IfXis real-valued andcdimis integer thenXwill be treated as complex-valued, in this case,cdimspecifies the complex axis; otherwise (None),Xwill 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) –
Truefor N,Falsefor N-1, by defaultFalsecdim (int or None) – If
Xis complex-valued,cdimis ignored. IfXis real-valued andcdimis integer thenXwill be treated as complex-valued, in this case,cdimspecifies the complex axis; otherwise (None),Xwill be treated as real-valueddim (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} \]
- 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
Xis complex-valued,cdimis ignored. IfXis real-valued andcdimis integer thenXwill be treated as complex-valued, in this case,cdimspecifies the complex axis; otherwise (None),Xwill be treated as real-valueddim (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 -'**'orpowfor 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
cdimorcaxis.B (Tensor) – any size tensor, both complex and real representation are supported. For real representation, the real and imaginary dimension is specified by
cdimorcaxis.cdim (int or None, optional) – if
AandBare complex tensors but represented in real format,cdimorcaxisshould be specified (Default isNone).
- Returns:
result of element-by-element complex multiplication with the same repesentation as
AandB.- 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
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
Xis complex-valued,cdimis ignored. IfXis real-valued andcdimis integer thenXwill be treated as complex-valued, in this case,cdimspecifies the complex axis; otherwise (None),Xwill be treated as real-valuedkeepdim (bool, optional) – keep dimensions? (include complex dim, defalut is
False) (only work when the dimension atcdimequals 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.log(x, a=None)
returns logarithm of the elements of input
- torchbox.base.mathops.mag2db(mag, s=20.0)
Converts decibel values to magnitudes
\[{\rm db} = s*{\rm log10}{\rm mag} \]
- 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
cdimorcaxis.B (Tensor) – any size tensor, both complex and real representation are supported. For real representation, the real and imaginary dimension is specified by
cdimorcaxis.cdim (int or None, optional) – if
AandBare complex tensors but represented in real format,cdimorcaxisshould be specified (Default isNone).dim (tulpe or list) – dimensions for multiplication (default is (-2, -1))
- Returns:
result of complex multiplication with the same repesentation as
AandB.- 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
Xis complex-valued,cdimis ignored. IfXis real-valued andcdimis integer thenXwill be treated as complex-valued, in this case,cdimspecifies the complex axis; otherwise (None),Xwill be treated as real-valueddim (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|\).
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
Xis complex-valued,cdimis ignored. IfXis real-valued andcdimis integer thenXwill be treated as complex-valued, in this case,cdimspecifies the complex axis; otherwise (None),Xwill be treated as real-valuedkeepdim (bool, optional) – keep dimensions? (include complex dim, defalut is
False) (only work when the dimension atcdimequals 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|\).
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:
- 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
Xis complex-valued,cdimis ignored. IfXis real-valued andcdimis integer thenXwill be treated as complex-valued, in this case,cdimspecifies the complex axis; otherwise (None),Xwill be treated as real-valuedkeepdim (bool, optional) – keep dimensions? (include complex dim, defalut is
False) (only work when the dimension atcdimequals 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) –
Truefor N,Falsefor N-1, by defaultFalsecdim (int or None) – If
Xis complex-valued,cdimis ignored. IfXis real-valued andcdimis integer thenXwill be treated as complex-valued, in this case,cdimspecifies the complex axis; otherwise (None),Xwill be treated as real-valueddim (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) –
Truefor N,Falsefor N-1, by defaultFalsecdim (int or None) – If
Xis complex-valued,cdimis ignored. IfXis real-valued andcdimis integer thenXwill be treated as complex-valued, in this case,cdimspecifies the complex axis; otherwise (None),Xwill be treated as real-valueddim (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
nnon-repeated random ints fromstarttostopwith step sizestep.When step is 1 and shake is 0, it works similar to randperm,
- Parameters:
- 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:
: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)
- 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