-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
filter.py
2942 lines (2628 loc) · 93.3 KB
/
filter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Authors: The MNE-Python contributors.
# License: BSD-3-Clause
# Copyright the MNE-Python contributors.
"""IIR and FIR filtering and resampling functions."""
from collections import Counter
from copy import deepcopy
from functools import partial
from math import gcd
import numpy as np
from scipy import fft, signal
from scipy.stats import f as fstat
from ._fiff.pick import _picks_to_idx
from ._ola import _COLA
from .cuda import (
_fft_multiply_repeated,
_fft_resample,
_setup_cuda_fft_multiply_repeated,
_setup_cuda_fft_resample,
_smart_pad,
)
from .fixes import minimum_phase
from .parallel import parallel_func
from .utils import (
_check_option,
_check_preload,
_ensure_int,
_pl,
_validate_type,
logger,
sum_squared,
verbose,
warn,
)
# These values from Ifeachor and Jervis.
_length_factors = dict(hann=3.1, hamming=3.3, blackman=5.0)
def next_fast_len(target):
"""Find the next fast size of input data to `fft`, for zero-padding, etc.
SciPy's FFTPACK has efficient functions for radix {2, 3, 4, 5}, so this
returns the next composite of the prime factors 2, 3, and 5 which is
greater than or equal to `target`. (These are also known as 5-smooth
numbers, regular numbers, or Hamming numbers.)
Parameters
----------
target : int
Length to start searching from. Must be a positive integer.
Returns
-------
out : int
The first 5-smooth number greater than or equal to `target`.
Notes
-----
Copied from SciPy with minor modifications.
"""
from bisect import bisect_left
hams = (
8,
9,
10,
12,
15,
16,
18,
20,
24,
25,
27,
30,
32,
36,
40,
45,
48,
50,
54,
60,
64,
72,
75,
80,
81,
90,
96,
100,
108,
120,
125,
128,
135,
144,
150,
160,
162,
180,
192,
200,
216,
225,
240,
243,
250,
256,
270,
288,
300,
320,
324,
360,
375,
384,
400,
405,
432,
450,
480,
486,
500,
512,
540,
576,
600,
625,
640,
648,
675,
720,
729,
750,
768,
800,
810,
864,
900,
960,
972,
1000,
1024,
1080,
1125,
1152,
1200,
1215,
1250,
1280,
1296,
1350,
1440,
1458,
1500,
1536,
1600,
1620,
1728,
1800,
1875,
1920,
1944,
2000,
2025,
2048,
2160,
2187,
2250,
2304,
2400,
2430,
2500,
2560,
2592,
2700,
2880,
2916,
3000,
3072,
3125,
3200,
3240,
3375,
3456,
3600,
3645,
3750,
3840,
3888,
4000,
4050,
4096,
4320,
4374,
4500,
4608,
4800,
4860,
5000,
5120,
5184,
5400,
5625,
5760,
5832,
6000,
6075,
6144,
6250,
6400,
6480,
6561,
6750,
6912,
7200,
7290,
7500,
7680,
7776,
8000,
8100,
8192,
8640,
8748,
9000,
9216,
9375,
9600,
9720,
10000,
)
if target <= 6:
return target
# Quickly check if it's already a power of 2
if not (target & (target - 1)):
return target
# Get result quickly for small sizes, since FFT itself is similarly fast.
if target <= hams[-1]:
return hams[bisect_left(hams, target)]
match = float("inf") # Anything found will be smaller
p5 = 1
while p5 < target:
p35 = p5
while p35 < target:
# Ceiling integer division, avoiding conversion to float
# (quotient = ceil(target / p35))
quotient = -(-target // p35)
p2 = 2 ** int(quotient - 1).bit_length()
N = p2 * p35
if N == target:
return N
elif N < match:
match = N
p35 *= 3
if p35 == target:
return p35
if p35 < match:
match = p35
p5 *= 5
if p5 == target:
return p5
if p5 < match:
match = p5
return match
def _overlap_add_filter(
x,
h,
n_fft=None,
phase="zero",
picks=None,
n_jobs=None,
copy=True,
pad="reflect_limited",
):
"""Filter the signal x using h with overlap-add FFTs."""
# set up array for filtering, reshape to 2D, operate on last axis
x, orig_shape, picks = _prep_for_filtering(x, copy, picks)
# Extend the signal by mirroring the edges to reduce transient filter
# response
_check_zero_phase_length(len(h), phase)
if len(h) == 1:
return x * h**2 if phase == "zero-double" else x * h
n_edge = max(min(len(h), x.shape[1]) - 1, 0)
logger.debug(f"Smart-padding with: {n_edge} samples on each edge")
n_x = x.shape[1] + 2 * n_edge
if phase == "zero-double":
h = np.convolve(h, h[::-1])
# Determine FFT length to use
min_fft = 2 * len(h) - 1
if n_fft is None:
max_fft = n_x
if max_fft >= min_fft:
# cost function based on number of multiplications
N = 2 ** np.arange(
np.ceil(np.log2(min_fft)), np.ceil(np.log2(max_fft)) + 1, dtype=int
)
cost = (
np.ceil(n_x / (N - len(h) + 1).astype(np.float64))
* N
* (np.log2(N) + 1)
)
# add a heuristic term to prevent too-long FFT's which are slow
# (not predicted by mult. cost alone, 4e-5 exp. determined)
cost += 4e-5 * N * n_x
n_fft = N[np.argmin(cost)]
else:
# Use only a single block
n_fft = next_fast_len(min_fft)
logger.debug(f"FFT block length: {n_fft}")
if n_fft < min_fft:
raise ValueError(
f"n_fft is too short, has to be at least 2 * len(h) - 1 ({min_fft}), got "
f"{n_fft}"
)
# Figure out if we should use CUDA
n_jobs, cuda_dict = _setup_cuda_fft_multiply_repeated(n_jobs, h, n_fft)
# Process each row separately
picks = _picks_to_idx(len(x), picks)
parallel, p_fun, _ = parallel_func(_1d_overlap_filter, n_jobs)
if n_jobs == 1:
for p in picks:
x[p] = _1d_overlap_filter(
x[p], len(h), n_edge, phase, cuda_dict, pad, n_fft
)
else:
data_new = parallel(
p_fun(x[p], len(h), n_edge, phase, cuda_dict, pad, n_fft) for p in picks
)
for pp, p in enumerate(picks):
x[p] = data_new[pp]
x.shape = orig_shape
return x
def _1d_overlap_filter(x, n_h, n_edge, phase, cuda_dict, pad, n_fft):
"""Do one-dimensional overlap-add FFT FIR filtering."""
# pad to reduce ringing
x_ext = _smart_pad(x, (n_edge, n_edge), pad)
n_x = len(x_ext)
x_filtered = np.zeros_like(x_ext)
n_seg = n_fft - n_h + 1
n_segments = int(np.ceil(n_x / float(n_seg)))
shift = ((n_h - 1) // 2 if phase.startswith("zero") else 0) + n_edge
# Now the actual filtering step is identical for zero-phase (filtfilt-like)
# or single-pass
for seg_idx in range(n_segments):
start = seg_idx * n_seg
stop = (seg_idx + 1) * n_seg
seg = x_ext[start:stop]
seg = np.concatenate([seg, np.zeros(n_fft - len(seg))])
prod = _fft_multiply_repeated(seg, cuda_dict)
start_filt = max(0, start - shift)
stop_filt = min(start - shift + n_fft, n_x)
start_prod = max(0, shift - start)
stop_prod = start_prod + stop_filt - start_filt
x_filtered[start_filt:stop_filt] += prod[start_prod:stop_prod]
# Remove mirrored edges that we added and cast (n_edge can be zero)
x_filtered = x_filtered[: n_x - 2 * n_edge].astype(x.dtype)
return x_filtered
def _filter_attenuation(h, freq, gain):
"""Compute minimum attenuation at stop frequency."""
_, filt_resp = signal.freqz(h.ravel(), worN=np.pi * freq)
filt_resp = np.abs(filt_resp) # use amplitude response
filt_resp[np.where(gain == 1)] = 0
idx = np.argmax(filt_resp)
att_db = -20 * np.log10(np.maximum(filt_resp[idx], 1e-20))
att_freq = freq[idx]
return att_db, att_freq
def _prep_for_filtering(x, copy, picks=None):
"""Set up array as 2D for filtering ease."""
x = _check_filterable(x)
if copy is True:
x = x.copy()
orig_shape = x.shape
x = np.atleast_2d(x)
picks = _picks_to_idx(x.shape[-2], picks)
x.shape = (np.prod(x.shape[:-1]), x.shape[-1])
if len(orig_shape) == 3:
n_epochs, n_channels, n_times = orig_shape
offset = np.repeat(np.arange(0, n_channels * n_epochs, n_channels), len(picks))
picks = np.tile(picks, n_epochs) + offset
elif len(orig_shape) > 3:
raise ValueError(
"picks argument is not supported for data with more"
" than three dimensions"
)
assert all(0 <= pick < x.shape[0] for pick in picks) # guaranteed by above
return x, orig_shape, picks
def _firwin_design(N, freq, gain, window, sfreq):
"""Construct a FIR filter using firwin."""
assert freq[0] == 0
assert len(freq) > 1
assert len(freq) == len(gain)
assert N % 2 == 1
h = np.zeros(N)
prev_freq = freq[-1]
prev_gain = gain[-1]
if gain[-1] == 1:
h[N // 2] = 1 # start with "all up"
assert prev_gain in (0, 1)
for this_freq, this_gain in zip(freq[::-1][1:], gain[::-1][1:]):
assert this_gain in (0, 1)
if this_gain != prev_gain:
# Get the correct N to satistify the requested transition bandwidth
transition = (prev_freq - this_freq) / 2.0
this_N = int(round(_length_factors[window] / transition))
this_N += 1 - this_N % 2 # make it odd
if this_N > N:
raise ValueError(
f"The requested filter length {N} is too short for the requested "
f"{transition * sfreq / 2.0:0.2f} Hz transition band, which "
f"requires {this_N} samples"
)
# Construct a lowpass
this_h = signal.firwin(
this_N,
(prev_freq + this_freq) / 2.0,
window=window,
pass_zero=True,
fs=freq[-1] * 2,
)
assert this_h.shape == (this_N,)
offset = (N - this_N) // 2
if this_gain == 0:
h[offset : N - offset] -= this_h
else:
h[offset : N - offset] += this_h
prev_gain = this_gain
prev_freq = this_freq
return h
def _construct_fir_filter(
sfreq, freq, gain, filter_length, phase, fir_window, fir_design
):
"""Filter signal using gain control points in the frequency domain.
The filter impulse response is constructed from a Hann window (window
used in "firwin2" function) to avoid ripples in the frequency response
(windowing is a smoothing in frequency domain).
If x is multi-dimensional, this operates along the last dimension.
"""
assert freq[0] == 0
if fir_design == "firwin2":
fir_design = signal.firwin2
else:
assert fir_design == "firwin"
fir_design = partial(_firwin_design, sfreq=sfreq)
# issue a warning if attenuation is less than this
min_att_db = 12 if phase == "minimum-half" else 20
# normalize frequencies
freq = np.array(freq) / (sfreq / 2.0)
if freq[0] != 0 or freq[-1] != 1:
raise ValueError(
f"freq must start at 0 and end an Nyquist ({sfreq / 2.0}), got {freq}"
)
gain = np.array(gain)
# Use overlap-add filter with a fixed length
N = _check_zero_phase_length(filter_length, phase, gain[-1])
# construct symmetric (linear phase) filter
if phase == "minimum-half":
h = fir_design(N * 2 - 1, freq, gain, window=fir_window)
h = minimum_phase(h)
else:
h = fir_design(N, freq, gain, window=fir_window)
if phase == "minimum":
h = minimum_phase(h, half=False)
assert h.size == N
att_db, att_freq = _filter_attenuation(h, freq, gain)
if phase == "zero-double":
att_db += 6
if att_db < min_att_db:
att_freq *= sfreq / 2.0
warn(
f"Attenuation at stop frequency {att_freq:0.2f} Hz is only {att_db:0.2f} "
"dB. Increase filter_length for higher attenuation."
)
return h
def _check_zero_phase_length(N, phase, gain_nyq=0):
N = int(N)
if N % 2 == 0:
if phase == "zero":
raise RuntimeError(f'filter_length must be odd if phase="zero", got {N}')
elif phase == "zero-double" and gain_nyq == 1:
N += 1
return N
def _check_coefficients(system):
"""Check for filter stability."""
if isinstance(system, tuple):
z, p, k = signal.tf2zpk(*system)
else: # sos
z, p, k = signal.sos2zpk(system)
if np.any(np.abs(p) > 1.0):
raise RuntimeError(
"Filter poles outside unit circle, filter will be "
"unstable. Consider using different filter "
"coefficients."
)
def _iir_filter(x, iir_params, picks, n_jobs, copy, phase="zero"):
"""Call filtfilt or lfilter."""
# set up array for filtering, reshape to 2D, operate on last axis
x, orig_shape, picks = _prep_for_filtering(x, copy, picks)
if phase in ("zero", "zero-double"):
padlen = min(iir_params["padlen"], x.shape[-1] - 1)
if "sos" in iir_params:
fun = partial(
signal.sosfiltfilt, sos=iir_params["sos"], padlen=padlen, axis=-1
)
_check_coefficients(iir_params["sos"])
else:
fun = partial(
signal.filtfilt,
b=iir_params["b"],
a=iir_params["a"],
padlen=padlen,
axis=-1,
)
_check_coefficients((iir_params["b"], iir_params["a"]))
else:
if "sos" in iir_params:
fun = partial(signal.sosfilt, sos=iir_params["sos"], axis=-1)
_check_coefficients(iir_params["sos"])
else:
fun = partial(signal.lfilter, b=iir_params["b"], a=iir_params["a"], axis=-1)
_check_coefficients((iir_params["b"], iir_params["a"]))
parallel, p_fun, n_jobs = parallel_func(fun, n_jobs)
if n_jobs == 1:
for p in picks:
x[p] = fun(x=x[p])
else:
data_new = parallel(p_fun(x=x[p]) for p in picks)
for pp, p in enumerate(picks):
x[p] = data_new[pp]
x.shape = orig_shape
return x
def estimate_ringing_samples(system, max_try=100000):
"""Estimate filter ringing.
Parameters
----------
system : tuple | ndarray
A tuple of (b, a) or ndarray of second-order sections coefficients.
max_try : int
Approximate maximum number of samples to try.
This will be changed to a multiple of 1000.
Returns
-------
n : int
The approximate ringing.
"""
if isinstance(system, tuple): # TF
kind = "ba"
b, a = system
zi = [0.0] * (len(a) - 1)
else:
kind = "sos"
sos = system
zi = [[0.0] * 2] * len(sos)
n_per_chunk = 1000
n_chunks_max = int(np.ceil(max_try / float(n_per_chunk)))
x = np.zeros(n_per_chunk)
x[0] = 1
last_good = n_per_chunk
thresh_val = 0
for ii in range(n_chunks_max):
if kind == "ba":
h, zi = signal.lfilter(b, a, x, zi=zi)
else:
h, zi = signal.sosfilt(sos, x, zi=zi)
x[0] = 0 # for subsequent iterations we want zero input
h = np.abs(h)
thresh_val = max(0.001 * np.max(h), thresh_val)
idx = np.where(np.abs(h) > thresh_val)[0]
if len(idx) > 0:
last_good = idx[-1]
else: # this iteration had no sufficiently lange values
idx = (ii - 1) * n_per_chunk + last_good
break
else:
warn("Could not properly estimate ringing for the filter")
idx = n_per_chunk * n_chunks_max
return idx
_ftype_dict = {
"butter": "Butterworth",
"cheby1": "Chebyshev I",
"cheby2": "Chebyshev II",
"ellip": "Cauer/elliptic",
"bessel": "Bessel/Thomson",
}
@verbose
def construct_iir_filter(
iir_params,
f_pass=None,
f_stop=None,
sfreq=None,
btype=None,
return_copy=True,
*,
phase="zero",
verbose=None,
):
"""Use IIR parameters to get filtering coefficients.
This function works like a wrapper for iirdesign and iirfilter in
scipy.signal to make filter coefficients for IIR filtering. It also
estimates the number of padding samples based on the filter ringing.
It creates a new iir_params dict (or updates the one passed to the
function) with the filter coefficients ('b' and 'a') and an estimate
of the padding necessary ('padlen') so IIR filtering can be performed.
Parameters
----------
iir_params : dict
Dictionary of parameters to use for IIR filtering.
* If ``iir_params['sos']`` exists, it will be used as
second-order sections to perform IIR filtering.
.. versionadded:: 0.13
* Otherwise, if ``iir_params['b']`` and ``iir_params['a']``
exist, these will be used as coefficients to perform IIR
filtering.
* Otherwise, if ``iir_params['order']`` and
``iir_params['ftype']`` exist, these will be used with
`scipy.signal.iirfilter` to make a filter.
You should also supply ``iir_params['rs']`` and
``iir_params['rp']`` if using elliptic or Chebychev filters.
* Otherwise, if ``iir_params['gpass']`` and
``iir_params['gstop']`` exist, these will be used with
`scipy.signal.iirdesign` to design a filter.
* ``iir_params['padlen']`` defines the number of samples to pad
(and an estimate will be calculated if it is not given).
See Notes for more details.
* ``iir_params['output']`` defines the system output kind when
designing filters, either "sos" or "ba". For 0.13 the
default is 'ba' but will change to 'sos' in 0.14.
f_pass : float or list of float
Frequency for the pass-band. Low-pass and high-pass filters should
be a float, band-pass should be a 2-element list of float.
f_stop : float or list of float
Stop-band frequency (same size as f_pass). Not used if 'order' is
specified in iir_params.
sfreq : float | None
The sample rate.
btype : str
Type of filter. Should be 'lowpass', 'highpass', or 'bandpass'
(or analogous string representations known to
:func:`scipy.signal.iirfilter`).
return_copy : bool
If False, the 'sos', 'b', 'a', and 'padlen' entries in
``iir_params`` will be set inplace (if they weren't already).
Otherwise, a new ``iir_params`` instance will be created and
returned with these entries.
phase : str
Phase of the filter.
``phase='zero'`` (default) or equivalently ``'zero-double'`` constructs and
applies IIR filter twice, once forward, and once backward (making it non-causal)
using :func:`~scipy.signal.filtfilt`; ``phase='forward'`` will apply
the filter once in the forward (causal) direction using
:func:`~scipy.signal.lfilter`.
.. versionadded:: 0.13
%(verbose)s
Returns
-------
iir_params : dict
Updated iir_params dict, with the entries (set only if they didn't
exist before) for 'sos' (or 'b', 'a'), and 'padlen' for
IIR filtering.
See Also
--------
mne.filter.filter_data
mne.io.Raw.filter
Notes
-----
This function triages calls to :func:`scipy.signal.iirfilter` and
:func:`scipy.signal.iirdesign` based on the input arguments (see
linked functions for more details).
.. versionchanged:: 0.14
Second-order sections are used in filter design by default (replacing
``output='ba'`` by ``output='sos'``) to help ensure filter stability
and reduce numerical error.
Examples
--------
iir_params can have several forms. Consider constructing a low-pass
filter at 40 Hz with 1000 Hz sampling rate.
In the most basic (2-parameter) form of iir_params, the order of the
filter 'N' and the type of filtering 'ftype' are specified. To get
coefficients for a 4th-order Butterworth filter, this would be:
>>> iir_params = dict(order=4, ftype='butter', output='sos') # doctest:+SKIP
>>> iir_params = construct_iir_filter(iir_params, 40, None, 1000, 'low', return_copy=False) # doctest:+SKIP
>>> print((2 * len(iir_params['sos']), iir_params['padlen'])) # doctest:+SKIP
(4, 82)
Filters can also be constructed using filter design methods. To get a
40 Hz Chebyshev type 1 lowpass with specific gain characteristics in the
pass and stop bands (assuming the desired stop band is at 45 Hz), this
would be a filter with much longer ringing:
>>> iir_params = dict(ftype='cheby1', gpass=3, gstop=20, output='sos') # doctest:+SKIP
>>> iir_params = construct_iir_filter(iir_params, 40, 50, 1000, 'low') # doctest:+SKIP
>>> print((2 * len(iir_params['sos']), iir_params['padlen'])) # doctest:+SKIP
(6, 439)
Padding and/or filter coefficients can also be manually specified. For
a 10-sample moving window with no padding during filtering, for example,
one can just do:
>>> iir_params = dict(b=np.ones((10)), a=[1, 0], padlen=0) # doctest:+SKIP
>>> iir_params = construct_iir_filter(iir_params, return_copy=False) # doctest:+SKIP
>>> print((iir_params['b'], iir_params['a'], iir_params['padlen'])) # doctest:+SKIP
(array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]), [1, 0], 0)
For more information, see the tutorials
:ref:`disc-filtering` and :ref:`tut-filter-resample`.
""" # noqa: E501
known_filters = (
"bessel",
"butter",
"butterworth",
"cauer",
"cheby1",
"cheby2",
"chebyshev1",
"chebyshev2",
"chebyshevi",
"chebyshevii",
"ellip",
"elliptic",
)
if not isinstance(iir_params, dict):
raise TypeError(f"iir_params must be a dict, got {type(iir_params)}")
# if the filter has been designed, we're good to go
Wp = None
if "sos" in iir_params:
system = iir_params["sos"]
output = "sos"
elif "a" in iir_params and "b" in iir_params:
system = (iir_params["b"], iir_params["a"])
output = "ba"
else:
output = iir_params.get("output", "sos")
_check_option("output", output, ("ba", "sos"))
# ensure we have a valid ftype
if "ftype" not in iir_params:
raise RuntimeError(
"ftype must be an entry in iir_params if 'b' and 'a' are not specified."
)
ftype = iir_params["ftype"]
if ftype not in known_filters:
raise RuntimeError(
"ftype must be in filter_dict from scipy.signal (e.g., butter, cheby1, "
f"etc.) not {ftype}"
)
# use order-based design
f_pass = np.atleast_1d(f_pass)
if f_pass.ndim > 1:
raise ValueError("frequencies must be 1D, got %dD" % f_pass.ndim)
edge_freqs = ", ".join(f"{f:0.2f}" for f in f_pass)
Wp = f_pass / (float(sfreq) / 2)
# IT will de designed
ftype_nice = _ftype_dict.get(ftype, ftype)
_validate_type(phase, str, "phase")
_check_option("phase", phase, ("zero", "zero-double", "forward"))
if phase in ("zero-double", "zero"):
ptype = "zero-phase (two-pass forward and reverse) non-causal"
else:
ptype = "non-linear phase (one-pass forward) causal"
logger.info("")
logger.info("IIR filter parameters")
logger.info("---------------------")
logger.info(f"{ftype_nice} {btype} {ptype} filter:")
# SciPy designs forward for -3dB, so forward-backward is -6dB
if "order" in iir_params:
singleton = btype in ("low", "lowpass", "high", "highpass")
use_Wp = Wp.item() if singleton else Wp
kwargs = dict(
N=iir_params["order"],
Wn=use_Wp,
btype=btype,
ftype=ftype,
output=output,
)
for key in ("rp", "rs"):
if key in iir_params:
kwargs[key] = iir_params[key]
system = signal.iirfilter(**kwargs)
if phase in ("zero", "zero-double"):
ptype, pmul = "(effective, after forward-backward)", 2
else:
ptype, pmul = "(forward)", 1
logger.info(
"- Filter order %d %s" % (pmul * iir_params["order"] * len(Wp), ptype)
)
else:
# use gpass / gstop design
Ws = np.asanyarray(f_stop) / (float(sfreq) / 2)
if "gpass" not in iir_params or "gstop" not in iir_params:
raise ValueError(
"iir_params must have at least 'gstop' and 'gpass' (or N) entries."
)
system = signal.iirdesign(
Wp,
Ws,
iir_params["gpass"],
iir_params["gstop"],
ftype=ftype,
output=output,
)
if system is None:
raise RuntimeError("coefficients could not be created from iir_params")
# do some sanity checks
_check_coefficients(system)
# get the gains at the cutoff frequencies
if Wp is not None:
if output == "sos":
cutoffs = signal.sosfreqz(system, worN=Wp * np.pi)[1]
else:
cutoffs = signal.freqz(system[0], system[1], worN=Wp * np.pi)[1]
cutoffs = 20 * np.log10(np.abs(cutoffs))
# 2 * 20 here because we do forward-backward filtering
if phase in ("zero", "zero-double"):
cutoffs *= 2
cutoffs = ", ".join([f"{c:0.2f}" for c in cutoffs])
logger.info(f"- Cutoff{_pl(f_pass)} at {edge_freqs} Hz: {cutoffs} dB")
# now deal with padding
if "padlen" not in iir_params:
padlen = estimate_ringing_samples(system)
else:
padlen = iir_params["padlen"]
if return_copy:
iir_params = deepcopy(iir_params)
iir_params.update(dict(padlen=padlen))
if output == "sos":
iir_params.update(sos=system)
else:
iir_params.update(b=system[0], a=system[1])
logger.info("")
return iir_params
def _check_method(method, iir_params, extra_types=()):
"""Parse method arguments."""
allowed_types = ["iir", "fir", "fft"] + list(extra_types)
_validate_type(method, "str", "method")
_check_option("method", method, allowed_types)
if method == "fft":
method = "fir" # use the better name
if method == "iir":
if iir_params is None:
iir_params = dict()
if len(iir_params) == 0 or (len(iir_params) == 1 and "output" in iir_params):
iir_params = dict(
order=4, ftype="butter", output=iir_params.get("output", "sos")
)
elif iir_params is not None:
raise ValueError('iir_params must be None if method != "iir"')
return iir_params, method
@verbose
def filter_data(
data,
sfreq,
l_freq,
h_freq,
picks=None,
filter_length="auto",
l_trans_bandwidth="auto",
h_trans_bandwidth="auto",
n_jobs=None,
method="fir",
iir_params=None,
copy=True,
phase="zero",
fir_window="hamming",
fir_design="firwin",
pad="reflect_limited",
*,
verbose=None,
):
"""Filter a subset of channels.
Parameters
----------
data : ndarray, shape (..., n_times)
The data to filter.
sfreq : float
The sample frequency in Hz.
%(l_freq)s
%(h_freq)s
%(picks_nostr)s
Currently this is only supported for 2D (n_channels, n_times) and
3D (n_epochs, n_channels, n_times) arrays.
%(filter_length)s
%(l_trans_bandwidth)s
%(h_trans_bandwidth)s
%(n_jobs_fir)s
%(method_fir)s
%(iir_params)s
copy : bool
If True, a copy of x, filtered, is returned. Otherwise, it operates
on x in place.
%(phase)s
%(fir_window)s
%(fir_design)s
%(pad_fir)s
The default is ``'reflect_limited'``.
.. versionadded:: 0.15
%(verbose)s
Returns
-------
data : ndarray, shape (..., n_times)
The filtered data.
See Also
--------
construct_iir_filter
create_filter
mne.io.Raw.filter
notch_filter
resample
Notes
-----
Applies a zero-phase low-pass, high-pass, band-pass, or band-stop
filter to the channels selected by ``picks``.
``l_freq`` and ``h_freq`` are the frequencies below which and above
which, respectively, to filter out of the data. Thus the uses are:
* ``l_freq < h_freq``: band-pass filter
* ``l_freq > h_freq``: band-stop filter
* ``l_freq is not None and h_freq is None``: high-pass filter
* ``l_freq is None and h_freq is not None``: low-pass filter