Labs / MicroPython tutorials

Quick Start Guide to ulab: A Lightweight Subset of numpy/scipy

Author: Li Zisheng · Source: FreakStudio open documentation, v1.0 · License: CC BY 4.0

Contents

I. Detailed Explanation of Core Information of ulab

1.1 Positioning and Design Objectives of ulab

ulab is a lightweight numpy/scipy subset built for MicroPython, optimized specifically for microcontroller use cases, with three core design objectives:

The core features supported by ulab include: multi-dimensional numerical arrays, vectorized computation, statistical analysis, linear algebra, FFT, filtering, polynomial fitting, etc. The default firmware is approximately 120kB and can be customized and reduced to less than 10kB.

1.2 Firmware Customization (The Key to Reducing Size)

The functions of ulab are controlled by preprocessor macro switches in ulab.h, the core customization methods are as follows:

1.3 Compatibility with numpy

ulab is designed to be as compatible with the NumPy interface as possible, enabling code to run across both CPython and MicroPython:

from ulab import numpy as np
from ulab import scipy as spy
try:
    # MicroPython environment
    from ulab import numpy as np
    from ulab import scipy as spy
except ImportError:
    # CPython environment
    import numpy as np
    import scipy as spy

# Common code that runs on both
x = np.array([1, 2, 3])
print(spy.special.erf(x))

1.4 Version String Interpretation

The version of ulab contains key information in the format: major.minor.patch-dimensionD[-c]:

import ulab
version = ulab.__version__
dims = int(version.split('-')[1].replace('D', ''))  # Extract the dimension (e.g., 2)
has_complex = '-c' in version  # Check whether complex numbers are supported

1.5 Check Functions Supported by the Firmware

1.5.1 View Modules / Functions

Use dir () to view the functions/submodules compiled into the firmware:

from ulab import numpy as np
from ulab import scipy as spy

# View the numpy core functions
print(dir(np))
# View the fft submodule functions
print(dir(np.fft))
# View the scipy signal submodule functions
print(dir(spy.signal))

1.5.2 View Array Methods

ndarray class methods need to be viewed via array objects:

from ulab import numpy as np
print(dir(np.array([1,2,3])))  # Output the supported methods (e.g., reshape, transpose, etc.)

1.5.3 Verify whether the operator is supported

Operators cannot be viewed via dir (); try invoking them and catching exceptions:

from ulab import numpy as np

a = np.array([1,2,3])
b = np.array([4,5,6])
try:
    print(a ** b)  # Verify the power operator
except Exception as e:
    print(f"运算符不支持:{e}")

II. Detailed Explanation of Core Knowledge Points of ndarray

2.1 Basic Features of ndarray

ndarray is the core container for storing numerical data in ulab, and it has two major core advantages over Python's native lists:

Key tool function: np.ndinfo (), which is used to print the core metadata of an array (shape/strides/itemsize/data pointer/dtype) to help understand the memory layout:

from ulab import numpy as np

a = np.array(range(5), dtype=np.float)
np.ndinfo(a)
# Output:
# class: ndarray
# shape: (5,)
# strides: (8,)
# itemsize: 8
# data pointer: 0x7f8f6fa2e240
# type: float

2.2 Array Initialization

2.2.1 Basic Construction: np.array ()

# 1D array
a = np.array([1,2,3], dtype=np.uint8)
# 2D array (mixed iterable types)
b = np.array([range(5), [44,55,66,77,88]], dtype=np.uint8)
# Initialize from another array (fast copy of the same type)
c = np.array(b, dtype=np.uint8)

2.2.2 Dedicated Initialization Function

FunctionFunctionKey notes
np.arange(start, stop, step, dtype)Generate a 1-D array with equal step sizestep is optional, default dtype is int16
np.concatenate((a, b), axis)Concatenate arraysRequires arrays to have exactly the same dtype, otherwise convert types first
np.frombuffer(buffer, dtype, offset, count)Map an array from a byte bufferReuses memory directly; modifying the byte data also modifies the array contents
np.linspace(start, stop, num, endpoint, dtype)Generate an evenly spaced arrayWith an integer dtype, rounding may cause uneven spacing
np.logspace(start, stop, num, base, dtype)Generate a logarithmically spaced arraybase defaults to 10
np.ones / np.zeros(shape, dtype)Generate an all-1 / all-0 arrayshape can be an integer (1-D) or a tuple (higher dimensions), and cannot exceed the maximum dimensions supported by the firmware
np.eye(N, M, k, dtype)Generate an identity matrixk is the diagonal offset; when M is omitted, a square matrix is generated
np.full(shape, value, dtype)Generate an array filled with a given valueSupports complex numbers (requires firmware with complex support enabled)

Example: Efficiently Peripheral Buffer Processing

# Quickly generate an array from an ADC byte buffer (no per-element conversion needed)
buffer = b'\x01\x02\x03\x04\x05'
a = np.frombuffer(buffer, dtype=np.uint8, offset=1, count=3)
print(a)  # array([2, 3, 4], dtype=uint8)

2.3 Attributes and Methods of ndarray

CategoryNameFunctionKey notes
Core attributesdtypeArray data typeWhen firmware ULAB_HAS_DTYPE_OBJECT = 0, returns the ASCII code (e.g., int8 corresponds to 98)
Core attributesshapeArray shape (tuple)Can be modified by direct assignment (e.g., a.shape = (3, 3))
Core attributessizeTotal number of array elementsFor higher-dimensional arrays, the product of the axis lengths
Core attributesitemsizeBytes per elementuint8 = 1, float = 4 / 8 (depends on platform)
Core attributesTTranspose the arrayEquivalent to transpose(), only supports dimensions > 1
Core methodscopy()Deep copy the arrayGenerates a new array with independent memory; modifying it does not affect the original array
Core methodsreshape(shape)Change the array shapeOnly modifies header information, data memory is unchanged, and the shape must match the total number of elements
Core methodsflatten(order='C' / 'F')Flatten the arrayC-style (row-major), F-style (column-major)
Core methodstobytes()Convert to a byte arrayModifying the byte array also modifies the original array; calling on a sliced array raises an exception
Core methodstolist()Convert to a Python listHigher-dimensional arrays are converted to nested lists
Core methodssort(axis)Sort in placeaxis=0 (columns), axis=1 (rows), None (flatten, then sort)
Special methodsbyteswap()Byte swapUsed to handle peripheral endianness mismatch, only valid for uint16 / int16 / float

Core Difference: View vs Copy

a = np.zeros((3,3), dtype=np.uint8)
b = a[:,:]  # View: shares data memory, only changes the header
c = a.copy() # Copy: independent memory

b[0] = 1     # Modifying the view changes the original array
print(a[0])  # array([1, 1, 1], dtype=uint8)
c[0] = 2     # Modifying the copy does not affect the original array
print(a[0])  # array([1, 1, 1], dtype=uint8)

2.4 Operator Usage Rules

2.4.1 Unary Operators

Operator / functionFunctionApplicable types
len()Returns the length of the first axisAll dimensions
~ (invert)Bitwise NOTInteger types only (uint8 / int8 / uint16 / int16)
abs()Absolute valueAll numeric types
- (neg)NegationNegates integer types; unsigned types will overflow (wrap)
#NAME?Returns a copyAll types

2.4.2 Binary Operators

Supports +/-/*/**/%/+=/-= and other operators, as well as bitwise operations (&/|/^), with the core rules as follows:

Example: Broadcasting Operation

a = np.array([[1,2],[3,4]], dtype=np.uint8)
b = np.array([10,20], dtype=np.uint8)
print(a + b)  # Broadcasting: array([[11,22],[13,24]], dtype=uint8)

2.5 Slicing and Indexing

2.5.1 Indexing Method

2.5.2 Core Principle: View-First

What slicing/indexing returns is a view (only the header metadata is modified, while the data memory is shared), which is the key to ulab's high efficiency:

Example: Filtering Data with Boolean Indexing

a = np.array(range(9), dtype=np.uint8)
b = np.array([4,4,4,3,3,3,13,13,13], dtype=np.uint8)
# Filter elements where a² > 100*sin(b)
result = a[a*a > np.sin(b)*100.0]
print(result)  # array([0, 1, 2, 4, 5, 7, 8], dtype=uint8)

3. Classification and Core Description of numpy Functions in ulab

As a lightweight numerical computation library under MicroPython, ulab adapts the core functions of NumPy while being streamlined and adjusted for embedded scenarios. The key functions are categorized by function as follows:

3.1 Logical Judgment Category

FunctionCore functionKey notes
np.all()Check whether all elements of the array along the specified axis are True (non-0 / non-False)When axis=None, checks the flattened array; supports complex arrays (requires complex support enabled at firmware compile time)
np.any()Check whether at least one element of the array along the specified axis is TrueLogic is consistent with all(), only checks "existence"
np.equal() / np.not_equal()Element-wise comparison for equal / not equalUsed in place of == / != in CPython, to avoid abnormal behavior in CircuitPython
np.isfinite()Determine whether elements are finite valuesInteger types return True by default; returns a boolean array with the same shape as the original array
np.isinf()Determine whether elements are infiniteInteger types return False by default; returns a boolean array with the same shape as the original array

3.2 Indexing and Sorting Category

FunctionCore functionKey notes
np.argmax() / np.argmin()Return the index of the maximum / minimum value in the arrayWhen axis=None, computed on the flattened array
np.argsort()Return the array of sorted indices (ascending)Output is uint16 type, dimensions cannot exceed 65535; axis=None (flatten and sort) is not yet supported
np.sort()Sort the array in ascending order along the specified axis (heap sort)Generates a new array (not in-place sort); when axis=None, flattens then sorts; NumPy's kind / order parameters are not supported
np.sort_complex()Sort a complex array (by real part first, then by imaginary part)Only supports 1-D arrays; requires firmware with complex support enabled
np.nonzero()Return the indices of non-zero elementsFor multi-dimensional arrays, returns a tuple of "dimensions × index arrays"
np.where()Select values from x / y according to a conditionOnly supports ndarray; the three arguments must be broadcastable; the condition is expanded into a boolean array (uses extra memory)

3.3 Numerical Calculation Category

FunctionCore functionKey notes
np.max() / np.min()Compute the maximum / minimum value of the array along the specified axisDoes not support NumPy's out parameter; supports generic iterables
np.maximum() / np.minimum()Element-wise maximum / minimum of two arrays or scalarsDifferent dtypes are automatically upcast; supports broadcasting
np.mean() / np.median()Compute mean / medianmedian always returns a float
np.std() / np.sum()Compute standard deviation / sumWhen axis=None, computed on the flattened array
np.trace()Compute the trace of a square matrix (sum of the diagonal elements)Square matrices only; return dtype is the same as the input
np.diff()Compute numerical difference (forward difference)Supports n-th order differences (n ≤ 9); does not support NumPy's prepend / append parameters
np.clip()Limit array elements to a specified intervalEquivalent to max(a_min, min(a, a_max)); supports broadcasting
np.interp()One-dimensional linear interpolationxp must be monotonically increasing; left / right control the values returned for out-of-range inputs (endpoint values by default)
np.polyfit()Polynomial fittingImplemented via matrix inversion; x can be omitted (range(len(y)) is generated automatically)
np.polyval()Polynomial evaluationSupports list / ndarray as coefficients or independent variable
np.trapz()Numerical integration using the trapezoidal ruleSupports specifying the independent variable x; one-dimensional arrays only

3.4 Array Operations

FunctionCore functionKey notes
np.asarray()Convert to ndarrayIf the input is already an ndarray of the same dtype, it is returned directly (no copy)
np.flip()Flip array elements along the specified axisWhen axis=None, flips along all axes; returns a new array
np.roll()Circular shift along the specified axisHorizontal shifting is faster but uses more memory; when axis=None, the array is flattened before shifting
np.delete()Delete elements along the specified axisSupports negative indices; when axis=None, the array is flattened first
np.compress()Select elements along the specified axis by conditionSupports complex arrays (complex support must be enabled in the firmware)
np.take()Extract elements at the specified indices along the specified axisSupports the mode parameter (raise / wrap / clip) to handle out-of-range indices
np.size()Return the number of elements of the array along the specified axisWhen axis=None, returns the total number of elements in the array

3.5 Bitwise Operations

FunctionCore functionKey notes
np.bitwise_and() / np.bitwise_or() / np.bitwise_xor()Element-wise bitwise AND / OR / XORInteger arrays only; supports broadcasting
np.left_shift() / np.right_shift()Element-wise bitwise left shift / right shiftInteger arrays only; the shift amount is specified by the second array or scalar
FunctionCore functionKey notes
np.conjugate()Compute the conjugate of a complex arrayFor real arrays, only returns a copy (original dtype preserved)
np.imag()Extract the imaginary part of a complex arrayReturns all zeros for real arrays; ndarray only
np.real()Extract the real part of a complex arrayBehaves the same as np.imag()

3.7 Matrix and Convolution Category

FunctionCore functionKey notes
np.dot()Matrix multiplicationulab returns a float matrix directly (NumPy upcasts); matrix dimensions must be compatible
np.convolve()One-dimensional discrete convolutionOnly full mode is supported; supports complex arrays (complex support must be enabled in the firmware)

3.8 File IO Classes

FunctionCore functionKey notes
np.load() / np.save()Read and write NumPy binary format filesEndianness differences are handled automatically; save must be run in CPython (MicroPython requires filesystem support)
np.loadtxt() / np.savetxt()Read and write text format filesloadtxt supports skiprows / max_rows / usecols; savetxt outputs in floating-point format and supports header / footer

IV. ulab Library General Mathematical function

The universal functions of ulab are element-wise mathematical functions implemented with reference to NumPy, adapted for embedded scenarios, with the core features as follows:

4.1 Common Rules for Basic General Functions

FeatureDetails
Supported input typesAccepts scalars, scalar iterables (range / list / tuple), and ndarray; an ndarray input gives the best performance (no type detection or conversion needed)
Return typeReturns a float64 ndarray by default; exp / sqrt can return a complex array if complex support is enabled
out parameterOptional parameter out=None; passing a float ndarray of the same size as the input avoids repeated memory allocation; an exception is raised if the size or type requirements are not met
Element-wise executionAll functions are "element-wise operations" (e.g., exp of a matrix takes the exponential of each element, not the matrix exponential)
Supported function listacos / acosh / arctan2 / around / asin / asinh / atan / atanh / ceil / cos / degrees / exp* / expm1 / floor / log / log10 / log2 / radians / sin / sinc / sinh / sqrt* / tan / tanh (* indicates complex support, which must be enabled in the firmware)

Key Performance Conclusions:

Example Verification (taking np.exp as an example):

from ulab import numpy as np

# 1. Supports multiple input types
a = range(3)  # Iterable object
b = np.array(a)  # ndarray
print(np.exp(a))  # [1.0, 2.718..., 7.389...]
print(np.exp(b))  # Same result, faster

# 2. Use the out parameter to avoid memory allocation
out_arr = np.zeros(3)
np.exp(b, out=out_arr)
print(out_arr)  # Write directly to out_arr, no new array created

4.2 Exclusive Rules for Special General Functions

4.2.1 arctan2 (two-argument arctangent)

4.2.2 around (rounding off)

4.2.3 exp (exponential function)

b = np.array([1+1j, 2+2j], dtype=np.complex)
print(np.exp(b))  # [1.4687+2.2874j, -3.0749+6.7188j]

4.2.4 sqrt (square root)

a = np.array([1, -1])
print(np.sqrt(a))  # [1.0, nan]
print(np.sqrt(a, dtype=np.complex))  # [1.0+0.0j, 0.0+1.0j]

4.3 Custom function vectorization (np.vectorize)

ulab provides np.vectorize to convert a single-argument Python function into a "pseudo-vectorized function", the core rules are as follows:

4.3.1 Basic Usage

from ulab import numpy as np

# Custom single-argument function
def square(x):
    return x * x

# Vectorized wrapper
vec_square = np.vectorize(square)

# Supports scalar/ndarray/iterable input
print(vec_square(4))  # array([16.0], dtype=float64)
print(vec_square([1,2,3]))  # array([1.0,4.0,9.0], dtype=float64)

4.3.2 otypes Parameter: Specify the Output dtype

vec_square_uint8 = np.vectorize(square, otypes=np.uint8)
print(vec_square_uint8([1,2,3]))  # array([1,4,9], dtype=uint8)

# Wrong example: the function returns float, specifying uint8 will raise an error
# vec_square_uint8([1.0,2.0]) → TypeError: can't convert float to int

4.3.3 Performance Characteristics

np.vectorize essentially works by "looping and calling Python functions at the C layer", thus its performance improvement is limited:

Example (custom vectorization function combined with hardware):

from ulab import numpy as np
# Assume the pyb library is available (embedded hardware)
# import pyb
# led = pyb.LED(2)

def square_with_led(x):
    # Hardware operation: toggle the LED when x<100
    # if x < 100:
    #     led.toggle()
    return x*x

vec_func = np.vectorize(square_with_led)
print(vec_func(range(10)))  # Can interact with hardware during execution, while also returning the squared result

4.4 Key Differences Between ulab Universal Functions and Standard NumPy

Featureulabnumpy
around inputndarray onlySupports any iterable
around parametersNo out parameterSupports the out parameter
vectorize limitationsotypes cannot force type conversionTypes can be converted implicitly (e.g., float → int)
Complex supportRequires ULAB_SUPPORTS_COMPLEX to be enabled when compiling the firmwareNatively supported
Performance optimizationHighly optimized for ndarray (embedded scenarios)General optimization, no embedded-specific tuning

5. FFT/IFFT in ulab

The numpy.fft module of ulab only implements two core fft (Fast Fourier Transform) and ifft (Inverse Fast Fourier Transform) functions, which have been greatly adapted for embedded scenarios. The core features are as follows:

5.1 Core Rules (Default Behavior When Plural Support Is Unavailable)

This is the most basic usage mode of ulab (no need to modify compile macros), and it is also the default choice in embedded scenarios:

Featurefft functionifft function
Input parametersRequired: real array (ndarray);
Optional: imaginary array (ndarray, all zeros by default)
Format: np.fft.fft(real_arr[, imag_arr])
Required: real array + imaginary array output by FFT. Format:
np.fft.ifft(fft_real, fft_imag)
Return valueTuple of 2 ndarrays (real_part, imag_part) (real / imaginary parts after transform)Tuple of 2 ndarrays (real_part, imag_part)
(real / imaginary parts after inverse transform)
NormalizationNo normalizationNormalized by the number of elements N (same as NumPy), guaranteeing ifft(fft(x)) ≈ x
Input length requirementMust be a power of 2 (e.g., 2 / 4 / 8 / 1024), otherwise ValueError is raisedSame as the corresponding FFT input length (must be a power of 2)

Basic Usage Example:

from ulab import numpy as np

# Generate a 1024-point (2^10) sine signal (meets the length requirement)
x = np.linspace(0, 10, num=1024)
y = np.sin(x)  # Real signal, imaginary part defaults to all 0

# Forward FFT: pass only a real array, imaginary part is automatically 0
fft_real, fft_imag = np.fft.fft(y)

# Inverse IFFT: pass in the real and imaginary parts of the FFT, returns the original signal (real part close to the original signal, imaginary part close to 0)
ifft_real, ifft_imag = np.fft.ifft(fft_real, fft_imag)

print("原信号前3个值:", y[:3])
print("逆变换实部前3个值:", ifft_real[:3])
print("逆变换虚部前3个值:", ifft_imag[:3])  # Close to 0 (floating-point error)

5.2 NumPy Compatibility Mode After Enabling Complex Number Support

Modify the two compile macros in ulab.h (recompile the firmware):

#define ULAB_SUPPORTS_COMPLEX               (1)  // Enable complex array support
#define ULAB_FFT_IS_NUMPY_COMPATIBLE    (1)  // Enable FFT compatibility mode

Core Changes in Compatibility Mode:

FeatureCompatibility mode behaviorComparison with default mode
Input formatAccepts a real array (imaginary part defaults to 0) or a complex array; only a single array argument is needed (e.g., np.fft.fft(complex_arr))Requires both a real and an imaginary array
Return valueReturns a complex array directly (instead of a tuple of separate real and imaginary parts)Returns a (real part, imaginary part) tuple
Memory overheadIncreases RAM usage by about 50% (due to complex array storage + compatibility logic)Minimal memory overhead
CompatibilityCalling convention is identical to numpyDiffers significantly from numpy

Compatibility Mode Example:

from ulab import numpy as np

# Complex array input (complex support must be enabled)
complex_arr = np.array([1+0j, 2+0j, 3+0j, 4+0j], dtype=np.complex)
fft_complex = np.fft.fft(complex_arr)  # Return a complex array
ifft_complex = np.fft.ifft(fft_complex)  # Return a complex array

print("FFT结果:", fft_complex)
print("IFFT结果:", ifft_complex)  # Close to the original complex array

5.3 Key Differences from Standard NumPy

Featureulab (default mode)numpy
Input formatTwo arrays with separate real and imaginary partsSingle complex array (real input is automatically converted to complex with imaginary part 0)
Return value formatTuple with separate real and imaginary partsSingle complex array
Input lengthMust be a power of 2 (otherwise an exception is raised)Supports any length (a slow algorithm is used when not a power of 2)
Memory overheadSmall (computed in place, only needs space for the returned array)Large (complex array storage)
Normalizationifft is normalized by N (same as numpy)ifft is normalized by N

VI. The linalg Linear Algebra Module in ulab

The linear algebra module of ulab is lightweight-implemented for embedded scenarios, with only 7 core functions retained. Each function has clear input constraints and performance characteristics, and the following is the analysis by function:

6.1 Overview of function Features

FunctionCore functionInput requirementsKey limitations / differences from numpyPerformance (reference values)
choleskyLower-triangular decomposition of a positive-definite symmetric square matrix (LLᵀ = A)Positive-definite + symmetric + squareRaises ValueError if the input does not meet the conditions; same behavior as numpy-
detComputes the determinant of a square matrixAny square matrixReturn value is always float; same calculation logic as numpy8×8 matrix ~294 μs
eigComputes eigenvalues / eigenvectors of a real symmetric square matrixReal symmetric + squareSupports only real symmetric matrices; eigenvalue / eigenvector order / sign may differ from numpy (mathematically equivalent)4×4 matrix ~111 μs
invInverse of a non-singular square matrix (A⁻¹A = I)Non-singular + squareRaises ValueError for a singular matrix; memory overhead is 2 times the original matrix2×2 ~65 μs / 4×4 ~105 μs / 8×8 ~299 μs
normComputes the 2-norm (L2) of a vector / matrixndarray of any dimensionSupports only the 2-norm (numpy supports multiple norm types)-
qrQR decomposition of a matrix (A = QR, Q orthogonal, R upper triangular)Any M×N matrixSupports the mode parameter (reduced / complete); same behavior as numpy-

6.2 In-depth Analysis of Key Functions

6.2.1 eig (eigenvalues / eigenvectors)

The limitation that ulab imposes on this function is the core difference:

Example Verification (Real Symmetric Matrix):

from ulab import numpy as np

# Real symmetric matrix (symmetric across rows and columns)
a = np.array([[1,2],[2,5]])
eigenvals, eigenvecs = np.linalg.eig(a)
print("特征值:", eigenvals)       # Theoretical values: 0.1716, 5.8284
print("特征向量:\n", eigenvecs)  # Column vectors are the corresponding eigenvectors

6.2.2 norm (2-norm)

ulab only implements the most commonly used 2-norm, and has no ord parameter (numpy allows specifying the 1-norm, infinity norm, etc.):

Quick Start Guide to ulab: A Lightweight Subset of numpy/scipy

Example:

from ulab import numpy as np

vec = np.array([1,2,3])
mat = np.array([[1,2],[3,4]])
print("向量2-范数:", np.linalg.norm(vec))  # √(1+4+9)=√14≈3.7417
print("矩阵2-范数:", np.linalg.norm(mat))  # √(1+4+9+16)=√30≈5.4772

6.2.3 inv (matrix inversion)

6.3 Core Differences Between ulab and numpy

Dimensionulabnumpy
Matrix type supporteig supports only real symmetric matrices; only real matrices are supported overalleig supports non-symmetric / complex matrices; all matrix types are supported
Norm functionalitySupports only the 2-norm, no parametersSupports the ord parameter (1 / 2 / ∞ / Frobenius, etc. norms)
Exception handlingRaises ValueError if the input does not meet the conditions, with a concise messageMore detailed error messages; in some cases returns a warning instead of an exception
Performance / memoryOptimized for embedded use (C implementation, low memory overhead)Optimized for general-purpose platforms; strong performance on desktop but high overhead on embedded
Result consistencyEigenvalue / eigenvector order / sign may differ (mathematically equivalent); results of other functions are identicalStable results, fixed order / sign

VII. Random Number Generation with ulab numpy.random

The numpy.random module of ulab only implements the Generator based on the PCG random algorithm (32/64-bit), which is lightweight-adapted focusing on three random number distributions frequently used in embedded scenarios, with the core features as follows.

7.1 Basics: Generator Object

Generator is the core carrier for generating random numbers, and all random number methods need to be called through instances. The core rules are as follows:

7.2 Three Major Random Number Methods: Comparison of Parameters and Functions

MethodDistribution typeCore parametersKey features (differences from numpy / other methods)
normalNormal (Gaussian) distributionloc=0.0 (mean), scale=1.0 (standard deviation), size=None (output shape)① Implemented internally with the Box-Muller transform;
② Supports calls with positional / keyword arguments;
③ No out parameter;
④ Core generation logic is identical to numpy.random.normal
random[0, 1) uniform distributionsize=None (output shape), out=None (output array)① The only method that supports the out parameter (core embedded optimization);
② out must be a float ndarray; a conflict between size and the shape of out raises an exception;
③ The out array can be reused to avoid repeated memory allocation;
④ Compared with numpy's random, keeps only core functionality, with fewer extension parameters
uniform[low, high) uniform distributionlow=0.0 (lower bound), high=1.0 (upper bound), size=None (output shape)① No out parameter;
② With low=0 and high=1, generates exactly the same sequence as random;
③ Supports custom intervals, making up for the fixed interval of random;
④ Supports calls with positional / keyword arguments

7.3 Key Usage Examples and Notes

7.3.1 Fix the seed to ensure result reproducibility

During debugging in embedded scenarios, a fixed seed ensures that the random number sequence remains completely consistent, which facilitates problem localization:

from ulab import numpy as np

# Same seed → same random number sequence
rng1 = np.random.Generator(123456)
rng2 = np.random.Generator(123456)

print(rng1.normal())  # -6.285246229407202
print(rng2.normal())  # Exactly the same result

7.3.2 Reuse of out array by random

Embedded devices have limited RAM, so reusing the out array can reduce memory allocation and deallocation overhead:

from ulab import numpy as np

rng = np.random.Generator(123456)
# Preallocate a float64 array as a buffer
buf = np.zeros((3,3), dtype=np.float)

print("复用前的缓冲区:\n", buf)
# Write random numbers directly into the buffer, no new array created
rng.random(out=buf)
print("复用后的缓冲区:\n", buf)

7.3.3 Equivalence of uniform and random

uniform is random in its general form, and the two are completely equivalent under default parameters:

from ulab import numpy as np

rng = np.random.Generator(123456)
# When low=0 and high=1, uniform is equivalent to random
print(rng.random(size=(2,2)))        # [0,1) uniform distribution
print(rng.uniform(0, 1, size=(2,2))) # Generates exactly the same sequence

7.3.4 Core Differences Between ulab and Standard NumPy

Dimensionulabnumpy
Generator supportSupports only the PCG algorithm GeneratorSupports multiple random number generators such as PCG, MT19937, Philox
Distribution typeSupports only normal distribution, [0,1] uniform distribution, and custom-interval uniform distributionSupports dozens of distributions (Poisson, exponential, binomial, etc.)
Parameter richnessMinimal method parameters, keeping only core functionality:
• random: only size / out
• uniform: no out
• normal: no out / dtype
Complete parameter system:
• Supports dtype to specify the output type
• All methods support the out parameter
• Supports multithreading / vectorization optimization
Memory optimizationThe out parameter of random is designed specifically for memory-constrained embedded scenariosSupports more general memory optimizations, but has no embedded-specific adaptation
CompatibilityCore parameters (size / loc / scale / low / high) are the same as numpyFully compatible with the numpy API, supports extension parameters and advanced features

VIII. Integration with ulab scipy.integrate

The scipy.integrate module of ulab is a lightweight subset of CPython's scipy.integrate. Its algorithms are not directly ported; instead, they are optimized and implemented based on embedded resources, retaining only 4 core numerical integration functions. The core features are as follows:

8.1 Basic Module Configuration (Prerequisite: Must Be Met First)

This module is not enabled by default and needs to be enabled by modifying the compilation macro in ulab.h, and its precision is strongly correlated with the floating-point configuration:

Configuration itemPurposeRecommended value (embedded)
ULAB_SCIPY_HAS_INTEGRATE_MODULEEnable the entire integration module1 (enabled)
ULAB_INTEGRATE_HAS_QUAD / ROMBERG / SIMPSON / TANHSINHEnable the corresponding integration function individuallyEnable as needed (reduces firmware size)
MICROPY_OBJ_REPR_A + MICROPY_FLOAT_IMPL_DOUBLEEnable float64 precision1 (preferred, higher precision)
Error tolerance (eps)Default error threshold of each integration functionfloat64: 1e-14;
float32: 1e-8

Key Limitations: All functions do not support complex integration, but can be extended based on existing functions (e. g., integrating the real part and imaginary part separately after splitting).

8.2 Four Major Integral Functions: Comparison of Core Parameters and Characteristics

FunctionImplemented algorithmCore parameters (required + optional)Return valueApplicable scenariosCompared with CPython scipy
Key differences
quadAdaptive Gauss–Kronrod (G10, K21) integrationRequired: f (callable function),
a / b (lower / upper integration limits)
Optional: order=5 (integration order), eps=default value (error tolerance)
(integration result, error estimate) (two floats)General-purpose numerical integration (first choice in most scenarios)CPython wraps QUADPACK (automatic switching among multiple algorithms); ulab implements only Gauss–Kronrod
rombergRomberg integration (Newton–Cotes extrapolation)Required: f, a / b
Optional: steps=100 (number of sampling steps), eps=default value
A single float (integration result only)Suited to integrands that are smooth, have continuous derivatives, and are sampled at equal spacingDeprecated in CPython 1.12+; still kept in ulab; no error estimate returned
simpsonAdaptive Simpson integrationRequired: f, a / b
Optional: steps=100, eps=default value
A single float (integration result only)Routine integration with moderate accuracy requirementsCPython requires passing an array of function values; ulab adapts the sampling interval automatically
tanhsinhOptimized double-exponential (DE) integration (Tanh-Sinh / Sinh-Sinh / Exp-Sinh)Required: f, a / b
Optional: levels=6 (number of iteration levels), eps=default value
(integration result, error estimate) (two floats)Endpoint singularities, infinite derivatives, or infinite integration intervals (such as Gaussian integrals)CPython exposes the interface only from 1.15+; ulab is an optimized implementation; the only one that supports infinite integration limits

8.3 In-depth Analysis of Key Functions

8.3.1 quad: General Preferred

Example (fix UsageError in the document, correct MicroPython code):

from ulab import scipy

# Define the integrand: f(x) = x² + 2x + 1
def f(x):
    return x**2 + 2*x + 1

# Integration interval [0,5], order 5, error tolerance 1e-10
result, error = scipy.integrate.quad(f, 0, 5, order=5, eps=1e-10)
print(f"积分结果 = {result}, 误差估计 = {error}")
# Theoretical value: ∫(0→5) (x+1)² dx = ( (5+1)³ - (0+1)³ )/3 = (216-1)/3 ≈ 71.66666666666667

8.3.2 tanhsinh: Handling Special Integrals (Infinite Limits / Singular Points)

from ulab import scipy, numpy as np
from math import exp, sqrt, pi

# Gaussian integral function: f(x) = e^(-x²)
def f(x):
    return exp(-x**2)

# Integration interval (-∞, +∞)
result, error = scipy.integrate.tanhsinh(f, -np.inf, np.inf)
print(f"积分结果 = {result}, 误差估计 = {error}")
print(f"理论值 = {sqrt(pi)}")

8.3.3 Romberg/Simpson: Supplementary Scenarios

Example (simpson):

from ulab import scipy

def f(x):
    return x**2 + 2*x + 1

# Integration interval [0,5], default steps=100
result = scipy.integrate.simpson(f, 0, 5)
print(f"辛普森积分结果 = {result}")

8.3.4 Notes on Performance and Accuracy

IX. Solving Linear Systems with ulab scipy.linalg

The scipy.linalg module of ulab only implements two linear system solving functions for "special matrices", serving as a supplement to numpy.linalg, and is designed for efficient computing in embedded scenarios (solving triangular matrices / Cholesky decomposed matrices is more efficient than general matrix inversion), with its core features as follows.

9.1 Core Comparison of Two Functions

FunctionCore functionInput parametersKey rulesCore differences from CPython scipy
cho_solveGiven the Cholesky decomposition matrix L of a known matrix A (A = LLᵀ), solve the linear system Ax = bRequired:
① L: lower-triangular matrix from the Cholesky decomposition (ndarray)
② b: right-hand-side vector of the system (ndarray)
1. L must be the correct lower triangular matrix from the Cholesky decomposition; otherwise the result is meaningless;
2. Returns the solution vector x directly (float64 ndarray);
3. No extra parameters; fixed computation path and minimal logic
CPython requires an (L, lower) tuple to specify upper/lower triangular explicitly; ulab takes the decomposed matrix directly and omits the redundant parameter, giving a simpler interface
solve_triangularAssuming matrix A is triangular (upper / lower), solve the linear system Ax = bRequired:
① A: matrix (ndarray)
② b: right-hand side vector (ndarray)
Optional: lower=False (default is upper triangular; True means lower triangular)
1. A does not need to be explicitly triangular; the function automatically ignores elements outside the specified triangular region (treated as 0);
2. A·x = b holds only when A is actually triangular;
3. Returns the solution vector x (float64 ndarray)
1. CPython supports more parameters (such as unit_diagonal, overwrite_b); ulab keeps only the core lower parameter;
2. ulab handles non-triangular matrices more leniently: it does not raise an error, but the result may deviate

9.2 In-depth Analysis of Key Functions

9.2.1 cho_solve: Efficient Solution after Cholesky Decomposition

Quick Start Guide to ulab: A Lightweight Subset of numpy/scipy

Full Usage Example:

from ulab import numpy as np
from ulab import scipy as spy

# 1. Define a symmetric positive definite matrix A (prerequisite for Cholesky decomposition)
A = np.array([[25, 15, -5], [15, 18, 0], [-5, 0, 11]])
# 2. Cholesky decomposition gives the lower triangular matrix L
L = np.linalg.cholesky(A)
# 3. Define the right-hand side vector b of the system of equations
b = np.array([10, 20, 30])

# 4. Solve Ax = b
x = spy.linalg.cho_solve(L, b)
print("解向量x:", x)

# 5. Verify: LL^T x should equal b (A=LL^T)
LT = L.T  # Transpose to get the upper triangular matrix
verify = np.dot(np.dot(L, LT), x)
print("验证 LL^T x = b:", verify)  # Output is close to [10,20,30] (floating-point error)

9.2.2 solve_triangular: Dedicated Solver for Triangular Matrices

Example of pitfalls (verifying the issue of non-triangular matrices):

from ulab import numpy as np
from ulab import scipy as spy

# Non-lower-triangular matrix (upper triangular elements deliberately scrambled)
a = np.array([[3, 2, 1], [2, 1, 0], [1, 0, 1]])
b = np.array([4, 2, 4])

# Solve with lower=True (uses only the lower-left triangle, ignores upper triangular elements)
x = spy.linalg.solve_triangular(a, b, lower=True)
print("解向量x:", x)  # [1.333, -0.666, 2.666]

# Check 1: direct dot(a, x) ≠ b (because a is not a lower triangular matrix)
print("dot(a, x):", np.dot(a, x))  # [5.333, 1.916, 3.666]

# Check 2: take only the lower-left triangle of a (remove the part treated as 0), and the dot result equals b
a_lower = np.array([[3, 0, 0], [2, 1, 0], [1, 0, 1]])
print("dot(左下三角a, x):", np.dot(a_lower, x))  # [4.0, 2.0, 4.0]

9.2.3 Advantages of Application in Embedded Scenarios

X. Root Finding for Univariate Functions with ulab scipy.optimize

The scipy.optimize module of ulab only implements three univariate optimization functions that are frequently used in embedded scenarios. Its core logic is "iterative loops implemented at the C layer + custom functions called at the Python layer", which delivers roughly 2x faster performance than pure Python (far lower than the performance improvement of ulab's vector operations). Its core features are as follows.

10.1 Core Comparison of the Three Major Functions

FunctionCore functionRequired parametersOptional control parametersReturn valueUnderlying algorithmKey features (advantages / limitations)Performance (vs pure Python)
bisectRoot finding for a single-variable function (solve f(x)=0)① f (single-argument callable)
② a / b (interval endpoints, must satisfy f(a)·f(b) < 0)
xtol=2.4e-7 (root precision) maxiter=100 (maximum iterations)Root location (float)Bisection method✅ Very robust (low requirement on initial value)
❌ Slow convergence (linear convergence)
About 2× faster. Example: Python ~1270 μs → C ~642 μs
fminMinimization of a single-variable function (solve min f(x))① f (single-argument callable)
② x0 (initial value)
xatol (x convergence precision)
fatol (function value precision)
maxiter (maximum iterations)
Minimum location (float)Downhill simplex method (Nelder–Mead)✅ No derivatives needed, robust
❌ Single variable only (scipy supports multiple variables)
About 2× faster (core iteration implemented in C)
newtonRoot finding for a single-variable function (solve f(x)=0)① f (single-argument callable)
② x0 (initial value)
tol (absolute tolerance)
rtol (relative tolerance)
maxiter (maximum iterations)
Root location (float)Newton–Raphson method (derivative estimated numerically and automatically)✅ Fast convergence (quadratic convergence)
❌ Sensitive to initial value (must be close to the true root)
About 2× faster (iteration logic implemented in C)

10.2 In-depth Analysis of Key Functions

10.2.1 bisect (bisection method for root finding) - robust and preferred

Complete runnable example:

from ulab import scipy as spy

# Define the root-finding function: f(x) = x² - 1 (roots at x=1 and x=-1)
def f(x):
    return x**2 - 1

# Basic usage: find the root in the interval 0~4 (expected ≈1.0)
root_basic = spy.optimize.bisect(f, 0, 4)
print(f"基础用法根位置:{root_basic}")  # 0.99999976 (close to 1.0)

# Limit the number of iterations (8): precision decreases
root_iter = spy.optimize.bisect(f, 0, 4, maxiter=8)
print(f"8次迭代根位置:{root_iter}")  # 0.984375

# Relax the precision (0.1): faster but less precise
root_tol = spy.optimize.bisect(f, 0, 4, xtol=0.1)
print(f"0.1精度根位置:{root_tol}")  # 0.9375

10.2.2 fmin (Downhill Simplex Method for Minimum Finding) - Derivative-Free Minimum Finding

Complete runnable example:

from ulab import scipy as spy

# Define the minimum-value function: f(x) = (x-1)² - 1 (minimum at x=1, function value=-1)
def f(x):
    return (x-1)**2 - 1

# Initial value 3.0, default precision
min_x = spy.optimize.fmin(f, 3.0)
print(f"默认精度最小值位置:{min_x}")  # 0.9996 (close to 1.0)

# Relax the x precision (0.1): result deviates slightly but is faster
min_x_tol = spy.optimize.fmin(f, 3.0, xatol=0.1)
print(f"0.1精度最小值位置:{min_x_tol}")  # 1.2 (acceptable within the precision range)

10.2.3 Newton (Newton-Raphson root-finding) — Fast Converging Root-Finding

Complete runnable example:

from ulab import scipy as spy

# Define the root-finding function: f(x) = x³ - 2 (root at x=∛2 ≈1.2599)
def f(x):
    return x**3 - 2

# Initial value 3.0, absolute tolerance 0.001, relative tolerance 0.01
root = spy.optimize.newton(f, 3.0, tol=0.001, rtol=0.01)
print(f"牛顿法根位置:{root}")  # 1.2601 (close to the true value)

10.3 Core Differences from CPython scipy

DimensionulabCPython scipy
Variable supportSingle-variable functions onlySupports single- and multi-variable functions
Parameter richnessKeeps only core control parameters
(precision / iterations)
Supports extended parameters (such as full_output for detailed output, callback)
Algorithm extensionsnewton supports only automatic numerical derivative estimation (cannot be passed manually)newton supports passing a derivative function manually, and can select the secant method / Halley's method
Performance optimizationC optimization for embedded scenarios (small size, low memory usage)General optimization for desktop (full-featured, but high overhead for embedded)

11. ulab scipy.signal.sosfilt Second-order IIR Filter

11.1 Brief Introduction

The sosfilt in ulab is a lightweight subset of CPython's scipy.signal.sosfilt. It retains only the core logic of cascaded second-order sections (SOS) IIR filtering for 1D signals, which is frequently used in embedded scenarios, and is implemented using the direct-form II transposed structure (to avoid numerical precision loss in high-order filters), adapting to the requirements of low memory footprint and small size for embedded systems.

Brief Introduction to IIR Filtering

The core of IIR filtering lies in its recursion structure, which calculates the current output by leveraging past outputs and the input. This structure defines its core advantages and disadvantages, and also serves as the key to scenario selection:

  • ✅ Advantages: With the same filtering effect, its order is much lower than that of FIR (e. g., a 10th-order IIR is roughly equivalent to a 100th-order FIR), featuring small computation load and extremely low memory usage; it can achieve "steep filtering characteristics"(high roll-off) with a low order.
  • ❌ Disadvantages: phase nonlinearity (non-constant group delay); high-order IIR filters are prone to numerical instability (however, ulab's sosfilt can avoid this issue by splitting the filter into second-order sections (SOS)).

Applicable to:

  • Embedded devices with low computing power / resource constraints (the core scenario): The core of IIR filtering lies in its recursion structure, which calculates the current output by combining the past outputs and the input — this defines its core advantages and disadvantages, and also serves as the key to scenario selection:
    • ✅ Advantages: With the same filtering effect, its order is much lower than that of FIR (e. g., a 10th-order IIR is roughly equivalent to a 100th-order FIR), featuring small computation load and extremely low memory usage; it can achieve "steep filtering characteristics"(high roll-off) with a low order.
    • ❌ Disadvantages: phase nonlinearity (non-constant group delay); high-order IIR filters are prone to numerical instability (however, this can be avoided by the sosfilt function in ulab which implements second-order section (SOS) decomposition).
  • Signal processing scenarios with extremely high real-time requirements: IIR filters do not require caching a large amount of historical input data (while FIR filters need to cache Nth-order inputs), and can complete calculations with only a small number of delay values, delivering extremely fast real-time response:
    • Applicable Scenarios: For instance, when processing sensor signals with a 1kHz sampling rate, the per-frame computation time of an IIR filter is less than 100μs, enabling zero-latency "acquisition - filtering - output" operation; in contrast, if a 100th-order FIR filter is used, the total time for buffering plus computation will increase significantly.
    • Practical Example:
      • Real-time current/voltage filtering in industrial control (requiring immediate feedback control);
      • Real-time smoothing of robot joint angles and drone attitudes (millisecond-level response required);
      • Real-time triggering of smart home sensors (such as filtering and debouncing of human body infrared signals).
  • Scenarios requiring "steep filtering characteristics"(narrowband / high roll-off): IIR filters can achieve "steep frequency roll-off" with an extremely low order (for example, to filter out 50Hz power-line noise, a 4th-order IIR alone can deliver a roll-off of 80dB per decade), while an FIR filter would require hundreds of orders to achieve the same effect, which is completely unaffordable for embedded systems:
    • Applicable Reason: IIR filters are designed based on poles and zeros (including Butterworth, Chebyshev, and elliptic filters), which inherently fit the narrowband filtering requirement of "precisely filtering out a specific frequency band while retaining the target frequency band".
    • Practical Example:
      • 50/60Hz power frequency filtering for power signals (to filter out grid interference);
      • Low-pass / high-pass filtering of audio signals (e. g., retaining the 200-3000Hz human voice frequency band while filtering out high-frequency noise);
      • Resonance peak filtering for vibration sensors (precisely filtering out the single frequency of mechanical resonance).
  • Scenarios insensitive to phase distortion: IIR features non-linear phase (i. e., different frequency components of a signal experience different delays), but in many scenarios, only the "amplitude" rather than the "phase" is a concern, making this characteristic fully acceptable:
    • Applicable reason: Phase distortion does not affect the core information of the signal (such as amplitude and trend).
    • Practical Example:
      • Filtering of static/slowly varying signals (temperature, pressure, humidity): such signals change slowly, so the phase delay is negligible;
      • Amplitude detection applications (e. g., signal strength, peak detection): only accurate amplitude is required, with no need to concern about the phase;
      • Switching value trigger scenarios (e. g., judging whether the threshold is exceeded after filtering): The phase does not affect the threshold judgment.

Only with clear boundaries can you better select a model. In the following scenarios, FIR should be preferred over IIR:

  • For scenarios with strict requirements for phase linearity (such as audio playback, communication signal demodulation, radar/ultrasonic ranging): FIR filters can be designed to have linear phase, while IIR filters cannot achieve this;
  • High-order scenarios that require "absolute stability" and cannot split second-order sections: Although ulab's sosfilt avoids instability with SOS, there is still numerical risk in very high-order IIR.
  • Multi-dimensional signal filtering (the sosfilt in ulab only supports one dimension, and the multi-dimensional implementation of IIR is complex): FIR is easier to extend to multiple dimensions.

scipy.signal.sosfilt (sos, x, zi= None) applies a cascaded second-order IIR filter defined by sos to the uniformly sampled one-dimensional signal x, and returns the filtered data (along with optional final delay values).

ParameterType requirementsCore rules
sos (required)2D float ndarray, shape (n_sections, 6)① Each row corresponds to one second-order section, in the format [b0, b1, b2, a0, a1, a2] (the first three are numerator coefficients, the last three are denominator coefficients);
② a0 is usually set to 1 (avoids denominator scaling and reduces numerical error);
③ The number of sections n_sections determines the filter order (total order = 2 × n_sections);
④ Must be float type (ulab implicitly converts integers to float, but explicit specification is recommended).
x (required)1D float ndarray① Supports 1D data only (core ulab constraint, no axis parameter);
② The input should be a uniformly sampled signal sequence (such as sensor voltage, acceleration, etc.).
zi (optional)2D float ndarray, shape (n_sections, 2)① Must strictly match the number of sections in sos (n_sections rows, 2 columns), otherwise a shape exception is raised;
② Represents the initial delay state of each second-order section (the filter's "initial state");
③ When not passed, defaults to all 0 (initial rest state).
Return valueTrigger conditionType / shape
yAll call scenarios1D float ndarray, same length as x (filtered output signal)
zfWhen zi is passed2D float ndarray, same shape as zi (final delay state after filtering, usable as zi for the next signal segment)

Complete runnable example:

from ulab import numpy as np
from ulab import scipy as spy

# ========== 1. Basic usage (no initial delay zi) ==========
# Define SOS coefficients for 2 second-order sections (example coefficients; in practice generate them from the filter design)
sos = np.array([[1, 2, 3, 1, 5, 6], [1, 2, 3, 1, 5, 6]], dtype=np.float)
# 1D input signal
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=np.float)

# Basic filtering (initial delay all zeros)
y = spy.signal.sosfilt(sos, x)
print("基础滤波结果 y:", y)

# ========== 2. Usage with initial delay zi ==========
# Define the initial delay (2 second-order sections, corresponding to 2 rows and 2 columns)
zi = np.array([[1, 2], [3, 4]], dtype=np.float)
# Filtering with initial delay
y_with_zi, zf = spy.signal.sosfilt(sos, x, zi=zi)
print("\n带初始延迟的滤波结果 y:", y_with_zi)
print("滤波结束后的最终延迟 zf:\n", zf)

# ========== 3. Continuous filtering (reuse zf as zi for the next segment) ==========
# New input signal segment
x_new = np.array([10, 11, 12], dtype=np.float)
# Use zf from the previous segment as the initial delay to ensure filtering continuity
y_new, zf_new = spy.signal.sosfilt(sos, x_new, zi=zf)
print("\n连续滤波结果 y_new:", y_new)

11.2 Core Differences from CPython scipy.signal.sosfilt

DimensionulabCPython scipy
Input dimensionsSupports 1D x only, no axis parameterSupports N-D x, filter axis can be specified via axis
zi flexibilitySupports only the fixed shape (n_sections, 2)Supports flexible shapes adapted to N-D x (such as (n_sections, ..., 2, ...))
Feature extensionsNo Array API support, no multiple backends (such as CuPy / PyTorch)Supports the Array API standard, multiple backends, detailed exception messages
Memory / sizeC implementation, suited to embedded, small size, low memory usageFull-featured, but high overhead for embedded (not suitable for microcontrollers)
Numerical optimizationKeeps only core filtering logic, no extra numerical optimizationIncludes various numerical optimizations, boundary handling and precision control

11.3 Application Example: Power Frequency Filtering

In the following case, we first configure the core parameters: a sampling rate of 200 Hz and a Q factor of 50.

from ulab import numpy as np
from ulab import scipy as spy
from math import sin, pi

# ===================== 1. Configure core parameters =====================
FS = 200.0
F0 = 50.0
DURATION = 1.0
N = int(FS * DURATION)
Q = 50.0

print("=== 1. Filter Configuration Parameters ===")
print(f"Sampling Rate (FS): {FS} Hz")
print(f"Target Notch Frequency (F0): {F0} Hz")
print(f"Signal Duration: {DURATION} s (Total Samples: {N})")
print(f"Notch Filter Quality Factor (Q): {Q}\n")

# ===================== 2. Generate simulated signal =====================
t = np.linspace(0, DURATION, N, endpoint=False)
useful_signal = np.array([sin(2 * pi * 10 * ti) for ti in t], dtype=np.float)
noise_50hz = np.array([0.5 * sin(2 * pi * 50 * ti) for ti in t], dtype=np.float)
mixed_signal = useful_signal + noise_50hz

print("=== 2. Original Signal Segments (First 10 Samples) ===")
print(f"Useful 10Hz Signal: {useful_signal[:10]}")
print(f"50Hz Power Frequency Noise: {noise_50hz[:10]}")
print(f"Mixed Signal (Useful + Noise): {mixed_signal[:10]}\n")

# ===================== 3. High-Q notch filter coefficients =====================
sos_notch_50hz = np.array([
    [0.970588235, 0.0, 0.970588235, 1.0, 0.0, 0.94117647]
], dtype=np.float)

print("=== 3. 50Hz Notch Filter SOS Coefficients ===")
print(f"SOS Matrix (shape: {sos_notch_50hz.shape}): {sos_notch_50hz}\n")

# ===================== 4. Filter warm-up (key fix: ensure consistent length) =====================
# Number of warm-up samples: first 10 points
warmup_len = 10
warmup_samples = mixed_signal[:warmup_len]
zi_warm = np.array([[0.0, 0.0]], dtype=np.float)
# Warm-up filtering: only obtain the stable delay values, discard the filtered results of the warm-up segment
_, zf_warm = spy.signal.sosfilt(sos_notch_50hz, warmup_samples, zi=zi_warm)

print("=== 4. Filter Warmup (Eliminate Initial Transient) ===")
print(f"Warmup Samples Length: {len(warmup_samples)}")
print(f"Stable Filter Delay After Warmup (zf_warm): {zf_warm}\n")

# ===================== 5. Main signal filtering (fixed concatenation logic) =====================
# Main signal: all 200 points (not with the first 10 removed), filtered using the delay values after warm-up
# This way the filtered signal length = 200, exactly the same as useful_signal
filtered_signal, _ = spy.signal.sosfilt(sos_notch_50hz, mixed_signal, zi=zf_warm)

print("=== 5. Filtered Signal Segment (First 10 Samples) ===")
print(f"Filtered Signal Length: {len(filtered_signal)}")
print(f"Filtered Signal: {filtered_signal[:10]}\n")

# ===================== 6. Verify filtering effect (no errors) =====================
noise_before = mixed_signal - useful_signal
noise_after = filtered_signal - useful_signal  

rms_noise_before = np.sqrt(np.mean(noise_before[warmup_len:] **2))
rms_noise_after = np.sqrt(np.mean(noise_after[warmup_len:]** 2))
attenuation_ratio = (rms_noise_before - rms_noise_after) / rms_noise_before * 100

print("=== 6. Noise Reduction Effect ===")
print(f"RMS Noise Before Filtering: {rms_noise_before:.6f}")
print(f"RMS Noise After Filtering: {rms_noise_after:.6f}")
print(f"50Hz Noise Attenuation Ratio: {attenuation_ratio:.2f}%")
print(f"Stable Noise Residual (Last 10 Samples): {noise_after[-10:]}")

The output is as follows:

Quick Start Guide to ulab: A Lightweight Subset of numpy/scipy

It can be seen that the RMS noise is 0.353553 before filtering and 0.097261 after filtering, with an attenuation rate of 72.49%, and the noise residue of the last 10 points in the stable section is less than 0.011.

12. ulab scipy.special Special Mathematical Functions

The scipy.special in ulab is a lightweight subset of the module with the same name in SciPy, which only implements 4 high-frequency special mathematical functions, with the core features:

The four core functions of the module are as follows:

Quick Start Guide to ulab: A Lightweight Subset of numpy/scipy

Complete runnable example:

from ulab import numpy as np
from ulab import scipy as spy

# Test gamma (gamma function)
x_scalar = 5  # Scalar input
x_list = [1,2,3,4,5]  # list input
x_ndarray = np.array([0.5, 1.5, 2.5])  # Non-integer ndarray input

print("=== gamma函数测试 ===")
print(f"gamma(5) (标量): {spy.special.gamma(x_scalar)}")  # 4!=24.0
print(f"gamma([1,2,3,4,5]) (list): {spy.special.gamma(x_list)}")  # [0!,1!,2!,3!,4!] = [1,1,2,6,24]
print(f"gamma([0.5,1.5,2.5]) (ndarray): {spy.special.gamma(x_ndarray)}")  # [√π≈1.772, √π/2≈0.886, 3√π/4≈1.329]

# Test gammaln (log gamma)
print("\n=== gammaln函数测试 ===")
print(f"gammaln(5): {spy.special.gammaln(5)}")  # ln(24)≈3.1781
print(f"gammaln([1,2,3]): {spy.special.gammaln([1,2,3])}")  # [ln(1),ln(1),ln(2)] = [0,0,0.6931]

13. ulab utils Module: Data Conversion and Spectrum Analysis

utils is a utility module designed by ulab specifically for embedded scenarios, which is not compatible with numpy, and it mainly addresses two pain points:

13.1 Module Enable Method (compile macro must be configured)

utils module is not compiled into the firmware by default, you need to modify the macro in ulab.h:

// 1. Enable the entire utils module
#ifndef ULAB_HAS_UTILS_MODULE
#define ULAB_HAS_UTILS_MODULE               (1)
#endif

// 2. Enable specific functions (enable as needed to reduce firmware size)
#ifndef ULAB_UTILS_HAS_FROM_INT16_BUFFER   // 16-bit signed integer conversion
#define ULAB_UTILS_HAS_FROM_INT16_BUFFER    (1)
#endif
#ifndef ULAB_UTILS_HAS_FROM_UINT32_BUFFER  // 32-bit unsigned integer conversion
#define ULAB_UTILS_HAS_FROM_UINT32_BUFFER   (1)
#endif
// Other functions: from_int32_buffer/from_uint16_buffer/spectrogram work the same way

13.2 Core Functions

13.2.1 Buffer Conversion Function (from_(u) int16/32_buffer)

Directly convert the byte buffer of 16/32-bit integers output by peripherals (such as 32-bit sampling data from ADCs and microphones) into a ulab float -type ndarray, eliminating the need for manual byte parsing and integer concatenation, and adapting to embedded peripheral data formats.

ParameterPurposeEmbedded value
buffer (required)Byte buffer (bytearray / bytes)Connects directly to raw byte output of peripherals (such as the DMA buffer of an ADC)
count=-1Number of floats to convert
(-1 means calculated automatically from buffer length)
Converts on demand, avoiding processing of redundant data
offset=0Skip the first N bytes of the buffer before convertingIgnore invalid data at the head of the buffer (such as peripheral frame header)
out=NoneWrites the result into a predefined float arrayReuses memory, avoiding a new array on every conversion (solves insufficient embedded RAM)
byteswap=FalseWhether to swap byte orderAdapts to endianness differences between peripheral and MCU (such as big-endian peripheral, little-endian MCU)
13.2.1.1 Basic Conversion (No Parameters)

A 32-bit integer is formed by concatenating 4 bytes (in little-endian order: the lower byte comes first), and the difference between unsigned and signed conversions is reflected in the most significant bit (the sign bit).

from ulab import utils

# Byte buffer: 8 bytes = 2 32-bit integers (little-endian)
a = bytearray([1,1,0,0, 0,0,0,255])
# Unsigned conversion: 0x00000101=257, 0xFF000000=4278190080
print(utils.from_uint32_buffer(a))  # array([257.0, 4278190080.0])
# Signed conversion: 0xFF000000=-16777216 (two's complement)
print(utils.from_int32_buffer(a))   # array([257.0, -16777216.0])
13.2.1.2 Reusing the out Array (Memory Optimization)

On embedded devices, RAM is a scarce resource, so reusing arrays can prevent the fragmentation caused by frequent memory allocation and deallocation operations.

from ulab import numpy as np, utils

# Predefined float array (reuse memory, avoid creating a new one)
a = np.array([1,2], dtype=np.float)
b = bytearray([1,0,1,0, 0,1,0,1])
# Result is written directly into a, no new memory allocation needed
utils.from_uint32_buffer(b, out=a)
print(a)  # array([65537.0, 16777472.0])
13.2.1.3 Byte Order Swap (Peripheral Endianness Adaptation)

Solve the compatibility issue caused by the big-endian format of peripherals (such as some sensors) and the little-endian format of the MCU.

a = bytearray([1,0,0,0, 0,0,0,1])
# No swap: 0x00000001=1, 0x01000000=16777216
print(utils.from_uint32_buffer(a))          # array([1.0, 16777216.0])
# With swap: after byte reversal 0x00000001→1, 0x01000000→1 are exchanged
print(utils.from_uint32_buffer(a, byteswap=True))  # array([16777216.0, 1.0])

13.2.2 Spectrogram (High-efficiency Spectrum Analysis)

13.2.2.1 Function Orientation

Computing the power spectrum of a signal (the absolute value of the FFT) is equivalent to np.abs (np.fft.fft (signal)), but improves memory efficiency by more than 10 times — it eliminates multiple memory allocations during FFT, absolute value, and logarithmic operations.

13.2.2.2 FFT Compatibility Adaptation

ulab's FFT supports two modes, and spectrogram will automatically adapt to them:

FFT modeInput parametersEquivalent logic
numpy compatible (recommended)1 argument (real or complex array)np.abs(np.fft.fft(signal))
Not numpy compatible2 arguments (real part + imaginary part)np.sqrt(real**2 + imag**2)

You can determine the FFT mode with the following code:

from ulab import numpy as np
if len(np.fft.fft(np.zeros(4))) == 2:
    print("FFT非numpy兼容(实虚部分开)")
else:
    print("FFT numpy兼容(复数输出)")
13.2.2.3 Core Parameters
ParameterPurposeEmbedded value
signal (required)1D real / complex array (signal to analyze)Connects directly to sensor sampling data
scratchpad=NoneTemporary buffer (length = 2 × signal length, float type)Reuses temporary memory, avoiding a new allocation on every FFT
out=NoneWrites the result into a predefined arrayReuses memory, reducing allocations
log=FalseWhether to return the logarithmic power spectrumComputed directly inside, avoiding a new array from np.log()
13.2.2.4 Example Interpretation

Example 1: Basic Usage

from ulab import numpy as np, utils

x = np.linspace(0, 10, 1024)
y = np.sin(x)
a = utils.spectrogram(y)  # Equivalent to np.abs(np.fft.fft(y))
print(a)  # Power spectrum array (absolute values)

Example 2: Memory Reuse for High-Frequency Calls (Core Advantage of Embedded Systems)

from ulab import numpy as np, utils

n = 1024
t = np.linspace(0, 2*np.pi, n)
scratchpad = np.zeros(2*n)  # Temporary buffer allocated only once

# Method 1: memory-efficient (reuse scratchpad+out)
for _ in range(10):
    signal = np.sin(t)
    # Result is written into signal itself, scratchpad is reused, compute the logarithm directly
    utils.spectrogram(signal, out=signal, scratchpad=scratchpad, log=True)

# Method 2: memory-inefficient (new arrays created each time, prone to fragmentation)
for _ in range(10):
    signal = np.sin(t)
    out = np.log(utils.spectrogram(signal))  # Creates 2 new arrays each time

13.2.3 Core Summary

Core functionCore embedded valueKey advantages
Buffer conversion functionsAdapts to peripheral 32/16-bit integer dataDirect conversion, byte-order support, memory reuse
spectrogramHigh-frequency spectrum analysis (e.g., audio / vibration detection)Memory reuse, avoids fragmentation, built-in logarithm operations
Overall designSuited to low-RAM / low-compute MCUsNo redundant memory allocation, implemented in C layer (fast)

14. Core Optimization Techniques for ulab

All the following techniques are designed around the core pain points of "limited MCU computing power (no FPU / low main frequency), scarce RAM, and fatal memory fragmentation", with each technique accompanied by its principle, applicable scenarios, and practical implementation suggestions.

14.1 Prefer using ndarray over native iterable objects

ulab functions process ndarray by directly manipulating memory pointers at the C layer: given the C type of the array (e. g. uint8/float32), only a single round of loop traversal of the pointer for accumulation/computation is required, with no overhead from function calls or type conversion; whereas for native iterable objects such as lists and tuples, Python variables need to be extracted one by one → converted to numeric types → then computed, which is extremely inefficient.

Practical Comparison:

OperationCode exampleSpeed comparison
List sumnp.sum([1, 2, 3, 4, 5])Baseline (1×)
ndarray suma = np.array([1, 2, 3, 4, 5]); np.sum(a)About 3× faster
Pure Python sumsum([1, 2, 3, 4, 5])About 40× slower (no hardware / C-layer acceleration)

14.2 Choose a reasonable dtype (core to memory saving)

The default dtype of ulab is float (float32/64, occupying 4/8 bytes), while data from embedded peripherals (such as ADCs/sensors) are mostly 8/16-bit integers. Using a smaller dtype can save 3 to 7 times RAM without sacrificing computational accuracy (e. g., for summation or finding maximum/minimum values).

Data sourceRecommended dtypeMemory savingsNotes
8-bit ADC datauint875% (8 → 1 byte)Take care to avoid numeric overflow (uint8 maximum is 255)
16-bit accelerometerint1650% (4 → 2 bytes)Covers positive and negative range (-32768 ~ 32767)
Only min/max / sum neededMatch the bit width of the data source4 ~ 8 timesNo float needed, integer computation is faster
Filtering / spectrum analysisfloat32—Floating-point precision needed, prefer float32 over float64

14.3 Optimize the Axis Order of Multidimensional Arrays (Place the Longest Axis at the End)

Rules for traversing multidimensional arrays in ulab: The outermost loop corresponds to the first axis, and the innermost loop corresponds to the last axis (the "fast axis"):

Array shapeCodeTraversal efficiencyReason
Efficienta = np.array(range(2000)).reshape((2, 1000))FastLast axis length is 1000, inner loop is long, only 2 outer repositionings needed
Inefficientb = np.array(range(2000)).reshape((1000, 2))SlowLast axis length is 2, inner loop is extremely short, 1000 outer repositionings needed

numpy automatically adjusts the axis order (placing the longest axis at the innermost position), whereas ulab uses a fixed axis order, so you need to manually place the longest dimension at the end.

14.4 Reduce Intermediate Products (Avoid Memory Fragmentation)

Compound expressions (e. g., b[1:: 2] = a[:-1] + a[1:]) generate temporary intermediate arrays, which consume RAM and cause fragmentation (in embedded systems without memory management, fragmentation will gradually deplete RAM); splitting such operations can avoid additional memory allocation.

StyleCodeMemory overheadApplicable scenarios
Inefficient (compound)b[1::2] = a[:-1] + a[1:]Creates a temporary array (a[:-1] + a[1:])Non-loop / one-time operation
Efficient (split)b[1::2] = a[:-1]; b[1::2] += a[1:]No temporary array (only reuses views)Loop / high-frequency operation

Additional Recommendations:

14.5 Image/Array Scaling (Low-Resolution Sensor Adaptation)

For low-resolution data such as 8x8 thermal imaging, replace the interpolation function with slicing + element-wise operations (interp) to avoid intermediate products and adapt to embedded low-computing-power scenarios.

Practical Example:

from ulab import numpy as np

# 8x8 thermal imaging raw data
a = np.random.randint(0, 255, (8,8), dtype=np.uint8)
# Preallocate the scaled array (15x15, allocated only once)
b = np.zeros((15,15), dtype=np.uint8)

# Row interpolation: odd rows are filled with the mean of adjacent rows
b[1::2,::2] = a[:-1,:]    # First assign the previous row
b[1::2,::2] += a[1:,:]    # Accumulate the next row
b[1::2,::2] //= 2         # Compute the mean (no floating point)

# Column interpolation: odd columns are filled with the mean of adjacent columns
b[:,1::2] = a[:,:-1]
b[:,1::2] += a[:,1:]
b[:,1::2] //= 2

No temporary arrays are used throughout the process, only slice views are reused, resulting in the lowest RAM usage.

15. A Brief Analysis of the Underlying Implementation and Extension of ulab

The underlying core of ulab is the ndarray data structure, which adopts a right-aligned shape/strides design (the longest axis serves as the fast axis for the highest traversal efficiency). Data is stored in contiguous memory, and sparse arrays (such as slices) return views instead of copies by adjusting strides and offsets, which greatly saves embedded RAM.Its core operations are all adapted to low-computing-power scenarios: iteration supports two modes: unrolled loop (high-speed) and rewinding function (dimension-independent); broadcasting achieves compatibility for arrays of different shapes through dimension padding + zero-step size; type promotion prioritizes overflow prevention (e. g., small types are promoted to larger types in integer operations, uint16 + int16 is converted to float), balancing compatibility and embedded-specific features.

Extending ulab can be achieved through three steps: enabling user modules, writing C-layer functions (including input validation, array creation, data traversal and calculation, and result return), and binding the Python namespace; after compile, the custom functions can be invoked. For embedded optimization, the following core principles shall be followed: prioritize dense arrays and fixed dtypes to reduce overhead, reuse arrays to avoid memory allocation, split composite expressions to circumvent fragmentation, and maximize adaptation to the constraints of low computing power and limited RAM of MCUs.

Key concept / operationCore characteristics
ndarray structureRight-aligned shape / strides, data pointer points to contiguous memory; includes metadata such as dtype / itemsize, supports multidimensional arrays
Memory layoutDense arrays have no skipped elements; "sparse" arrays such as slices produce views via strides / offset without copying data
Iteration mechanismProvides unrolled loops (high speed, fixed dimensions) and rewind functions (dimension-independent, saves Flash); both use the fast axis as the inner loop
Broadcasting mechanismLower dimensions are padded with 1; lengths in the same dimension must be equal or 1; elements are reused via zero strides, enabling computation between arrays of different shapes
Type promotionIf any operand is float, the result is float; integer operations promote from smaller type to larger type; uint16 + int16 automatically converts to float to prevent overflow
Extension procedureEnable ULAB_USER_MODULE → write C function (validate input → create array → compute → return) → bind to namespace → compile firmware

For this section, you can visit the following link:

https://micropython-ulab.readthedocs.io/en/latest/ulab-programming.html

Quick Start Guide to ulab: A Lightweight Subset of numpy/scipy

Source Code

https://github.com/v923z/micropython-ulab

ulab Firmware Download

https://github.com/v923z/micropython-builder/releases/tag/latest

Quick Start Guide to ulab: A Lightweight Subset of numpy/scipy

Document

https://micropython-ulab.readthedocs.io/en/latest

https://micropython-ulab.readthedocs.io/en/latest/scipy-signal.html

https://docs.scipy.org/doc/scipy/reference/signal.html#module-scipy.signal

Version Record

Version Number

Revision Date

Modifier

Modify Content

v1.0

2026-01-19

Lee Eryong

Initial version, based on the release date 2026-01-19 (MicroPython v1.24.0).