Introduction to numerics
The numerics package provides NumPy-like numerical computing for Maxima. It wraps BLAS and LAPACK via the magicl library, giving Maxima users access to fast dense linear algebra, element-wise array operations, and statistical aggregations.
Requirements: SBCL (Steel Bank Common Lisp). Other Lisp implementations are not supported.
Key concepts
ndarray is the central data type – an opaque handle wrapping a dense numeric array. Unlike Maxima matrices, ndarrays:
- Use 0-based indexing (like NumPy, C, and most programming languages)
- Store elements as double-float (64-bit IEEE 754)
- Use column-major memory layout for BLAS compatibility
- Are mutable – functions like
np_setmodify the array in place
Quick start
(%i1) load("numerics")$
(%i2) A : ndarray(matrix([1, 2], [3, 4]));
(%o2) ndarray([2, 2], DOUBLE-FLOAT)
(%i3) B : np_inv(A);
(%o3) ndarray([2, 2], DOUBLE-FLOAT)
(%i4) np_to_matrix(np_matmul(A, B));
(%o4) matrix([1.0, 0.0], [0.0, 1.0])
Creating arrays
(%i1) np_zeros([3, 3]);
(%o1) ndarray([3, 3], DOUBLE-FLOAT)
(%i2) np_ones([2, 4]);
(%o2) ndarray([2, 4], DOUBLE-FLOAT)
(%i3) np_arange(5);
(%o3) ndarray([5], DOUBLE-FLOAT)
(%i4) np_linspace(0, 1, 5);
(%o4) ndarray([5], DOUBLE-FLOAT)
Element access
(%i1) A : ndarray(matrix([10, 20, 30], [40, 50, 60]));
(%o1) ndarray([2, 3], DOUBLE-FLOAT)
(%i2) np_ref(A, 0, 2);
(%o2) 30.0
(%i3) np_set(A, 1, 1, 99.0);
(%o3) ndarray([2, 3], DOUBLE-FLOAT)
(%i4) np_ref(A, 1, 1);
(%o4) 99.0
Element-wise operations
All element-wise functions support ndarray-ndarray and ndarray-scalar combinations:
(%i1) A : ndarray(matrix([1, 2], [3, 4]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_add(A, 10);
(%o2) ndarray([2, 2], DOUBLE-FLOAT)
(%i3) np_mul(A, A);
(%o3) ndarray([2, 2], DOUBLE-FLOAT)
(%i4) np_sqrt(A);
(%o4) ndarray([2, 2], DOUBLE-FLOAT)
Linear algebra
(%i1) A : ndarray(matrix([2, 1], [5, 3]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_det(A);
(%o2) 1.0
(%i3) [U, S, Vt] : np_svd(A);
(%o3) [ndarray, ndarray, ndarray]
(%i4) [Q, R] : np_qr(A);
(%o4) [ndarray, ndarray]
Converting back to Maxima
(%i1) A : np_linspace(0, 1, 5);
(%o1) ndarray([5], DOUBLE-FLOAT)
(%i2) np_to_list(A);
(%o2) [0.0, 0.25, 0.5, 0.75, 1.0]
(%i3) M : ndarray(matrix([1, 2], [3, 4]));
(%o3) ndarray([2, 2], DOUBLE-FLOAT)
(%i4) np_to_matrix(M);
(%o4) matrix([1.0, 2.0], [3.0, 4.0])
Definitions for numerics
Conversion
ndarray (a) / ndarray (a, complex) — Function
Convert a Maxima matrix or list to an ndarray.
If a is a Maxima matrix, it is converted element-by-element into a double-float ndarray with column-major layout. If a is a Maxima list, it creates a 1D ndarray unless a shape argument is provided. Pass complex as the last argument to create a complex-double-float array.
If a is already an ndarray, it is returned unchanged.
Calling forms:
ndarray(matrix)– convert a Maxima matrix to a 2D ndarrayndarray(matrix, complex)– convert to a complex 2D ndarrayndarray(list)– convert a flat Maxima list to a 1D ndarrayndarray(list, shape)– convert a list and reshape to the given dimensionsndarray(list, shape, complex)– convert a list to a complex ndarray with shape
The shape argument is a Maxima list of dimensions, e.g. [2, 3]. The total number of elements in the list must match the product of the dimensions.
Elements are filled in row-major order from the list, matching the convention that ndarray([1,2,3,4], [2,2]) produces a matrix with first row [1, 2] and second row [3, 4].
Examples
(%i1) load("numerics")$
(%i2) A : ndarray(matrix([1, 2], [3, 4]));
(%o2) ndarray([2, 2], DOUBLE-FLOAT)
(%i3) np_ref(A, 0, 0);
(%o3) 1.0
(%i4) B : ndarray([1, 2, 3, 4, 5, 6], [2, 3]);
(%o4) ndarray([2, 3], DOUBLE-FLOAT)
(%i5) np_shape(B);
(%o5) [2, 3]
(%i6) C : ndarray([10, 20, 30]);
(%o6) ndarray([3], DOUBLE-FLOAT)
(%i7) D : ndarray(matrix([1+%i, 2-3*%i], [4, 5+%i]), complex);
(%o7) ndarray([2, 2], COMPLEX-DOUBLE-FLOAT)
See also: np_to_matrix, np_to_list, ndarray_p
ndarray_p (x) — Function
Test whether x is an ndarray.
Returns true if x is an ndarray handle, false otherwise.
Examples
(%i1) ndarray_p(np_zeros([2, 2]));
(%o1) true
(%i2) ndarray_p(42);
(%o2) false
(%i3) ndarray_p(matrix([1, 2]));
(%o3) false
See also: ndarray
np_to_matrix (a) — Function
Convert a 2D ndarray back to a Maxima matrix.
The ndarray must be 2-dimensional. For 1D ndarrays, use np_to_list instead, or reshape to 2D first with np_reshape. Complex elements are returned in Maxima form (a + b*%i).
Examples
(%i1) A : ndarray(matrix([1, 2], [3, 4]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_to_matrix(A);
(%o2) matrix([1.0, 2.0], [3.0, 4.0])
(%i3) B : np_eye(3);
(%o3) ndarray([3, 3], DOUBLE-FLOAT)
(%i4) np_to_matrix(B);
(%o4) matrix([1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0])
See also: ndarray, np_to_list, np_reshape
np_to_list (a) — Function
Flatten an ndarray to a Maxima list.
Returns all elements as a flat Maxima list in row-major order (rows first, matching NumPy convention). Works for ndarrays of any dimensionality. Complex elements are returned in Maxima form (a + b*%i).
Round-tripping is consistent: ndarray(list, shape) fills in row-major order, and np_to_list returns elements in row-major order.
Examples
(%i1) A : np_arange(4);
(%o1) ndarray([4], DOUBLE-FLOAT)
(%i2) np_to_list(A);
(%o2) [0.0, 1.0, 2.0, 3.0]
(%i3) B : ndarray(matrix([1, 2], [3, 4]));
(%o3) ndarray([2, 2], DOUBLE-FLOAT)
(%i4) np_to_list(B);
(%o4) [1.0, 2.0, 3.0, 4.0]
See also: ndarray, np_to_matrix, np_flatten
Constructors
np_zeros (shape) / np_zeros (shape, dtype) — Function
Create a zero-filled ndarray.
The shape argument is either an integer (for 1D) or a Maxima list of dimensions (for 2D or higher). Pass complex as the optional second argument to create a complex array.
Examples
(%i1) np_zeros(5);
(%o1) ndarray([5], DOUBLE-FLOAT)
(%i2) np_to_list(np_zeros(3));
(%o2) [0.0, 0.0, 0.0]
(%i3) np_zeros([2, 3]);
(%o3) ndarray([2, 3], DOUBLE-FLOAT)
(%i4) np_ref(np_zeros([2, 2]), 0, 0);
(%o4) 0.0
(%i5) np_zeros([2, 2], complex);
(%o5) ndarray([2, 2], COMPLEX-DOUBLE-FLOAT)
See also: np_ones, np_full, np_empty
np_ones (shape) / np_ones (shape, dtype) — Function
Create an ndarray filled with ones.
The shape argument is either an integer (for 1D) or a Maxima list of dimensions. Pass complex as the optional second argument to create a complex array.
Examples
(%i1) np_ones(4);
(%o1) ndarray([4], DOUBLE-FLOAT)
(%i2) np_to_list(np_ones(3));
(%o2) [1.0, 1.0, 1.0]
(%i3) np_ones([2, 2]);
(%o3) ndarray([2, 2], DOUBLE-FLOAT)
(%i4) np_ref(np_ones([3, 3]), 1, 1);
(%o4) 1.0
(%i5) np_ones([2, 2], complex);
(%o5) ndarray([2, 2], COMPLEX-DOUBLE-FLOAT)
See also: np_zeros, np_full, np_empty
np_eye (n) / np_eye (n, m) / np_eye (n, m, dtype) — Function
Create an identity matrix.
Returns an n x n identity matrix (ones on the diagonal, zeros elsewhere). An optional second argument m creates an n x m rectangular identity matrix. Pass complex as the last argument to create a complex array.
Calling forms:
np_eye(n)– square identity matrixnp_eye(n, m)– rectangular identity matrixnp_eye(n, m, complex)– complex identity matrix
Examples
(%i1) np_eye(3);
(%o1) ndarray([3, 3], DOUBLE-FLOAT)
(%i2) np_to_matrix(np_eye(3));
(%o2) matrix([1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0])
(%i3) np_ref(np_eye(3), 0, 0);
(%o3) 1.0
(%i4) np_ref(np_eye(3), 0, 1);
(%o4) 0.0
See also: np_diag, np_zeros, np_ones
np_rand (shape) — Function
Create an ndarray filled with uniform random values in [0, 1).
Each element is independently drawn from a uniform distribution on the interval [0, 1). Always returns double-float.
Examples
(%i1) np_rand([2, 3]);
(%o1) ndarray([2, 3], DOUBLE-FLOAT)
(%i2) A : np_rand(5);
(%o2) ndarray([5], DOUBLE-FLOAT)
(%i3) is(np_min(A) >= 0 and np_max(A) < 1);
(%o3) true
See also: np_randn, np_zeros, np_ones
np_randn (shape) — Function
Create an ndarray filled with standard normal random values.
Each element is independently drawn from a normal distribution with mean 0 and standard deviation 1, using the Box-Muller transform. Always returns double-float.
Examples
(%i1) np_randn([3, 3]);
(%o1) ndarray([3, 3], DOUBLE-FLOAT)
(%i2) A : np_randn(10000);
(%o2) ndarray([10000], DOUBLE-FLOAT)
See also: np_rand
np_arange (stop) / np_arange (start, stop) / np_arange (start, stop, step) — Function
Create a 1D ndarray of evenly spaced values.
Generates values from start (inclusive) to stop (exclusive) with the given step. Supports non-integer step values. Always returns double-float.
Calling forms:
np_arange(stop)– values 0, 1, …, stop-1np_arange(start, stop)– values start, start+1, …, stop-1np_arange(start, stop, step)– values start, start+step, start+2*step, …
Examples
(%i1) np_to_list(np_arange(5));
(%o1) [0.0, 1.0, 2.0, 3.0, 4.0]
(%i2) np_to_list(np_arange(2, 6));
(%o2) [2.0, 3.0, 4.0, 5.0]
(%i3) np_to_list(np_arange(0, 1, 0.25));
(%o3) [0.0, 0.25, 0.5, 0.75]
(%i4) np_to_list(np_arange(10, 0, -2));
(%o4) [10.0, 8.0, 6.0, 4.0, 2.0]
See also: np_linspace, np_zeros
np_linspace (start, stop, n) — Function
Create n evenly spaced points from start to stop (inclusive).
Both endpoints are included. If n is 1, returns a single-element array containing start. Always returns double-float.
Examples
(%i1) np_linspace(0, 1, 5);
(%o1) ndarray([5], DOUBLE-FLOAT)
(%i2) np_to_list(np_linspace(0, 1, 5));
(%o2) [0.0, 0.25, 0.5, 0.75, 1.0]
(%i3) np_to_list(np_linspace(0, 10, 3));
(%o3) [0.0, 5.0, 10.0]
See also: np_arange
np_full (shape, val) / np_full (shape, val, dtype) — Function
Create an ndarray filled with a constant value.
Every element is set to val. Pass complex as the optional third argument to create a complex array; otherwise values are coerced to double-float.
Examples
(%i1) np_full([2, 3], 7);
(%o1) ndarray([2, 3], DOUBLE-FLOAT)
(%i2) np_ref(np_full([2, 2], 42), 0, 0);
(%o2) 42.0
(%i3) np_to_list(np_full(3, %pi));
(%o3) [3.141592653589793, 3.141592653589793, 3.141592653589793]
(%i4) np_full([2, 2], 1+2*%i, complex);
(%o4) ndarray([2, 2], COMPLEX-DOUBLE-FLOAT)
See also: np_zeros, np_ones
np_empty (shape) / np_empty (shape, dtype) — Function
Create an uninitialized ndarray.
The contents are unspecified and may contain arbitrary values. Use this when you plan to fill every element before reading, as it avoids the cost of zero-initialization. Pass complex as the optional second argument to create a complex array.
Examples
(%i1) A : np_empty([3, 3]);
(%o1) ndarray([3, 3], DOUBLE-FLOAT)
(%i2) np_shape(A);
(%o2) [3, 3]
(%i3) np_empty([2, 2], complex);
(%o3) ndarray([2, 2], COMPLEX-DOUBLE-FLOAT)
See also: np_zeros, np_full
np_diag (list) / np_diag (list, dtype) — Function
Create a diagonal matrix from a Maxima list.
The argument must be a Maxima list of numbers. Returns a square ndarray with the list elements on the main diagonal and zeros elsewhere. Pass complex as the optional second argument to create a complex array.
Examples
(%i1) np_diag([1, 2, 3]);
(%o1) ndarray([3, 3], DOUBLE-FLOAT)
(%i2) np_to_matrix(np_diag([1, 2, 3]));
(%o2) matrix([1.0, 0.0, 0.0], [0.0, 2.0, 0.0], [0.0, 0.0, 3.0])
(%i3) np_ref(np_diag([5, 10]), 0, 1);
(%o3) 0.0
(%i4) np_diag([1+%i, 2-%i], complex);
(%o4) ndarray([2, 2], COMPLEX-DOUBLE-FLOAT)
See also: np_eye, np_zeros
np_copy (a) — Function
Create a deep copy of an ndarray.
Returns a new ndarray with the same shape, dtype, and values. Modifications to the copy do not affect the original.
Examples
(%i1) A : np_ones([2, 2]);
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) B : np_copy(A);
(%o2) ndarray([2, 2], DOUBLE-FLOAT)
(%i3) np_set(B, 0, 0, 99.0);
(%o3) ndarray([2, 2], DOUBLE-FLOAT)
(%i4) np_ref(A, 0, 0);
(%o4) 1.0
(%i5) np_ref(B, 0, 0);
(%o5) 99.0
See also: ndarray, np_reshape
np_logspace (start, stop, n) — Function
Create n logarithmically spaced points from 10^start to 10^stop (inclusive).
Both endpoints are included. If n is 1, returns a single-element array containing 10^start. Always returns double-float.
Examples
(%i1) np_to_list(np_logspace(0, 3, 4));
(%o1) [1.0, 10.0, 100.0, 1000.0]
(%i2) np_to_list(np_logspace(2, 5, 1));
(%o2) [100.0]
(%i3) np_size(np_logspace(0, 1, 50));
(%o3) 50
See also: np_linspace, np_arange
Slicing
All slicing and indexing operations preserve the dtype of the input array.
np_ref (a, i) — Function
Access a single element of an ndarray by index.
Indices are 0-based. For 1D arrays, pass one index. For 2D arrays, pass row and column indices.
Calling forms:
np_ref(a, i)– element at positioniin a 1D arraynp_ref(a, i, j)– element at rowi, columnjin a 2D array
Examples
(%i1) A : np_arange(5);
(%o1) ndarray([5], DOUBLE-FLOAT)
(%i2) np_ref(A, 0);
(%o2) 0.0
(%i3) np_ref(A, 3);
(%o3) 3.0
(%i4) B : ndarray(matrix([10, 20], [30, 40]));
(%o4) ndarray([2, 2], DOUBLE-FLOAT)
(%i5) np_ref(B, 1, 0);
(%o5) 30.0
See also: np_set, np_row, np_col
np_set (a, i, j, val) — Function
Set a single element of an ndarray (mutating).
Indices are 0-based. The last argument is the value to set, preceding arguments are indices. The array is modified in place and returned.
Calling forms:
np_set(a, i, val)– set element at positioniin a 1D arraynp_set(a, i, j, val)– set element at rowi, columnjin a 2D array
Examples
(%i1) A : np_zeros([2, 2]);
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_set(A, 0, 0, 42.0);
(%o2) ndarray([2, 2], DOUBLE-FLOAT)
(%i3) np_ref(A, 0, 0);
(%o3) 42.0
(%i4) B : np_zeros(3);
(%o4) ndarray([3], DOUBLE-FLOAT)
(%i5) np_set(B, 1, 99.0);
(%o5) ndarray([3], DOUBLE-FLOAT)
(%i6) np_to_list(B);
(%o6) [0.0, 99.0, 0.0]
See also: np_ref
np_row (a, i) — Function
Extract a row from a 2D ndarray as a 1D ndarray.
The row index i is 0-based. Returns a new 1D ndarray containing a copy of the row.
Examples
(%i1) A : ndarray(matrix([1, 2, 3], [4, 5, 6]));
(%o1) ndarray([2, 3], DOUBLE-FLOAT)
(%i2) np_to_list(np_row(A, 0));
(%o2) [1.0, 2.0, 3.0]
(%i3) np_to_list(np_row(A, 1));
(%o3) [4.0, 5.0, 6.0]
See also: np_col, np_slice, np_ref
np_col (a, j) — Function
Extract a column from a 2D ndarray as a 1D ndarray.
The column index j is 0-based. Returns a new 1D ndarray containing a copy of the column.
Examples
(%i1) A : ndarray(matrix([1, 2, 3], [4, 5, 6]));
(%o1) ndarray([2, 3], DOUBLE-FLOAT)
(%i2) np_to_list(np_col(A, 0));
(%o2) [1.0, 4.0]
(%i3) np_to_list(np_col(A, 2));
(%o3) [3.0, 6.0]
See also: np_row, np_slice, np_ref
np_slice (a, spec0, spec1, …, specN) — Function
Extract a sub-array from an N-dimensional ndarray.
One spec argument is required per dimension. Each spec can be:
all— select the entire dimension[start, end]— half-open range[start, end), 0-based, end exclusive- An integer — select a single index, collapsing (removing) that dimension from the result
Negative indices count from the end of the dimension (-1 is the last element).
Calling forms:
np_slice(a, rows, cols)— 2D sub-matrix (unchanged from earlier versions)np_slice(a, all, all, [0, 1])— 3D slice selecting a channel from an imagenp_slice(a, 0, all)— select row 0, returning a 1D resultnp_slice(a, [2, 5])— slice a 1D array
Examples
(%i1) A : ndarray(matrix([1, 2, 3], [4, 5, 6], [7, 8, 9]));
(%o1) ndarray([3, 3], DOUBLE-FLOAT)
(%i2) /* Range slicing */
B : np_slice(A, [0, 2], [1, 3]);
(%o2) ndarray([2, 2], DOUBLE-FLOAT)
(%i3) np_to_matrix(B);
(%o3) matrix([2.0, 3.0], [5.0, 6.0])
(%i4) /* Use 'all' to select entire rows */
C : np_slice(A, all, [0, 2]);
(%o4) ndarray([3, 2], DOUBLE-FLOAT)
(%i5) /* Scalar index collapses a dimension */
D : np_slice(A, 0, all);
(%o5) ndarray([3], DOUBLE-FLOAT)
(%i6) np_to_list(D);
(%o6) [1.0, 2.0, 3.0]
(%i7) /* All indices scalar: returns a number */
np_slice(A, 1, 2);
(%o7) 6.0
3D slicing (e.g. extracting a colour channel from an image):
(%i1) img : np_reshape(np_arange(24), [2, 3, 4]);
(%o1) ndarray([2, 3, 4], DOUBLE-FLOAT)
(%i2) /* Extract channel 0 as a 2D array */
ch0 : np_slice(img, all, all, 0);
(%o2) ndarray([2, 3], DOUBLE-FLOAT)
(%i3) np_shape(ch0);
(%o3) [2, 3]
(%i4) /* Keep channel dimension with a range */
ch0_3d : np_slice(img, all, all, [0, 1]);
(%o4) ndarray([2, 3, 1], DOUBLE-FLOAT)
See also: np_row, np_col, np_ref, np_reshape
np_reshape (a, shape) — Function
Reshape an ndarray to new dimensions.
The total number of elements must remain the same. Returns a new ndarray with the specified shape. The shape argument is a Maxima list of dimensions.
Examples
(%i1) A : np_arange(6);
(%o1) ndarray([6], DOUBLE-FLOAT)
(%i2) B : np_reshape(A, [2, 3]);
(%o2) ndarray([2, 3], DOUBLE-FLOAT)
(%i3) np_shape(B);
(%o3) [2, 3]
(%i4) C : np_reshape(A, [3, 2]);
(%o4) ndarray([3, 2], DOUBLE-FLOAT)
See also: np_flatten, np_shape
np_flatten (a) — Function
Flatten an ndarray to 1D.
Returns a new 1D ndarray containing all elements in storage order (column-major).
Examples
(%i1) A : np_ones([2, 3]);
(%o1) ndarray([2, 3], DOUBLE-FLOAT)
(%i2) B : np_flatten(A);
(%o2) ndarray([6], DOUBLE-FLOAT)
(%i3) np_size(B);
(%o3) 6
(%i4) np_shape(B);
(%o4) [6]
See also: np_reshape, np_to_list
np_hstack (a, b) — Function
Concatenate two 2D ndarrays horizontally (along columns).
Both arrays must have the same number of rows. The result has the combined number of columns. Promotes to complex if either input is complex.
Examples
(%i1) A : ndarray(matrix([1, 2], [3, 4]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) B : ndarray(matrix([5], [6]));
(%o2) ndarray([2, 1], DOUBLE-FLOAT)
(%i3) C : np_hstack(A, B);
(%o3) ndarray([2, 3], DOUBLE-FLOAT)
(%i4) np_to_matrix(C);
(%o4) matrix([1.0, 2.0, 5.0], [3.0, 4.0, 6.0])
See also: np_vstack
np_vstack (a, b) — Function
Concatenate two 2D ndarrays vertically (along rows).
Both arrays must have the same number of columns. The result has the combined number of rows. Promotes to complex if either input is complex.
Examples
(%i1) A : ndarray(matrix([1, 2], [3, 4]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) B : ndarray(matrix([5, 6]));
(%o2) ndarray([1, 2], DOUBLE-FLOAT)
(%i3) C : np_vstack(A, B);
(%o3) ndarray([3, 2], DOUBLE-FLOAT)
(%i4) np_to_matrix(C);
(%o4) matrix([1.0, 2.0], [3.0, 4.0], [5.0, 6.0])
See also: np_hstack
np_shape (a) — Function
Return the shape of an ndarray as a Maxima list.
For a 1D array, returns a list with one element. For a 2D array, returns [rows, cols].
Examples
(%i1) np_shape(np_zeros([3, 4]));
(%o1) [3, 4]
(%i2) np_shape(np_arange(10));
(%o2) [10]
(%i3) np_shape(np_eye(5));
(%o3) [5, 5]
See also: np_size, np_dtype, np_reshape
np_size (a) — Function
Return the total number of elements in an ndarray.
Examples
(%i1) np_size(np_zeros([3, 4]));
(%o1) 12
(%i2) np_size(np_arange(10));
(%o2) 10
(%i3) np_size(np_eye(5));
(%o3) 25
See also: np_shape, np_dtype
np_dtype (a) — Function
Return the element type of an ndarray as a string.
Returns "DOUBLE-FLOAT" for real arrays or "COMPLEX-DOUBLE-FLOAT" for complex arrays.
Examples
(%i1) np_dtype(np_zeros([2, 2]));
(%o1) DOUBLE-FLOAT
See also: np_shape, np_size
Element-wise Operations
All element-wise arithmetic and math operations support complex arrays unless noted otherwise. When one operand is complex and the other is real, the result is complex.
np_add (a, b) — Function
Element-wise addition.
Supports ndarray + ndarray (same shape), ndarray + scalar, and scalar + ndarray. Returns a new ndarray.
Examples
(%i1) A : ndarray(matrix([1, 2], [3, 4]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_to_matrix(np_add(A, A));
(%o2) matrix([2.0, 4.0], [6.0, 8.0])
(%i3) np_to_matrix(np_add(A, 10));
(%o3) matrix([11.0, 12.0], [13.0, 14.0])
(%i4) np_to_matrix(np_add(5, A));
(%o4) matrix([6.0, 7.0], [8.0, 9.0])
See also: np_sub, np_scale
np_sub (a, b) — Function
Element-wise subtraction.
Supports ndarray - ndarray, ndarray - scalar, and scalar - ndarray. Returns a new ndarray.
Examples
(%i1) A : ndarray(matrix([10, 20], [30, 40]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) B : ndarray(matrix([1, 2], [3, 4]));
(%o2) ndarray([2, 2], DOUBLE-FLOAT)
(%i3) np_to_matrix(np_sub(A, B));
(%o3) matrix([9.0, 18.0], [27.0, 36.0])
(%i4) np_to_matrix(np_sub(A, 5));
(%o4) matrix([5.0, 15.0], [25.0, 35.0])
See also: np_add, np_neg
np_mul (a, b) — Function
Element-wise (Hadamard) product.
This is NOT matrix multiplication. Each element of a is multiplied by the corresponding element of b. For matrix multiplication, use np_matmul.
Supports ndarray * ndarray, ndarray * scalar, and scalar * ndarray.
Examples
(%i1) A : ndarray(matrix([1, 2], [3, 4]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_to_matrix(np_mul(A, A));
(%o2) matrix([1.0, 4.0], [9.0, 16.0])
(%i3) np_to_matrix(np_mul(A, 3));
(%o3) matrix([3.0, 6.0], [9.0, 12.0])
See also: np_matmul, np_div, np_scale
np_div (a, b) — Function
Element-wise division.
Supports ndarray / ndarray, ndarray / scalar, and scalar / ndarray. Returns a new ndarray.
Examples
(%i1) A : ndarray(matrix([10, 20], [30, 40]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_to_matrix(np_div(A, 10));
(%o2) matrix([1.0, 2.0], [3.0, 4.0])
(%i3) B : ndarray(matrix([2, 4], [5, 8]));
(%o3) ndarray([2, 2], DOUBLE-FLOAT)
(%i4) np_to_matrix(np_div(A, B));
(%o4) matrix([5.0, 5.0], [6.0, 5.0])
See also: np_mul
np_pow (a, p) — Function
Element-wise exponentiation.
Raises each element of a to the power p. If p is an ndarray, the operation is applied element-wise between a and p.
Examples
(%i1) A : ndarray(matrix([1, 2], [3, 4]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_to_matrix(np_pow(A, 2));
(%o2) matrix([1.0, 4.0], [9.0, 16.0])
(%i3) np_to_matrix(np_pow(A, 0.5));
(%o3) matrix([1.0, 1.414..], [1.732.., 2.0])
See also: np_sqrt, np_exp, np_log
np_sqrt (a) — Function
Element-wise square root.
Returns a new ndarray where each element is the square root of the corresponding element in a.
Examples
(%i1) A : ndarray(matrix([1, 4], [9, 16]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_to_matrix(np_sqrt(A));
(%o2) matrix([1.0, 2.0], [3.0, 4.0])
See also: np_pow, np_exp
np_exp (a) — Function
Element-wise exponential (e^x).
Returns a new ndarray where each element is e raised to the power of the corresponding element in a.
Examples
(%i1) A : ndarray(matrix([0, 1], [2, 3]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_ref(np_exp(A), 0, 0);
(%o2) 1.0
(%i3) B : np_log(np_exp(A));
(%o3) ndarray([2, 2], DOUBLE-FLOAT)
(%i4) np_ref(B, 1, 1);
(%o4) 3.0
See also: np_log, np_expm
np_log (a) — Function
Element-wise natural logarithm.
Returns a new ndarray where each element is the natural log of the corresponding element in a. Elements must be positive.
Examples
(%i1) A : ndarray(matrix([1, %e], [%e^2, %e^3]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_to_matrix(np_log(A));
(%o2) matrix([0.0, 1.0], [2.0, 3.0])
See also: np_exp
np_sin (a) — Function
Element-wise sine.
Returns a new ndarray where each element is the sine of the corresponding element in a (radians).
Examples
(%i1) A : ndarray(matrix([0, %pi/2], [%pi, 3*%pi/2]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_ref(np_sin(A), 0, 0);
(%o2) 0.0
(%i3) np_ref(np_sin(A), 0, 1);
(%o3) 1.0
See also: np_cos, np_tan
np_cos (a) — Function
Element-wise cosine.
Returns a new ndarray where each element is the cosine of the corresponding element in a (radians).
Examples
(%i1) A : ndarray(matrix([0, %pi/2], [%pi, 2*%pi]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_ref(np_cos(A), 0, 0);
(%o2) 1.0
See also: np_sin, np_tan
np_tan (a) — Function
Element-wise tangent.
Returns a new ndarray where each element is the tangent of the corresponding element in a (radians).
Examples
(%i1) A : ndarray(matrix([0, %pi/4]));
(%o1) ndarray([1, 2], DOUBLE-FLOAT)
(%i2) np_ref(np_tan(A), 0, 0);
(%o2) 0.0
See also: np_sin, np_cos
np_abs (a) — Function
Element-wise absolute value.
Returns a new ndarray where each element is the absolute value of the corresponding element in a. For complex arrays, returns the magnitude (modulus) as double-float.
Examples
(%i1) A : ndarray(matrix([-1, 2], [-3, 4]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_to_matrix(np_abs(A));
(%o2) matrix([1.0, 2.0], [3.0, 4.0])
See also: np_neg
np_neg (a) — Function
Element-wise negation.
Returns a new ndarray where each element is negated (multiplied by -1).
Examples
(%i1) A : np_ones([2, 2]);
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_to_matrix(np_neg(A));
(%o2) matrix([-1.0, -1.0], [-1.0, -1.0])
See also: np_abs, np_sub
np_clip (a, lo, hi) — Function
Clamp values element-wise.
Returns a new ndarray where each element is clamped to the range [lo, hi]. Values below lo become lo, values above hi become hi.
Examples
(%i1) A : ndarray([1.0, 5.0, 3.0, 8.0, 2.0]);
(%o1) ndarray([5], DOUBLE-FLOAT)
(%i2) np_to_list(np_clip(A, 2.0, 6.0));
(%o2) [2.0, 5.0, 3.0, 6.0, 2.0]
See also: np_abs, np_where
np_scale (alpha, a) — Function
Multiply every element of an ndarray by a scalar.
The scalar alpha is coerced to double-float. Returns a new ndarray.
Examples
(%i1) A : ndarray(matrix([1, 2], [3, 4]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_to_matrix(np_scale(3, A));
(%o2) matrix([3.0, 6.0], [9.0, 12.0])
(%i3) np_to_matrix(np_scale(0.5, A));
(%o3) matrix([0.5, 1.0], [1.5, 2.0])
See also: np_mul, np_add
np_map (f, a) — Function
Apply a user-defined function element-wise to an ndarray.
Evaluates f(x) for each element x in a and returns a new ndarray of the same shape. The function f can be a named function or a lambda expression, and must accept a single numeric argument and return a numeric result.
Performance: There are three speed tiers, from fastest to slowest:
- Translated named function (
translate(f)first) — calls the compiled CL function directly. Use this for large arrays. - Named function — calls through the Maxima evaluator. Convenient but slower.
- Lambda expression — also calls through the Maxima evaluator. Most convenient for one-off use, similar speed to an untranslated named function.
Calling forms:
np_map(f, A)– apply named functionfelement-wisenp_map(lambda([x], expr), A)– apply lambda element-wise
Examples
(%i1) f(x) := x^2 + 1$
(%i2) A : np_arange(5);
(%o2) ndarray([5], DOUBLE-FLOAT)
(%i3) np_to_list(np_map(f, A));
(%o3) [1.0, 2.0, 5.0, 10.0, 17.0]
(%i4) translate(f)$
(%i5) np_to_list(np_map(f, A));
(%o5) [1.0, 2.0, 5.0, 10.0, 17.0]
Using a lambda expression:
(%i1) A : np_arange(5)$
(%i2) np_to_list(np_map(lambda([x], x^2 + 1), A));
(%o2) [1.0, 2.0, 5.0, 10.0, 17.0]
(%i3) np_to_list(np_map(lambda([x], sin(x) + 1), A));
(%o3) [1.0, 1.841, 1.909, 1.141, 0.243]
For best performance on large arrays, use a translated named function:
(%i1) g(x) := exp(-x^2)$
(%i2) translate(g)$
(%i3) A : np_linspace(-3, 3, 10000)$
(%i4) B : np_map(g, A)$
See also: np_map2, np_sqrt, np_exp
np_map2 (f, a, b) — Function
Apply a binary function element-wise to two ndarrays.
Evaluates f(x, y) for corresponding elements of a and b. Both arrays must have the same shape. Returns a new ndarray. The function f can be a named function or a lambda expression.
Like np_map, uses the fast compiled path if f is a named function that has been translated. Lambda expressions use the slow path.
Examples
(%i1) f(x, y) := x^2 + y^2$
(%i2) A : np_arange(3);
(%o2) ndarray([3], DOUBLE-FLOAT)
(%i3) B : np_ones(3);
(%o3) ndarray([3], DOUBLE-FLOAT)
(%i4) np_to_list(np_map2(f, A, B));
(%o4) [1.0, 2.0, 5.0]
(%i5) np_to_list(np_map2(lambda([x, y], x + 2*y), A, B));
(%o5) [2.0, 3.0, 4.0]
See also: np_map, np_add, np_mul
np_where (condition) / np_where (condition, x, y) — Function
Conditional selection.
Form 1: np_where(condition) — returns a Maxima list of index arrays indicating where the condition ndarray has nonzero elements.
- For 1D input: returns
[indices](a list containing one 1D ndarray). - For 2D input: returns
[row_indices, col_indices](two 1D ndarrays).
Form 2: np_where(condition, x, y) — element-wise selection. Returns a new ndarray: takes from x where condition is nonzero, from y where condition is zero. The arguments x and y can be ndarrays (same shape as condition) or scalars.
Examples
(%i1) /* Form 1: find nonzero indices */
A : ndarray([0, 1, 0, 3, 0], [5]);
(%o1) ndarray([5], DOUBLE-FLOAT)
(%i2) np_to_list(np_where(A)[1]);
(%o2) [1.0, 3.0]
(%i3) /* Form 1: 2D */
B : ndarray(matrix([1, 0], [0, 4]));
(%o3) ndarray([2, 2], DOUBLE-FLOAT)
(%i4) [rows, cols] : np_where(B);
(%o4) [ndarray, ndarray]
(%i5) np_to_list(rows);
(%o5) [0.0, 1.0]
(%i6) /* Form 2: select from x or y */
cond : ndarray([1, 0, 1], [3]);
(%o6) ndarray([3], DOUBLE-FLOAT)
(%i7) np_to_list(np_where(cond, ndarray([10,20,30],[3]),
ndarray([100,200,300],[3])));
(%o7) [10.0, 200.0, 30.0]
(%i8) /* Form 2: scalar broadcasting */
np_to_list(np_where(np_greater(A, 2), A, 0));
(%o8) [0.0, 0.0, 0.0, 3.0, 0.0]
See also: np_greater, np_extract, np_map
np_greater (a, b) — Function
Element-wise greater-than comparison.
Returns a new ndarray with 1.0 where a > b and 0.0 elsewhere. Supports ndarray + ndarray, ndarray + scalar, and scalar + ndarray. Signals an error for complex arrays (complex numbers are not ordered).
Examples
(%i1) A : ndarray([1, 5, 3, 7, 2], [5]);
(%o1) ndarray([5], DOUBLE-FLOAT)
(%i2) np_to_list(np_greater(A, 3));
(%o2) [0.0, 1.0, 0.0, 1.0, 0.0]
(%i3) B : ndarray([2, 4, 3], [3]);
(%o3) ndarray([3], DOUBLE-FLOAT)
(%i4) np_to_list(np_greater(ndarray([1,5,3],[3]), B));
(%o4) [0.0, 1.0, 0.0]
See also: np_less, np_greater_equal, np_equal
np_greater_equal (a, b) — Function
Element-wise greater-than-or-equal comparison. Returns 1.0/0.0 ndarray. Signals an error for complex arrays.
See also: np_greater, np_less_equal
np_less (a, b) — Function
Element-wise less-than comparison. Returns 1.0/0.0 ndarray. Signals an error for complex arrays.
See also: np_greater, np_less_equal
np_less_equal (a, b) — Function
Element-wise less-than-or-equal comparison. Returns 1.0/0.0 ndarray. Signals an error for complex arrays.
See also: np_less, np_greater_equal
np_equal (a, b) — Function
Element-wise equality comparison. Returns 1.0/0.0 ndarray. Supports complex arrays.
See also: np_not_equal
np_not_equal (a, b) — Function
Element-wise not-equal comparison. Returns 1.0/0.0 ndarray. Supports complex arrays.
See also: np_equal
np_logical_and (a, b) — Function
Element-wise logical AND. Nonzero is true. Returns 1.0/0.0 ndarray.
Examples
(%i1) A : ndarray([1, 0, 1, 0], [4]);
(%o1) ndarray([4], DOUBLE-FLOAT)
(%i2) B : ndarray([1, 1, 0, 0], [4]);
(%o2) ndarray([4], DOUBLE-FLOAT)
(%i3) np_to_list(np_logical_and(A, B));
(%o3) [1.0, 0.0, 0.0, 0.0]
See also: np_logical_or, np_logical_not
np_logical_or (a, b) — Function
Element-wise logical OR. Nonzero is true. Returns 1.0/0.0 ndarray.
See also: np_logical_and, np_logical_not
np_logical_not (a) — Function
Element-wise logical NOT. Nonzero becomes 0.0, zero becomes 1.0.
See also: np_logical_and, np_logical_or
np_test (f, a) — Function
Apply a predicate function element-wise, returning a 1.0/0.0 mask ndarray.
The function f can be:
- A named function:
np_test(is_positive, A)— fast if translated - A lambda:
np_test(lambda([x], is(x > 3)), A)— slow, uses Maxima evaluator
The result of f(x) is converted to 1.0 (truthy) or 0.0 (falsy). Numbers, booleans, and Maxima relational expressions are all handled.
Performance: Named functions with translate(f) are fastest. Lambda expressions use the Maxima evaluator and are much slower for large arrays. For simple comparisons, prefer np_greater, np_less, etc.
Examples
(%i1) gt3(x) := if x > 3 then 1 else 0$
(%i2) A : ndarray([1, 5, 3, 7, 2], [5]);
(%o2) ndarray([5], DOUBLE-FLOAT)
(%i3) np_to_list(np_test(gt3, A));
(%o3) [0.0, 1.0, 0.0, 1.0, 0.0]
(%i4) /* Lambda form */
np_to_list(np_test(lambda([x], is(x > 3)), A));
(%o4) [0.0, 1.0, 0.0, 1.0, 0.0]
See also: np_greater, np_extract, np_map
np_extract (mask, a) — Function
Extract elements where mask is nonzero (boolean indexing).
Returns a 1D ndarray containing the elements of a where the corresponding element in mask is nonzero. Elements are taken in row-major order. Returns an empty Maxima list [] if no elements match.
This is the equivalent of NumPy’s A[mask].
Examples
(%i1) A : ndarray([10, 20, 30, 40, 50], [5]);
(%o1) ndarray([5], DOUBLE-FLOAT)
(%i2) mask : ndarray([1, 0, 1, 0, 1], [5]);
(%o2) ndarray([5], DOUBLE-FLOAT)
(%i3) np_to_list(np_extract(mask, A));
(%o3) [10.0, 30.0, 50.0]
(%i4) /* With comparison-generated mask: A[A > 25] */
np_to_list(np_extract(np_greater(A, 25), A));
(%o4) [30.0, 40.0, 50.0]
See also: np_where, np_greater, np_test
Signal Processing
Functions for frequency-domain analysis and filtering. The FFT implementation uses Maxima’s fftpack5 library (a Lisp translation of FFTPACK), which supports arbitrary input lengths (most efficient when the length has the form 2^r * 3^s * 5^t).
np_fft (a) — Function
Compute the discrete Fourier transform of a 1D ndarray.
Scaling convention (matches NumPy):
Y[k] = sum(x[n] * exp(-2 * %pi * %i * k * n / N), n, 0, N-1)
The forward transform does not include a 1/N factor. Use np_ifft to invert.
The input a must be a 1D ndarray (real or complex). The result is always a complex 1D ndarray of the same length.
Examples
(%i1) /* FFT of a real signal */
A : ndarray([1.0, 2.0, 3.0, 4.0]);
(%o1) ndarray([4], DOUBLE-FLOAT)
(%i2) F : np_fft(A);
(%o2) ndarray([4], COMPLEX-DOUBLE-FLOAT)
(%i3) np_to_list(F);
(%o3) [10.0, 2.0 %i - 2.0, - 2.0, - 2.0 %i - 2.0]
(%i4) /* DC component = sum of signal */
np_ref(F, 0);
(%o4) 10.0
(%i5) /* Round-trip: ifft(fft(x)) = x */
np_to_list(np_real(np_ifft(F)));
(%o5) [1.0, 2.0, 3.0, 4.0]
Frequency analysis of a sine wave:
(%i1) N : 128$
(%i2) t : np_linspace(0, 1, N)$
(%i3) /* 10 Hz sine wave, sampled at 128 Hz */
x : np_sin(np_scale(2 * %pi * 10, t))$
(%i4) F : np_fft(x)$
(%i5) /* Magnitude spectrum */
mag : np_abs(F)$
See also: np_ifft, np_fft2d, np_abs, np_real, np_imag, np_angle
np_ifft (a) — Function
Compute the inverse discrete Fourier transform of a 1D ndarray.
Scaling convention (matches NumPy):
x[n] = (1/N) * sum(Y[k] * exp(+2 * %pi * %i * k * n / N), k, 0, N-1)
The inverse transform includes the 1/N normalization factor.
The input a must be a 1D ndarray (real or complex). The result is always a complex 1D ndarray of the same length. For real-valued signals, use np_real to extract the real part of the result.
Examples
(%i1) /* Frequency-domain filtering */
x : np_arange(0, 64)$
(%i2) F : np_fft(x)$
(%i3) /* Zero out high-frequency components (low-pass) */
(%i4) y : np_real(np_ifft(F))$
(%i5) /* Verify round-trip */
closeto(np_ref(y, 0), 0.0);
(%o5) true
See also: np_fft, np_ifft2d, np_real
np_fft2d (a) — Function
Compute the 2D discrete Fourier transform of a 2D ndarray.
Scaling convention (matches NumPy’s fft2):
Y[k1,k2] = sum_n1 sum_n2 x[n1,n2] * exp(-2 * %pi * %i * (k1*n1/N1 + k2*n2/N2))
The forward transform does not include a 1/(N1*N2) factor. Use np_ifft2d to invert.
The input a must be a 2D ndarray (real or complex). The result is always a complex 2D ndarray of the same shape. Internally uses separable 1D FFTs along columns then rows.
Examples
(%i1) A : ndarray(matrix([1, 2, 3], [4, 5, 6], [7, 8, 9]));
(%o1) ndarray([3, 3], DOUBLE-FLOAT)
(%i2) F : np_fft2d(A);
(%o2) ndarray([3, 3], COMPLEX-DOUBLE-FLOAT)
(%i3) /* DC component = sum of all elements */
realpart(np_ref(F, 0, 0));
(%o3) 45.0
(%i4) /* Round-trip: ifft2d(fft2d(x)) = x */
B : np_ifft2d(F)$
(%i5) realpart(np_ref(B, 0, 0));
(%o5) 1.0
See also: np_ifft2d, np_fft
np_ifft2d (a) — Function
Compute the inverse 2D discrete Fourier transform of a 2D ndarray.
Scaling convention (matches NumPy’s ifft2):
x[n1,n2] = (1/(N1*N2)) * sum_k1 sum_k2 Y[k1,k2] * exp(+2 * %pi * %i * (k1*n1/N1 + k2*n2/N2))
The inverse transform includes the 1/(N1*N2) normalization factor.
The input a must be a 2D ndarray (real or complex). The result is always a complex 2D ndarray of the same shape. For real-valued data, use np_real to extract the real part.
Examples
(%i1) A : ndarray(matrix([1, 2], [3, 4]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) F : np_fft2d(A)$
(%i3) B : np_ifft2d(F)$
(%i4) /* Recovered values match original */
realpart(np_ref(B, 0, 0));
(%o4) 1.0
(%i5) realpart(np_ref(B, 1, 1));
(%o5) 4.0
See also: np_fft2d, np_ifft, np_real
np_convolve (a, b) — Function
Compute the 1D discrete linear convolution of two real signals.
Returns a 1D ndarray of length len(a) + len(b) - 1 (“full” mode, matching NumPy’s default). Both inputs must be 1D real ndarrays. Uses direct computation with O(len(a) * len(b)) complexity.
Examples
(%i1) /* Convolve with impulse: identity operation */
A : ndarray([1.0, 2.0, 3.0]);
(%o1) ndarray([3], DOUBLE-FLOAT)
(%i2) np_to_list(np_convolve(A, ndarray([1.0])));
(%o2) [1.0, 2.0, 3.0]
(%i3) /* Moving average (box filter) */
signal : ndarray([1.0, 3.0, 2.0, 5.0, 4.0]);
(%o3) ndarray([5], DOUBLE-FLOAT)
(%i4) kernel : np_scale(1/3, np_ones(3));
(%o4) ndarray([3], DOUBLE-FLOAT)
(%i5) np_to_list(np_convolve(signal, kernel));
(%o5) [0.333, 1.333, 2.0, 3.333, 3.666, 3.0, 1.333]
(%i6) /* Output length = len(signal) + len(kernel) - 1 */
np_shape(np_convolve(signal, kernel));
(%o6) [7]
See also: np_fft, np_ifft, np_convolve2d
np_convolve2d (a, kernel) — Function
Compute the 2D discrete convolution of a matrix with a kernel (“valid” mode).
Both inputs must be 2D real ndarrays. Returns a 2D ndarray of shape (h - kh + 1, w - kw + 1), where (h, w) is the input shape and (kh, kw) is the kernel shape. Only positions where the kernel fully overlaps the input are computed (no padding).
Uses direct O(h * w * kh * kw) computation with flat column-major indexing for performance.
Examples
(%i1) /* Identity convolution with a 1x1 kernel */
A : ndarray(matrix([1, 2, 3], [4, 5, 6]));
(%o1) ndarray([2, 3], DOUBLE-FLOAT)
(%i2) np_to_matrix(np_convolve2d(A, ndarray(matrix([1]))));
(%o2) matrix([1.0, 2.0, 3.0], [4.0, 5.0, 6.0])
(%i3) /* 3x3 box blur kernel */
blur : np_scale(1/9, np_ones([3, 3]));
(%o3) ndarray([3, 3], DOUBLE-FLOAT)
(%i4) img : np_ones([5, 5]);
(%o4) ndarray([5, 5], DOUBLE-FLOAT)
(%i5) result : np_convolve2d(img, blur);
(%o5) ndarray([3, 3], DOUBLE-FLOAT)
(%i6) /* Sobel horizontal edge detector */
sobel_x : ndarray(matrix([-1, 0, 1], [-2, 0, 2], [-1, 0, 1]));
(%o6) ndarray([3, 3], DOUBLE-FLOAT)
See also: np_convolve, np_fft
Image Processing
Functions for reading, writing, and displaying images as ndarrays. Requires the numerics-image module (loaded separately from the core numerics package). Images are represented as ndarrays with pixel values in the range 0.0 to 255.0.
Requirements: The opticl library (installed automatically via Quicklisp when numerics-image is loaded).
Loading the module
(%i1) load("numerics")$
(%i2) load("numerics-image")$
Image representation
- Grayscale images have shape
[height, width] - Colour images have shape
[height, width, 3](RGB channels) - Pixel values are
double-floatin the range 0.0 to 255.0 - RGBA images have the alpha channel dropped on load (only RGB is kept)
np_read_image (path) — Function
Read an image file and return an ndarray.
Supports PNG, JPEG, TIFF, PBM, and other formats supported by opticl. The path argument is a string. Returns shape [h, w] for grayscale or [h, w, 3] for colour images.
Examples
(%i1) img : np_read_image("/path/to/photo.png");
(%o1) ndarray([480, 640, 3], DOUBLE-FLOAT)
(%i2) np_shape(img);
(%o2) [480, 640, 3]
See also: np_write_image, np_mandrill
np_write_image (a, path) — Function
Write an ndarray to an image file.
The output format is inferred from the file extension (.png, .jpg, .tiff, etc.). Values are clamped to [0, 255] and rounded to the nearest integer before writing.
Examples
(%i1) img : np_mandrill()$
(%i2) np_write_image(img, "/tmp/mandrill_copy.png");
(%o2) done
See also: np_read_image, np_imshow
np_imshow (a) — Function
Display an ndarray as an image in the notebook.
Writes a temporary PNG file and prints its path for the notebook renderer to pick up. Supports 2D grayscale [h, w] and 3D colour [h, w, 3] arrays. Values are clamped to [0, 255].
Examples
(%i1) img : np_mandrill()$
(%i2) np_imshow(img);
(%o2) done
(%i3) /* Display a single colour channel */
red : np_slice(img, all, all, 0)$
(%i4) np_imshow(red);
(%o4) done
See also: np_write_image, np_read_image
np_mandrill () — Function
Return the bundled 512x512 mandrill test image as an ndarray.
Returns shape [512, 512, 3] (RGB colour). The image is cached after the first call for efficient reuse. This is the standard “mandrill” (baboon) test image commonly used in image processing.
Examples
(%i1) img : np_mandrill();
(%o1) ndarray([512, 512, 3], DOUBLE-FLOAT)
(%i2) np_shape(img);
(%o2) [512, 512, 3]
(%i3) /* Extract green channel */
green : np_slice(img, all, all, 1);
(%o3) ndarray([512, 512], DOUBLE-FLOAT)
See also: np_read_image, np_slice
np_to_image (a) — Function
Convert an ndarray to a raw opticl image array (unsigned-byte 8).
Returns a wrapped CL array suitable for passing to opticl functions directly. Values are clamped to [0, 255] and rounded. Useful for interoperating with opticl’s image manipulation functions from Lisp.
Examples
(%i1) img : np_mandrill()$
(%i2) raw : np_to_image(img);
(%o2) opticl_image(...)
See also: np_from_image
np_from_image (img) — Function
Convert an opticl image array back to an ndarray.
Accepts either a wrapped opticl_image(...) form (from np_to_image) or a raw CL array (from :lisp calls). Returns a double-float ndarray with values 0.0 to 255.0.
Examples
(%i1) img : np_mandrill()$
(%i2) raw : np_to_image(img)$
(%i3) back : np_from_image(raw);
(%o3) ndarray([512, 512, 3], DOUBLE-FLOAT)
See also: np_to_image
Aggregation
np_sum (a) — Function
Sum of array elements. Supports complex arrays.
Without an axis argument, returns the scalar sum of all elements. With an axis argument, sums along that axis and returns an ndarray.
Calling forms:
np_sum(a)– total sum, returns a scalarnp_sum(a, 0)– sum across rows (column sums), returns a 1D ndarray of lengthncolnp_sum(a, 1)– sum across columns (row sums), returns a 1D ndarray of lengthnrow
Examples
(%i1) A : ndarray(matrix([1, 2], [3, 4]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_sum(A);
(%o2) 10.0
(%i3) np_to_list(np_sum(A, 0));
(%o3) [4.0, 6.0]
(%i4) np_to_list(np_sum(A, 1));
(%o4) [3.0, 7.0]
See also: np_mean, np_cumsum
np_mean (a) — Function
Mean (average) of array elements. Supports complex arrays.
Without an axis argument, returns the scalar mean of all elements. With an axis argument, computes the mean along that axis.
Calling forms:
np_mean(a)– total mean, returns a scalarnp_mean(a, 0)– column means, returns a 1D ndarraynp_mean(a, 1)– row means, returns a 1D ndarray
Examples
(%i1) A : ndarray(matrix([1, 2], [3, 4]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_mean(A);
(%o2) 2.5
(%i3) np_to_list(np_mean(A, 0));
(%o3) [2.0, 3.0]
(%i4) np_to_list(np_mean(A, 1));
(%o4) [1.5, 3.5]
See also: np_sum, np_std, np_var
np_min (a) / np_min (a, axis) — Function
Minimum element of an ndarray. Signals an error for complex arrays.
Without an axis argument, returns the smallest element as a scalar. With an axis argument, computes the minimum along that axis and returns an ndarray.
Calling forms:
np_min(a)– global minimum, returns a scalarnp_min(a, 0)– minimum across rows (column mins), returns a 1D ndarray of lengthncolnp_min(a, 1)– minimum across columns (row mins), returns a 1D ndarray of lengthnrow
Examples
(%i1) A : ndarray(matrix([3, 1], [4, 2]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_min(A);
(%o2) 1.0
(%i3) np_to_list(np_min(A, 0));
(%o3) [3.0, 1.0]
(%i4) np_to_list(np_min(A, 1));
(%o4) [1.0, 2.0]
See also: np_max, np_argmin
np_max (a) / np_max (a, axis) — Function
Maximum element of an ndarray. Signals an error for complex arrays.
Without an axis argument, returns the largest element as a scalar. With an axis argument, computes the maximum along that axis and returns an ndarray.
Calling forms:
np_max(a)– global maximum, returns a scalarnp_max(a, 0)– maximum across rows (column maxes), returns a 1D ndarray of lengthncolnp_max(a, 1)– maximum across columns (row maxes), returns a 1D ndarray of lengthnrow
Examples
(%i1) A : ndarray(matrix([3, 1], [4, 2]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_max(A);
(%o2) 4.0
(%i3) np_to_list(np_max(A, 0));
(%o3) [4.0, 2.0]
(%i4) np_to_list(np_max(A, 1));
(%o4) [3.0, 4.0]
See also: np_min, np_argmax
np_argmin (a) / np_argmin (a, axis) — Function
Index of the minimum element. Signals an error for complex arrays.
Without an axis argument, returns a 0-based integer index into the flattened (column-major) storage. With an axis argument, returns a 1D ndarray of indices along the specified axis.
Calling forms:
np_argmin(a)– flat index of global minimum, returns an integernp_argmin(a, 0)– row index of minimum per column, returns a 1D ndarraynp_argmin(a, 1)– column index of minimum per row, returns a 1D ndarray
Examples
(%i1) A : ndarray(matrix([3, 1], [4, 2]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_argmin(A);
(%o2) 2
(%i3) np_to_list(np_argmin(A, 0));
(%o3) [0.0, 0.0]
(%i4) np_to_list(np_argmin(A, 1));
(%o4) [1.0, 1.0]
See also: np_argmax, np_min
np_argmax (a) / np_argmax (a, axis) — Function
Index of the maximum element. Signals an error for complex arrays.
Without an axis argument, returns a 0-based integer index into the flattened (column-major) storage. With an axis argument, returns a 1D ndarray of indices along the specified axis.
Calling forms:
np_argmax(a)– flat index of global maximum, returns an integernp_argmax(a, 0)– row index of maximum per column, returns a 1D ndarraynp_argmax(a, 1)– column index of maximum per row, returns a 1D ndarray
Examples
(%i1) A : ndarray(matrix([3, 1], [4, 2]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_argmax(A);
(%o2) 1
(%i3) np_to_list(np_argmax(A, 0));
(%o3) [1.0, 1.0]
(%i4) np_to_list(np_argmax(A, 1));
(%o4) [0.0, 0.0]
See also: np_argmin, np_max
np_var (a) / np_var (a, axis) — Function
Variance of array elements.
Computes the population variance (divides by N, not N-1). Without an axis argument, returns a scalar. With an axis argument, computes variance along that axis. For complex arrays, computes |x - mean|^2; the result is always double-float.
Calling forms:
np_var(a)– total variance, returns a scalarnp_var(a, 0)– column variances, returns a 1D ndarraynp_var(a, 1)– row variances, returns a 1D ndarray
Examples
(%i1) A : ndarray(matrix([1, 5], [3, 7]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_var(A);
(%o2) 5.0
(%i3) np_to_list(np_var(A, 0));
(%o3) [1.0, 1.0]
(%i4) np_to_list(np_var(A, 1));
(%o4) [4.0, 4.0]
See also: np_std, np_mean
np_std (a) / np_std (a, axis) — Function
Standard deviation of array elements.
Computes the population standard deviation (divides by N, not N-1). Without an axis argument, returns a scalar. With an axis argument, computes standard deviation along that axis. The result is always double-float, even for complex input.
Calling forms:
np_std(a)– total standard deviation, returns a scalarnp_std(a, 0)– column standard deviations, returns a 1D ndarraynp_std(a, 1)– row standard deviations, returns a 1D ndarray
Examples
(%i1) A : ndarray(matrix([1, 5], [3, 7]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_std(A);
(%o2) 2.23606797749979
(%i3) np_to_list(np_std(A, 0));
(%o3) [1.0, 1.0]
(%i4) np_to_list(np_std(A, 1));
(%o4) [2.0, 2.0]
See also: np_var, np_mean
np_cumsum (a) — Function
Cumulative sum of a 1D ndarray. Supports complex arrays.
Returns a new 1D ndarray where element i is the sum of elements 0 through i of the input.
Examples
(%i1) A : np_arange(5);
(%o1) ndarray([5], DOUBLE-FLOAT)
(%i2) np_to_list(np_cumsum(A));
(%o2) [0.0, 1.0, 3.0, 6.0, 10.0]
(%i3) np_to_list(np_cumsum(np_ones(4)));
(%o3) [1.0, 2.0, 3.0, 4.0]
See also: np_sum
np_dot (a, b) — Function
Dot product of two 1D vectors. Supports complex arrays.
Both arguments must be 1D ndarrays of the same length. Returns a scalar.
Examples
(%i1) a : np_arange(3);
(%o1) ndarray([3], DOUBLE-FLOAT)
(%i2) b : np_ones(3);
(%o2) ndarray([3], DOUBLE-FLOAT)
(%i3) np_dot(a, b);
(%o3) 3.0
(%i4) np_dot(a, a);
(%o4) 5.0
See also: np_matmul, np_sum
np_sort (a) / np_sort (a, axis) — Function
Sort array elements in ascending order. Signals an error for complex arrays.
Without an axis argument, flattens to 1D and sorts. With an axis argument, sorts along the specified axis (preserving shape). Uses a stable sort — equal elements maintain their relative order. Returns a new ndarray; the input is not modified.
Calling forms:
np_sort(a)– flatten and sort, returns a 1D ndarraynp_sort(a, 0)– sort each column independently, returns same shapenp_sort(a, 1)– sort each row independently, returns same shape
Examples
(%i1) A : ndarray([3, 1, 4, 1, 5], [5]);
(%o1) ndarray([5], DOUBLE-FLOAT)
(%i2) np_to_list(np_sort(A));
(%o2) [1.0, 1.0, 3.0, 4.0, 5.0]
(%i3) B : ndarray(matrix([3, 1], [1, 4]));
(%o3) ndarray([2, 2], DOUBLE-FLOAT)
(%i4) np_to_matrix(np_sort(B, 0));
(%o4) matrix([1.0, 1.0], [3.0, 4.0])
(%i5) np_to_matrix(np_sort(B, 1));
(%o5) matrix([1.0, 3.0], [1.0, 4.0])
See also: np_argsort, np_min, np_max
np_argsort (a) / np_argsort (a, axis) — Function
Indices that would sort array elements in ascending order. Signals an error for complex arrays.
Without an axis argument, returns flat indices for the flattened array. With an axis argument, returns indices along the specified axis. Indices are stored as double-float values. Uses a stable sort.
Calling forms:
np_argsort(a)– flat indices, returns a 1D ndarraynp_argsort(a, 0)– row indices that sort each column, returns same shapenp_argsort(a, 1)– column indices that sort each row, returns same shape
Examples
(%i1) A : ndarray([3, 1, 2], [3]);
(%o1) ndarray([3], DOUBLE-FLOAT)
(%i2) np_to_list(np_argsort(A));
(%o2) [1.0, 2.0, 0.0]
(%i3) B : ndarray(matrix([3, 1], [1, 4]));
(%o3) ndarray([2, 2], DOUBLE-FLOAT)
(%i4) np_to_matrix(np_argsort(B, 0));
(%o4) matrix([1.0, 0.0], [0.0, 1.0])
(%i5) np_to_matrix(np_argsort(B, 1));
(%o5) matrix([1.0, 0.0], [0.0, 1.0])
See also: np_sort, np_argmin, np_argmax
np_trapz (y) / np_trapz (y, x) — Function
Trapezoidal numerical integration of a 1D ndarray.
Without an x argument, uses unit spacing (dx = 1). With an x argument, uses the spacing defined by the x array. Both y and x must be 1D ndarrays of the same length. Returns a scalar.
Calling forms:
np_trapz(y)– integrate with unit spacingnp_trapz(y, x)– integrate with variable spacing defined by x
Examples
(%i1) /* Unit spacing: integral of [1, 2, 3] = 0.5*(1+2) + 0.5*(2+3) = 4 */
np_trapz(ndarray([1, 2, 3], [3]));
(%o1) 4.0
(%i2) /* Variable spacing: y=x^2 on [0,1,2] */
x : ndarray([0, 1, 2], [3]);
(%o2) ndarray([3], DOUBLE-FLOAT)
(%i3) y : ndarray([0, 1, 4], [3]);
(%o3) ndarray([3], DOUBLE-FLOAT)
(%i4) np_trapz(y, x);
(%o4) 3.0
See also: np_sum, np_cumsum, np_diff
np_diff (a) — Function
First-order finite differences of a 1D ndarray.
Returns a new 1D ndarray of length n-1 where element i is a[i+1] - a[i]. The input must be a 1D ndarray with at least 2 elements.
Examples
(%i1) np_to_list(np_diff(ndarray([1, 3, 6, 10], [4])));
(%o1) [2.0, 3.0, 4.0]
(%i2) np_size(np_diff(np_arange(10)));
(%o2) 9
(%i3) /* Constant array: all diffs are zero */
np_to_list(np_diff(np_ones([5])));
(%o3) [0.0, 0.0, 0.0, 0.0]
See also: np_cumsum, np_trapz
np_cov (a) — Function
Sample covariance matrix of a 2D ndarray.
Treats each column as a variable and each row as an observation. Returns a p-by-p covariance matrix (where p is the number of columns) using the sample covariance formula (divides by n-1). The result is symmetric.
Examples
(%i1) /* 3 observations of 2 variables, perfectly correlated */
A : ndarray(matrix([1, 2], [3, 6], [5, 10]));
(%o1) ndarray([3, 2], DOUBLE-FLOAT)
(%i2) np_to_matrix(np_cov(A));
(%o2) matrix([4.0, 8.0], [8.0, 16.0])
(%i3) /* Symmetry: C[i,j] = C[j,i] */
C : np_to_matrix(np_cov(ndarray(matrix([1,2,3],[4,5,6],[7,8,9]))));
(%o3) matrix([9.0, 9.0, 9.0], [9.0, 9.0, 9.0], [9.0, 9.0, 9.0])
See also: np_corrcoef, np_var, np_std
np_corrcoef (a) — Function
Pearson correlation coefficient matrix of a 2D ndarray.
Treats each column as a variable and each row as an observation. Returns a p-by-p correlation matrix where element (i,j) is the Pearson correlation between columns i and j. Diagonal elements are always 1.0. Built on np_cov.
Examples
(%i1) /* Perfect positive correlation gives 1 */
A : ndarray(matrix([1, 2], [3, 6], [5, 10]));
(%o1) ndarray([3, 2], DOUBLE-FLOAT)
(%i2) np_to_matrix(np_corrcoef(A));
(%o2) matrix([1.0, 1.0], [1.0, 1.0])
(%i3) /* Anti-correlation gives -1 */
B : ndarray(matrix([1, 10], [3, 6], [5, 2]));
(%o3) ndarray([3, 2], DOUBLE-FLOAT)
(%i4) np_to_matrix(np_corrcoef(B));
(%o4) matrix([1.0, -1.0], [-1.0, 1.0])
See also: np_cov, np_var, np_std
Optimization
Numerical optimization using the L-BFGS (Limited-memory Broyden-Fletcher-Goldfarb-Shanno) algorithm. Wraps Maxima’s built-in L-BFGS implementation to work directly with ndarrays.
The optimization functions are in a separate sub-module (loaded separately from the core numerics package):
(%i1) load("numerics")$
(%i2) load("numerics-optimize")$
np_minimize (f, grad, x0) — Function
np_minimize (f, grad, x0, tolerance) — Function
np_minimize (f, grad, x0, tolerance, max_iter) — Function
Minimize a scalar-valued function using gradient-based L-BFGS optimization.
Arguments:
f— objective function taking an ndarray, returning a scalargrad— gradient function taking an ndarray, returning an ndarray of the same shapex0— initial point (real ndarray, any shape)tolerance— convergence tolerance (default:1e-8)max_iter— maximum number of iterations (default:200)
Returns: a list [x_opt, f_opt, converged] where:
x_opt— the optimized ndarray (same shape asx0)f_opt— the final objective valueconverged—trueif L-BFGS converged,falseotherwise
Both f and grad can be named functions or lambda expressions. The shape of x0 is preserved in the output — if you pass a [p, 1] column vector, you get a [p, 1] result.
Examples
Simple quadratic:
(%i1) f(x) := np_sum(np_pow(x, 2))$
(%i2) grad(x) := np_scale(2.0, x)$
(%i3) [x_opt, f_opt, ok] : np_minimize(f, grad, ndarray([3.0, 4.0]));
(%o3) [ndarray([2], DOUBLE-FLOAT), 1.97e-30, true]
(%i4) np_to_list(x_opt);
(%o4) [2.80e-16, 3.55e-16]
Rosenbrock function (classic optimization benchmark):
(%i1) f_rosen(x) := block([x1, x2],
x1 : np_ref(x, 0), x2 : np_ref(x, 1),
(1 - x1)^2 + 100 * (x2 - x1^2)^2)$
(%i2) g_rosen(x) := block([x1, x2],
x1 : np_ref(x, 0), x2 : np_ref(x, 1),
ndarray([-2*(1 - x1) - 400*x1*(x2 - x1^2),
200*(x2 - x1^2)]))$
(%i3) [x_opt, f_opt, ok] : np_minimize(f_rosen, g_rosen,
ndarray([-1.0, 1.0]), 1e-10, 500);
(%o3) [ndarray([2], DOUBLE-FLOAT), 0.0, true]
(%i4) np_to_list(x_opt);
(%o4) [1.0, 1.0]
Linear regression (symbolic-numeric bridge):
(%i1) /* Derive gradient symbolically */
L_i(a, b, x_i, y_i) := (1/2) * (y_i - a - b*x_i)^2$
(%i2) diff(L_i(a, b, x[i], y[i]), a);
(%o2) -(y_i - b*x_i - a)
(%i3) /* Implement as ndarray functions */
cost(w) := block([pred, res],
pred : np_matmul(X, w),
res : np_sub(pred, y),
np_sum(np_pow(res, 2)) / (2*n))$
(%i4) grad(w) := np_scale(1.0/n,
np_matmul(np_transpose(X), np_sub(np_matmul(X, w), y)))$
(%i5) [w_opt, loss, ok] : np_minimize(cost, grad, np_zeros([2, 1]))$
With lambda expressions:
(%i1) [x_opt, _, ok] : np_minimize(
lambda([x], np_sum(np_pow(x, 2))),
lambda([x], np_scale(2.0, x)),
ndarray([5.0, 5.0]));
(%o1) [ndarray([2], DOUBLE-FLOAT), 1.42e-29, true]
See also: np_lstsq (for linear least-squares problems)
Linear Algebra
np_matmul (a, b) — Function
Matrix multiplication. Supports complex arrays.
Computes the matrix product of two 2D ndarrays using BLAS. The number of columns of a must equal the number of rows of b.
Examples
(%i1) A : ndarray(matrix([1, 2], [3, 4]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) I : np_eye(2);
(%o2) ndarray([2, 2], DOUBLE-FLOAT)
(%i3) np_to_matrix(np_matmul(I, A));
(%o3) matrix([1.0, 2.0], [3.0, 4.0])
(%i4) np_to_matrix(np_matmul(A, A));
(%o4) matrix([7.0, 10.0], [15.0, 22.0])
See also: np_dot, np_inv, np_solve
np_inv (a) — Function
Matrix inverse. Supports complex arrays.
Computes the inverse of a square matrix using LAPACK. Signals an error if the matrix is singular or nearly singular.
Examples
(%i1) A : ndarray(matrix([1, 2], [3, 4]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) Ainv : np_inv(A);
(%o2) ndarray([2, 2], DOUBLE-FLOAT)
(%i3) np_to_matrix(np_matmul(A, Ainv));
(%o3) matrix([1.0, 0.0], [0.0, 1.0])
(%i4) errcatch(np_inv(ndarray(matrix([1, 0], [0, 0]))));
(%o4) []
See also: np_solve, np_det, np_pinv
np_det (a) — Function
Determinant of a square matrix.
Returns a scalar (complex for complex input). Uses LAPACK for computation.
Examples
(%i1) A : ndarray(matrix([1, 2], [3, 4]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_det(A);
(%o2) -2.0
(%i3) np_det(np_eye(5));
(%o3) 1.0
See also: np_inv, np_rank
np_solve (a, b) — Function
Solve the linear system Ax = b. Supports complex arrays.
Computes the solution to a system of linear equations where a is a square coefficient matrix and b is a right-hand side vector or matrix. Uses LAPACK.
Examples
(%i1) A : ndarray(matrix([2, 1], [5, 3]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) b : ndarray(matrix([4], [7]));
(%o2) ndarray([2, 1], DOUBLE-FLOAT)
(%i3) x : np_solve(A, b);
(%o3) ndarray([2, 1], DOUBLE-FLOAT)
(%i4) np_to_matrix(np_matmul(A, x));
(%o4) matrix([4.0], [7.0])
See also: np_inv, np_lstsq
np_svd (a) — Function
Singular Value Decomposition. Supports complex arrays.
Decomposes a into U, S, and Vt such that A = U * diag(S) * Vt, where U and Vt are orthogonal (or unitary for complex) matrices. S is returned as a 1D ndarray of singular values (not a diagonal matrix), always double-float. Returns a Maxima list [U, S, Vt].
Returns the economy (reduced) SVD: for an m-by-n matrix with k = min(m,n), U is m-by-k, S has k elements, and Vt is k-by-n. This means np_matmul(np_matmul(U, np_diag(np_to_list(S))), Vt) reconstructs A directly for any shape.
Examples
(%i1) A : ndarray(matrix([1, 0], [0, 2], [0, 0]));
(%o1) ndarray([3, 2], DOUBLE-FLOAT)
(%i2) [U, S, Vt] : np_svd(A);
(%o2) [ndarray, ndarray, ndarray]
(%i3) np_shape(U);
(%o3) [3, 2]
(%i4) np_shape(Vt);
(%o4) [2, 2]
(%i5) np_to_list(S);
(%o5) [2.0, 1.0]
(%i6) /* Reconstruct: U * diag(S) * Vt works directly */
np_norm(np_sub(A, np_matmul(np_matmul(U, np_diag(np_to_list(S))), Vt)));
(%o6) 0.0
See also: np_eig, np_rank, np_lstsq, np_pinv
np_eig (a) — Function
Eigendecomposition.
Computes eigenvalues and eigenvectors of a square matrix. Returns a Maxima list [eigenvalues, eigenvectors] where eigenvalues is a 1D ndarray and eigenvectors is a 2D ndarray whose columns are the eigenvectors.
When eigenvalues have non-negligible imaginary parts (e.g. rotation matrices, non-symmetric matrices), the returned ndarrays use complex-double-float dtype. When all eigenvalues are real, returns double-float ndarrays.
Examples
(%i1) A : ndarray(matrix([2, 1, 0], [1, 3, 1], [0, 1, 2]));
(%o1) ndarray([3, 3], DOUBLE-FLOAT)
(%i2) [vals, vecs] : np_eig(A);
(%o2) [ndarray, ndarray]
(%i3) np_to_list(vals);
(%o3) [1.0, 2.0, 4.0]
(%i4) /* Verify A*v = lambda*v */
np_to_matrix(np_sub(np_matmul(A, vecs),
np_matmul(vecs, np_diag(np_to_list(vals)))));
(%o4) matrix([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0])
See also: np_svd
np_qr (a) — Function
QR decomposition. Works for any m-by-n matrix. Supports complex arrays.
Decomposes a into an orthogonal (or unitary for complex) matrix Q and an upper triangular (or upper trapezoidal) matrix R such that A = Q * R. Returns a Maxima list [Q, R]. For tall/square matrices (m >= n), uses LAPACK. For wide matrices (m < n), uses Householder reflections.
Examples
(%i1) A : ndarray(matrix([1, 2], [3, 4], [5, 6]));
(%o1) ndarray([3, 2], DOUBLE-FLOAT)
(%i2) [Q, R] : np_qr(A);
(%o2) [ndarray, ndarray]
(%i3) np_shape(Q);
(%o3) [3, 3]
(%i4) np_shape(R);
(%o4) [3, 2]
See also: np_lu, np_svd
np_lu (a) — Function
LU decomposition with partial pivoting. Supports complex arrays.
Decomposes a into a lower triangular matrix L (unit diagonal), an upper triangular matrix U, and a permutation matrix P such that P * A = L * U. Returns a Maxima list [L, U, P].
For an m-by-n matrix, L is m-by-min(m,n), U is min(m,n)-by-n, and P is m-by-m.
Examples
(%i1) A : ndarray(matrix([1, 2, 3], [4, 5, 6], [7, 8, 10]));
(%o1) ndarray([3, 3], DOUBLE-FLOAT)
(%i2) [L, U, P] : np_lu(A);
(%o2) [ndarray, ndarray, ndarray]
(%i3) /* Verify P*A = L*U */
np_to_matrix(np_sub(np_matmul(P, A), np_matmul(L, U)));
(%o3) matrix([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0])
See also: np_qr, np_svd, np_solve
np_norm (a) / np_norm (a, ord) — Function
Matrix or vector norm. Supports complex arrays.
By default, computes the 2-norm for vectors and the Frobenius norm for matrices. The optional ord parameter selects the norm type. The result is always real (double-float).
Calling forms:
np_norm(a)– default norm (2-norm for vectors, Frobenius for matrices)np_norm(a, 1)– 1-norm (sum of abs for vectors, max column sum for matrices)np_norm(a, 2)– 2-norm (Euclidean for vectors, spectral/largest singular value for matrices)np_norm(a, inf)– infinity norm (max abs for vectors, max row sum for matrices)np_norm(a, fro)– Frobenius norm (matrices only, same as default)
Examples
(%i1) v : ndarray([1, -2, 3], [3]);
(%o1) ndarray([3], DOUBLE-FLOAT)
(%i2) np_norm(v);
(%o2) 3.7416573867739413
(%i3) np_norm(v, 1);
(%o3) 6.0
(%i4) np_norm(v, inf);
(%o4) 3.0
(%i5) A : ndarray(matrix([1, -7], [2, -3]));
(%o5) ndarray([2, 2], DOUBLE-FLOAT)
(%i6) np_norm(A, 1);
(%o6) 10.0
(%i7) np_norm(A, inf);
(%o7) 8.0
(%i8) np_norm(A, 2);
(%o8) 7.649700064568801
See also: np_det, np_rank
np_rank (a) — Function
Numerical rank of a matrix.
Computed via SVD. Counts the number of singular values above a tolerance threshold (proportional to machine epsilon and the largest singular value). Returns an integer.
Examples
(%i1) np_rank(np_eye(3));
(%o1) 3
(%i2) np_rank(ndarray(matrix([1, 2], [2, 4])));
(%o2) 1
(%i3) np_rank(np_zeros([3, 3]));
(%o3) 0
See also: np_svd, np_det
np_trace (a) — Function
Matrix trace (sum of diagonal elements).
Returns a scalar equal to the sum of the elements on the main diagonal (complex for complex input).
Examples
(%i1) A : ndarray(matrix([1, 2], [3, 4]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_trace(A);
(%o2) 5.0
(%i3) np_trace(np_eye(5));
(%o3) 5.0
See also: np_det, np_diag
np_transpose (a) — Function
Matrix transpose. Supports complex arrays (transpose only, no conjugation; see np_ctranspose).
Returns a new ndarray with rows and columns swapped.
Examples
(%i1) A : ndarray(matrix([1, 2], [3, 4]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_to_matrix(np_transpose(A));
(%o2) matrix([1.0, 3.0], [2.0, 4.0])
(%i3) np_shape(np_transpose(ndarray(matrix([1, 2, 3]))));
(%o3) [3, 1]
See also: np_conj, np_ctranspose, np_reshape
np_conj (a) — Function
Element-wise complex conjugate.
Returns a new ndarray where each element is the complex conjugate of the corresponding element in a. For real (double-float) arrays, this returns a copy of a unchanged. For complex arrays, conjugates each element (negates the imaginary part).
Examples
(%i1) A : ndarray(matrix([1+%i, 2-3*%i]), complex);
(%o1) ndarray([1, 2], COMPLEX-DOUBLE-FLOAT)
(%i2) np_to_list(np_conj(A));
(%o2) [1.0 - 1.0*%i, 2.0 + 3.0*%i]
(%i3) /* Real arrays are unchanged */
np_to_list(np_conj(ndarray([1, 2, 3], [3])));
(%o3) [1.0, 2.0, 3.0]
See also: np_ctranspose, np_transpose, np_real, np_imag
np_ctranspose (a) — Function
Conjugate transpose (Hermitian transpose).
For real matrices, this is the same as np_transpose. For complex matrices, it transposes and takes the complex conjugate of each element.
Examples
(%i1) A : ndarray(matrix([1, 2], [3, 4]));
(%o1) ndarray([2, 2], DOUBLE-FLOAT)
(%i2) np_to_matrix(np_ctranspose(A));
(%o2) matrix([1.0, 3.0], [2.0, 4.0])
See also: np_conj, np_transpose
np_real (a) — Function
Extract real parts element-wise.
Returns a new double-float ndarray containing the real part of each element. For real arrays, this is equivalent to np_copy.
Examples
(%i1) A : ndarray(matrix([1+2*%i, 3-4*%i]), complex);
(%o1) ndarray([1, 2], COMPLEX-DOUBLE-FLOAT)
(%i2) np_to_list(np_real(A));
(%o2) [1.0, 3.0]
See also: np_imag, np_angle, np_conj
np_imag (a) — Function
Extract imaginary parts element-wise.
Returns a new double-float ndarray containing the imaginary part of each element. For real arrays, returns all zeros.
Examples
(%i1) A : ndarray(matrix([1+2*%i, 3-4*%i]), complex);
(%o1) ndarray([1, 2], COMPLEX-DOUBLE-FLOAT)
(%i2) np_to_list(np_imag(A));
(%o2) [2.0, -4.0]
See also: np_real, np_angle, np_conj
np_angle (a) — Function
Element-wise phase angle.
Returns a new double-float ndarray containing the phase angle (argument) of each element in radians. For real positive numbers, returns 0; for real negative numbers, returns pi.
Examples
(%i1) A : ndarray(matrix([1, -1, %i]), complex);
(%o1) ndarray([1, 3], COMPLEX-DOUBLE-FLOAT)
(%i2) np_to_list(np_angle(A));
(%o2) [0.0, 3.141592653589793, 1.5707963267948966]
See also: np_real, np_imag, np_abs
np_expm (a) — Function
Matrix exponential. Supports complex arrays.
Computes the matrix exponential e^A, which is defined as the infinite series I + A + A^2/2! + A^3/3! + …. This is different from element-wise np_exp, which applies the scalar exponential to each element independently.
Uses the scaling-and-squaring method with adaptive diagonal Pade approximation (orders 3, 5, 7, 9, or 13 selected automatically based on the matrix 1-norm). The algorithm follows Higham (2005), “The Scaling and Squaring Method for the Matrix Exponential Revisited”.
Examples
(%i1) /* expm(0) = I */
np_to_matrix(np_expm(np_zeros([2, 2])));
(%o1) matrix([1.0, 0.0], [0.0, 1.0])
(%i2) /* expm(I) = e*I */
np_ref(np_expm(np_eye(2)), 0, 0);
(%o2) 2.718281828459045
(%i3) /* Rotation matrix from skew-symmetric */
R : ndarray(matrix([0, -1], [1, 0]));
(%o3) ndarray([2, 2], DOUBLE-FLOAT)
(%i4) E : np_to_matrix(np_expm(R));
(%o4) matrix([0.5403023058681398, -0.8414709848078965],
[0.8414709848078965, 0.5403023058681398])
(%i5) /* expm(A) * expm(-A) = I */
A : ndarray(matrix([1, 2], [3, 4]));
(%o5) ndarray([2, 2], DOUBLE-FLOAT)
(%i6) np_to_matrix(np_matmul(np_expm(A), np_expm(np_neg(A))));
(%o6) matrix([1.0, 0.0], [0.0, 1.0])
See also: np_exp, np_matmul
np_lstsq (a, b) — Function
Least-squares solution to Ax = b. Supports complex arrays.
Finds x that minimizes ||Ax - b||_2 using SVD. Works for over-determined systems (more equations than unknowns) and under-determined systems. For square full-rank matrices, gives the same result as np_solve.
Returns a Maxima list [x, residuals, rank, S] where:
- x — n-by-p solution ndarray
- residuals — 1D ndarray of squared residual norms
||Ax_j - b_j||^2for each column j of b (alwaysdouble-float). Only non-empty whenm > n(overdetermined) and A is full rank; otherwise an empty list[]. - rank — effective rank of A (integer)
- S — 1D ndarray of singular values of A (always
double-float)
Breaking change: Previous versions returned only x. Update callers from x : np_lstsq(A, b) to [x, residuals, rank, S] : np_lstsq(A, b).
Examples
(%i1) /* Linear fit: y = a + b*x through (1,1), (2,2), (3,3) */
A : ndarray(matrix([1, 1], [1, 2], [1, 3]));
(%o1) ndarray([3, 2], DOUBLE-FLOAT)
(%i2) b : ndarray(matrix([1], [2], [3]));
(%o2) ndarray([3, 1], DOUBLE-FLOAT)
(%i3) [x, residuals, rank, S] : np_lstsq(A, b);
(%o3) [ndarray, ndarray, 2, ndarray]
(%i4) np_to_list(x);
(%o4) [0.0, 1.0]
(%i5) rank;
(%o5) 2
(%i6) np_to_list(S);
(%o6) [3.86..., 0.64...]
See also: np_solve, np_pinv, np_svd
np_pinv (a) — Function
Moore-Penrose pseudo-inverse. Supports complex arrays.
Computed via SVD as A+ = V * S+ * Ut, where S+ inverts the non-zero singular values. For invertible square matrices, this is equivalent to np_inv. For non-square or rank-deficient matrices, it gives the best least-squares inverse.
The pseudo-inverse satisfies the four Moore-Penrose conditions: AA+A = A, A+AA+ = A+, (AA+)^T = AA+, and (A+*A)^T = A+*A.
For an m-by-n matrix, the pseudo-inverse is n-by-m.
Examples
(%i1) A : ndarray(matrix([1, 2], [3, 4], [5, 6]));
(%o1) ndarray([3, 2], DOUBLE-FLOAT)
(%i2) Ap : np_pinv(A);
(%o2) ndarray([2, 3], DOUBLE-FLOAT)
(%i3) /* Verify A * pinv(A) * A = A */
np_to_matrix(np_sub(np_matmul(np_matmul(A, Ap), A), A));
(%o3) matrix([0.0, 0.0], [0.0, 0.0], [0.0, 0.0])
(%i4) /* pinv(A) * b gives least-squares solution */
b : ndarray(matrix([1], [2], [3]));
(%o4) ndarray([3, 1], DOUBLE-FLOAT)
(%i5) np_to_list(np_matmul(Ap, b));
(%o5) [0.0, 1.0]
See also: np_inv, np_lstsq, np_svd
np_outer (a, b) — Function
Outer product of two 1D ndarrays.
Returns an m-by-n 2D ndarray where element (i,j) is a[i] * b[j]. Both arguments must be 1D ndarrays.
Examples
(%i1) np_to_matrix(np_outer(ndarray([1, 2, 3], [3]), ndarray([4, 5], [2])));
(%o1) matrix([4.0, 5.0], [8.0, 10.0], [12.0, 15.0])
(%i2) np_shape(np_outer(np_ones([4]), np_ones([3])));
(%o2) [4, 3]
(%i3) /* Outer product with self gives rank-1 matrix */
v : ndarray([1, 2], [2]);
(%o3) ndarray([2], DOUBLE-FLOAT)
(%i4) np_det(np_outer(v, v));
(%o4) 0.0
See also: np_matmul, np_dot