{"id":501,"date":"2017-11-16T23:52:35","date_gmt":"2017-11-16T23:52:35","guid":{"rendered":"http:\/\/www.billconnelly.net\/?p=501"},"modified":"2025-07-05T04:15:09","modified_gmt":"2025-07-05T03:15:09","slug":"filtering-a-practical-guide","status":"publish","type":"post","link":"https:\/\/www.billconnelly.net\/?p=501","title":{"rendered":"Filtering &#8211; A practical guide"},"content":{"rendered":"<p>Finding good information on how filters work, what the different types of filters mean, and how you should filter your data is hard. Lots of explanations only make sense if you have a year or two of electrical engineering education, and most of the rest are just a list of rules of thumb. I want to try to get you to a place where you can test your own filter settings, and show you the importance of the rules of thumb without going into the relatively complex math that is often used to explain filters. Warning: a lot of the code I&#8217;m going to use requires the Matlab Signal Processing Toolbox. If you don&#8217;t have it, you wont be able to execute the code yourself, but hopefully you&#8217;ll still be able to follow along with the logic.<br \/>\n<!--more--><\/p>\n<p><strong>What is a filter?<\/strong><br \/>\n<div id=\"attachment_502\" style=\"width: 310px\" class=\"wp-caption alignright\"><a href=\"http:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/time-frequency.png\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-502\" src=\"http:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/time-frequency-300x157.png\" alt=\"On the left is a recording from a neuron shown in the &quot;time domain&quot;. The two graphs on the right show the same recording in the &quot;frequency domain&quot;\" width=\"300\" height=\"157\" class=\"size-medium wp-image-502\" srcset=\"https:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/time-frequency-300x157.png 300w, https:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/time-frequency.png 889w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/a><p id=\"caption-attachment-502\" class=\"wp-caption-text\">Fig 1. On the left is a recording from a neuron shown in the &#8220;time domain&#8221;. The two graphs on the right show the same recording in the &#8220;frequency domain&#8221;<\/p><\/div>In the context of signal processing, a filter is anything the removes unwanted things from your signal. However, in the context of physiological recordings a filter is nearly always referring to a process which removes a certain frequency range from the signal. Because of that, we need to get comfortable looking at data in both the &#8220;time domain&#8221; and the &#8220;frequency domain&#8221;. The &#8220;time domain&#8221; should be very easy to understand, this is just the normal way of looking at data, where time is on the x axis, and the amplitude of the signal is on the y axis. The &#8220;frequency domain&#8221; isn&#8217;t that hard to understand either, it just tells you what frequencies make up your original signal, so you have frequency on the x axis, and &#8220;magnitude&#8221; on the y axis. Why is it &#8220;magnitude&#8221; and not amplitude on the y axis? Because there is another feature we need to consider, which is &#8220;phase&#8221;. Which, roughly speaking is how much the waves that make up the signal are shifted in time. More concretely, a graph of y = sin(2\u03c0 x) and a graph of y = sin(2\u03c0x + \u03c0\/2) are similar, but very different, one is the other shifted along the x axis (Fig 2). Or another way of saying it is: they have the exact same frequency components (i.e. they are both 1 Hz signals), but different phases. So if frequency and magnitude were all we had, those two graphs would appear to be indistinguishable. So in order to get a complete picture of the signal, we need to keep track of the phase of each frequency component. &#8220;Magnitude&#8221; reminds us that we need to remember &#8220;phase&#8221; as well.<br \/>\n<div id=\"attachment_526\" style=\"width: 310px\" class=\"wp-caption alignleft\"><a href=\"http:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/phase.png\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-526\" src=\"http:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/phase-300x229.png\" alt=\"Fig 2. Different phases \" width=\"300\" height=\"229\" class=\"size-medium wp-image-526\" srcset=\"https:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/phase-300x229.png 300w, https:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/phase.png 525w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/a><p id=\"caption-attachment-526\" class=\"wp-caption-text\">Fig 2. A graph of Y = sin(2\u03c0 X) and a graph of Y = sin(2\u03c0X + \u03c0\/2) have the same frequency components, but different phases<\/p><\/div>To see this in action, have a look at figure 1. On the left is a typical recording shown in the time domain. On the right the two graphs are the exact same signal shown in the frequency domain. The top left graph shows the magnitude of all the frequency components of the signal (showing that most of the signal is made up of low frequency components, and generally less and less as the frequency goes up). The bottom left graph doesn&#8217;t look like much, but we need this information to completely describe the time domain signal. And importantly, thinking about phase is super important when it comes to discussing filters.<\/p>\n<p>There are a huge variety of filters, but one of the simplest ways of dividing them up is to consider what signals they don&#8217;t affect, i.e. what signals they let <em>pass<\/em> through them. So a low-pass filter lets through low frequency signals and a high-pass filter lets through high frequency data. There are also band-pass filters which only let through signals in a particular frequency range and to break convention, band-stop filters, which stop signals inside a particular frequency range. The frequency at which the signal begins to be filtered is called the &#8220;corner frequency&#8221; or the &#8220;cut-off frequency&#8221;. When we describe the actions of a filter, we are often show it&#8217;s frequency response, which is shows you what the filter does to various frequency components of your data. This can be estimated by applying the filter to your data, viewing it in the frequency domain and then dividing that by your original signal in the frequency domain. However, as your data doesn&#8217;t usually contain all frequency components, it better to create white noise, which is a signal that has the same amount of power in all frequency components. We can convert data to the frequency domain by using the Fourier transform (which I&#8217;ve talked about before <a href=\"http:\/\/www.billconnelly.net\/?p=276\">here<\/a>). In code, that looks like this.<\/p>\n<pre class=\"prettyprint\">\r\nsignal = randn(1000,1); %Create white noise\r\ndt = 0.5; %dt is the time between samples\r\ntime = 1:dt:1000 ; %create time base\r\n\r\n%% Filter the data\r\n%Make a simple running average filter\r\n%Take the mean of the original data in a window\r\n%of the data tempC(i:i+window)\r\n%I know there are faster ways of doing this.\r\n\r\ntempC_filt = zeros(size(signal));\r\n\r\nwindow = 5;\r\nfor i = 1:length(signal)\r\nend_idx = i+window;\r\nif end_idx &gt; length(signal)\r\n    end_idx = length(signal);\r\nend\r\ntempC_filt(i) = mean(signal(i:end_idx));\r\nend\r\n\r\n%% Now convert data to frequency domain\r\n\r\nnfft = 2^nextpow2(length(signal)); %FFTs are faster if you perform them\r\n                                  %on power of 2 lengths vectors\r\n\r\nf = (1&#47;dt)&#47;2*linspace(0,1,nfft&#47;2+1)&#39;; %Create Frequency vector&#39;\r\n\r\ndft      = fft(signal, nfft)&#47;(length(signal)&#47;2); % take the FFT of original\r\ndft_filt = fft(tempC_filt, nfft)&#47;(length(tempC_filt)&#47;2); %take FFT of filters\r\nmag = abs(dft(1:nfft&#47;2+1));                     %Calculate magnitude\r\nmag_filt = abs(dft_filt(1:nfft&#47;2+1));           %Calculate magnitude\r\n\r\nloglog(f, mag_filt.&#47;mag)\r\nxlabel(&#39;Frequency (Hz)&#39;)\r\nylabel(&#39;Signal Out &#47; Signal In&#39;)\r\n<\/pre>\n<p><\/p>\n<p><div id=\"attachment_503\" style=\"width: 310px\" class=\"wp-caption alignleft\"><a href=\"http:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/freqresp_of_movingaverage1.png\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-503\" src=\"http:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/freqresp_of_movingaverage1-300x241.png\" alt=\"freqresp_of_movingaverage\" width=\"300\" height=\"241\" class=\"alignleft size-medium wp-image-504\" srcset=\"https:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/freqresp_of_movingaverage1-300x241.png 300w, https:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/freqresp_of_movingaverage1.png 512w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/a><p id=\"caption-attachment-503\" class=\"wp-caption-text\">Fig 3. The frequency response of a running average filter.<\/p><\/div> The above code produces the graph in figure 3, which shows the the frequency components of the filtered signal divided by the frequency component of the original signal. What it shows us is that the running average filter doesn&#8217;t affect signals below 10^-1 Hz (0.1 Hz), but attenuates them above that. It also shows us that a running average filter doesn&#8217;t uniformly attenuation signals above 0.1 Hz, but instead filters out signals more strongly at about 0.4 Hz and 0.8 Hz than it does at  0.6 Hz and 1 Hz. This problem is refereed to as &#8220;ripples in the stop band&#8221;, where the &#8220;stop band&#8221; is the region of frequencies where the signal is attenuated, and &#8220;ripples&#8221; are the changing amount of attenuation of your signal with frequency.  Compare this the &#8220;perfect&#8221; filter, where the signal is not attenuated at all up until some frequency, and then the signal is completely obliterated beyond that (I know it&#8217;s shown as only being attenuated by 10^-3, but you can&#8217;t show 0 on a log axis). This &#8220;perfect&#8221; filter is what most filters want to be. They want to not alter the signal in frequency ranges of the &#8220;pass band&#8221;, and completely remove the signal in the stop band. But filters like that are impossible to create in real life.<\/p>\n<p>Now I&#8217;ve said a perfect filter doesn&#8217;t want to alter signals in the pass-band, and by looking at the graph above, it might appear that so long as you are below about 0.1 Hz you wont affect the signal, but as I alluded to before, we need to consider what the filter does to the phase. We can achieve that by adding only a few more lines to our above code.<\/p>\n<pre class=\"prettyprint\">\r\nsignal = randn(1000,1); %Create random time series data\r\ndt = 0.5; %dt is the time between samples\r\ntime = 1:dt:1000 ; %create time base\r\n\r\n%% Filter the data\r\n%Make a simple running average filter\r\n%Take the mean of the original data in a window\r\n%of the data tempC(i:i+window)\r\n%I know there are faster ways of doing this.\r\n\r\ntempC_filt = zeros(size(signal));\r\n\r\nwindow = 5;\r\nfor i = 1:length(signal)\r\nend_idx = i+window;\r\nif end_idx &gt; length(signal)\r\n    end_idx = length(signal);\r\nend\r\ntempC_filt(i) = mean(signal(i:end_idx));\r\nend\r\n\r\n%% Now convert data to frequency domain\r\n\r\nnfft = 2^nextpow2(length(signal)); %FFTs are faster if you perform them\r\n                                  %on power of 2 lengths vectors\r\n\r\nf = (1&#47;dt)&#47;2*linspace(0,1,nfft&#47;2+1)&#39;; %Create Frequency vector&#39;\r\n\r\ndft      = fft(signal, nfft)&#47;(length(signal)&#47;2); % take the FFT of original\r\ndft_filt = fft(tempC_filt, nfft)&#47;(length(tempC_filt)&#47;2); %take FFT of filters\r\nmag = abs(dft(1:nfft&#47;2+1));                     %Calculate magnitude\r\nmag_filt = abs(dft_filt(1:nfft&#47;2+1));           %Calculate magnitude\r\n\r\nphase = angle(dft(1:nfft&#47;2+1));\r\nphase_filt = angle(dft_filt(1:nfft&#47;2+1));\r\n\r\n%% Create an ideal filter frequency response\r\nmag_perf = ones(size(mag_filt));\r\nmag_perf(100:end) = 10^-3;\r\n\r\nsubplot(1,2,1)\r\nloglog(f, mag_filt.&#47;mag, f, mag_perf)\r\nxlabel(&#39;Frequency (Hz)&#39;)\r\nylabel(&#39;Signal Out &#47; Signal In&#39;)\r\nlegend(&#39;Running Average Filter&#39;, &#39;Perfect Filter&#39;)\r\n\r\nsubplot(1,2,2)\r\nsemilogx(f, unwrap(phase-phase_filt));\r\nxlabel(&#39;Frequency (Hz)&#39;)\r\nylabel(&#39;Phase Shift (Rad)&#39;)\r\n<\/pre>\n<p>\n<div style=\"width: 876px\" class=\"wp-caption alignleft\"><a href=\"http:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/freqresp_of_movingaveragephase.png\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/freqresp_of_movingaveragephase.png\" width=\"866\" height=\"391\" class \/><\/a><p class=\"wp-caption-text\">Fig 4. Magnitude and Phase response of a running average filter<\/p><\/div> Here we can clearly see that the phase of the signal is being affected at frequencies as low as 0.05 Hz. So while the amplitude of these frequency components isn&#8217;t being changed, they are being shifted later in time. So this is not a particularly good filter. Let&#8217;s move on in our quest to both understand, and create a better filter.<\/p>\n<p><strong>Filter Poles<\/strong><\/p>\n<p><div id=\"attachment_506\" style=\"width: 310px\" class=\"wp-caption alignright\"><a href=\"http:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/poles.png\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-506\" src=\"http:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/poles-300x235.png\" alt=\"Fig 5.  How the frequency response of a filter varies with the number of poles. \" width=\"300\" height=\"235\" class=\"size-medium wp-image-506\" srcset=\"https:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/poles-300x235.png 300w, https:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/poles.png 516w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/a><p id=\"caption-attachment-506\" class=\"wp-caption-text\">Fig 5.  How the frequency response of a filter varies with the number of poles.<\/p><\/div>(From here on in, I&#8217;m only going to be talking about low-pass filters, as everyone uses them. But everything I say is applicable to high-pass filters too)<\/p>\n<p>Another way of describing a filter is by the number of &#8220;poles&#8221; it has. I&#8217;m not going to explain to you what a pole is, because it comes from the mathematical analysis of filters, and ultimately, it is irrelevant for understanding what the consequence of the filter is. Simply put a filter with more poles attenuates frequencies more heavily for each Hz you go up. Here a figure will paint a thousand words, so see fig 5. We can create that figure with the below code.<\/p>\n<pre class=\"prettyprint\">\r\n%All our filters will have a corner\r\n%frequence (fc) of 1000 Hz\r\nfc = 1000; % Corner Frequency of \r\n\r\n&#091;b2pole,a2pole&#093; = butter(2,2*pi*fc,&#39;s&#39;); %Create a 2 pole butterworth filter\r\n&#091;h2pole,freq2&#093; = freqs(b2pole,a2pole,4096);     %Calculate Frequency Response\r\n\r\n&#091;b6pole,a6pole&#093; = butter(6,2*pi*fc,&#39;s&#39;); %Create a 2 pole butterworth filter\r\n&#091;h6pole,freq6&#093; = freqs(b6pole,a6pole,4096);     %Calculate Frequency Response\r\n\r\n%Plot frequency response\r\nloglog(freq2&#47;(2*pi),abs(h2pole));\r\nhold on\r\nloglog(freq6&#47;(2*pi),abs(h6pole));\r\nxlabel(&#39;Frequency (Hz)&#39;);\r\nylabel(&#39;Magnitude&#39;);\r\nlegend(&#39;2 Pole Butterworth&#39;, &#39;6 Pole Butterworth&#39;)\r\n<\/pre>\n<p><\/p>\n<p>As you can see, as we increase the number of poles in our filter the closer it gets to our perfect filter. Or in electronic engineering terms, it has a steeper &#8220;roll off&#8221;. You might ask &#8220;well then why don&#8217;t we use 1 million pole filters then?&#8221;. Well digitally, we can create very high order filters. However, when it comes to real circuits there are a bunch of reasons why this is difficult, one of which is that it becomes very difficult to find resistors and capacitors of the exact correct value needed. Another reason is that by the time you get up to 8 poles, that is usually good enough. For instance, with an 8 pole Butterworth filter, you attenuate a signal at twice the corner frequency to about 4% of it&#8217;s original value. At 10x the corner frequency, the signal is attenuated by about 1 billion fold. But the important thing to note is that even with a filter with a large number of poles it does not remove ALL of the signal above the corner frequency.<\/p>\n<p><strong>Butterworth?<\/strong><br \/>\n<div id=\"attachment_508\" style=\"width: 310px\" class=\"wp-caption alignright\"><a href=\"http:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/filter_types.png\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-508\" src=\"http:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/filter_types-300x242.png\" alt=\"Fig 6. Frequency Response of filters of various types.\" width=\"300\" height=\"242\" class=\"size-medium wp-image-508\" srcset=\"https:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/filter_types-300x242.png 300w, https:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/filter_types.png 509w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/a><p id=\"caption-attachment-508\" class=\"wp-caption-text\">Fig 6. Frequency Response of filters of various types.<\/p><\/div>You may have noticed previously I was talking about &#8220;Butterworth&#8221; filters. You may have been wondering what that means. There are a litany of other filter types, most notably Bessel and Chebyshev. To give a perfectly accurate definition of the difference between these is beyond me, but the practical difference is a trade off between the steepness of the roll off (for a give number of poles) and the behaviour in the time domain. A Chebyshev filter has the steepest roll off, but the worst behaviour in the time domain, while a Bessel filter has the shallowest roll off, but the best behaviour in the time domain. The Butterworth filter is between the two. Again, let&#8217;s look at the frequency response of these filters to get a better idea (Fig 6). From looking at that, you can see why Chebychev filters aren&#8217;t used for physiological data, it attenuates signals that you might think you weren&#8217;t touching (i.e. ones well below the corner frequency). But it is great for some applications because of it&#8217;s very steep roll off. Code Below:<\/p>\n<pre class=\"prettyprint\">\r\n%All our filters will have a corner\r\n%frequence (fc) of 1000 Hz\r\nfc = 1000; % Corner Frequency of \r\nn_poles = 8;\r\n\r\n&#091;zbess, pbess, kbess&#093; = besself(n_poles, 2*pi*fc); %Create 8 pole Bessel\r\n&#091;bbess,abess&#093; = zp2tf(zbess,pbess,kbess);          %Convert to transfer function\r\n&#091;hbess,freqbess&#093; = freqs(bbess,abess,4096);        %Calculate Frequency Response\r\n\r\n&#091;bbut,abut&#093; = butter(n_poles,2*pi*fc,&#39;s&#39;); %Create a 8 butterworth filter\r\n&#091;hbut,freqbut&#093; = freqs(bbut,abut,4096);         %Calculate Frequency Response\r\n\r\n&#091;bcheb,acheb&#093; = cheby1(n_poles,3,2*pi*fc,&#39;s&#39;); %Create 8 pole Chebychev   cheby1(n,3,2*pi*f,&#39;s&#39;);\r\n                                                    % with 3dB of ripple\r\n&#091;hcheb,freqcheb&#093; = freqs(bcheb,acheb,4096);         %Calculate Frequency Response\r\n\r\n%Plot frequency response\r\nfigure;\r\nloglog(freqbess&#47;(2*pi), abs(hbess))\r\nhold on\r\nloglog(freqbut&#47;(2*pi),abs(hbut));\r\nloglog(freqcheb&#47;(2*pi),abs(hcheb));\r\nxlabel(&#39;Frequency (Hz)&#39;);\r\nylabel(&#39;Magnitude&#39;);\r\nlegend(&#39;Bessel&#39;, &#39;Butterworth&#39;, &#39;Chebychev&#39;)\r\nxlim(&#091;10 10000&#093;)\r\nylim(&#091;10^-4 2&#093;)\r\n<\/pre>\n<p><\/p>\n<p><div id=\"attachment_509\" style=\"width: 310px\" class=\"wp-caption alignright\"><a href=\"http:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/filter_types_timedomain.png\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-509\" src=\"http:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/filter_types_timedomain-300x194.png\" alt=\"Fig 7. Different types of filters in the time domain.\" width=\"300\" height=\"194\" class=\"size-medium wp-image-509\" srcset=\"https:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/filter_types_timedomain-300x194.png 300w, https:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/filter_types_timedomain.png 634w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/a><p id=\"caption-attachment-509\" class=\"wp-caption-text\">Fig 7. Different types of filters in the time domain.<\/p><\/div>However, when comparing the Bessel and the Butterworth, it may seem like the Butterworth is clearly superior: The Bessel filter attenuates signals below the corner frequency just like the Chebyshev! But when you look in the time domain, the reason why physiologists nearly always use a Bessel filter becomes obvious. Other filters producing &#8220;ringing&#8221; after encountering a step-like response. This is because the other filters delay waves of different frequencies by different times (remember, a step like response is created by a sum of a large number of waves). However, the Bessel filter doesn&#8217;t do this. The technical way to describe this is that a Bessel filter has linear phase response. This doesn&#8217;t mean it affects the phase of all the frequencies in the pass band equally, but that the way if shifts the phase means that the various frequency components aren&#8217;t shifted in time by different amounts (think about the fact that one cycle of a slow wave lasts for longer than a faster wave, so if both waves were shifted by half a wave, then slow wave would be shifted by more time). It turns out the Bessel filter is the best possible way to achieve this.<\/p>\n<p><strong>Digitizing &#8211; The hidden filter<\/strong><br \/>\n<div id=\"attachment_511\" style=\"width: 310px\" class=\"wp-caption alignleft\"><a href=\"http:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/digitizing.png\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-511\" src=\"http:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/digitizing-300x240.png\" alt=\"Fig 8. The affect of digitizing inappropriately\" width=\"300\" height=\"240\" class=\"size-medium wp-image-511\" srcset=\"https:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/digitizing-300x240.png 300w, https:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/digitizing.png 511w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/a><p id=\"caption-attachment-511\" class=\"wp-caption-text\">Fig 8. The affect of digitizing a signal with a 32 Hz, 64 Hz and 256 Hz component, inappropriately<\/p><\/div>So what have we learnt so far? That filters remove unwanted frequency components in your data. That for a given filter type, a filter with a high number of poles has a steeper roll off. Finally, we&#8217;ve learnt that different types of filters have different behaviour in the time and frequency domain, and that a Bessel filter has the best behaviour in the time domain. But there is one type of filter we haven&#8217;t covered: your digitizer AKA your analog to digital converter AKA your ADC. No, I&#8217;m not saying there is a filter built into your ADC, I am saying that the mere act of digitizing your signal filters your data, and if you&#8217;re not careful, it can do some very strange things. Don&#8217;t believe me, look at this code, and the figure it produces (Fig 8).<\/p>\n<pre class=\"prettyprint\">\r\n%% Original, high sample rate signal\r\n% Let us imagine this is like our analog signal\r\n\r\nnfft = 4096;\r\n\r\ndt = 0.001; % inter sample time = 0.001s = 1kHz sampling\r\nt = (1:nfft)*0.001; % time vector\r\n\r\n% Create signal vector that is the sum of 32 Hz, 64 Hz, and 256 Hz\r\n\r\nsignal = sin(32*2*pi*t) + sin(2*pi*64*t) + sin(2*pi*256*t);\r\n\r\nf = (1&#47;dt)&#47;2*linspace(0,1,nfft&#47;2+1)&#39;; %Create Frequency vector\r\ndft  = fft(signal, nfft)&#47;(length(signal)&#47;2); % take the FFT of original\r\nmag = abs(dft(1:nfft&#47;2+1));                  %Calculate magnitude\r\n\r\nsemilogx(f, mag, &#39;LineWidth&#39;, 2 );\r\n\r\n%% Now lets digitize our faux-analog signal\r\n% Essentially we are down sampling,\r\n% by sampling it every 0.005s = 200 Hz = every 5th sample.\r\n\r\nsignal_dig = signal(1:5:end);\r\nnfft_dig = 2^nextpow2(length(signal_dig)); %FFTs are faster if you perform them\r\n                                           %on power of 2 lengths vectors\r\n\r\n\r\nf_dig = (1&#47;(dt*5))&#47;2*linspace(0,1,nfft_dig&#47;2+1)&#39;; %Create Frequency vector\r\ndft_dig = fft(signal_dig, nfft_dig)&#47;(length(signal_dig)&#47;2);\r\nmag_dig = abs(dft_dig(1:nfft_dig&#47;2+1));\r\nhold on\r\nsemilogx(f_dig, mag_dig, &#39;LineWidth&#39;, 2);\r\nxlim(&#091;10 1000&#093;)\r\nxlabel(&#39;Frequency (Hz)&#39;);\r\nylabel(&#39;Magnitude&#39;);\r\nlegend(&#39;Original Signal&#39;, &#39;Digitized Signal&#39;);\r\n<\/pre>\n<p><\/p>\n<p><div id=\"attachment_524\" style=\"width: 760px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/digitizing_filtering_with_time.png\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-524\" src=\"http:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/digitizing_filtering_with_time.png\" alt=\"Fig 9. By filtering before we digitize, we avoid aliasing our data.\" width=\"750\" height=\"409\" class=\"size-full wp-image-524\" srcset=\"https:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/digitizing_filtering_with_time.png 750w, https:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/digitizing_filtering_with_time-300x164.png 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/a><p id=\"caption-attachment-524\" class=\"wp-caption-text\">Fig 9. By filtering before we digitize, we avoid aliasing our data.<\/p><\/div>In the code, we create a signal that is a sum of 32, 64 and 256 Hz sine waves. We&#8217;ll think of this signal as being our analog signal. We then &#8220;digitize&#8221; it as 200 Hz. We then look at the two signals in the frequency domain. In the original signal we see peaks at 32, 64 and 256 Hz, and after we digitize it at 200 Hz, we see a loss of 256 Hz signal, which perhaps isn&#8217;t too surprising when you think about it. But something very disturbing has happened, we now have a new signal with a peak at 56 Hz. This signal is a complete phantom and is called &#8220;Aliasing&#8221;, and it happened because we need to filter before we digitize (See Fig 9B). This is a correlate of the Nyquist-Shannon sampling theorem, which says that any signal which has no frequency component higher than F, can be perfectly reconstructed if it is sampled at 2F. So, inversely, if we digitize a signal at rate 2F, but it has frequency components higher than F, then the digitized signal we end up with is not a faithful representation of the original. Now let&#8217;s try to follow the rules. If we add in these lines of code, then we get Fig 9A.<\/p>\n<pre class=\"prettyprint\">\r\n%% Let&#39;s filter the signal before we digitize it\r\n\r\n&#091;bbut,abut&#093; = butter(8,100&#47;(1000&#47;2));      %Create a 100Hz, 8 pole butterworth filter\r\nsignal_filt = filter(bbut, abut, signal);  %Filter the data\r\nsignal_filt_dig = signal_filt(1:5:end);\r\ndft_filt_dig = fft(signal_filt_dig, nfft_dig)&#47;(length(signal_filt_dig)&#47;2);\r\nmag_filt_dig = abs(dft_filt_dig(1:nfft_dig&#47;2+1));\r\nsemilogx(f_dig, mag_filt_dig, &#39;LineWidth&#39;, 2);\r\n<\/pre>\n<p><\/br><\/p>\n<p>And this is one of the two reasons why we must ALWAYS low-pass filter data before we digitize it: if we don&#8217;t, we will get aliases, i.e. spurious frequency components. This is also what causes <a href=\"https:\/\/upload.wikimedia.org\/wikipedia\/commons\/f\/fb\/Moire_pattern_of_bricks_small.jpg\" target=\"_blank\" rel=\"noopener\">strange patterns in some photographs<\/a>, the original data had higher frequencies (i.e. patterns changing in space) than the camera CCD could sample. The other reason we filter BEFORE was digitize is that high frequency noise can sometimes be larger than the signal we want to record, and hence filtering before digitization allows us to amplify the signal as much as possible without saturating the digitizer.<\/p>\n<p><strong>Choosing a corner and sampling frequency<\/strong><br \/>\n<div id=\"attachment_516\" style=\"width: 310px\" class=\"wp-caption alignright\"><a href=\"http:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/corner_frequency1.png\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-516\" src=\"http:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/corner_frequency1-300x260.png\" alt=\"Fig 10. Trying to choose the corner frequency for a Bessel filter isn&#039;t obvious.\" width=\"300\" height=\"260\" class=\"size-medium wp-image-516\" srcset=\"https:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/corner_frequency1-300x260.png 300w, https:\/\/www.billconnelly.net\/wp-content\/uploads\/2017\/11\/corner_frequency1.png 534w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/a><p id=\"caption-attachment-516\" class=\"wp-caption-text\">Fig 10. Trying to choose the corner frequency for a Bessel filter isn&#8217;t obvious.<\/p><\/div>So now we know we need to digitize at least twice as fast as we filter (and in reality probably a bit faster than that, because filters have a roll off, so there is still some signals at X Hz if we filter at X Hz, so I would say we should probably digitize at 3 to 10 times faster than you filter). But how do we choose what frequency we filter at? Just see what frequency components are in the signal we want to record, and set the corner frequency to just above what we want to keep, right? Well let&#8217;s give that a go. I&#8217;m going to make a faux action potential with a Gaussian with a full width at half maximum of 1 ms, then look at the signal in the frequency domain. Unsurprisingly, the signal has basically no power above 1 kHz, so lets apply an 1kHz 8-pole Bessel filter to the data. And what do we see? Our &#8220;action potential&#8221; has been reduced by 10% and significantly shifted in time (Fig 10). How the hell did that happen? Well go up and have a close look at figure 6, even though the corner frequency is 1 kHz, you can see that the Bessel filter is attenuating signals down to ~200 Hz. And that is your rule of thumb for an 8-pole Bessel filter: you need to set the corner frequency to 5 times higher than the highest frequency you want to record, for a 4-pole filter you need to be 4 times higher. So in our case, where the highest frequency is about 1kHz, we need to set our 8-pole Bessel filter to about 5 kHz, which means we need to digitize at at least 15 kHz. (I might add that Bessel filters are odd about this. For most filters, the more poles you get the closer a signal can get to the corner frequency without being filtered. However, this is the opposite with a Bessel filter.)<\/p>\n<pre class=\"prettyprint\">\r\ndt = 1&#47;20000; % 20kHz sampling rate\r\nt = 0:dt:0.02; % time vector 4ms long\r\nsignal = exp(-(t-0.01).^2&#47;(0.001&#47;sqrt(2*log(2)))^2); %Gaussian with 1ms FWHM\r\nnfft = 2^nextpow2(length(signal)); %FFTs are faster if you perform them\r\n                                   %on power of 2 lengths vectors\r\n\r\nf = (1&#47;dt)&#47;2*linspace(0,1,nfft&#47;2+1)&#39;; %Create Frequency vector\r\ndft = fft(signal, nfft)&#47;(length(signal)&#47;2);      %take the FFT of original\r\nmag = abs(dft(1:nfft&#47;2+1));                      %Calculate magnitude\r\n\r\nsubplot(1,2,1);\r\nsemilogx(f, mag, &#39;LineWidth&#39;, 2);\r\ntitle(&#39;Freq Components of Original&#39;)\r\nxlabel(&#39;Frequency (Hz)&#39;);\r\nylabel(&#39;Magnitude&#39;);\r\nxlim(&#091;30 10000&#093;);\r\nxticks(&#091;100, 1000, 10000&#093;);\r\n\r\n&#091;bbess, abess&#093; = besself(8, 2*pi*1000); %Create 8 pole 1kHz filter\r\n&#091;num,den&#093; = bilinear(bbess,abess,1&#47;dt);\r\nsignalbess1k = filter(num, den, signal); %Apply Filter\r\n\r\n&#091;bbess, abess&#093; = besself(8, 2*pi*5000); %Create 8-pole 5kHz filter\r\n&#091;num,den&#093; = bilinear(bbess,abess,1&#47;dt);\r\nsignalbess5k = filter(num, den, signal); %Apply Filter\r\n\r\nsubplot(1,2,2);\r\nplot(t*1000,signal, t*1000, signalbess1k, t*1000, signalbess5k, &#39;LineWidth&#39;, 2);\r\nxlabel(&#39;Time (ms)&#39;)\r\nylabel(&#39;Amplitude&#39;)\r\nlegend(&#39;Original Signal&#39;, &#39;Filtered Signal (1kHz)&#39;, &#39;Filtered Signal (5kHz)&#39;, &#39;Location&#39;, &#39;south&#39;);\r\n<\/pre>\n<p><\/p>\n<p>I should probably add that these rules of thumb are not absolute (apart from digitizing at greater than twice your filter rate: always do that!). If your filter slightly deforms the shape of your action potential, or slightly delays it in time, this may not matter for your particular experiments. But you should still be aware of the fact that if you&#8217;re filtering too close to your signal of interest, you are not recording the &#8220;true&#8221; signal.<\/p>\n<p><strong>Conclusion\/Rules of Thumb<\/strong><\/p>\n<ul>\n<li>A filter removes unwanted frequeny components<\/li>\n<li>A low-pass filter removes high frequency signals<\/li>\n<li>A filter with more poles has a steeper roll off<\/li>\n<li>A Bessel filter has the best behaviour in the time domain<\/li>\n<li>For a 4-pole Bessel, you must filter at at least 4 times the frequency of the fastest wanted component of your signal<\/li>\n<li>For an 8-pole Bessel, you must filter at at least 5 times the frequency of the fastest wanted component of your signal<\/li>\n<li>You must digitize at more than 2-3 times the frequency of your low-pass filter<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Finding good information on how filters work, what the different types of filters mean, and how you should filter your data is hard. Lots of explanations only make sense if you have a year or two of electrical engineering education, and most of the rest are just a list of rules of thumb. I want&hellip;<a href=\"https:\/\/www.billconnelly.net\/?p=501\">Read more <span class=\"screen-reader-text\">Filtering &#8211; A practical guide<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[11,7,1],"tags":[],"_links":{"self":[{"href":"https:\/\/www.billconnelly.net\/index.php?rest_route=\/wp\/v2\/posts\/501"}],"collection":[{"href":"https:\/\/www.billconnelly.net\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.billconnelly.net\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.billconnelly.net\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.billconnelly.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=501"}],"version-history":[{"count":15,"href":"https:\/\/www.billconnelly.net\/index.php?rest_route=\/wp\/v2\/posts\/501\/revisions"}],"predecessor-version":[{"id":806,"href":"https:\/\/www.billconnelly.net\/index.php?rest_route=\/wp\/v2\/posts\/501\/revisions\/806"}],"wp:attachment":[{"href":"https:\/\/www.billconnelly.net\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=501"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.billconnelly.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=501"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.billconnelly.net\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=501"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}<br />
<b>Notice</b>:  ob_end_flush(): Failed to send buffer of zlib output compression (0) in <b>/home/public/wp-includes/functions.php</b> on line <b>5373</b><br />
