Importing ulab

So that parts of ulab can potentially be disabled in special builds, it is split into multiple submodules.  When you want to use functionality from a submodule, such as filter, write import ulab.filter or import ulab.filter as filter.  When you do this, an error will be signaled early if the filter functionality is not available on the particular board.

Working with CircuitPython and Blinka

Where possible, if a ulab function and a numpy function have the same name, ulab's functionality is a subset of numpy.  However, numpy is not split like ulab.  Therefore, you can use a sequence like the following to make the convolve function available on both CircuitPython and Blinka:

try:
  import ulab
  import ulab.filter as filter
except ImportError:
  import numpy as ulab
  import numpy as filter

u = ulab.array([1,2,3,4])
v = ulab.array([1,-2,1])
print(filter.convolve(u, v))

Numpy/ulab differences

Many ulab functions do not support all the same arguments as numpy.  For instance, numpy.convolve supports several ways of controlling how the boundary conditions are handled, using the mode= named parameter.  However, ulab.filter.convolve always acts like numpy's mode='full'.

Due to technical limitations, when broadcasting a scalar to an array, the scalar has to go on the right.  This means that in ulab when you have an array a and a number n, you can write a*n but not n*a.

In a few cases, numpy accepts a positional argument but ulab requires a named parameter.  This is true of ulab.linspace's num= argument, for instance.

ulab does not support complex numbers.  Because of this, ulab's fft returns a pair of arrays, where the first array holds the real part of the fft and the second array holds the imaginary part.  Instead of using fft directly, consider whether to use ulab.fft.spectrum [may be moved to ulab.extra.spectrum] instead.  For compatibility with both CircuitPython and Blinka, spectrum can be implemented as follows:

try:
  import ulab
  from ulab.fft import spectrum
except ImportError:
  import numpy as ulab
  import numpy.fft
  def spectrum(arr):
    return abs(numpy.fft.fft(arr))

data = ulab.array([1,2,1,4])
print(spectrum(data))

This guide was first published on Mar 06, 2020. It was last updated on Mar 06, 2020.

This page (Writing code for ulab and numpy) was last updated on Apr 15, 2021.

Text editor powered by tinymce.