FIR filter with magnitude from function.

import math

import matplotlib.pyplot as plt
from mplsignal import freqz_fir

from fird.designer import FIRDesigner
from fird.objective import FunctionLinearObjective

First, design a filter minimizing the approximation error when approximating cos in the range 0 to 0.3π.

o = FunctionLinearObjective([0, 0.3], lambda f: (1 - math.sin(f * math.pi)))
d = FIRDesigner(15, o)
d.solve()
fig, ax = plt.subplots()
freqz_fir(d.get_impulse_response(), ax=ax, magnitude_scale="linear", style="magnitude")
o.plot(ax, label="Desired")
ax.legend()
fig.show()
arbitrarymagnitude

To avoid that the magnitude becomes large in the band that we do not care about, add a constraint.

from fird.constraint import PiecewiseLinearConstraint  # noqa: E402

c = PiecewiseLinearConstraint([0.3, 1], [0, 0], [1])
d = FIRDesigner(15, o, c)
d.solve()
fig, ax = plt.subplots()
freqz_fir(d.get_impulse_response(), ax=ax, magnitude_scale="linear", style="magnitude")
o.plot(ax, label="Desired")
ax.legend()
fig.show()
arbitrarymagnitude

Total running time of the script: (0 minutes 0.287 seconds)

Gallery generated by Sphinx-Gallery