0% found this document useful (0 votes)
43 views6 pages

Lab Activity 7

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)
43 views6 pages

Lab Activity 7

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/ 6

Lab Activity 7: Application of Correlation in Digital Signal

Processing (DSP) Using Python (Signal Detection, Filtering


and Time Delay Estimation)
I. Objective
• In this lab activity, you will use Python to implement and understand the application of correlation
in various DSP tasks, including:
1. Signal Detection using Cross-Correlation.
2. Filtering with Convolution and Cross-Correlation.
3. Time Delay Estimation using Cross-Correlation
Each code block contains errors. Follow the procedures below to troubleshoot and correct these
errors.

II. Lab Activity Procedures


Install libraries numpy, scipy and matplotlib.
Part 1: Signal Detection Using Cross-Correlation
To detect a known reference signal x[n] inside a received signal y[n] using cross-correlation.his sc
• Define the signals
• Reference signal: x[n]=[1,2,1]
• Received signal: y[n]=[0,1,2,1,0,0]
• Calculate the cross-correlation between x[n] and y[n] using Python.
• Plot the cross-correlation to visualize where the reference signal matches in the received signal.
• Expected Output
• The plot will show the correlation values for different lags, and the maximum value will
correspond to the lag where the reference signal x[n] aligns most closely with y[n].
• The output will indicate the lag (position) at which x[n] is detected in y[n].
• Code:
import numpy as np
import matplotlib.pyplot as plt
# Define signals
x = np.array([1, 2, 1])
y = np.array([0, 1, 2, 1, 0, 0])
# Cross-correlation
correlation = np.correlate(x, y, mode='wrong')

# Plotting the cross-correlation


lags = np.arange(-len(x), len(y))

plt.figure(figsize=(10, 6))
plt.stem(lags, correlation, use_line_collection='False')

plt.title("Cross-Correlation between y[n] and x[n]")


plt.xlabel("Lag (m)")
plt.ylabel("Correlation Value")
plt.grid(True)
plt.show()

max_lag = lags[np.argmax(correlation)]
print(f"Maximum correlation occurs at lag {max_lag}")
Part 2: Filtering with Convolution and Cross-Correlation
To apply a simple filter on the input signal using convolution and then use cross-correlation to detect the
filtered signal.
• Define an input signal x[n]=[1,2,3,4,5] and a filter h[n]=[1,0,−1]
• Perform convolution of x[n] with h[n] to get the filtered output y[n].
• Use cross-correlation to compare the filtered signal with the original signal.
• Visualize the output of the convolution and the cross-correlation.
• Expected Output
• The first plot will show the filtered signal obtained via convolution.
• The second plot will display the cross-correlation of the input signal with the filter.
• The filtered signal will be smoothed or modified according to the characteristics of the
filter.
• Code:
# Define input signal and filter
x = np.array([1, 2, 3, 4, 5]) # Input signal
h = np.array([1, 0, -1]) # Filter

# Convolution (Filtering)
y = np.convolve(x, h, mode='correct')

# Cross-correlation between input signal and filter


cross_corr = np.correlate(h, x, mode='full')

# Plotting the results


plt.figure(figsize=(10, 6))
# Plot Convolution Result
plt.subplot(2, 1, 1)
plt.stem(np.arange(len(y)), y, use_line_collection=True)
plt.title("Filtered Signal (Convolution of x[n] and h[n])")
plt.xlabel("n")
plt.ylabel("y[n]")

# Plot Cross-Correlation
plt.subplot(2, 1, 2)
plt.stem(np.arange(len(cross_corr)), cross_corr, use_line_collection='True')

plt.tight_layout()
plt.show()

# Display results
print("Filtered Signal y[n]:", y)
print("Cross-Correlation values:", cross_corr)

Part 3: Time Delay Estimation Using Cross-Correlation


To estimate the time delay between two signals by calculating the cross-correlation and finding the lag with
the maximum correlation.
• Define two signals:
• x[n]=[1,2,3,4,5]
• y[n]=[0,1,2,3,4,5]
• Compute the cross-correlation between x[n] and y[n].
• Determine the time delay (lag) where the signals are most aligned.
• Expected Output
• The plot will show the cross-correlation values at different lags.
• The lag with the maximum cross-correlation value will indicate the time delay between
the two signals.
• The output will display the estimated time delay (lag) where the signals are most aligned.
• Code:
# Define signals
x = np.array([1, 2, 3, 4, 5]) # Signal x[n]
y = np.array([0, 1, 2, 3, 4, 5]) # Signal y[n]
# Compute cross-correlation
correlation = np.correlate(x, y, mode='half')
# Plot the cross-correlation
lags = np.arange(len(x), len(y))

plt.figure(figsize=(10, 6))
plt.stem(lags, correlation, use_line_collection=True)
plt.title("Cross-Correlation between y[n] and x[n]")
plt.xlabel("Lag (m)")
plt.ylabel("Correlation Value")
plt.grid(True)
plt.show()
# Find the lag with maximum correlation
max_lag = np.argmax(correlation)
print(f"Maximum correlation occurs at lag {max_lag}")

III. Output Graph Description


• Part 1: The plot in this part shows the cross-correlation between the reference signal x[n] and the
received signal y[n]. The X-axis represents the lags or shifts applied to the reference signal, while
the Y-axis shows the correlation values at each lag. A peak in the plot indicates the point where the
two signals are most aligned, revealing the time delay between them. The lag corresponding to
this peak is the estimated delay between x[n] and y[n].
• Part 2: Convolution Plot: This plot shows the result of convolution between the input signal x[n]
and the filter h[n]. The X-axis represents the sample number n, and the Y-axis displays the filtered
signal y[n]. The output signal demonstrates how the filter modifies the original signal, depending
on its characteristics. Cross-Correlation Plot: Here, the cross-correlation between the input signal
x[n] and the filter h[n] is shown. The X-axis represents lags, and the Y-axis shows the correlation
values. The plot identifies where the filter matches the signal, with peaks indicating areas of strong
similarity.
• Part 3: This plot shows the cross-correlation between two signals x[n] and y[n]. The X-axis
represents lags (time shifts), and the Y-axis shows the correlation values. The plot reveals a peak at
the lag where the signals are most aligned, which corresponds to the time delay between them.
The lag of the peak gives the estimated delay between the two signals.

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
The goal of this activity is to apply signal detection, filtering, and time delay estimation techniques to
identify errors in a transmitted signal, particularly focusing on detecting error codes through cross-
correlation and filtering methods.
• Required Python libraries: numpy, matplotlib, scipy. You are provided with a reference signal
(ideal signal) x[n] and a received signal y[n] which contains noise and possible error codes. The
error code may appear as a distortion or shift in the received signal. The Steps are:
• Signal Detection and Error Code Identification
1. Generate the reference signal x[n] (e.g., a sinusoidal signal) and the received signal y[n]
by adding noise and a shift (time delay or phase shift) to the reference signal.
A. Reference signal x[n]=sin (2πfn)
B. Received signal y[n]=x[n−Δn] + noise (where Δn is the time shift and noise is
added)
2. Perform cross-correlation between x[n] and y[n]. Plot the cross-correlation and identify
the peak that corresponds to the time delay. This will help detect if there is a shift or
delay in the received signal, which may indicate an error in transmission.
3. Identify error code. If the peak is not aligned as expected, an error code may be
detected. The misalignment suggests that either the time delay or noise distortion is
affecting the signal. Determine the lag at which the peak occurs and estimate the error
in time delay or alignment.
• Signal Filtering for Error Correction
1. Design a filter (e.g., low-pass filter) to remove high-frequency noiseUse scip. y.signal to
design a filter (e.g., scipy.signal.butter for a Butterworth filter).
2. Filter the received signal y[n] and plot the result. Compare the filtered signal with the
original reference signal x[n] to check if the noise and error have been mitigated.
3. Evaluate filter performance. Check if the error code is removed by comparing the cross-
correlation of the filtered signal with the reference signal. If the time delay has been
corrected, the cross-correlation plot should show a clear peak at the expected lag.
• Time Delay Estimation and Error Detection. Use cross-correlation to estimate the time delay
between the reference signal x[n] and the received (and filtered) signal y[n]. Compare this
time delay with the known time shift to detect errors.
1. Estimate the time delay. Use cross-correlation on the filtered signal to detect the lag
that gives the best alignment between x[n] and y[n].
2. Detect the error. If the estimated time delay deviates significantly from the expected
delay (based on Δn), report this as an error. The error can be attributed to a distortion
or noise introduced in the received signal.
Note:
• After each part of the code (especially filtering and cross-correlation), visually inspect the signals (plots) and
check for any noticeable issues, such as misalignments, unexpected peaks, or noise artifacts.
• Use print statements to check intermediate results, such as the length of signals after the roll or filter, and the
values of the cross-correlation at various lags.
• Look for out-of-bounds errors or unexpected behaviors (e.g., spikes in the correlation or strange signal patterns)
to locate potential issues in signal processing steps.
Questions:
1. How does cross-correlation help in detecting time delays or shifts in the received signal?
2. How does the filtering process affect the accuracy of time delay estimation?
3. What challenges did you face in detecting the error code, and how did the combination of filtering and cross-
correlation help mitigate these errors?
4. What role does noise play in error detection, and how effective was the filter in reducing the impact of noise?
5. Explain how you could improve this system for more complex error detection scenarios, such as in
communication systems with more significant distortions or multiple error codes.
CODE FOR ITEM 5
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal

# Step 1: Generate the reference and received signals with noise


f = 5 # Frequency of the signal
n = np.arange(0, 100) # Sample range
x = np.sin(2 * np.pi * f * n) # Reference signal
# Introduce a time shift and noise to create the received signal
delta_n = 5 # Time shift (delay)
noise = np.random.normal(0, 0.1, size=n.shape) # Gaussian noise
y = np.roll(x, delta_n) + noise # Shifted and noisy received signal

# Step 2: Plot cross-correlation to detect error


correlation = np.correlate(y, x, mode='full')
lags = np.arange(-len(x) + 1, len(x))
plt.figure()
plt.plot(lags, correlation)
plt.title('Cross-Correlation between Reference and Received Signal')
plt.xlabel('Lag')
plt.ylabel('Correlation')
plt.show()

# Step 3: Design a low-pass filter to remove noise


b, a = signal.butter(4, 0.1, btype='low', analog=False)
y_filtered = signal.filtfilt(b, a, y)

# Step 4: Plot the filtered signal


plt.figure()
plt.plot(n, y_filtered, label='Filtered Signal')
plt.plot(n, x, label='Reference Signal', linestyle='--')
plt.title('Filtered Signal Comparison')
plt.xlabel('Sample Index')
plt.ylabel('Amplitude')
plt.legend()
plt.show()

# Step 5: Estimate time delay with cross-correlation of filtered signal


correlation_filtered = np.correlate(y_filtered, x, mode='full')
plt.figure()
plt.plot(lags, correlation_filtered)
plt.title('Cross-Correlation between Reference and Filtered Signal')
plt.xlabel('Lag')
plt.ylabel('Correlation')
plt.show()
# Step 6: Error detection
estimated_delay = lags[np.argmax(correlation_filtered)] # Time delay estimate
print(f"Estimated Time Delay: {estimated_delay} samples")
if estimated_delay != delta_n:
print(f"Error detected! Expected delay: {delta_n}, Estimated delay: {estimated_delay}")
else:
print("No error detected. Time delay is correct.")
VI. Questions: (reflected on individual report)
1. Explain the concept of cross-correlation and its role in signal detection. How does the peak in the cross-
correlation plot help identify the time delay between a reference signal and a received signal? Discuss how
noise can affect the accuracy of this detection process.
2. Describe the process of convolution in signal processing and its application in filtering. How does the choice
of filter (e.g., low-pass or high-pass) affect the characteristics of the filtered signal? Provide an example of
how convolution can be used to modify an input signal.
3. In time delay estimation, cross-correlation is used to determine the lag between two signals. Explain how
cross-correlation is calculated and how the peak in the cross-correlation plot can be used to estimate the
time delay between two signals.
4. Discuss the significance of time delay estimation in practical applications such as synchronization of signals in
communication systems. What challenges might arise in accurately estimating time delay when the signals
are noisy or distorted?
5. Compare and contrast the cross-correlation technique used in signal detection and time delay estimation
with other methods, such as Fourier analysis. In what scenarios might one method be preferred over the
other?

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