Lab Activity 8

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Lab Activity 8: Application of Z Transform (Finite Duration

Signals) in Digital Signal Processing (DSP) Using Python


I. Objective
1. Understand and compute the Z-transform of finite-duration signals using Python with real z-values.
2. Develop problem-solving skills by troubleshooting Python code with intentional errors.
3. Visualize the Z-transform for real z-values and analyze its behavior.
II. Lab Activity Procedures
Install libraries numpy, scipy, sympy and matplotlib.
PART 1: SYMBOLIC COMPUTATION OF Z-TRANSFORM
• Expected Output
• The corrected code will output a clean symbolic formula representing the Z-transform of
the finite-duration signal x[n], such as X(z)=1+2z−1+3z−2+4z−3 calculated without errors or
warnings.
• Code:
from sympy import symbols, summation

# Define the finite-duration signal


x = [1, 2, 3, 4]
n = symbols('n') # Signal index
z = symbols('z') # Z-transform variable

# Attempt to compute the Z-transform


X_z = summation(x[n] * z**(-n), (n, 0, len(x)))
print(f"Symbolic Z-transform: {X_z}")

PART 2: NUMERICAL COMPUTATION OF Z-TRANSFORM


• Expected Output
• The corrected code will produce a plot of the Z-transform X(z) as a smooth curve for
real z-values, showing how X(z) varies with z. The plot will be properly labeled with no
division-by-zero errors, and the data will align with the theoretical Z-transform equation.
• Code:
import numpy as np

# Define the finite-duration signal


x = [1, 2, 3, 4]
z_values = np.linspace(0, 2, 50) # Range includes z=0, causing division by zero

# Compute the Z-transform for real z-values


X = [sum([x[k] * z**(-k) for k in range(len(x))]) for z in z_values]

# Plot the Z-transform


plt.figure(figsize=(8, 4))
plt.plot(z_values, X, label="Z-transform")
plt.title("Z-transform for Real z")
plt.xlabel("z")
plt.ylabel("X(z)")
plt.legend()
plt.show()
PART 3: SIGNAL VISUALIZATION AND Z-TRANSFORM
• Expected Output
• The corrected code will first display a stem plot of the finite-duration signal x[n], clearly showing its
time indices and amplitudes, followed by a properly labeled graph of the Z-transform X(z) for
real z-values, highlighting its trend with no errors in computation or visualization.
• Code:
import matplotlib.pyplot as plt

# Define the finite-duration signal


x = [1, 2, 3, 4]
n = range(len(x))

# Plot the signal


plt.figure(figsize=(8, 4))
plt.stem(n, x)
plt.xlabel("Time Index (n)")
plt.ylabel("x[n]")
plt.show()

# Compute the Z-transform


z_values = np.linspace(0.5, 1.5, 100)
X_z = [sum([x[k] * z**(-k) for k in range(len(x))]) for z in z_values]

# Plot the Z-transform magnitude


plt.figure(figsize=(8, 4))
plt.plot(z_values, X_z)
plt.title("Z-transform for Real z")
plt.xlabel("z")
plt.ylabel("X(z)")
plt.show()

III. Output Graph Description


• Part 1: No graph is generated in this snippet, as the focus is on printing the symbolic Z-transform
formula. The output will be a text-based symbolic expression of the Z-transform.
• Part 2: The graph will display the Z-transform X(z) as a smooth curve plotted against real z-values.
The X-axis represents the range of z, and the Y-axis represents the computed X(z) values. The plot
will clearly show the variation in X(z) as z changes, with proper labels and a title for interpretation.
• Part 3: The first graph is a stem plot of the finite-duration signal x[n], showing discrete points with
the X-axis as the time index n and the Y-axis as the signal amplitude x[n]. The second graph plots
the Z-transform X(z) against real z-values, showing how X(z) changes with z. This plot includes clear
axes labels and a title to make the trend of X(z) easily understandable.

IV. Reminders:
• Part 1 (Enumerate each)
1. ERRORS
2. CORRECTION
3. GRAPH
4. EXPLANATION ON THE CORRECTED CODE
5. Corrected Code (softcopy)
Note: Accomplish item 1-4 in handwriting. On BB, attach your checked output then include the code -on the last part
in one PDF File only for your progress report.
V. Supplementary Item
• Objective: To design a digital filter using the Z-transform, apply it to a finite-duration input signal,
and analyze the results using Python. This activity involves computing the Z-transform of both the
filter and the signal, applying the filter in the frequency domain, and reconstructing the filtered
signal in the time domain.
• Problem Statement: Design a low-pass filter using the Z-transform for a finite-duration input
signal x[n], such as a sine wave combined with noise. Perform the following steps:
1. Compute the Z-transform of the input signal.
2. Apply the designed filter in the Z-domain by multiplying the input signal's Z-transform with the
filter's Z-transform.
3. Reconstruct the filtered signal in the time domain using the inverse Z-transform (numerically).
4. Plot and compare the original signal, noisy signal, and filtered signal.
• Reminders
1. Ensure all required libraries, such as numpy, matplotlib, and scipy, are installed and correctly
imported. Use pip to install any missing libraries if a ModuleNotFoundError occurs.
2. Confirm that the input signal xx is properly defined as a finite-duration signal. Use print
statements to verify the sine wave, noise, and combined signal values.
3. Double-check the filter's numerator (b) and denominator (a) coefficients to ensure they are
correctly specified and compatible with the desired filter type (e.g., FIR or IIR).
4. If plots appear incorrectly or do not render, verify the data format, use plt.tight_layout() to
adjust spacing, and ensure matplotlib.pyplot is imported.
5. Check the compatibility of signal length with filter coefficients during computations like lfilter.
Handle warnings such as division by zero or unstable computations carefully.
6. Use the freqz function to analyze the filter's frequency response and confirm that it matches
the desired behavior, such as low-pass or high-pass filtering.
7. Inspect the filtered signal to ensure the filter's effects are correct. Compare the original, noisy,
and filtered signals both visually and numerically.
8. Verify that filter coefficients and signal values are within a range that prevents numerical
instability or overflow during computations.
9. Include appropriate titles, axis labels, and legends for all plots to make the outputs easy to
understand.
10. Add print statements to trace intermediate values such as signal components, filter
coefficients, and filtered output. Remove these prints after resolving issues for cleaner code.
• Questions for Supplementary:
1. How does the Z-transform of the filter H(z) affect the input signal X(z) when applied in the
frequency domain, and what changes can be observed in the filtered output?
2. What is the significance of the filter coefficients (b and a) in determining the behavior of the
filter, and how do these coefficients influence the magnitude and phase response of the filter?
3. After applying the filter, how does the filtered signal compare to the original signal and the
noisy signal in terms of frequency content and noise reduction?
4. Why is it important to avoid including z=0 in the range of z-values during Z-transform
computations, and what issues might arise if z=0 is used?
5. How can the choice of the filter type (e.g., low-pass, high-pass, band-pass) and its design
impact the reconstruction of the original signal from a noisy observation?
CODE:
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import lfilter, freqz

# Step 1: Define the finite-duration signal (a sine wave with noise)


n = np.arange(0, 50) # Time index
freq = 0.1 # Frequency of the sine wave
signal = np.sin(2 * np.pi * freq * n) # Pure sine wave
noise = np.random.normal(0, 0.5, len(n)) # Additive white noise
x = signal + noise

# Plot the original signal and noisy signal


plt.figure(figsize=(10, 6))
plt.subplot(2, 1, 1)
plt.stem(n, signal, label="Original Signal", basefmt=" ")
plt.title("Original Signal")
plt.xlabel("n")
plt.ylabel("Amplitude")
plt.subplot(2, 1, 2)
plt.stem(n, x, label="Noisy Signal", basefmt=" ", linefmt='r')
plt.title("Noisy Signal")
plt.xlabel("n")
plt.ylabel("Amplitude")
plt.tight_layout()
plt.show()

# Step 2: Design a low-pass filter using the Z-transform coefficients


b = [0.1, 0.15, 0.5, 0.15, 0.1] # Filter coefficients (numerator)
a = [1] # Denominator coefficients (no recursive terms for FIR filter)

# Compute the frequency response of the filter


w, h = freqz(b, a)

# Plot the frequency response


plt.figure(figsize=(10, 4))
plt.plot(w, np.abs(h))
plt.title("Frequency Response of the Low-pass Filter")
plt.xlabel("Frequency (rad/sample)")
plt.ylabel("Magnitude")
plt.grid()
plt.show()

# Step 3: Apply the filter in the Z-domain


filtered_signal = lfilter(b, a, x) # Apply the filter to the noisy signal

# Step 4: Compare original, noisy, and filtered signals


plt.figure(figsize=(10, 6))
plt.subplot(3, 1, 1)
plt.stem(n, signal, label="Original Signal", basefmt=" ")
plt.title("Original Signal")
plt.xlabel("n")
plt.ylabel("Amplitude")
plt.subplot(3, 1, 2)
plt.stem(n, x, label="Noisy Signal", basefmt=" ", linefmt='r')
plt.title("Noisy Signal")
plt.xlabel("n")
plt.ylabel("Amplitude")
plt.subplot(3, 1, 3)
plt.stem(n, filtered_signal, label="Filtered Signal", basefmt=" ", linefmt='g')
plt.title("Filtered Signal")
plt.xlabel("n")
plt.ylabel("Amplitude")
plt.tight_layout()
plt.show()
# The noisy signal is cleaned, retaining the lower frequencies while suppressing high-frequency noise.

VI. Questions: (reflected on individual report)


1. How does the Z-transform provide insight into the frequency characteristics of a finite-duration signal,
and why is it important in Digital Signal Processing (DSP)?
2. What challenges might arise when computing the Z-transform symbolically or numerically, and how can
these be addressed to ensure accurate results?
3. How does the design of filter coefficients influence the behavior of the filtered signal, and what
considerations must be made to achieve the desired output?
4. Why is it important to compare the original, noisy, and filtered signals, and what does this comparison
reveal about the effectiveness of the applied filter?
5. How can you verify that the numerical computations of the Z-transform and filtering are consistent with
theoretical expectations, and what debugging techniques are most effective for this purpose?

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy