Importing ulab

The ulab module is split into two main parts ulab.numpy and ulab.scipy each of which provide similar functionality to their respective CPython library counterpart. You can rename ulab.numpy when you import it to use the shorthand name np. from ulab import numpy as np then in your code you can call the functions like np.sum() etc. Many existing CPython numpy examples are written to use this shorthand name.

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.

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

u = np.array([1,2,3,4])
v = np.array([1,-2,1])
print(np.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.numpy.convolve always acts like numpy's mode='full'.

In a few cases, numpy accepts a positional argument but ulab requires a named parameter.  This is true of ulab.numpy.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.scipy.signal.spectrogram instead.  For compatibility with both CircuitPython and Blinka, spectrum can be implemented as follows:

try:
  from ulab import numpy as np
except ImportError:
  import numpy as np
  
try:
  from ulab.scipy.signal import spectrogram
except ImportError:
  def spectrogram(arr):
    return abs(np.fft.fft(arr))

data = np.array([1,2,1,4])
print(spectrogram(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 Mar 04, 2020.

Text editor powered by tinymce.