v923z / micropython-ulab

a numpy-like fast vector module for micropython, circuitpython, and their derivatives
https://micropython-ulab.readthedocs.io/en/latest
MIT License
432 stars 117 forks source link

ulab.numpy: implement sinc for creating audio filters #617

Closed jepler closed 1 year ago

jepler commented 1 year ago

This is useful for generating FIR filters using code snippets generated at https://fiiir.com/ (at least those with a rectangular window type; other window types need additional functions but we can revisit it later if needed)

I think this will come in handy for folks who are using the advanced features of our audio synthesizer module, synthio.

e.g., the following block now gives highly similar results on ulab or numpy:


try:
    import numpy as np
except:
    from ulab import numpy as np

# Example code, computes the coefficients of a low-pass windowed-sinc filter.

# Configuration.
fS = 48000  # Sampling rate.
fL = 4000  # Cutoff frequency.
N = 23  # Filter length, must be odd.

# Compute sinc filter.
h = np.sinc(2 * fL / fS * (np.arange(N) - (N - 1) / 2))

# Normalize to get unity gain.
h /= np.sum(h)

# Applying the filter to a signal s can be as simple as writing
# s = np.convolve(s, h)
v923z commented 1 year ago

@jepler If you think that this is useful, then we should definitely add it.

However, before merging, could you, please, add build to the requirements list, as you suggested in https://github.com/v923z/micropython-ulab/pull/616, so that the checks pass?

jepler commented 1 year ago

This isn't critical, because it's quite possible to implement sinc in python (thanks @gamblor21):

def sinc(x):
    y = np.pi * np.where(x == 0, 1.0e-20, x)
    return np.sin(y)/y
v923z commented 1 year ago

This isn't critical, because it's quite possible to implement sinc in python (thanks @gamblor21):

You should just merge it, if you are satisfied.

def sinc(x):
    y = np.pi * np.where(x == 0, 1.0e-20, x)
    return np.sin(y)/y

Indeed. In that case, it could've been implemented as a snippet.