0% found this document useful (0 votes)
69 views8 pages

Computer Exercise Chap5-已解锁

Uploaded by

hrlu
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)
69 views8 pages

Computer Exercise Chap5-已解锁

Uploaded by

hrlu
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/ 8

COMPUTER EXERCISE Tasks:

Co 165.8-1 Consider a message signal that consists of three sinusoids

that lasts 0.2 second.


m(t) = 2 cos(2π · 400t) + cos(2π · 800t) − 3 sin(2π · 1200t)
EE
(a) Using a sampling frequency of 4000 Hz, illustrate the spectrum of the ideally sampled signal and

py 0@ compare with the spectrum of the original signal m(t).


(b) Using an ideal LPF of bandwidth B = 2000 Hz for reconstruction, illustrate the difference in
time domain between the reconstructed signal and the original signal. What happens if we select
B = 1500 Hz instead?
(c) If we use a simple rectangular pulse of width Ts Π(t/Ts ) to reconstruct the original signal from the
C
rig quantized samples, design and implement the equalizer filter to recover the message as discussed
in Section 5.1.2.
5.8-2 Consider the same message signal m(t) and the sampling of Prob. 5.8-1. In this exercise, the signal
samples are quantized using 16-level uniform quantizer.

(a) Using an ideal LPF of bandwidth B = 2000 Hz for reconstruction, illustrate the difference in time
domain between the reconstructed signal and the original signal.
(b) If we use a simple rectangular pulse Π(t/Ts ) of width Ts to reconstruct the original signal from the
ht quantized samples, design and implement the equalizer filter to recover the message as discussed
in Section 5.1.2. Compare the difference between the original signal and the recovered signal.
(c) If we use a simple triangular pulse ∆(t/Ts ) of width Ts to reconstruct the original signal from the
quantized samples, design and implement the equalizer filter to recover the message as discussed
in Section 5.1.2. Compare the difference signal recovery using the two different pulses Π(t/Ts )
and ∆(t/Ts ).
ma Da
COMPUTER EXERCISE Examples
U
ter vis
Computer exercises of this section provide examples of signal sampling, quantization, signal reconstruction
from samples, and image compression and coding.
As an initial step, the next few lines of Python code serve to load the necessary Python packages to be
C

used in the later exercises.


ial
LOAD PYTHON PACKAGES AND DATA
# Save the next few lines to import necessary packages, such as numpy
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import dct, idct

To load your own data or dataset, different Jupyter platforms offer different choices. On Google Colab,
one could first upload a data folder, e.g., “chapter5images” to “MyDrive” under “ColabDataFolders”. Once
the data folder is uploaded, run the following lines to enable access:

This content is protected and may not be shared, uploaded, or distributed.


Co 16
Section 5.9. Computer Exercises

from google.colab import drive


drive.mount(’/content/drive’)
285
EE
When accessing the data files within the user data folder, we can set a data directory “chapter5images”
as follows:

py 0@ import os
# Load the cameraman image on Google Colab
data_dirbook=’/content/drive/MyDrive/ColabDataFolders/chapter5images’

The data files within the data folder can be accessed by Jupyter notebook via Python code. For example,
C
rig
to read the image file “cameraman.tiff”, we can use the following line:

G = plt.imread(os.path.join(data_dirbook,’cameraman.tiff’))

Readers are encouraged to explore how to access user data files using their chosen Jupyter nodebook
platforms.
ht
5.9.1 Sampling and Reconstruction of Low-Pass Signals
In the sampling example, we first construct a signal g(t) with two sinusoidal components of 1-second duration;
their frequencies are 1 and 3 Hz. Note, however, that when the signal duration is infinite, the bandwidth of
g(t) would be 3 Hz. However, the finite duration of the signal implies that the actual signal is not strictly
band-limited, although most of the signal content stays within a bandwidth of 5 Hz. For this reason, we
select a sampling frequency of 50 Hz, much higher than the minimum Nyquist frequency of 6 Hz. The
Python program, Exsample.py, implements sampling and signal reconstruction. Figure 5.40 illustrates the
ma Da
original signal, its uniform samples at the 50 Hz sampling rate, and the frequency response of the sampled
signal. In accordance with our analysis of Section 5.1, the spectrum of the sampled signal gT (t) consists of
the original signal spectrum periodically repeated every 50 Hz.
SAMPLING AND RECONSTRUCTION EXAMPLE
# Save this codeblock as ExSample.py
U

td = 0.002 #original sampling rate 500 Hz


ter vis
t = np.arange(0, 1+td, td) # Time interval of 1 second
xsig = np.sin(2*np.pi*t)-np.sin(6*np.pi*t) # 1Hz+3Hz sinusoids
Lsig = len(xsig)
C

ts = 0.02 #new sampling rate = 50Hz.


Nfactor = int(ts/td)
# send the signal through a 16-level uniform quantizer
ial
s_out, sq_out, sqh_out, Delta, SQNR = sampandquant(xsig, 16, td, ts)

# receive 3 signals:
# 1. sampled signal s_out
# 2. sampled and quantized signal sq_out
# 3. sampled, quantized, and zero-order hold signal sqh_out
# calculate the Fourier transforms
Lfft = 2**int(np.ceil(np.log2(Lsig)+1))
Fmax = 1/(2*td)
Faxis = np.linspace(-Fmax, Fmax, Lfft)
Xsig = np.fft.fftshift(np.fft.fft(xsig, Lfft))
S_out = np.fft.fftshift(np.fft.fft(s_out, Lfft))

# Examples of sampling and reconstruction using


This content is protected and may not be shared, uploaded, or distributed.
Co 16
Section 5.9.
#
#
Computer Exercises
a) ideal impulse train through LPF
b) flat top pulse reconstruction through LPF
# plot the original signal and the sample signals in time and frequency domain
286
EE
fig1 = plt.figure(figsize=(6.5,6)); fig1.subplots_adjust(hspace=0.5,wspace=0.4)
plt.subplot(311);

py 0@ sfig1a = plt.plot(t,xsig,’m’,linewidth=1.5)
sfig1b = plt.plot(t,s_out[:Lsig],’b’,linewidth=2)
plt.xlabel(’time (sec)’)
plt.title(r’Signal ${\it g}({\it t})$ and its uniform samples’)

plt.subplot(312); sfig1c = plt.plot(Faxis,np.abs(Xsig),’b’,linewidth=1.5)


C
rig plt.xlabel(r’frequency (Hz)’); plt.axis([-100, 100, 0, 300])
plt.title(r’Spectrum of ${\it g}({\it t})$’); plt.grid()

plt.subplot(313); sfig1d = plt.plot(Faxis,np.abs(S_out),’b’,linewidth=1.5)


plt.xlabel(r’$frequency (Hz)$’); plt.axis([-100, 100, 0, 300/Nfactor])
plt.title(r’Spectrum of ${\it g}_T({\it t})$’); plt.grid()
# Set the spacing between subfigures
plt.tight_layout(pad=1.0); plt.show()
ht
# calculate the reconstructed signal from ideal sampling and ideal LPF
# Maximum LPF bandwidth equals to BW = floor((Lfft/Nfactor)/2);
BW = 10 # Bandwidth is no larger than 10Hz.
H_lpf = np.zeros(Lfft)
H_lpf[int(Lfft/2)-BW:int(Lfft/2)+BW] = 1 # ideal LPF
ma Da
S_recv = Nfactor*S_out*H_lpf # ideal filtering
s_recv = np.real(np.fft.ifft(np.fft.fftshift(S_recv))) # reconstructed f-domain
s_recv = s_recv[:Lsig]

# non-ideal reconstruction
ZOH = np.ones(Nfactor)
s_ni = np.kron(s_out[::Nfactor], ZOH)
U

S_ni = np.fft.fftshift(np.fft.fft(s_ni, Lfft))


ter vis
S_recv2 = S_ni*H_lpf # ideal filtering
s_recv2 = np.real(np.fft.ifft(np.fft.fftshift(S_recv2))) # reconstructed f-domain
s_recv2 = s_recv2[:Lsig] # reconstructed t-domain
C

# plot the ideally reconstructed signal in time and frequency domain


fig2 = plt.figure(figsize=(6.5,6)); fig2.subplots_adjust(hspace=0.5,wspace=0.4)
plt.subplot(311); sfig2a = plt.plot(Faxis,np.abs(S_recv),’b’,linewidth=1.5)
ial
plt.xlabel(’frequency (Hz)’); plt.axis([-100, 100, 0, 300]); plt.grid()
plt.title(’Spectrum of ideal filtering (reconstruction)’)

plt.subplot(312); sfig2b = plt.plot(t,xsig,’m-.’,t,s_recv[:Lsig],’b’,linewidth=2)


plt.legend([’Original signal’,’Reconstructed signal’])
plt.xlabel(’time (sec)’); plt.grid()
plt.title(’Original signal versus ideally reconstructed signal’)
# Set the spacing between subfigures
plt.tight_layout(pad=1.0); plt.show()

# plot the ideally reconstructed signal in time and frequency domain


fig3 = plt.figure(); fig3.subplots_adjust(hspace=0.5,wspace=0.4)
plt.subplot(211); sfig3a = plt.plot(t,xsig,’m’,t,s_ni[:Lsig],’b’,linewidth=2)

This content is protected and may not be shared, uploaded, or distributed.


Co 16
Section 5.9. Computer Exercises
plt.xlabel(’time (sec)’); plt.grid()
plt.title(’Original signal versus flat-top reconstruction’)
287
EE
plt.subplot(212); sfig3b = plt.plot(t,xsig,’m’,t,s_recv2[:Lsig],’b--’,linewidth=2)
plt.legend([’original signal’,’LPF reconstruction’])

py 0@ plt.xlabel(’time (sec)’); plt.grid()


plt.title(’Original and flat-top reconstruction after LPF’)
# Set the spacing between subfigures
plt.tight_layout(pad=1.0); plt.show()
C
Signal g(t) and its uniform samples
2
rig 0

–2
0.0 0.2 0.4 0.6 0.8 1.0
time (sec)

Spectrum of g(t)
30

20

10
ht 0
–100 –75 –50 –25 0 25 50 75 100
frequency (Hz)

Spectrum of gT (t)
300

200

100

0
–100 –75 –50 –25 0 25 50 75 100
ma Da
frequency (Hz)

Figure 5.40: The relationship between the original signal and the ideal uniformly sampled signal in the
time (a) and frequency (b, c) domains.

To reconstruct the original signal g(t) from the impulse sampling train gT (t), we applied an ideal LPF
with bandwidth 10 Hz in the frequency domain. This corresponds to the interpolation using the ideal sinc
U

function as shown in Section 5.1.1. The resulting spectrum, as shown in Fig. 5.41, is nearly identical to
ter vis
the original message spectrum of g(t). Moreover, the time domain signal waveforms are also compared in
Fig. 5.41 and show near-perfect match.
Spectrum of ideal filtering (reconstruction)
300
C

200

100

0
ial
–100 –75 –50 –25 0 25 50 75 100
frequency (Hz)

Original signal versus ideally reconstructed signal


2
Original signal
Reconstructed signal
0

–2
0.0 0.2 0.4 0.6 0.8 1.0
time (sec)

Figure 5.41: Reconstructed signal spectrum and waveform from applying the ideal impulse sampling and
ideal LPF reconstruction.

In our last exercise in sampling and reconstruction, given in the same program, we use a simple rectangular
pulse of width Ts (sampling period) to reconstruct the original signal from the samples (Fig. 5.42). An LPF
is applied on the rectangular reconstruction and also shown in Fig. 5.42. It is clear from comparison to the
This content is protected and may not be shared, uploaded, or distributed.
Co 16Section 5.9. Computer Exercises

original source signal that the recovered signal is still very close to the original signal g(t). This is because
we have chosen a high sampling rate such that Tp = Ts is so small that the approximation of Eq. (5.16)
holds. Certainly, based on our analysis, by applying the low-pass equalization filter of Eq. (5.15a), the
288
EE
reconstruction error can be greatly reduced.
Original signal versus flat-top reconstruction

py 0@ 2
1
0
–1
–2
0.0 0.2 0.4
time (sec)
0.6

Original and flat-top reconstruction after LPF


0.8 1.0
C
2
Original signal
rig 1
0
–1
–2
0.0 0.2 0.4 0.6
LPF reconstruction

0.8 1.0
time (sec)

Figure 5.42: Reconstructed signal spectrum and waveform from applying the simple rectangular recon-
struction pulse (Fig. 5.6) followed by LPF without equalization.
ht
5.9.2 PCM Illustration
The uniform quantization of an analog signal using L quantization levels can be implemented by the Python
function uniquan.py.
DEFINING UNIFORM QUANTIZER
ma Da
def uniquan(sig_in, L):
"""
Usage:
q_out, Delta, SQNR = uniquan(sig_in, L)
L - number of uniform quantization levels
sig_in - input signal vector
U

Function outputs:
ter vis
q_out - quantized output
Delta - quantization interval
SQNR - actual signal to quantization noise ratio
"""
C

sig_pmax = np.max(sig_in) # finding the positive peak


sig_nmax = np.min(sig_in) # finding the negative peak
Delta = (sig_pmax - sig_nmax) / L # quantization interval
ial
# define Q-levels
q_level = np.arange(sig_nmax + Delta / 2, sig_pmax - Delta / 2 + Delta, Delta)
L_sig = len(sig_in) # find signal length
sigp = (sig_in - sig_nmax) / Delta + 1/2 # convert into 1/2 to L+1/2 range
qindex = np.round(sigp).astype(int) # round to 1,2, ... L levels
qindex[qindex < 1] = 1
qindex[qindex > L] = L # eliminate L+1 as a rare possibility
q_out = q_level[qindex - 1] # use index vector to generate output
SQNR = 20*np.log10(np.linalg.norm(sig_in)/np.linalg.norm(sig_in-q_out)) # SQNR
return q_out, Delta, SQNR

The function sampandquant.py executes both sampling and uniform quantization simultaneously. The
sampling period ts is needed, along with the number L of quantization levels, to generate the sampled
This content
output is protected
s out, the and may
sampled and quantized not sq
output beout,
shared,
and the uploaded, or distributed.
signal after sampling, quantizing, and
Co 16
Section 5.9. Computer Exercises

zero-order-hold sqh out.


DEFINING JOINT SAMPLING AND QUANTIZATION FUNCTION
289
EE
def sampandquant(sig_in, L, td, ts):
"""

py 0@ Usage:
s_out, sq_out, sqh_out, Delta, SQNR = sampandquant(sig_in, L, td, ts)
L - number of uniform quantization levels
sig_in - input signal vector
td - original signal sampling period of sig_in
ts - new sampling period
C
rig NOTE: td*fs must be a positive integer;
Function outputs:
s_out - sampled output
sq_out - sample-and-quantized output
sqh_out - sample,quantize, and hold output
Delta - quantization interval
SQNR - actual signal to quantization noise ratio
"""
ht if (ts/td).is_integer():
nfac = int(np.round(ts/td))
p_zoh = np.ones(nfac)
s_out = sig_in[::nfac]
sq_out, Delta, SQNR = uniquan(s_out, L)
s_out = np.stack([s_out] +[s_out*0] * (nfac-1),axis=-1).reshape(-1)
ma Da
sqh_out = np.kron(sq_out, p_zoh)
else:
print("Errors! ts/td is not an integer!")
s_out = sq_out = sqh_out = Delta = SQNR = []
return s_out, sq_out, sqh_out, Delta, SQNR

The Python program ExPCM.py provides a numerical example that uses these two Python functions to
U

generate PCM signals.


ter vis
PCM SIGNAL GENERATING EXAMPLE
# Save the following code block as ExPCM.py
C

td = 0.002 # original sampling rate 500 Hz


t = np.arange(0, 1 + td, td) # time interval of 1 second
xsig = np.sin(2 * np.pi * t) - np.sin(6 * np.pi * t) # 1Hz+3Hz sinusoids
ial
Lsig = len(xsig)
Lfft = int(2 ** (np.ceil(np.log2(Lsig)) + 1))
Xsig = np.fft.fftshift(np.fft.fft(xsig, Lfft))
Fmax = 1 / (2 * td)
Faxis = np.linspace(-Fmax, Fmax, Lfft)
ts = 0.02 # new sampling rate = 50Hz.
Nfact = int(ts / td)
# send the signal through a 16-level uniform quantizer
(s_out, sq_out, sqh_out1, Delta, SQNR) = sampandquant(xsig, 16, td, ts)
# obtained the PCM signal which is
# - sampled, quantized, and zero-order hold signal sqh_out

# plot the original signal and the PCM signal in time domain
fig1 = plt.figure()
This content is protected and may not be shared, uploaded, or distributed.
Co 16
Section 5.9. Computer Exercises
fig1.subplots_adjust(hspace=0.5,wspace=0.4)

plt.subplot(211)
290
EE
sfig1 = plt.plot(t,xsig,’k’,t,sqh_out1[:Lsig],’b’,linewidth=2)
plt.title(r’Signal ${\it g}({\it t})$ and its 16 level PCM signal’)

py 0@ plt.xlabel(’time (sec.)’); plt.grid()

# send the signal through a 4-level uniform quantizer


(s_out, sq_out, sqh_out2, Delta, SQNR) = sampandquant(xsig, 4, td, ts)
# obtained the PCM signal which is
# - sampled, quantized, and zero-order hold signal sqh_out
C
rig # plot the original signal and the PCM signal in time domain
plt.subplot(212)
sfig2 = plt.plot(t,xsig,’k’,t,sqh_out2[:Lsig],’b’,linewidth=2)
plt.title(r’Signal ${\it g}({\it t})$ and its 4 level PCM signal’)
plt.xlabel(’time (sec.)’); plt.grid()
# Set the spacing between subfigures
plt.tight_layout(pad=1.0); plt.show()
ht
Lfft = int(2 ** (np.ceil(np.log2(Lsig)) + 1))
Fmax = 1 / (2 * td)
Faxis = np.linspace(-Fmax, Fmax, Lfft)
SQH1 = np.fft.fftshift(np.fft.fft(sqh_out1, Lfft))
SQH2 = np.fft.fftshift(np.fft.fft(sqh_out2, Lfft))
# Now use LPF to filter the two PCM signals
ma Da
BW = 10
# Bandwidth is no larger than 10Hz.
H_lpf = np.zeros(Lfft)
H_lpf[Lfft // 2 - BW:Lfft // 2 + BW] = 1 # ideal LPF
S1_recv = SQH1 * H_lpf # ideal filtering
s_recv1 = np.real(np.fft.ifft(np.fft.fftshift(S1_recv))) # reconstructed f-domain
s_recv1 = s_recv1[:Lsig] # reconstructed t-domain
U

S2_recv = SQH2 * H_lpf # ideal filtering


ter vis
s_recv2 = np.real(np.fft.ifft(np.fft.fftshift(S2_recv))) # reconstructed f-domain
s_recv2 = s_recv2[:Lsig] # reconstructed t-domain

# Plot the filtered signals against the original signal


C

fig2 = plt.figure()
fig2.subplots_adjust(hspace=0.5,wspace=0.4)
ial
plt.subplot(211)
sfig3 = plt.plot(t,xsig,’b-’,t,s_recv1,’b-.’,linewidth=2)
plt.legend([’original’,’recovered’])
plt.title(r’Signal ${\it g}({\it t})$ and filtered 16-level PCM signal’)
plt.xlabel(’time (sec.)’); plt.grid()

plt.subplot(212)
sfig4 = plt.plot(t,xsig,’b-’,t,s_recv2[:Lsig],’b-.’,linewidth=2)
plt.legend([’original’,’recovered’])
plt.title(r’Signal ${\it g}({\it t})$ and filtered 4-level PCM signal’)
plt.xlabel(’time (sec.)’); plt.grid()
# Set the spacing between subfigures
plt.tight_layout(pad=1.0); plt.show()

This content is protected and may not be shared, uploaded, or distributed.


Co 16
Section 5.9. Computer Exercises 291

In the first example, we maintain the 50 Hz sampling frequency and utilize L = 16 uniform quantization
levels. The resulting PCM signal is shown in Fig. 5.43. This PCM signal can be low-pass-filtered at the
EE
receiver and compared against the original message signal, as shown in Fig. 5.44. The recovered signal is
seen to be very close to the original signal g(t).

py 0@ To illustrate the effect of quantization, we next apply L = 4 PCM quantization levels. The resulting
PCM signal is again shown in Fig. 5.43. The corresponding signal recovery is given in Fig. 5.44. It is very
clear that a smaller number of quantization levels (L = 4) leads to much larger approximation error.
C
rig
ht
ma Da
Figure 5.43: Original signal and the PCM signals with different numbers of quantization levels.
U
ter vis
C
ial

Figure 5.44: Comparison between the original signal and the PCM signals after LPF to recover the original
message.
This content is protected and may not be shared, uploaded, or distributed.

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