numpy — numpy-compatible array operations
The numpy submodule of ulab provides a numpy-compatible API built
around the ndarray n-dimensional array type. It
implements a curated subset of CPython numpy: array construction,
element-wise math, reductions and statistics, linear algebra, FFTs,
random number generation, polynomial fitting, and basic I/O.
The submodule is conventionally imported as np:
from ulab import numpy as np
a = np.array([1, 2, 3, 4], dtype=np.float)
b = np.linspace(0, 1, num=5)
c = np.dot(a.reshape((2, 2)), a.reshape((2, 2)))
Each dtype argument is one of the integer constants exposed at module
level: numpy.bool, numpy.uint8, numpy.int8, numpy.uint16,
numpy.int16, numpy.float (the default), and (when complex support is
compiled in) numpy.complex. The result type ndarray refers to
numpy.ndarray.
Submodules
class ndarray — the n-dimensional array
The ndarray is the n-dimensional, dtype-aware container at the core
of numpy / ulab. The data is stored in a
contiguous block whose interpretation is described by a small header
(dtype, shape, strides, ndim, itemsize). Many
operations – reshape, transpose, slicing – only adjust this
header and so are very cheap; methods that allocate new storage
(copy, flatten, most arithmetic) return a new dense array.
The same type is reachable as ulab.ndarray,
numpy.ndarray, and (within this page) simply ndarray.
- class numpy.ndarray(values: ndarray | bytes | list | tuple, *, dtype: int = numpy.float)
Create a new
ndarray.- Parameters:
values – Source data. Either another
ndarray(which is deep-copied, with type conversion ifdtypediffers) or any MicroPython iterable. Nested iterables produce multi-dimensional arrays; the inner iterables must all have the same length or aValueErroris raised.dtype – Element type for the new array. One of the type-code integers exposed by
numpy(numpy.bool,numpy.uint8,numpy.int8,numpy.uint16,numpy.int16,numpy.float, and – when supported –numpy.complex), or adtypeinstance. Defaults tonumpy.float.
The factory function
numpy.arrayis the conventional way to create anndarray; it forwards to this constructor.- byteswap(*, inplace: bool = False) ndarray
Swap the byte order of every element. For
uint16,int16,floatandcomplexarrays this reverses the per-element byte order, which is useful when consuming data from peripherals whose endianness does not match the microcontroller’s. For single-byte dtypes (bool,uint8,int8) this is a no-op that returns a view or copy.If
inplaceisFalse(the default) a newndarrayis returned and the original is left untouched. IfinplaceisTruethe bytes ofselfare swapped in place and a view ofselfis returned.
- copy() ndarray
Return a new dense, deep copy of the array. The copy owns its own data; modifications to it do not affect the original.
- flatten(*, order: str = 'C') ndarray
Return a new one-dimensional copy of the array.
- Parameters:
order –
'C'(the default) walks the data in C order (last axis varies fastest);'F'walks it in Fortran order (first axis varies fastest).
- reshape(shape: int | tuple[int, ...]) ndarray
Return a view of the array with a new shape. The total number of elements must be unchanged or a
ValueErroris raised. Only available whenULAB_MAX_DIMS > 1. Equivalent to assigning toshape.
- sort(*, axis: int | None = -1) None
Sort the array in place.
- Parameters:
axis – Axis along which to sort.
-1(the default) sorts along the last axis;Nonefirst flattens the array and then sorts.
- tobytes() bytearray
Return a
bytearraythat aliases the array’s underlying data buffer. Writes through the returnedbytearraymodify the array in place. RaisesValueErrorif the array is not dense (e.g. a sliced view).
- tolist() list
Return the contents of the array as a (possibly nested) Python
list. The nesting depth equalsndim.
- transpose() ndarray
Return the transpose of the array (axes reversed). For one-dimensional arrays this returns
self. Only available whenULAB_MAX_DIMS > 1. TheTattribute is a shorthand for this method.
- dtype: dtype | int
The data type of the array’s elements. Returns a
dtypeinstance when the firmware is built withULAB_HAS_DTYPE_OBJECTenabled, otherwise the underlying single-character type code as an integer.
- flat: flatiter
A flat iterator that yields every element of the array in C order. Unlike
flatten(), iteratingflatdoes not allocate a new array.
- shape: tuple[int, ...]
Lengths of the array along each axis. Assigning a tuple to
shapereshapes the array in place (equivalent toreshape()).
- strides: tuple[int, ...]
Number of bytes to step in memory along each axis to reach the next element along that axis.
- T: ndarray
The transpose of the array; equivalent to
transpose().
Supported operators
ndarray instances support the following operators. Binary operators
broadcast their operands following standard numpy broadcasting rules
and follow numpy’s upcasting rules (e.g. uint8 + int8 => int16,
uint16 + int16 => float); operations involving a complex operand
produce a complex result.
Arithmetic (binary): +, -, *, /, //, %, **.
Reflected (right-hand) operands and the in-place variants
+=, -=, *=, /=, %=, **= are also supported. Both
ndarray-with-ndarray and ndarray-with-scalar forms are
accepted. Floor division (//) and the modulo operator (%) are
not implemented for complex arrays.
Comparison: ==, !=, <, <=, >, >=. Each
returns a boolean ndarray of the broadcast shape.
Bitwise (integer arrays only): &, |, ^. Applying
these to a float or complex array raises TypeError.
Unary: + (returns a copy), - (negation; on unsigned
dtypes the values wrap modulo \(2^N\)), abs() (element-wise
absolute value; on unsigned dtypes returns a copy without
computation), ~ (bitwise inversion, integer dtypes only),
len() (returns the length of the first axis).
Indexing and slicing: a[i], a[i, j, ...], a[start:stop:step],
boolean-mask indexing (a[mask]) and integer-array (fancy)
indexing are all supported on both reads and writes.
Iteration: Iterating over an ndarray yields sub-arrays along
the first axis (one element at a time for 1-D arrays). Use
flat to iterate over every scalar element regardless of
dimensionality.
The matrix-multiplication operator @ is not implemented; use
numpy.dot (np.dot(a, b)) instead.
The shift (<<, >>) operators are not implemented at the
operator level. Use numpy.left_shift and numpy.right_shift for
element-wise integer shifts.
Array construction
- numpy.array(values: ndarray | list | tuple, *, dtype: int = float) ndarray
Construct a new
ndarrayfrom a nested iterable of numbers. Equivalent alternate constructor fornumpy.ndarray.
- numpy.arange(start: int | float, stop: int | float = ..., step: int | float = 1, *, dtype: int | None = None) ndarray
Return evenly spaced values over the half-open interval
[start, stop). If only one positional argument is given, it is treated asstopwithstart = 0. If dtype is omitted, it is inferred from the inputs (integer if all of start, stop, step are ints and within range).
- numpy.asarray(a: ndarray | list | tuple, *, dtype: int | None = None) ndarray
If a is already an
ndarraywhose dtype matches dtype (or dtype isNone), return a unchanged; otherwise create a new array (with the requested dtype conversion when given). Iterables are converted as innumpy.array.
- numpy.concatenate(arrays: tuple, *, axis: int = 0) ndarray
Join a sequence of
ndarrayalong an existing axis. All input arrays must share the same dtype, ndim, and shape on every axis other than axis.
- numpy.diag(a: ndarray, *, k: int = 0) ndarray
For a 2-D a, return a 1-D array containing the k-th diagonal. For a 1-D a, return a 2-D square array with a placed on the k-th diagonal. k may be positive (above main diagonal) or negative (below).
- numpy.empty(shape: int | tuple[int, ...], *, dtype: int = float) ndarray
Alias for
zeros; returns a zero-filled array of shape and dtype. (ulab does not leave the buffer uninitialised.)
- numpy.eye(N: int, M: int | None = None, k: int = 0, *, dtype: int = float) ndarray
Return a 2-D N x M array (square N x N if M is
None) with ones on the k-th diagonal and zeros elsewhere.
- numpy.frombuffer(buffer: bytes, *, dtype: int = float, count: int = -1, offset: int = 0) ndarray
Interpret a buffer-protocol object as a 1-D
ndarrayof dtype. count is the number of items to read (-1reads all available items); offset skips that many bytes at the start of the buffer.
- numpy.full(shape: int | tuple[int, ...], fill_value: int | float | bool, *, dtype: int = float) ndarray
Return a new array of shape and dtype with every element set to fill_value.
- numpy.linspace(start: float, stop: float, num: int = 50, *, endpoint: bool = True, retstep: bool = False, dtype: int = float) ndarray | tuple[ndarray, float]
Return num evenly spaced samples over the closed interval
[start, stop](or half-open if endpoint isFalse). When retstep isTrue, return a tuple(samples, step). Complex start/stop produce a complex array (when complex support is enabled).
- numpy.logspace(start: float, stop: float, num: int = 50, *, base: float = 10.0, endpoint: bool = True, dtype: int = float) ndarray
Return num samples spaced evenly on a log scale: the result starts at
base ** startand ends atbase ** stop.
- numpy.meshgrid(*xi: ndarray, indexing: str = 'xy') tuple[ndarray, ...]
Return a tuple of coordinate matrices from a sequence of one-dimensional coordinate arrays. With indexing
'xy'(the default) the first two inputs are treated as Cartesian coordinates and their output axes are swapped; with'ij'matrix-style indexing is used. The implementation corresponds to the NumPy equivalent withcopy=Trueandsparse=False.
Inspection / printing
- numpy.get_printoptions() dict
Return the current array printing options as a dict with keys
thresholdandedgeitems.
- numpy.set_printoptions(*, threshold: int | None = None, edgeitems: int | None = None) None
Set array printing options. threshold is the maximum number of array elements printed in full; edgeitems is the number of items shown at each end of an axis when the array is summarised.
Comparison
- numpy.clip(a: ndarray | int | float, a_min: ndarray | int | float, a_max: ndarray | int | float) ndarray | int | float
Clip the values of a so that
a_min <= result <= a_max. Equivalent tomaximum(a_min, minimum(a, a_max)); broadcasting follows the same rules asminimum.
- numpy.equal(x1: ndarray | int | float, x2: ndarray | int | float) ndarray | bool
Element-wise
x1 == x2; returns a booleanndarray(or aboolscalar if both inputs are scalars). Provided for portability – the==operator on arrays gives the same result.
- numpy.not_equal(x1: ndarray | int | float, x2: ndarray | int | float) ndarray | bool
Element-wise
x1 != x2; the boolean counterpart toequal.
- numpy.isfinite(x: ndarray | int | float) ndarray | bool
Return a boolean array (or scalar) that is
Truewhere the input is finite. Integer inputs are always finite.
- numpy.isinf(x: ndarray | int | float) ndarray | bool
Return a boolean array (or scalar) that is
Truewhere the input is infinite. Integer inputs are never infinite.
- numpy.maximum(x1: ndarray | int | float, x2: ndarray | int | float) ndarray | int | float
Element-wise maximum of two arrays / scalars. The arguments are broadcast together; if dtypes differ, the output is upcast.
- numpy.minimum(x1: ndarray | int | float, x2: ndarray | int | float) ndarray | int | float
Element-wise minimum of two arrays / scalars; counterpart to
maximum.
Numerical reductions
- numpy.all(a: ndarray | list | tuple, *, axis: int | None = None) ndarray | bool
Test whether all elements along axis evaluate to
True. Withaxis=None(the default) the flattened array is tested and a singleboolis returned.
- numpy.any(a: ndarray | list | tuple, *, axis: int | None = None) ndarray | bool
Test whether any element along axis evaluates to
True. Withaxis=Nonethe flattened array is tested.
- numpy.argmax(a: ndarray | list | tuple, *, axis: int | None = None) ndarray | int
Return the index of the maximum element along axis. With
axis=Nonethe array is flattened and a single integer is returned.
- numpy.argmin(a: ndarray | list | tuple, *, axis: int | None = None) ndarray | int
Return the index of the minimum element along axis. With
axis=Nonethe array is flattened and a single integer is returned.
- numpy.argsort(a: ndarray, *, axis: int = -1) ndarray
Return an unsigned integer index
ndarraywhose entries sort a in ascending order along axis. The output dtype isuint16, so no axis may exceed 65535 elements.axis=Noneis not supported.
- numpy.cross(a: ndarray, b: ndarray) ndarray
Return the cross product of two 1-D arrays of length 3.
- numpy.diff(a: ndarray, *, n: int = 1, axis: int = -1) ndarray
Return the n-th discrete forward difference of a along axis. n must be in
0..9(the differentiation stencil is stored in anint8); the length of axis shrinks by n. The numpyprependandappendkeywords are not implemented.
- numpy.flip(a: ndarray, *, axis: int | None = None) ndarray
Return a new array with the order of elements reversed along axis; with
axis=Nonethe array is reversed along every axis.
- numpy.max(a: ndarray | list | tuple, *, axis: int | None = None, keepdims: bool = False) ndarray | int | float
Return the maximum element along axis. With
axis=None(the default) the flattened array is reduced to a scalar. The numpyoutkeyword is not implemented.
- numpy.min(a: ndarray | list | tuple, *, axis: int | None = None, keepdims: bool = False) ndarray | int | float
Return the minimum element along axis; counterpart to
max.
- numpy.mean(a: ndarray | list | tuple, *, axis: int | None = None, keepdims: bool = False) ndarray | float
Return the arithmetic mean along axis. With
axis=None(the default) the flattened array’s mean is returned as afloat.
- numpy.median(a: ndarray, *, axis: int | None = None) ndarray | float
Return the median along axis. With
axis=Nonethe array is flattened first. The output dtype is always float.
- numpy.roll(a: ndarray, shift: int, *, axis: int | None = None) ndarray
Return a with its elements rolled (cyclically shifted) by shift positions. With
axis=None(the default) the array is flattened first. Negative shifts roll in the opposite direction.
- numpy.sort(a: ndarray, *, axis: int = -1) ndarray
Return a sorted copy of a along axis using heap sort. With
axis=Nonethe array is flattened first. The numpykindandorderkeywords are not implemented.
Statistics
- numpy.bincount(x: ndarray, *, weights: ndarray | None = None, minlength: int | None = None) ndarray
Count the number of occurrences of each value in the one-dimensional, non-negative integer array x. The x dtype must be
uint8oruint16. If weights is given, each entry of x contributes its matching weight rather than1and the output is of dtypefloat; otherwise the output is of dtypeuint16. If minlength is given, the output array has at least that many elements (extra entries are zero).
Transform
- numpy.compress(condition: ndarray | list | tuple, a: ndarray, *, axis: int | None = None) ndarray
Return slices of a selected along axis by the boolean condition. With
axis=Nonethe flattened array is used.
- numpy.delete(a: ndarray, indices: int | ndarray | list | tuple | range, *, axis: int | None = None) ndarray
Return a copy of a with the entries at indices removed along axis. With
axis=Nonethe array is flattened first. Negative indices count from the end of axis; indices is sorted internally before deletion.
Approximation
- numpy.interp(x: ndarray, xp: ndarray, fp: ndarray, *, left: float | None = None, right: float | None = None) ndarray
One-dimensional linear interpolation. xp must be a monotonically increasing 1-D array of independent values; fp contains the corresponding dependent values; x are the points at which the interpolant is evaluated. left and right override the value returned for
x < xp[0]andx > xp[-1]respectively (defaults:fp[0]andfp[-1]).
Selection
- numpy.take(a: ndarray, indices: ndarray | list | tuple, *, axis: int | None = None, out: ndarray | None = None, mode: str | None = None) ndarray
Take elements from a at the given indices along axis. With
axis=Nonethe flattened array is used. mode selects the out-of-bounds behaviour:"raise"(default – raiseValueError),"wrap"(modulo the axis length), or"clip"(clip to the valid range; negative indices are not allowed). If out is given the result is written into it.
Bitwise
- numpy.bitwise_and(x1: ndarray, x2: ndarray) ndarray
Element-wise bitwise AND of two integer arrays; broadcasting is supported. A non-integer dtype raises an exception.
- numpy.bitwise_xor(x1: ndarray, x2: ndarray) ndarray
Element-wise bitwise XOR of two integer arrays.
Filtering
Polynomial
I/O
- numpy.load(file: str) ndarray
Read an array previously written with
savefrom file (numpy’s platform-independent.npyformat). Endianness is converted on the fly if the file’s byte order differs from the host’s.
- numpy.loadtxt(file: str, *, delimiter: str | None = None, comments: str = '#', max_rows: int = -1, usecols: int | ndarray | list | tuple | None = None, dtype: int = float, skiprows: int = 0) ndarray
Read numeric data from a text file and return it as an
ndarray. delimiter defaults to whitespace; comments is the line-comment marker; max_rows limits the number of data rows read (-1for all); usecols selects columns by index; skiprows skips that many leading rows. If dtype is not float, values are converted by rounding.
- numpy.savetxt(file: str, a: ndarray, *, delimiter: str = ' ', header: str | None = None, footer: str | None = None, comments: str = '# ') None
Write a to file as text. delimiter separates values within a row; header and footer, if provided, are written before/after the data, each prefixed by comments. Values are written as floating point.
Complex helpers
These functions are only available when ulab was compiled with complex
support (ULAB_SUPPORTS_COMPLEX).
- numpy.real(val: ndarray) ndarray
Return the real part of val. For a real-dtype input, returns a copy preserving the dtype; for a complex input, returns a float
ndarray.
- numpy.imag(val: ndarray) ndarray
Return the imaginary part of val. For a real-dtype input, returns an array of zeros with the same dtype; for a complex input, returns a float
ndarray.
Universal functions
Element-wise math functions. Each accepts a scalar or an ndarray and returns
a result of matching shape (a float scalar for scalar input, an ndarray for
array input). When called with an ndarray, the result is a new floating
point ndarray; an optional out keyword may be passed to write the result
into a pre-allocated float ndarray of the same size.
- numpy.acos(x: ndarray | float, /) ndarray | float
Compute the inverse cosine (arc cosine) of each element of x; result is in radians.
- numpy.acosh(x: ndarray | float, /) ndarray | float
Compute the inverse hyperbolic cosine of each element of x.
- numpy.arctan2(y: ndarray | float, x: ndarray | float, /) ndarray | float
Compute the two-argument inverse tangent
atan2(y, x)element-wise; supports broadcasting between the two inputs.
- numpy.around(x: ndarray, /, decimals: int = 0) ndarray
Round the elements of the
ndarrayx to the given number of decimals; the first argument must be anndarray.
- numpy.asin(x: ndarray | float, /) ndarray | float
Compute the inverse sine (arc sine) of each element of x; result is in radians.
- numpy.asinh(x: ndarray | float, /) ndarray | float
Compute the inverse hyperbolic sine of each element of x.
- numpy.atan(x: ndarray | float, /) ndarray | float
Compute the inverse tangent (arc tangent) of each element of x; result is in radians.
- numpy.atanh(x: ndarray | float, /) ndarray | float
Compute the inverse hyperbolic tangent of each element of x.
- numpy.ceil(x: ndarray | float, /) ndarray | float
Compute the ceiling (smallest integer not less than the value) of each element of x.
- numpy.cos(x: ndarray | float, /) ndarray | float
Compute the cosine of each element of x (in radians).
- numpy.cosh(x: ndarray | float, /) ndarray | float
Compute the hyperbolic cosine of each element of x.
- numpy.degrees(x: ndarray | float, /) ndarray | float
Convert each element of x from radians to degrees.
- numpy.exp(x: ndarray | float, /) ndarray | float
Compute the exponential
e**xof each element of x; may return a complexndarraywhen given complex input (if complex support is enabled).
- numpy.expm1(x: ndarray | float, /) ndarray | float
Compute
exp(x) - 1of each element of x with improved precision near zero.
- numpy.floor(x: ndarray | float, /) ndarray | float
Compute the floor (largest integer not greater than the value) of each element of x.
- numpy.log(x: ndarray | float, /) ndarray | float
Compute the natural logarithm of each element of x.
- numpy.log10(x: ndarray | float, /) ndarray | float
Compute the base-10 logarithm of each element of x.
- numpy.log2(x: ndarray | float, /) ndarray | float
Compute the base-2 logarithm of each element of x.
- numpy.radians(x: ndarray | float, /) ndarray | float
Convert each element of x from degrees to radians.
- numpy.sin(x: ndarray | float, /) ndarray | float
Compute the sine of each element of x (in radians).
- numpy.sinc(x: ndarray | float, /) ndarray | float
Compute the normalized sinc function
sin(pi*x) / (pi*x)of each element of x.
- numpy.sinh(x: ndarray | float, /) ndarray | float
Compute the hyperbolic sine of each element of x.
- numpy.sqrt(x: ndarray | float, /, *, dtype: int = float) ndarray | float
Compute the square root of each element of x; pass
dtype=numpy.complexto obtain complex results for negative real inputs (if complex support is enabled).
- numpy.tan(x: ndarray | float, /) ndarray | float
Compute the tangent of each element of x (in radians).
Constants
- numpy.bool: int
ulab.dtypecode for boolean arrays (stored asuint8).
- numpy.uint8: int
ulab.dtypecode for unsigned 8-bit integer arrays.
- numpy.int8: int
ulab.dtypecode for signed 8-bit integer arrays.
- numpy.uint16: int
ulab.dtypecode for unsigned 16-bit integer arrays.
- numpy.int16: int
ulab.dtypecode for signed 16-bit integer arrays.
- numpy.float: int
ulab.dtypecode for floating-point arrays. Element width is either 32 bits or 64 bits depending on how MicroPython was built.
- numpy.complex: int
ulab.dtypecode for complex arrays. Only available when the firmware was built withULAB_SUPPORTS_COMPLEXenabled. Complex elements pack twofloatvalues (real, imaginary).