0% found this document useful (0 votes)
23 views4 pages

Objective:: in All Exercises, Remember To Import The Necessary Libraries

tp dsp

Uploaded by

yacinea580
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views4 pages

Objective:: in All Exercises, Remember To Import The Necessary Libraries

tp dsp

Uploaded by

yacinea580
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

DSP / 3 ING / 2024_2025 1

Tp2
Objective:

The objective of this lab is to provide a practical and theoretical understanding of filters
used in signal processing, enabling students to select and adapt the appropriate type of
filter based on the signal characteristics and processing goals. Students will have the
opportunity to understand the importance of windowing in signal processing to design
effective filters. They will become familiar with comb filters, averaging filters, linear phase
filters, and notch filters by applying them to a common signal processing task.

In all exercises, remember to import the necessary libraries.


Exercise 1
The sinc function is often used in filter design, but its abrupt truncation leads to artifacts
in the frequency domain (ripples in the passband and stopband). To improve the filter's
performance, a windowing function is applied.

Te = 0.2 ;fe = 1 / Te ;N = 50 ;t = Te * np.arange(-N/2, N/2 + 1) ;N = len(t) ;h = np.sinc(t) ;


plt.figure() ;plt.subplot(2, 1, 1) ;plt.plot(t, h) ;plt.grid() ;plt.xlabel('t') ;plt.ylabel('Amplitude')
plt.title('Truncated Sinc Function') ;NF = 2048 ;H = np.fft.fft(h, NF) ;H = np.fft.fftshift(H)
axe_f = fe * np.linspace(-0.5, 0.5, NF) ;plt.subplot(2, 1, 2) ;plt.plot(axe_f,
np.abs(H)/fe) ;plt.grid() ;plt.xlabel('Frequency (f)') ;plt.ylabel('Amplitude') ;plt.title('Fourier
Transform of Truncated Sinc') ;plt.tight_layout() ;plt.show()

Using the program above


1. Identify this filter.
2. Explain the origin of the observed oscillations.
3. Measure the overshoot in the passband.
4. Determine fs, fp, ∆𝑓 and fc.
5. Set N = 100, then 500, and then 1000, and measure the overshoot and the three
frequencies again. Comment on your findings.
6. What does N represent? What is the drawback of increasing N?
7. How can the oscillations be reduced?
8. Apply windowing (h = h * window; window = np.hamming(N)); use other windows
and then comment on the results.)

Exercise 2
Let’s consider the following program: what do the two functions represent?

def linear_phase_fir_filter(num_taps, cutoff_frequency, fs):


# num_taps: number of filter coefficients (must be odd for linear phase)
# cutoff_frequency: cutoff frequency in Hz
# fs: sampling frequency in Hz
# Normalize the cutoff frequency relative to the Nyquist frequency (fs/2)
normalized_frequency = cutoff_frequency / (fs / 2)
DSP / 3 ING / 2024_2025 2

# Design the FIR filter using a Hamming window


fir_coefficients = firwin(num_taps, normalized_frequency, window='hamming')

return fir_coefficients

def calculate_group_delay(w, h, fs):


# w: normalized frequencies (in radians per sample)
# h: frequency response of the filter
# fs: sampling frequency
# Calculate the phase of the filter
phase = np.unwrap(np.angle(h))
# Calculate the group delay (-d(phase)/d(omega))
delta_w = np.diff(w) # Difference of frequencies
delta_phase = np.diff(phase) # Difference of phases
group_delay = -np.diff(phase) / np.diff(w)
# Average frequencies corresponding to the calculated group delays
average_freqs = (w[1:] + w[:-1]) / 2
# Convert frequencies to Hz
average_freqs_hz = average_freqs * fs / (2 * np.pi)

return average_freqs_hz, group_delay

num_taps = 51 ;cutoff_frequency = 100.0 ;fs = 1000.0;


fir_filter = linear_phase_fir_filter(num_taps, cutoff_frequency, fs)

w, h = freqz(fir_filter, worN=8000)
frequencies = w * fs / (2 * np.pi)

frequencies_delay, group_delay = calculate_group_delay(w, h, fs)

1. Plot the frequency response of the filter on a graph with three subplots:
• The first subplot should show the magnitude response (in dB) of the filter.
• The second subplot should display the phase response (in radians) of the filter.
• The third subplot should illustrate the group delay of the filter (in samples).
2. Add titles and axis labels to make the graphs informative.
3. Discuss the results obtained:
4. What is the passband of the filter?
5. How does the group delay vary with frequency?
6. What impact could this have on signals processed by the filter?

7. Modify the cutoff frequency and the number of taps (coefficients) to observe how this
affects the frequency response and group delay. Test at least three different cutoff
frequencies (for example, 50 Hz, 100 Hz, and 200 Hz) and different numbers of taps (for
example, 31, 51, and 101).

Exercise 3
Let the following program
def moving_average_filter(x, window_size):
DSP / 3 ING / 2024_2025 3

# Generate the coefficients for the moving average filter


b = np.ones(window_size) / window_size # Filter coefficients
a = 1 # No recursive term (FIR)
# Apply the filter to the signal
y = lfilter(b, a, x)
return y, b
fs = 2000 ;t = np.arange(0, 1.0, 1.0 / fs) ;x = np.sin(2 * np.pi * 5 * t) + 0.5 *
np.random.randn(len(t)) ;window_size = 25 # Size of the smoothing window (number
of samples) ;y, b = moving_average_filter(x, window_size) ;w, h = freqz(b, worN=8000,
fs=fs) ;impulse = np.zeros(50) ;impulse[0] = 1 # Dirac impulse ;imp_response = lfilter(b,
1, impulse) ;frequencies, gd = group_delay((b, 1), fs=fs) ;plt.figure(figsize=(10, 6))
plt.subplot(2, 1, 1) ;plt.plot(t, x, label='Original Signal') ;plt.plot(t, y, label='Filtered
Signal (Moving Average)', color='red') ;plt.title('Original Signal (Sine Wave with Noise)
and Filtered Signal') ;plt.xlabel('Time [s]') ;plt.ylabel('Amplitude') ;plt.grid()
plt.subplot(2, 1, 2) ;plt.plot(t, y, label='Filtered Signal (Moving Average)', color='red')
plt.title('Signal After Filtering (Moving Average Filter)') ;plt.xlabel('Time [s]')
plt.ylabel('Amplitude') ;plt.grid() ;plt.figure(figsize=(10, 12)) ;plt.subplot(4, 1, 1)
plt.stem(b, use_line_collection=True) ;plt.title("Impulse Response of the Moving Average
Filter") ;plt.xlabel("Samples") ;plt.ylabel("Amplitude") ;plt.subplot(4, 1, 2) ;plt.plot(w,
(abs(h)), 'b') ;plt.title("Magnitude Response of the Moving Average Filter")
plt.xlabel("Frequency [Hz]") ;plt.ylabel("Magnitude [dB]") ;plt.grid() ;plt.subplot(4, 1, 3)
plt.plot(w, np.angle(h), 'g') ;plt.title("Phase Response of the Moving Average Filter")
plt.xlabel("Frequency [Hz]") ;plt.ylabel("Phase [radians]") ;plt.grid() ;plt.subplot(4, 1, 4)
plt.plot(frequencies, gd, 'purple') ;plt.title("Group Delay of the Moving Average Filter")
plt.xlabel("Frequency [Hz]") ;plt.ylabel("Group Delay [samples]") ;plt.grid()
def all_pass_filter(coef, x):
b = [coef, 1.0] # Numerator coefficients
a = [1.0, coef] # Denominator coefficients
yy = lfilter(b, a, x)
return yy
coef = -0.8 ;yy = all_pass_filter(coef, x) ;w, h = freqz([coef, 1.0], [1.0, coef], worN=2000)
plt.figure(figsize=(12, 8)) ;plt.subplot(3, 1, 1) ;plt.plot(t, x, label='Original Signal')
plt.plot(t, yy, label='Filtered Signal (All-Pass)') ;plt.title('Original and Filtered Signal')
plt.xlabel('Time [s]') ;plt.legend() ;plt.grid() ;plt.subplot(3, 1, 2) ;plt.plot(0.5 * fs * w /
np.pi, (abs(h)), 'b') ;plt.title('Magnitude Response of the All-Pass Filter')
plt.xlabel('Frequency [Hz]') ;plt.ylabel('Magnitude [dB]') ;plt.grid() ; plt.subplot(3, 1, 3)
plt.plot(0.5 * fs * w / np.pi, np.unwrap(np.angle(h)), 'g') ;plt.title('Phase Response of the
All-Pass Filter') ;plt.xlabel('Frequency [Hz]') ;plt.ylabel('Phase [radians]') ;plt.grid()
plt.tight_layout() ;plt.show() ;plt.tight_layout() ;plt.show()
Questions
1. What is the sampling frequency of the input signal, and what is its duration?
2. What is the frequency of the sine wave in the input signal x?
3. What is the purpose of the line b = np.ones(window_size) / window_size in the
moving_average_filter function?
DSP / 3 ING / 2024_2025 4

4. What does the window_size parameter control in the moving average filter?
5. What does the np.ones(window_size) / window_size expression do?
6. What is the role of coef in the all_pass_filter function?
7. What effect does increasing the window_size have on the filtered signal?
8. Explain the purpose of freqz and what it calculates for the filters.
9. Why does the freqz function use a high number of points (2000) for frequency?
10. What is the role of the group_delay function, and what does it represent in the filter’s
context?
11. In the all_pass_filter function, how does changing coef affect the phase response of
the filter?
12. Why is np.unwrap applied to the phase response in the all_pass_filter plot?
13. How would you modify the code to implement a low-pass filter instead of a moving
average filter?
14. Why does the group delay fluctuate at specific frequencies?
15. In practical applications, why might a non-constant group delay be problematic?
16.What are the advantages and limitations of using an all-pass filter, as implemented
here, to alter a signal's phase?
17. If the sampling rate (fs) were doubled, how would the filter responses and signal
representation change?

Exercise 4
We apply a notch filter (band-stop filter) to eliminate unwanted frequency components
in a noisy signal, specifically at 50 Hz and its harmonics (100 Hz and 150 Hz).

Create a signal containing a sinusoidal component with a frequency of 10 Hz (signal of


interest) with an amplitude of 1 and a duration of 3 seconds, using a sampling frequency
of fs = 1000 Hz. Add interference (or noise) at 50 Hz, 100 Hz, and 150 Hz to simulate
disturbing harmonics, ensuring that the amplitude of the interferences is less than 1.

Using the given notch_filter function below, apply the notch filter to eliminate the
interferences at 50 Hz, 100 Hz, and 150 Hz from the noisy signal. Graphically represent
the original signal and the filtered signal to compare the effectiveness of the noise
suppression.

def notch_filter(data, fs, freq, quality=30):


w0 = freq / (fs / 2) # Normalize the frequency
b, a = iirnotch(w0, quality)
filtered_data = filtfilt(b, a, data)
return filtered_data

Exercise 5
Consider Exercise 2 from the TD series. Develop a program that computes and visualizes
the impulse response, frequency response, phase response, and group delay of the
system. Provide a commentary on the results.

You might also like