Array#

class brainpy.math.Array(value, dtype=None)[source]#

Multiple-dimensional array in BrainPy.

Compared to jax.Array, Array has the following advantages:

  • In-place updating is supported.

>>> import brainpy.math as bm
>>> a = bm.asarray([1, 2, 3.])
>>> a[0] = 10.
  • Keep sharding constraints during computation.

  • More dense array operations with PyTorch syntax.

abs_()[source]#

in-place version of Array.abs()

absolute(*, out=None)[source]#

alias of Array.abs

Return type:

Optional[Array]

absolute_()[source]#

alias of Array.abs_()

addr(vec1, vec2, *, beta=1.0, alpha=1.0, out=None)[source]#

Performs the outer-product of vectors vec1 and vec2 and adds it to the matrix input.

Optional values beta and alpha are scaling factors on the outer product between vec1 and vec2 and the added matrix input respectively.

\[out = \beta \mathrm{input} + \alpha (\text{vec1} \bigtimes \text{vec2})\]
Parameters:
  • vec1 (Union[Array, Array, ndarray]) – the first vector of the outer product

  • vec2 (Union[Array, Array, ndarray]) – the second vector of the outer product

  • beta (float) – multiplier for input

  • alpha (float) – multiplier

  • out (Union[Array, Array, ndarray, None]) – the output tensor.

Return type:

Optional[Array]

all(axis=None, keepdims=False)[source]#

Returns True if all elements evaluate to True.

any(axis=None, keepdims=False)[source]#

Returns True if any of the elements of a evaluate to True.

argmax(axis=None)[source]#

Return indices of the maximum values along the given axis.

argmin(axis=None)[source]#

Return indices of the minimum values along the given axis.

argpartition(kth, axis=-1, kind='introselect', order=None)[source]#

Returns the indices that would partition this array.

argsort(axis=-1, kind=None, order=None)[source]#

Returns the indices that would sort this array.

as_variable()[source]#

As an instance of Variable.

astype(dtype)[source]#

Copy of the array, cast to a specified type.

Parameters:

dtype (str, dtype) – Typecode or data-type to which the array is cast.

byteswap(inplace=False)[source]#

Swap the bytes of the array elements

Toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Arrays of byte-strings are not swapped. The real and imaginary parts of a complex number are swapped individually.

choose(choices, mode='raise')[source]#

Use an index array to construct a new array from a set of choices.

clamp(min_value=None, max_value=None, *, out=None)[source]#

return the value between min_value and max_value, if min_value is None, then no lower bound, if max_value is None, then no upper bound.

Return type:

Optional[Array]

clamp_(min_value=None, max_value=None)[source]#

return the value between min_value and max_value, if min_value is None, then no lower bound, if max_value is None, then no upper bound.

clip(min=None, max=None, out=None)[source]#

Return an array whose values are limited to [min, max]. One of max or min must be given.

clip_(min_value=None, max_value=None)[source]#

alias for clamp_

compress(condition, axis=None)[source]#

Return selected slices of this array along given axis.

conj()[source]#

Complex-conjugate all elements.

conjugate()[source]#

Return the complex conjugate, element-wise.

copy()[source]#

Return a copy of the array.

cumprod(axis=None, dtype=None)[source]#

Return the cumulative product of the elements along the given axis.

cumsum(axis=None, dtype=None)[source]#

Return the cumulative sum of the elements along the given axis.

diagonal(offset=0, axis1=0, axis2=1)[source]#

Return specified diagonals.

dot(b)[source]#

Dot product of two arrays.

property dtype#

Variable dtype.

expand(*sizes)[source]#

Expand an array to a new shape.

Parameters:

sizes (tuple or int) – The shape of the desired array. A single integer i is interpreted as (i,).

Returns:

expanded – A readonly view on the original array with the given shape. It is typically not contiguous. Furthermore, more than one element of a expanded array may refer to a single memory location.

Return type:

Array

expand_as(array)[source]#

Expand an array to a shape of another array.

Parameters:

array (Array) –

Returns:

expanded – A readonly view on the original array with the given shape of array. It is typically not contiguous. Furthermore, more than one element of a expanded array may refer to a single memory location.

Return type:

Array

expand_dims(axis)[source]#

1. 如果axis类型为int: 返回一个在self基础上的第axis维度前插入一个维度Array, axis<0表示倒数第|axis|维度, 令n=len(self._value.shape),则axis的范围为[-(n+1),n]

2. 如果axis类型为Sequence[int]: 则返回依次扩展axis[i]的结果, 即self.expand_dims(axis)==self.expand_dims(axis[0]).expand_dims(axis[1])…expand_dims(axis[len(axis)-1])

Return type:

Array

  1. If the type of axis is int:

Returns an Array of dimensions inserted before the axis dimension based on self,

The first | axis < 0 indicates the bottom axis | dimensions,

Set n=len(self._value.shape), then axis has the range [-(n+1),n]

  1. If the type of axis is Sequence[int] :

Returns the result of extending axis[i] in sequence,

self.expand_dims(axis)==self.expand_dims(axis[0]).expand_dims(axis[1])… expand_dims(axis[len(axis)-1])

fill(value)[source]#

Fill the array with a scalar value.

item(*args)[source]#

Copy an element of an array to a standard Python scalar and return it.

log_normal_(mean=1, std=2)[source]#

Fills self tensor with numbers samples from the log-normal distribution parameterized by the given mean \(\mu\) and standard deviation \(\sigma\). Note that mean and std are the mean and standard deviation of the underlying normal distribution, and not of the returned distribution:

\[f(x)=\frac{1}{x \sigma \sqrt{2 \pi}} e^{-\frac{(\ln x-\mu)^2}{2 \sigma^2}}\]
Parameters:
  • mean – the mean value.

  • std – the standard deviation.

max(axis=None, keepdims=False, *args, **kwargs)[source]#

Return the maximum along a given axis.

mean(axis=None, dtype=None, keepdims=False, *args, **kwargs)[source]#

Returns the average of the array elements along given axis.

min(axis=None, keepdims=False, *args, **kwargs)[source]#

Return the minimum along a given axis.

mul_(value)[source]#

In-place version of mul().

multiply(value) Tensor[source]#

See torch.multiply().

multiply_(value) Tensor[source]#

In-place version of multiply().

nonzero()[source]#

Return the indices of the elements that are non-zero.

normal_()[source]#

Fills self tensor with elements samples from the normal distribution parameterized by mean and std.

numpy(dtype=None)[source]#

Convert to numpy.ndarray.

prod(axis=None, dtype=None, keepdims=False, initial=1, where=True)[source]#

Return the product of the array elements over the given axis.

ptp(axis=None, keepdims=False)[source]#

Peak to peak (maximum - minimum) value along a given axis.

put(indices, values)[source]#

Replaces specified elements of an array with given values.

Parameters:
  • indices (array_like) – Target indices, interpreted as integers.

  • values (array_like) – Values to place in the array at target indices.

ravel(order=None)[source]#

Return a flattened array.

repeat(repeats, axis=None)[source]#

Repeat elements of an array.

reshape(*shape, order='C')[source]#

Returns an array containing the same data with a new shape.

resize(new_shape)[source]#

Change shape and size of array in-place.

round(decimals=0)[source]#

Return a with each element rounded to the given number of decimals.

searchsorted(v, side='left', sorter=None)[source]#

Find indices where elements should be inserted to maintain order.

Find the indices into a sorted array a such that, if the corresponding elements in v were inserted before the indices, the order of a would be preserved.

Assuming that a is sorted:

side

returned index i satisfies

left

a[i-1] < v <= a[i]

right

a[i-1] <= v < a[i]

Parameters:
  • v (array_like) – Values to insert into a.

  • side ({'left', 'right'}, optional) – If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of a).

  • sorter (1-D array_like, optional) – Optional array of integer indices that sort array a into ascending order. They are typically the result of argsort.

Returns:

indices – Array of insertion points with the same shape as v.

Return type:

array of ints

property shape#

Variable shape.

sort(axis=-1, kind='quicksort', order=None)[source]#

Sort an array in-place.

Parameters:
  • axis (int, optional) – Axis along which to sort. Default is -1, which means sort along the last axis.

  • kind ({'quicksort', 'mergesort', 'heapsort', 'stable'}) – Sorting algorithm. The default is ‘quicksort’. Note that both ‘stable’ and ‘mergesort’ use timsort under the covers and, in general, the actual implementation will vary with datatype. The ‘mergesort’ option is retained for backwards compatibility.

  • order (str or list of str, optional) – When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.

split(indices_or_sections, axis=0)[source]#

Split an array into multiple sub-arrays as views into ary.

Parameters:
  • indices_or_sections (int, 1-D array) –

    If indices_or_sections is an integer, N, the array will be divided into N equal arrays along axis. If such a split is not possible, an error is raised.

    If indices_or_sections is a 1-D array of sorted integers, the entries indicate where along axis the array is split. For example, [2, 3] would, for axis=0, result in

    • ary[:2]

    • ary[2:3]

    • ary[3:]

    If an index exceeds the dimension of the array along axis, an empty sub-array is returned correspondingly.

  • axis (int, optional) – The axis along which to split, default is 0.

Returns:

sub-arrays – A list of sub-arrays as views into ary.

Return type:

list of ndarrays

squeeze(axis=None)[source]#

Remove axes of length one from a.

std(axis=None, dtype=None, ddof=0, keepdims=False)[source]#

Compute the standard deviation along the specified axis.

Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

Parameters:
  • axis (None or int or tuple of ints, optional) – Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array. If this is a tuple of ints, a standard deviation is performed over multiple axes, instead of a single axis or all the axes as before.

  • dtype (dtype, optional) – Type to use in computing the standard deviation. For arrays of integer type the default is float64, for arrays of float types it is the same as the array type.

  • ddof (int, optional) – Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

  • keepdims (bool, optional) –

    If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

    If the default value is passed, then keepdims will not be passed through to the std method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.

Returns:

standard_deviation – If out is None, return a new array containing the standard deviation, otherwise return a reference to the output array.

Return type:

ndarray, see dtype parameter above.

sum(axis=None, dtype=None, keepdims=False, initial=0, where=True)[source]#

Return the sum of the array elements over the given axis.

swapaxes(axis1, axis2)[source]#

Return a view of the array with axis1 and axis2 interchanged.

take(indices, axis=None, mode=None)[source]#

Return an array formed from the elements of a at the given indices.

tile(reps)[source]#

Construct an array by repeating A the number of times given by reps.

If reps has length d, the result will have dimension of max(d, A.ndim).

If A.ndim < d, A is promoted to be d-dimensional by prepending new axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication, or shape (1, 1, 3) for 3-D replication. If this is not the desired behavior, promote A to d-dimensions manually before calling this function.

If A.ndim > d, reps is promoted to A.ndim by pre-pending 1’s to it. Thus for an A of shape (2, 3, 4, 5), a reps of (2, 2) is treated as (1, 1, 2, 2).

Note : Although tile may be used for broadcasting, it is strongly recommended to use numpy’s broadcasting operations and functions.

Parameters:

reps (array_like) – The number of repetitions of A along each axis.

Returns:

c – The tiled output array.

Return type:

ndarray

to_jax(dtype=None)[source]#

Convert to jax.numpy.ndarray.

to_numpy(dtype=None)[source]#

Convert to numpy.ndarray.

tobytes()[source]#

Construct Python bytes containing the raw data bytes in the array.

Constructs Python bytes showing a copy of the raw contents of data memory. The bytes object is produced in C-order by default. This behavior is controlled by the order parameter.

tolist()[source]#

Return the array as an a.ndim-levels deep nested list of Python scalars.

Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible builtin Python type, via the ~numpy.ndarray.item function.

If a.ndim is 0, then since the depth of the nested list is 0, it will not be a list at all, but a simple Python scalar.

trace(offset=0, axis1=0, axis2=1, dtype=None)[source]#

Return the sum along diagonals of the array.

transpose(*axes)[source]#

Returns a view of the array with axes transposed.

For a 1-D array this has no effect, as a transposed vector is simply the same vector. To convert a 1-D array into a 2D column vector, an additional dimension must be added. np.atleast2d(a).T achieves this, as does a[:, np.newaxis]. For a 2-D array, this is a standard matrix transpose. For an n-D array, if axes are given, their order indicates how the axes are permuted (see Examples). If axes are not provided and a.shape = (i[0], i[1], ... i[n-2], i[n-1]), then a.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0]).

Parameters:

axes (None, tuple of ints, or n ints) –

  • None or no argument: reverses the order of the axes.

  • tuple of ints: i in the j-th place in the tuple means a’s i-th axis becomes a.transpose()’s j-th axis.

  • n ints: same as an n-tuple of the same ints (this form is intended simply as a “convenience” alternative to the tuple form)

Returns:

out – View of a, with axes suitably permuted.

Return type:

ndarray

unsqueeze(dim)[source]#

equals Array.expand_dims(dim)

See brainpy.math.unsqueeze()

Return type:

Array

update(value)[source]#

Update the value of this Array.

var(axis=None, dtype=None, ddof=0, keepdims=False)[source]#

Returns the variance of the array elements, along given axis.

view(*args, dtype=None)[source]#

New view of array with the same data.

This function is compatible with pytorch syntax.

Returns a new tensor with the same data as the self tensor but of a different shape.

The returned tensor shares the same data and must have the same number of elements, but may have a different size. For a tensor to be viewed, the new view size must be compatible with its original size and stride, i.e., each new view dimension must either be a subspace of an original dimension, or only span across original dimensions \(d, d+1, \dots, d+k\) that satisfy the following contiguity-like condition that \(\forall i = d, \dots, d+k-1\),

\[\text{stride}[i] = \text{stride}[i+1] \times \text{size}[i+1]\]

Otherwise, it will not be possible to view self tensor as shape without copying it (e.g., via contiguous()). When it is unclear whether a view() can be performed, it is advisable to use reshape(), which returns a view if the shapes are compatible, and copies (equivalent to calling contiguous()) otherwise.

Parameters:

shape (int...) – the desired size

Example:

 >>> x = brainpy.math.random.randn(4, 4)
 >>> x.size
[4, 4]
 >>> y = x.view(16)
 >>> y.size
 [16]
 >>> z = x.view(-1, 8)  # the size -1 is inferred from other dimensions
 >>> z.size
 [2, 8]

 >>> a = brainpy.math.random.randn(1, 2, 3, 4)
 >>> a.size
 [1, 2, 3, 4]
 >>> b = a.transpose(1, 2)  # Swaps 2nd and 3rd dimension
 >>> b.size
 [1, 3, 2, 4]
 >>> c = a.view(1, 3, 2, 4)  # Does not change tensor layout in memory
 >>> c.size
 [1, 3, 2, 4]
 >>> brainpy.math.equal(b, c)
 False
view(dtype) Tensor[source]

Returns a new tensor with the same data as the self tensor but of a different dtype.

If the element size of dtype is different than that of self.dtype, then the size of the last dimension of the output will be scaled proportionally. For instance, if dtype element size is twice that of self.dtype, then each pair of elements in the last dimension of self will be combined, and the size of the last dimension of the output will be half that of self. If dtype element size is half that of self.dtype, then each element in the last dimension of self will be split in two, and the size of the last dimension of the output will be double that of self. For this to be possible, the following conditions must be true:

  • self.dim() must be greater than 0.

  • self.stride(-1) must be 1.

Additionally, if the element size of dtype is greater than that of self.dtype, the following conditions must be true as well:

  • self.size(-1) must be divisible by the ratio between the element sizes of the dtypes.

  • self.storage_offset() must be divisible by the ratio between the element sizes of the dtypes.

  • The strides of all dimensions, except the last dimension, must be divisible by the ratio between the element sizes of the dtypes.

If any of the above conditions are not met, an error is thrown.

Parameters:

dtype (dtype) – the desired dtype

Example:

>>> x = brainpy.math.random.randn(4, 4)
>>> x
Array([[ 0.9482, -0.0310,  1.4999, -0.5316],
        [-0.1520,  0.7472,  0.5617, -0.8649],
        [-2.4724, -0.0334, -0.2976, -0.8499],
        [-0.2109,  1.9913, -0.9607, -0.6123]])
>>> x.dtype
brainpy.math.float32

>>> y = x.view(brainpy.math.int32)
>>> y
tensor([[ 1064483442, -1124191867,  1069546515, -1089989247],
        [-1105482831,  1061112040,  1057999968, -1084397505],
        [-1071760287, -1123489973, -1097310419, -1084649136],
        [-1101533110,  1073668768, -1082790149, -1088634448]],
    dtype=brainpy.math.int32)
>>> y[0, 0] = 1000000000
>>> x
tensor([[ 0.0047, -0.0310,  1.4999, -0.5316],
        [-0.1520,  0.7472,  0.5617, -0.8649],
        [-2.4724, -0.0334, -0.2976, -0.8499],
        [-0.2109,  1.9913, -0.9607, -0.6123]])

>>> x.view(brainpy.math.cfloat)
tensor([[ 0.0047-0.0310j,  1.4999-0.5316j],
        [-0.1520+0.7472j,  0.5617-0.8649j],
        [-2.4724-0.0334j, -0.2976-0.8499j],
        [-0.2109+1.9913j, -0.9607-0.6123j]])
>>> x.view(brainpy.math.cfloat).size
[4, 2]

>>> x.view(brainpy.math.uint8)
tensor([[  0, 202, 154,  59, 182, 243, 253, 188, 185, 252, 191,  63, 240,  22,
           8, 191],
        [227, 165,  27, 190, 128,  72,  63,  63, 146, 203,  15,  63,  22, 106,
          93, 191],
        [205,  59,  30, 192, 112, 206,   8, 189,   7,  95, 152, 190,  12, 147,
          89, 191],
        [ 43, 246,  87, 190, 235, 226, 254,  63, 111, 240, 117, 191, 177, 191,
          28, 191]], dtype=brainpy.math.uint8)
>>> x.view(brainpy.math.uint8).size
[4, 16]