Category Archives: DSP Filtering

DSP Filtering

Low frequency Butterworth and optimal Wiener ECG filters

Regular ad hoc filters don’t guarantee optimal signal filtering as there is no any criteria that evaluates filter characteristics. Usually filter parameters are calculated empirically and filtering is done by best results.
In order to avoid such shortage there are optimal filters used where parameters are optimized by some criteria. The main idea of optimal filtering is to give bigger weight coefficients to signal spectra parts where signal noise has less power and true signal spectral components has bigger power.
Lets project simple Butterworth filter that will be used as comparative filter to optimal Wiener DSP filter.
Butterworth filter transfer characteristics:

butterworth1.gif

 

Where N – indicates filter Tap number. I will skip description of butterworth filter for now as main idea is constructing optimal wiener filter. Butterworth filter characteristics are pretty plain:

butterworth_chart.jpg

 

Butterworth characteristics with bandpass of 70Hz

Main disadvantage of Butterworth filter is that signal is distorted on filter output. If you want minimal signal distortions it is better to use optimal Wiener filter. Filter chart looks as follows:

Wiener_chart3.gif

 

As you can see to make this filter functional wee need additional conditions like signal model reference. Filter coefficients are calculated using MMSE. root mean square error. Lets see how it works.
Filter input is ideal signal plus noise:

 

signal_input4.gif

and filter output depends on filter weights of coefficients wk

output_weights5.gif

Further wee need to optimize filter coefficients wk in order to meet minimal signal error e(n):

minimal_error6.gif

As we can see minimal root mean square error depends on ideal signal model construction.
In frequency domain optimal Wiener filter coefficients are calculated by using Wiener – Hoph equation:

Wiener_Hoph7.gif

 

Where Sη(w) – noise power spectral density;

Sd(w) – signal model power spectral density.

noise_power_spectral_density8.gif

 

Where Rη(m)- noise self correlation function.

Lets see what results wee get. First of all we have made Butterworth low frequency filter. Signal sampling frequency were used – 1000Hz. We have made couple examples when filter tap numbers are 4 and 8 and cutoff frequencies are 30 and 70Hz:

butterworth_tap4_cut30Hz.jpg

butterworth_tap4_cut70Hz.jpg

butterworth_tap8_cut30Hz.jpg

butterworth_tap8_cut70Hz.jpg

It is really hard to assemble good parameters for Butterwoth filter because there is no good criteria to value filter accuracy. So following step is optimal filter construction.

First of all we need signal model reference:

 

ECG_signal model.jpg

According to previous formulas we calculate filter coefficients depending on signal and signal model spectral densities:

ECG_signal_AND_model_SD.jpg

a) Signal noise spectral density; b) real signal spectral density; c) signal model spectral density ; d) Filter coefficients dependency on frequency.

When we have Wiener-Hoph equation with all required coefficients we can filter ECG signal. First of all filtering is done in frequency domain. Lets calculate signal Fourier transformation, then filtering is nothing more than multiplying signal Fourier transformation by filter coefficients. Results are in following picture:

ECG_FIlterin_Freq.jpg

a) real signalo Fourier transformation; b) filtered signal Fourier transformation; c) real signal; d) filtered signal

Of course you can filter signal in time domain. For this you have to make reverse Fourier transformation of filter coefficients. If wee take 30 of filter coefficients we get:

ECG_filtering_Time_Domain.jpg

Signal filtered in time domain using 30 of filter coefficients.

Now we can compare filtered signals by using Butterworth and Wiener filters. One of comparative methods can be calculation of group delay. In following results we can see that using Butterworth filter group delay is biggest at 70Hz while Wiener filters resulting group delay oscillates around 0.

Group_Delay.jpg

a) Butterworth filter group delay; b) Wiener filter group delay

According to results it is really hard to say which filtering method is better. We can see, that using tap 8 and 30Hz Butterworth filter it gives more clear Q segment while using Wiener filter this part of signal is hardly noticeable. Of course signal model is quite rough, this results in less precise filter coefficients.

 

%%%%%%%%Matlabsource%%%%%%%%%%%%%%%%%%%%%

%Optimal ECG signal filtering using Wiener filter”

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

close all;

clear all;

clc;

%1. Projecting Butterworth filter

Fp=70;

Fd=1000;

eil=8;

%Cut-Off

ecg = load(‘ecg_hfn.dat’);

ecg=ecg/max(ecg(2100:2800));

figure

[B,A]=butter(eil/2,Fp/(Fd/2));

N=length(ecg);

timeall=N/Fd;

tecg=0:1/Fd:timeall;

plot(tecg(1:700),ecg(2101:2800));

grid on;

title(‘measured signal and filtered with Butterworth filter’);

xlabel(‘t, s’);

ylabel(‘Amplitude, mV’);

hold on;

fecg1 = filter(B,A,ecg);

for i=1:N

ecg1rev(i)=fecg1(N+1-i);

end

fecg2rev = filter(B,A,ecg1rev);

for i=1:N

fecg(i)=fecg2rev(N+1-i);

end

poslinkis=eil*3+1

plot(tecg(1:700),fecg(2101:2800),’red’);

xlabel(‘t, s’);

ylabel(‘Amplitude, mV’);

legend(‘Real signal and filtered signal’);

hold off;

%Butterworth characteristics

figure;

freqz(B,A,700,Fd);

figure

grpdelay(B,A,700,Fd);

%Group delay

load mas1.mat xd yd;

clear des_x; clear des_y;

des_x=[]; des_y=[];

%Model Interpolation

des_x=xd-xd(1);

tasku=round(xd(end)-xd(1));

des_y=max(ecg(2100:2800))*yd;

xi=0:tasku-1;

% Aproximation with cubic spine

yi=interp1(des_x,des_y,xi,’cubic’);

figure

plot(des_x,des_y,’o',xi,yi);

grid on;

xlabel(‘t, s’);

ylabel(‘Amplitude, mV’);

des_x = des_x(1:13);

des_y = des_y(1:13);

figure(3);

plot(des_x,des_y,’*',des_x,des_y);

hold on;

grid on;

xlabel(‘Time, ms’);

ylabel(‘Amplitude’);

axis tight;

hold off;

ans = 1;

end

%

load trm.mat

x1=trm;

L1=x1(2)-x1(1);

L2=x1(4)-x1(3);

L3=x1(6)-x1(5);

L4=x1(8)-x1(7);

L=[L1; L2; L3; L4];

Lmin=min(L);

ecgtr=[ecg(x1(2):x1(2)+Lmin), ecg(x1(3):x1(3)+Lmin), ...

ecg((x1(6)-Lmin):x1(6)),ecg(x1(7):x1(7)+Lmin)];

Tr=mean(ecgtr,2);

Trvid=mean(Tr,1);

Tr=Tr-Trvid;

%noise power spectral density

[Ptr,f]=periodogram(Tr,[],514,Fd); %512

%periodogram(Tr,[],512,Fd);

figure

psdplot(Ptr,f,’Hz’);

figure

subplot (2,2,1);psdplot(Ptr,f,’Hz’);

%Real signal spectral density

ecg=ecg-Trvid;

ecg=ecg/max(ecg(2100:2800));

[Psig,f]=periodogram(ecg(2100:2800),[],512,Fd); %512

subplot(2,2,2);psdplot(Psig,f,’Hz’);

%Model spectral density

[Pmod,f]=periodogram(yi,[],514,Fd); %512

subplot(2,2,3);psdplot(Pmod,f,’Hz’);

%Wiener coefficients

for ii=1:length(Pmod)

W(ii)=1/(1+(Ptr(ii)/Pmod(ii)));

end

ii=1:length(Pmod);

subplot(2,2,4); plot(ii,W);

grid on;

xlabel(‘f, Hz’);

ylabel(‘W’);

%Low freq filtering

ecgfft = fft(ecg(2100:2800),700);

figure

subplot(2,2,1);plot(abs(ecgfft(1:258)))

grid on;

xlabel(‘f, Hz’);

ylabel(‘Amplitude’);

for ii=1:(length(Pmod))

ecgfd(ii)=W(ii)*ecgfft(ii);

end

subplot(2,2,2);plot(abs(ecgfd));

grid on;

xlabel(‘f, Hz’);

ylabel(‘Amplitude’);

subplot(2,2,3);plot(tecg(1:700),ecg(2101:2800));

grid on;

xlabel(‘t, s’);

ylabel(‘Amplitude, mV’);

ecgiff= (ifft(ecgfd(1:length(Pmod)), 700));

ecgiff=real(ecgiff)/real(max(ecgiff))+Trvid/4;

subplot(2,2,4);plot(tecg(1:700),real(ecgiff));

grid on;

xlabel(‘t, s’);

ylabel(‘Amplitude, mV’);

figure

plot(tecg(1:700),ecg(2101:2800),’red’);

grid on;

xlabel(‘t, s’);

ylabel(‘Amplitude, mV’);

%Filtering in time domain

koef=abs(ifft(W));

ecgtd = filter(koef(1:30),1, ecg);

ecgtd=ecgtd/max(ecgtd);

figure

plot(tecg(1:700),ecgtd(1:700))

grid on;

xlabel(‘t, s’);

ylabel(‘Amplitude, mV’);

figure

subplot(1,2,1);grpdelay(B,A,700,Fd);

subplot(1,2,2);grpdelay(koef(1:30),1,700,Fd);

Files:  mat1.mat and trm.mat files

Second Order DSP Filter explained

Second order DSP filter is more complex than first order filters. There is one more delay block (z-1) added. Function diagram of second order DSP filter.

image001.gif

The equation for second order DSP Filter can be written as follows:

image003.jpg
And transfer function expressed in Z transform would be:
image005.jpg

There can be two particular cases of filter. If we can write general expression of filter like this:

image007.jpg

Then:

1) When N=0 we get non recursive digital filter (FIR – Finite Impulse Response). This is simple sum of finite number of samples. In other words – averaging filter.

2) When N>0 we get recursive filter. This filter (IIR – Infinite Impulse Response) has a feedback where output samples are branched to input together with input samples. This type of filter has stability issues and so on.

General form of transfer function may look like this – applies to all filter types:

image009.jpg

What about realization of filter? Using digital filters in embedded systems is a critical issue. Sampled signal is forwarded to filter input as x(nT) queue and output is y(nT) is a result of digital processing of signal. Speed of processing may be defined as minimal clock period Tmin of sampled input signal x(nT) or by frequency band Fmax=1/(2Tmin) of signal (according to Nyquist identity). The lower Tmin is – the higher Fmax – speed of DSP processing. The main target of DSP processing usually is real time processing of wide band signals.

Universal microcontrollers are almost useless in higher speed signal processing. To make effective there are needed parallel modules in microcontrollers, but universal microcontrollers can perform one task at one time. Other situation is with DSP processors. They have ability to parallel some instructions and increase speed of critical parts of algorithms.

The most effective DSP can be done using FPGA. There all commands can be performed in parallel and high speed. I am not going to deep in this as this needs a separate analysis thread…

From analog to digital signal filtering

Signal filter is electrical equipment that attenuates the unwanted signal characteristic wave. Filters can be analog or digital.

An analog filter processes analog signals. They are mainly arranged with capacitors and resistors.

Digital signal filters process digital signals which are quantized. Digital filters are arranged with solid state components to process the signals.

Let’s start from analog filters.

Analog filter is a circuit which filters unwanted frequencies. Filtering is done by choosing circuit transfer function.

Simplest analog low pass filter:

image001.gif

The current in RC circuit can be calculated as follows:

image003.gif

Then if we think about digital filtering, then Uin(t) and Uex(t) we can change to xn=x(nT) and yn=y(nT). Then we can rewrite equation:

image005.gif

Then we get:

yn=a0xn+a1xn-1-b1yn-1,

Where

a0=1/(1+T/RC), a1=-1/(1+T/RC), b1=-1/(1+T/RC).

This equation now can be used to build digital filter.

Filter can be described using response function. Response function of analog filter is reaction to step function while digital filter response function is response to step function in samples:

u[n] = 1, if n>=0
u[n] = 0, otherwise

According to method described in previous article we can calculate filter transfer function h(n);

Results are in following table:

Filter

h at t/RC

0

0.5

1

1.5

2

Analog

1

0.779

0.368

0.223

0.136

Digital

T=0.5RC

0.667

0.444

0.296

0.198

0.132

T=0.25RC

0.8

0.512

0.328

0.21

0.134

T=0.125RC

0.889

0.555

0.346

0.216

0.135

image007.gif

From this chart you can see, if time T between samples is smaller then digital filter trends to analog filter characteristic. This means that you may choose digital filter error by varying sample step.

Digital filters have some advantages against analog filters. For instance in some circumstances analog filter can’t be valid while digital can be valid.

Besides transfer function filter can be described using Laplace transform:

H(s)=y(s)/x(s).

And x transform:

H(z)=Y(z)/X(z).

Z transform can be done in following way:

image009.jpg

Inverse Z transform:

image011.jpg

I am not going too deep in it as there are tons of information about Z transform:

Using Z transform we can rewrite our filter equation in following form:

image013.jpg

This is one Tap filter and its structure:

image015.jpg

z­-1 means delay by on sample, T – one clock period. a0, a1 and b1 are filter coefficients (multipliers).

We can rewrite filter equation in other way:

image017.jpg

Now its easy to write filter transfer function:

H(z)=(a0+a1z-1)/(1+b1z-1)

And filter frequency response:

image019.jpg
New on WinAVR Tutorial New on WinARM Tutorial