ulab.numpy: implement sinc for creating audio filters

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:

```py
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)
This commit is contained in:
Jeff Epler 2023-05-15 18:00:59 -05:00
parent ac2e9954ed
commit 1150554ad5
No known key found for this signature in database
GPG key ID: D5BF15AB975AB4DE
4 changed files with 29 additions and 0 deletions

View file

@ -340,6 +340,9 @@ static const mp_rom_map_elem_t ulab_numpy_globals_table[] = {
#if ULAB_NUMPY_HAS_SIN
{ MP_ROM_QSTR(MP_QSTR_sin), MP_ROM_PTR(&vector_sin_obj) },
#endif
#if ULAB_NUMPY_HAS_SINC
{ MP_ROM_QSTR(MP_QSTR_sinc), MP_ROM_PTR(&vector_sinc_obj) },
#endif
#if ULAB_NUMPY_HAS_SINH
{ MP_ROM_QSTR(MP_QSTR_sinh), MP_ROM_PTR(&vector_sinh_obj) },
#endif

View file

@ -570,6 +570,27 @@ MATH_FUN_1(sin, sin);
MP_DEFINE_CONST_FUN_OBJ_1(vector_sin_obj, vector_sin);
#endif
#if ULAB_NUMPY_HAS_SINC
//| def sin(a: _ArrayLike) -> ulab.numpy.ndarray:
//| """Computes the sine function"""
//| ...
//|
static mp_float_t ulab_sinc1(mp_float_t x) {
if (fpclassify(x) == FP_ZERO) {
return MICROPY_FLOAT_CONST(1.);
}
x *= MP_PI;
return MICROPY_FLOAT_C_FUN(sin)(x) / x;
}
static mp_obj_t vector_sinc(mp_obj_t x_obj) {
return vector_generic_vector(x_obj, ulab_sinc1);
}
MP_DEFINE_CONST_FUN_OBJ_1(vector_sinc_obj, vector_sinc);
#endif
#if ULAB_NUMPY_HAS_SINH
//| def sinh(a: _ArrayLike) -> ulab.numpy.ndarray:
//| """Computes the hyperbolic sine"""

View file

@ -39,6 +39,7 @@ MP_DECLARE_CONST_FUN_OBJ_1(vector_log10_obj);
MP_DECLARE_CONST_FUN_OBJ_1(vector_log2_obj);
MP_DECLARE_CONST_FUN_OBJ_1(vector_radians_obj);
MP_DECLARE_CONST_FUN_OBJ_1(vector_sin_obj);
MP_DECLARE_CONST_FUN_OBJ_1(vector_sinc_obj);
MP_DECLARE_CONST_FUN_OBJ_1(vector_sinh_obj);
#if ULAB_SUPPORTS_COMPLEX
MP_DECLARE_CONST_FUN_OBJ_KW(vector_sqrt_obj);

View file

@ -616,6 +616,10 @@
#define ULAB_NUMPY_HAS_SIN (1)
#endif
#ifndef ULAB_NUMPY_HAS_SINC
#define ULAB_NUMPY_HAS_SINC (1)
#endif
#ifndef ULAB_NUMPY_HAS_SINH
#define ULAB_NUMPY_HAS_SINH (1)
#endif