Mudanças entre as edições de "PSD29007-Engtelecom(2019-2) - Prof. Marcos Moecke"

De MediaWiki do Campus São José
Ir para navegação Ir para pesquisar
Linha 1: Linha 1:
 +
==Registro on-line das aulas==
 +
{{collapse top |  Unidade 1}}
 +
===Unidade 1===
 +
 +
;Aula 1 (29 jul):
 +
*[[PSD-EngTel (Plano de Ensino) | Apresentação da disciplina]]
 +
* Auto inscrição na [https://moodle.sj.ifsc.edu.br/course/index.php?categoryid=163 Plataforma Moodle de PSD29007] (engtelecom2019-2)
 +
 +
;Aula 2 (1 ago):
 +
*[[Transformadas de Fourier]]
 +
<!--
 +
;Aula 3 (15 fev):
 +
 +
* Revisão de Sinais e Sistemas no tempo discreto em Matlab:
 +
:* Explorar a interface do Matlab. 
 +
:* Funções de visualização das variáveis no workspace.
 +
:* Execução de instruções passo a passo.
 +
:* Escrita de script .m
 +
:* Uso da execução das seções de um script. 
 +
:* Incremento de valor e execução.
 +
:EXEMPLOS:
 +
* Leia com atenção e execute o exemplo (Moving-Avarage Filter) na página de help da função [http://www.mathworks.com/help/matlab/ref/filter.html filter].
 +
* Revisão de Sinais e Sistemas no tempo discreto em Matlab:
 +
* Leia com atenção o help [https://www.mathworks.com/help/matlab/examples/using-fft.html Using FFT], abra o script clicando no botão ['''Open this Example'''].  Execute o script seção após seção. Note o uso da fft para determinar a frequência das manchas solares.
 +
* Para melhorar o desempenho no Matlab recomendo que leiam a pagina do  [http://www.mathworks.com/help/matlab/learn_matlab/help.html Help], .  Também gostaria de lembra-los que a tecla F9 executa o código destacado no Help. [http://www.mathworks.com/help/matlab/learn_matlab/scripts.html Programação com scripts .m].
 +
:* Leia sobre [https://en.wikipedia.org/wiki/Sunspot manchas solares] para entender o que são os dados do segundo exemplo.
 +
 +
: Sinais no dominio do tempo e dominio da frequencia.  Uso da função [https://www.mathworks.com/help/matlab/ref/fft.html fft]
 +
{{collapse top| Exemplo de uso da FFT}}
 +
<syntaxhighlight lang=matlab>
 +
%% Signal in Time Domain
 +
% Use Fourier transforms to find the frequency components of a signal buried in noise.
 +
% Specify the parameters of a signal with a sampling frequency of 1 kHz and a signal duration of 1.5 seconds
 +
Fs = 1000;            % Sampling frequency                   
 +
T = 1/Fs;            % Sampling period     
 +
L = 1500;            % Length of signal
 +
t = (0:L-1)*T;        % Time vector
 +
 +
% Form a signal containing a 50 Hz sinusoid of amplitude 0.7 and a 120 Hz sinusoid of amplitude 1.
 +
S = 0.7*sin(2*pi*50*t) + sin(2*pi*120*t);
 +
 +
% Corrupt the signal with zero-mean white noise with a variance of 4.
 +
X = S + 2*randn(size(t));
 +
 +
% Plot the noisy signal in the time domain. It is difficult to identify the frequency components by looking at the signal X(t).
 +
subplot(211);
 +
plot(1000*t(1:200),X(1:200))
 +
title('Signal Corrupted with Zero-Mean Random Noise')
 +
xlabel('t (milliseconds)')
 +
ylabel('X(t)')
 +
 +
%% Signal in Frequency Domain
 +
% Compute the Fourier transform of the signal.
 +
Y = fft(X);
 +
 +
% Compute the two-sided spectrum P2. Then compute the single-sided spectrum P1 based on P2 and the even-valued signal length L.
 +
P2 = abs(Y/L);
 +
P1 = P2(1:L/2+1);
 +
P1(2:end-1) = 2*P1(2:end-1);
 +
 +
% Define the frequency domain f and plot the single-sided amplitude spectrum P1.
 +
% The amplitudes are not exactly at 0.7 and 1, as expected, because of the added noise.
 +
% On average, longer signals produce better frequency approximations.
 +
f = Fs*(0:(L/2))/L;
 +
subplot(212);
 +
plot(f,P1)
 +
ylim([0 1.05])
 +
title('Single-Sided Amplitude Spectrum of X(t)')
 +
xlabel('f (Hz)')
 +
ylabel('|P1(f)|')
 +
 +
% Now, take the Fourier transform of the original, uncorrupted signal and retrieve the exact amplitudes, 0.7 and 1.0.
 +
Y = fft(S);
 +
P2 = abs(Y/L);
 +
P1 = P2(1:L/2+1);
 +
P1(2:end-1) = 2*P1(2:end-1);
 +
 +
plot(f,P1)
 +
title('Single-Sided Amplitude Spectrum of S(t)')
 +
xlabel('f (Hz)')
 +
ylabel('|P1(f)|')
 +
</syntaxhighlight>
 +
{{collapse bottom}}
 +
 +
:* Amostragem de Sinais (Experimento 1.2)
 +
::* Relembrar teorema da amostragem. Efeito da amostragem abaixo da frequência de Nyquist.  Aliasing.
 +
::* Notar que as amostras de um sinal <math>s_1(t) = cos (2\pi \times 3 t)</math> (3 Hz) e um sinal <math>s_2(t) = cos (2\pi \times 7 t)</math> (7 Hz) são idênticas quando amostrado com um sinal de 10 Hz.
 +
 +
{{collapse top| Experimento 1.2}}
 +
<syntaxhighlight lang=matlab>
 +
%  Exemplos e Experimentos baseados no livro:
 +
% DINIZ, P. S. R., DA SILVA, E. A. B., e LIMA NETTO, S. Processamento Digital de Sinais: Projeto e Análise de Sistemas. 2. ed. Porto Alegre: Bookman, 2014. 976 p. ISBN 978-8582601235.
 +
%% Experimento 1.2
 +
fs = 10; % frequencia (Hz) de amostragem dos sinais
 +
Ts = 1/fs; fase = 0;
 +
time = 0:Ts:(1-Ts);
 +
f1 = 3; % frequencia (Hz) do sinal s_1
 +
f2 = 7; % frequencia (Hz) do sinal s_2
 +
s_1 = cos(2*pi*f1*time+fase);
 +
s_2 = cos(2*pi*f2*time+fase);
 +
fsa = 1000; % frequência auxiliar de amostragem usada apenas para representação dos sinais originais
 +
Tsa = 1/fsa;
 +
time_aux = 0:Tsa:(1-Tsa);
 +
figure(1);
 +
stem(time,s_1,'ob');
 +
hold on;
 +
plot(time_aux, cos(2*pi*f1*time_aux+fase),'--k');
 +
stem(time,s_2,'+r');
 +
plot(time_aux, cos(2*pi*f2*time_aux+fase),'--m');
 +
hold off;
 +
legend('s_1 discreto','s_1 contínuo','s_2 discreto','s_2 contínuo')
 +
</syntaxhighlight>
 +
{{collapse bottom}}
 +
 +
:'''DICAS:'''
 +
*No help on-line da Matworks, usando o botão ['''Try This Example > Try in your browser'''], permite executar o código no próprio browser sem ter nenhuma instalação do Matlab.  Para verificar que o código realmente é executado mude a amplitude do ruído randômico para 0.1 ou 0.5, insira o comando '''close all''' antes da primeira linha, e execute todo o código ['''Run All''']
 +
*No help do Matlab, usando o botão ['''Open this Example'''], é possível executar o código seção a seção.
 +
 +
 +
;Aula 3 (20 fev):
 +
*Revisão de Sinais e Sistemas no tempo discreto em Matlab:
 +
:* Filtragem de Sinais (Experimentos 1.3, 2.1 e 2.2)
 +
:* Consulte a documentação do Matlab sobre [http://www.mathworks.com/access/helpdesk/help/techdoc/ref/roots.html roots], [http://www.mathworks.com/help/matlab/ref/poly.html poly], [http://www.mathworks.com/help/matlab/ref/linspace.html linspace], [http://www.mathworks.com/help/matlab/ref/logspace.html logspace], [http://www.mathworks.com/help/matlab/ref/residue.html residue], [http://www.mathworks.com/help/signal/ref/residuez.html residuez], [http://www.mathworks.com/help/matlab/ref/pretty.html pretty], [http://www.mathworks.com/help/matlab/ref/latex.html latex], [http://www.mathworks.com/help/signal/ref/freqs.html freqs],  [http://www.mathworks.com/help/signal/ref/freqz.html freqz],  [http://www.mathworks.com/help/symbolic/syms.html syms], [http://www.mathworks.com/help/signal/ref/symfun.html symfun],  [http://www.mathworks.com/help/signal/ref/zplane.html zplane].
 +
:* Ver também o [http://www.mathworks.com/help/matlab/ref/publish.html Publish] para a geração automática de relatórios em html, doc, pdf, latex ou ppt. Ver também [http://www.mathworks.com/help/matlab/matlab_prog/publishing-matlab-code.html Publishing MATLAB Code].
 +
:* Ver pag. 138 a 141 de <ref name="DINIZ2014"/>
 +
{{collapse top | Variação do Experimento 2.2}}
 +
<syntaxhighlight lang=matlab>
 +
%  Exemplos e Experimentos baseados no livro:
 +
% DINIZ, P. S. R., DA SILVA, E. A. B., e LIMA NETTO, S. Processamento Digital de Sinais: Projeto e Análise de Sistemas. 2. ed. Porto Alegre: Bookman, 2014. 976 p. ISBN 978-8582601235.
 +
%% Experimento 2.2
 +
% Resposta em frequencia usando a função freqz
 +
N = 1;
 +
num = [1 0 0 0];
 +
den = poly([0.8 0.2])
 +
%den = [1 0.6 -0.16];
 +
% modo 1
 +
%[H,w]=freqz(num,den,[0:pi/100:N*pi-pi/100]);
 +
%plot(w/pi, abs(H));
 +
% modo 2
 +
%[H,w]=freqz(num,den);
 +
%plot(w/pi, abs(H));
 +
% modo 3
 +
%[H,w]=freqz(num, den, 'whole');
 +
%plot(w/pi, abs(H));
 +
% modo 4
 +
freqz(num, den, 'whole');
 +
figure(2);
 +
zplane(num,den);
 +
 +
%% Resposta em frequencia substituindo z -> e^(jw)
 +
syms z
 +
Hf(z) = symfun(z^2/(z-0.2)/(z+0.8),z);
 +
pretty(Hf)
 +
latex(Hf)
 +
N = 1;
 +
w = [0:pi/100:N*pi-pi/100];
 +
plot(w/pi,abs(Hf(exp(1i*w))))
 +
%title(['$' latex(Hf) '$'],'interpreter','latex')
 +
text(0.2,2,['H(z) = ' '$$' latex(Hf) '$$'],'interpreter','latex')
 +
xlabel(['w/' '$$' '\pi' '$$'],'interpreter','latex')
 +
</syntaxhighlight>
 +
#Verifique a diferença entre os tipos de plots comentados no código.
 +
#substitua o denominador de H(z) por dois polos em [-0.8 -0.8].
 +
#verifique o que ocorre se forem utilizados polos complexos conjugados [0.3-0.4i  0.3+0.4i 0.1]
 +
#verifique o que ocorre se forem utilizados polos complexos não conjugados [0.3-0.4i  0.3+0.8i]
 +
#verifique o que ocorre se os polos estiverem fora do circulo unitário  [1.2 -0.2].  Interprete este resultado 
 +
{{collapse bottom}}
 +
 +
:* Consulte a documentação do Matlab sobre [http://www.mathworks.com/help/matlab/ref/zeros.html zeros], [http://www.mathworks.com/help/matlab/ref/ones.html ones], [http://www.mathworks.com/help/matlab/ref/plot.html plot], [http://www.mathworks.com/help/matlab/ref/stem.html stem], [http://www.mathworks.com/help/matlab/ref/subplot.html subplot], [http://www.mathworks.com/help/matlab/ref/filter.html filter].
 +
:* Para usar melhor a interface do Matlab leia também [http://www.mathworks.com/help/matlab/matlab_prog/run-sections-of-programs.html?searchHighlight=script%20sections Execução de seções e variação de valores nos scripts], e ainda [http://www.mathworks.com/help/matlab/learn_matlab/plots.html Uso de gráficos no Matlab].
 +
:* Ver pag. 65 a 71 de <ref name="DINIZ2014"> DINIZ, P. S. R., DA SILVA, E. A. B., e LIMA NETTO, S. '''Processamento Digital de Sinais: Projeto e Análise de Sistemas'''. 2. ed. Porto Alegre: Bookman, 2014. 976 p. ISBN 978-8582601235 </ref>
 +
:*Ver também [http://www.mathworks.com/help/releases/R2014a/pdf_doc/matlab/index.html PDF Documentation for MATLAB]. Principalmente [http://www.mathworks.com/help/releases/R2014a/pdf_doc/matlab/getstart.pdf MATLAB Primer].
 +
 +
;Aula 4 (22 fev):
 +
*Revisão de Sinais e Sistemas no tempo discreto em Matlab:
 +
:* Filtros Digitais ([https://owncloud.ifsc.edu.br/index.php/s/WWY2LWexts8PKDs Experimento 2.3])
 +
<syntaxhighlight lang=matlab>
 +
%% Experimento 2.3 - Filtros Digitais
 +
% Exemplos e Experimentos baseados no livro:
 +
% DINIZ, P. S. R., DA SILVA, E. A. B., e LIMA NETTO, S. Processamento Digital de Sinais: Projeto e Análise de Sistemas. 2. ed. Porto Alegre: Bookman, 2014. 976 p. ISBN 978-8582601235.
 +
% FILE: Exp2_3.m
 +
 +
%% 1º filtro
 +
p1 = 0.9*exp(1j*pi/4);
 +
Z = [1 -1 ]'; P = [p1 p1']';
 +
[num,den] = zp2tf(Z,P,1);
 +
[h,w] = freqz(num,den);
 +
figure(1); plot(w,abs(h)/max(abs(h)));
 +
figure(2); zplane(num,den);
 +
 +
%% 2º filtro
 +
z1 = exp(1j*pi/8);
 +
z2 = exp(1j*3*pi/8);
 +
p1 = 0.9*exp(1j*pi/4);
 +
Z = [1 -1 z1 z1' z2 z2']';
 +
P = [p1 p1' p1 p1' p1 p1']';
 +
[num,den] = zp2tf(Z,P,1);
 +
[h,w] = freqz(num,den);
 +
figure(1); plot(w,abs(h)/max(abs(h)));
 +
figure(2); zplane(num,den);
 +
 +
%% 3º filtro
 +
z1 = exp(1j*pi/8);
 +
z2 = exp(1j*3*pi/8);
 +
p1 = 0.99*exp(1j*pi/4);
 +
p2 = 0.9*exp(1j*pi/4 - 1j*pi/30);
 +
p3 = 0.9*exp(1j*pi/4 + 1j*pi/30);
 +
Z = [1 -1 z1 z1' z2 z2']';
 +
P = [p1 p1' p2 p2' p3 p3']';
 +
[num,den] = zp2tf(Z,P,1);
 +
[h,w] = freqz(num,den);
 +
figure(1); plot(w,abs(h)/max(abs(h)));
 +
figure(2); zplane(num,den);
 +
</syntaxhighlight>
 +
:* Diferentes formas de realizar a filtragem de Sinais (
 +
::* convolução (conv(x,h)),
 +
::* filtragem no domínio do tempo (y = a1.x(n)+ a2.x(n-1)+ .. ak.x(n-k));
 +
::* no domínio da frequência (y = ifft(fft(x)fft(h))
 +
 +
{{collapse top | Variação do Experimento 3.1}}
 +
<syntaxhighlight lang=matlab>
 +
%% Variação do Experimento 3.1 do livro:
 +
% DINIZ, P. S. R., DA SILVA, E. A. B., e LIMA NETTO, S. Processamento Digital de Sinais: Projeto e Análise de Sistemas. 2. ed. Porto Alegre: Bookman, 2014. 976 p. ISBN 978-8582601235.
 +
% FILE: Ex3_1.m
 +
% Exemplificando as possiveis formas de realizar a filtragem de um sinal x(n)
 +
 +
clc; clear all; close all;
 +
%% Definindo valores iniciais
 +
Nh = 10; Nx = 20;
 +
%Nh = 400; Nx = 10000;
 +
x = ones(1,Nx);
 +
% A resposta ao inpulso de um sistema h(n)
 +
% no filtro FIR aos coeficientes b(n) = h(n)
 +
h = [1:Nh]; b = h;
 +
%% Filtrando o sinal e medindo tempos
 +
 +
% Filtragem utilizando a convolução
 +
% NOTE: length(y) = length(x) + length(h) -1
 +
tic;  % iniciar a contagem do tempo
 +
y1 = conv(x,h);
 +
t(1) = toc; % terminar acontagem e mostrar tempo no console
 +
 +
% filtragem utilizando a equação recursiva
 +
% NOTE: length(y) = length(x)
 +
tic;
 +
y2 = filter(b,1,x);
 +
t(2) = toc;
 +
 +
% filtragem utilizando a equação recursiva
 +
% aumentando o tamanho de x para que length(y3) = length(y1)
 +
x3 = [x zeros(1,length(h)-1)];
 +
tic;
 +
y3 = filter(h,1,x3);
 +
t(3) = toc;
 +
 +
length_y = length(x) + length(h) - 1;
 +
 +
% filtragem utilizando a FFT
 +
% a y = IFFT(FFT(x)*FFT(h))
 +
tic;
 +
X = fft(x,length_y);
 +
H = fft(h,length_y);
 +
Y4 = X.*H;
 +
y4 = ifft(Y4);
 +
t(4) = toc;
 +
 +
% filtragem utilizando a função fftfilt
 +
% a y = IFFT(FFT(x)*FFT(h))
 +
 +
tic
 +
y5 = fftfilt(h,x3);
 +
t(5) = toc;
 +
 +
disp('Comprimento do vetor de saída length(y)')
 +
disp(['    ' num2str([length(y1) length(y2) length(y3) length(y4) length(y5)])])
 +
disp('Tempo usado na filtragem em micro segundos')
 +
disp(['    ' num2str(t*1e6) ' us'])
 +
 +
%%  Plotando o gráfico
 +
subplot(411);stem(y1);
 +
hold on;
 +
stem(y2,'xr');
 +
stem(y3,'+m');
 +
legend('y1', 'y2', 'y3')
 +
hold off
 +
subplot(412);stem(y1, 'ob');legend('y1')
 +
subplot(413);stem(y2, 'xr'); hold on; stem(zeros(size(y1)),'.w');hold off; legend('y2')
 +
subplot(414);stem(y3, '+m');legend('y3')
 +
</syntaxhighlight>
 +
{{collapse bottom}}
 +
* Notar a diferença de tempo de processamento entre os processos de filtragem. 
 +
* A situação pode ser muito diferente conforme muda o tamanho do sinal e ordem do filtro (h(n)).
 +
 +
;Aula 5 (27 fev):
 +
:* Exercício - Sinal DTMF com ruído
 +
::* Verifique se o Matlab está reproduzindo corretamente o som.
 +
<syntaxhighlight lang=matlab>
 +
%% Carregando o som
 +
clear, close, clc
 +
load handel;
 +
 +
%% Reproduzindo o som
 +
sound(y,Fs)
 +
 +
% Reproduzindo o som
 +
%soundsc(y,Fs)
 +
 +
% Reproduzindo o som
 +
%player = audioplayer(y, Fs);
 +
%play(player);
 +
</syntaxhighlight>
 +
::* Usando o Matlab (ou Audacity) para gerar um sinal [https://pt.wikipedia.org/wiki/DTMF DTMF] correspondente a um número N e adicionar um ruido ao sinal. Opcionalmente utilize um [[Media:DFMT EX1.ogg | sinal DTMF gravado]]
 +
::* Utilizar uma frequência de amostragem de 8000Hz de fazer a duração do sinal igual a 2 segundos.
 +
<center> [[Arquivo:audacity_DTMF.png | Sinal 1234567890*# | 600 px]] </center>
 +
::* Para adicionar o ruído utilize a função y = [http://www.mathworks.com/help/comm/ref/awgn.html awgn](x,snr), ou  y = x + nivel*[http://www.mathworks.com/help/matlab/ref/randn.html randn](n).
 +
 +
::* Observe este sinal no domínio do tempo (DT) e domínio da frequência (DF).
 +
<syntaxhighlight lang=matlab>
 +
%% Carregando o som
 +
clear, close, clc
 +
[y,Fs] = audioread('DTMF_8kHz.ogg');
 +
 +
%% Reproduzindo o som
 +
sound(y,Fs)
 +
 +
%% Visualizando o som no DT
 +
time = [0:length(y)-1]'/Fs;
 +
plot(time',y'); xlabel('segundos');
 +
xlim([0 time(end)]), ylim([-1 1]);
 +
 +
%% Visualizando o som no DF
 +
Nfreq = length(y);
 +
freq = linspace(0,2*pi,Nfreq)'*Fs/pi/2;
 +
Y = fft(y,Nfreq)/Nfreq;
 +
plot(freq,abs(Y)); xlabel('Hertz');
 +
xlim([0 Fs/2]);
 +
</syntaxhighlight>
 +
:* Utilizar no Audacity um sinal DTMF ("1234567890") com fa= 8kHz
 +
::* Visualizar no domínio do tempo e frequência.
 +
::* Realizar a filtragem passa-baixas com fc = 1066 Hz, (selecionar a maior atenuação permitida)
 +
::* Realizar a filtragem passa-faixa  com f0 = 770 Hz e B = 70Hz (selecionar a maior ordem permitida)
 +
:* Repetir o procedimento anterior para um sinal de ruído branco.
 +
 +
:* Consulte a documentação do Matlab sobre <syntaxhighlight lang=matlab> fft, ifft, fftshift, randn </syntaxhighlight>
 +
:* Consulte a documentação do Matlab sobre <syntaxhighlight lang=matlab> plot, grid, subplot, hold, xlabel, ylabel, title, legend, xlim, ylim, log10, log </syntaxhighlight>
 +
:* Consulte a documentação do Matlab sobre [https://www.mathworks.com/help/matlab/ref/text.html text], [http://www.mathworks.com/help/signal/ref/zp2tf.html zp2tf], [http://www.mathworks.com/help/signal/ref/tf2zp.html tf2zp], [http://www.mathworks.com/help/signal/ref/fftfilt.html fftfilt], [http://www.mathworks.com/help/matlab/ref/awgn.html awgn]
 +
:*Ver pag. 141 a 145 e 230 a 235 de <ref name="DINIZ2014"/>
 +
-->
 +
{{collapse bottom}}
 +
 
*[[Transformadas de Fourier]]
 
*[[Transformadas de Fourier]]

Edição das 13h41min de 1 de agosto de 2019

Registro on-line das aulas

Unidade 1

Unidade 1

Aula 1 (29 jul)
Aula 2 (1 ago)