本文整理汇总了Python中mne.utils.catch_logging函数的典型用法代码示例。如果您正苦于以下问题:Python catch_logging函数的具体用法?Python catch_logging怎么用?Python catch_logging使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了catch_logging函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_calculate_chpi_positions
def test_calculate_chpi_positions():
"""Test calculation of cHPI positions
"""
trans, rot, t = head_pos_to_trans_rot_t(read_head_pos(pos_fname))
with warnings.catch_warnings(record=True):
raw = Raw(chpi_fif_fname, allow_maxshield=True, preload=True)
t -= raw.first_samp / raw.info['sfreq']
quats = _calculate_chpi_positions(raw, verbose='debug')
trans_est, rot_est, t_est = head_pos_to_trans_rot_t(quats)
_compare_positions((trans, rot, t), (trans_est, rot_est, t_est), 0.003)
# degenerate conditions
raw_no_chpi = Raw(test_fif_fname)
assert_raises(RuntimeError, _calculate_chpi_positions, raw_no_chpi)
raw_bad = raw.copy()
for d in raw_bad.info['dig']:
if d['kind'] == FIFF.FIFFV_POINT_HPI:
d['coord_frame'] = 999
break
assert_raises(RuntimeError, _calculate_chpi_positions, raw_bad)
raw_bad = raw.copy()
for d in raw_bad.info['dig']:
if d['kind'] == FIFF.FIFFV_POINT_HPI:
d['r'] = np.ones(3)
raw_bad.crop(0, 1., copy=False)
with warnings.catch_warnings(record=True): # bad pos
with catch_logging() as log_file:
_calculate_chpi_positions(raw_bad, verbose=True)
# ignore HPI info header and [done] footer
for line in log_file.getvalue().strip().split('\n')[4:-1]:
assert_true('0/5 good' in line)
示例2: test_make_inverse_operator
def test_make_inverse_operator():
"""Test MNE inverse computation (precomputed and non-precomputed)."""
# Test old version of inverse computation starting from forward operator
evoked = _get_evoked()
noise_cov = read_cov(fname_cov)
inverse_operator = read_inverse_operator(fname_inv)
fwd_op = convert_forward_solution(read_forward_solution_meg(fname_fwd),
surf_ori=True, copy=False)
with catch_logging() as log:
my_inv_op = make_inverse_operator(evoked.info, fwd_op, noise_cov,
loose=0.2, depth=0.8,
limit_depth_chs=False, verbose=True)
log = log.getvalue()
assert 'rank 302 (3 small eigenvalues omitted)' in log
_compare_io(my_inv_op)
assert_equal(inverse_operator['units'], 'Am')
_compare_inverses_approx(my_inv_op, inverse_operator, evoked,
rtol=1e-2, atol=1e-5, depth_atol=1e-3)
# Test MNE inverse computation starting from forward operator
with catch_logging() as log:
my_inv_op = make_inverse_operator(evoked.info, fwd_op, noise_cov,
loose=0.2, depth=0.8, verbose=True)
log = log.getvalue()
assert 'rank 302 (3 small eigenvalues omitted)' in log
_compare_io(my_inv_op)
_compare_inverses_approx(my_inv_op, inverse_operator, evoked,
rtol=1e-3, atol=1e-5)
assert ('dev_head_t' in my_inv_op['info'])
assert ('mri_head_t' in my_inv_op)
示例3: test_chpi_subtraction
def test_chpi_subtraction():
"""Test subtraction of cHPI signals."""
raw = read_raw_fif(chpi_fif_fname, allow_maxshield='yes', preload=True)
raw.info['bads'] = ['MEG0111']
raw.del_proj()
with catch_logging() as log:
filter_chpi(raw, include_line=False, verbose=True)
assert 'No average EEG' not in log.getvalue()
assert '5 cHPI' in log.getvalue()
# MaxFilter doesn't do quite as well as our algorithm with the last bit
raw.crop(0, 16)
# remove cHPI status chans
raw_c = read_raw_fif(sss_hpisubt_fname).crop(0, 16).load_data()
raw_c.pick_types(
meg=True, eeg=True, eog=True, ecg=True, stim=True, misc=True)
assert_meg_snr(raw, raw_c, 143, 624)
# Degenerate cases
raw_nohpi = read_raw_fif(test_fif_fname, preload=True)
pytest.raises(RuntimeError, filter_chpi, raw_nohpi)
# When MaxFliter downsamples, like::
# $ maxfilter -nosss -ds 2 -f test_move_anon_raw.fif \
# -o test_move_anon_ds2_raw.fif
# it can strip out some values of info, which we emulate here:
raw = read_raw_fif(chpi_fif_fname, allow_maxshield='yes')
raw = raw.crop(0, 1).load_data().resample(600., npad='auto')
raw.info['lowpass'] = 200.
del raw.info['maxshield']
del raw.info['hpi_results'][0]['moments']
del raw.info['hpi_subsystem']['event_channel']
with catch_logging() as log:
filter_chpi(raw, verbose=True)
pytest.raises(ValueError, filter_chpi, raw, t_window=-1)
assert '2 cHPI' in log.getvalue()
示例4: test_head_translation
def test_head_translation():
"""Test Maxwell filter head translation"""
with warnings.catch_warnings(record=True): # maxshield
raw = Raw(raw_fname, allow_maxshield=True).crop(0., 1., False)
# First try with an unchanged destination
raw_sss = maxwell_filter(raw, destination=raw_fname,
origin=mf_head_origin, regularize=None,
bad_condition='ignore')
assert_meg_snr(raw_sss, Raw(sss_std_fname).crop(0., 1., False), 200.)
# Now with default
with warnings.catch_warnings(record=True):
with catch_logging() as log:
raw_sss = maxwell_filter(raw, destination=mf_head_origin,
origin=mf_head_origin, regularize=None,
bad_condition='ignore', verbose='warning')
assert_true('over 25 mm' in log.getvalue())
assert_meg_snr(raw_sss, Raw(sss_trans_default_fname), 125.)
destination = np.eye(4)
destination[2, 3] = 0.04
assert_allclose(raw_sss.info['dev_head_t']['trans'], destination)
# Now to sample's head pos
with warnings.catch_warnings(record=True):
with catch_logging() as log:
raw_sss = maxwell_filter(raw, destination=sample_fname,
origin=mf_head_origin, regularize=None,
bad_condition='ignore', verbose='warning')
assert_true('= 25.6 mm' in log.getvalue())
assert_meg_snr(raw_sss, Raw(sss_trans_sample_fname), 350.)
assert_allclose(raw_sss.info['dev_head_t']['trans'],
read_info(sample_fname)['dev_head_t']['trans'])
# Degenerate cases
assert_raises(RuntimeError, maxwell_filter, raw,
destination=mf_head_origin, coord_frame='meg')
assert_raises(ValueError, maxwell_filter, raw, destination=[0.] * 4)
示例5: test_chpi_adjust
def test_chpi_adjust():
"""Test cHPI logging and adjustment"""
raw = read_raw_fif(chpi_fif_fname, allow_maxshield='yes')
with catch_logging() as log:
_get_hpi_info(raw.info, adjust=True, verbose='debug')
# Ran MaxFilter (with -list, -v, -movecomp, etc.), and got:
msg = ['HPIFIT: 5 coils digitized in order 5 1 4 3 2',
'HPIFIT: 3 coils accepted: 1 2 4',
'Hpi coil moments (3 5):',
'2.08542e-15 -1.52486e-15 -1.53484e-15',
'2.14516e-15 2.09608e-15 7.30303e-16',
'-3.2318e-16 -4.25666e-16 2.69997e-15',
'5.21717e-16 1.28406e-15 1.95335e-15',
'1.21199e-15 -1.25801e-19 1.18321e-15',
'HPIFIT errors: 0.3, 0.3, 5.3, 0.4, 3.2 mm.',
'HPI consistency of isotrak and hpifit is OK.',
'HP fitting limits: err = 5.0 mm, gval = 0.980.',
'Using 5 HPI coils: 83 143 203 263 323 Hz', # actually came earlier
]
log = log.getvalue().splitlines()
assert_true(set(log) == set(msg), '\n' + '\n'.join(set(msg) - set(log)))
# Then took the raw file, did this:
raw.info['dig'][5]['r'][2] += 1.
# And checked the result in MaxFilter, which changed the logging as:
msg = msg[:8] + [
'HPIFIT errors: 0.3, 0.3, 5.3, 999.7, 3.2 mm.',
'Note: HPI coil 3 isotrak is adjusted by 5.3 mm!',
'Note: HPI coil 5 isotrak is adjusted by 3.2 mm!'] + msg[-2:]
with catch_logging() as log:
_get_hpi_info(raw.info, adjust=True, verbose='debug')
log = log.getvalue().splitlines()
assert_true(set(log) == set(msg), '\n' + '\n'.join(set(msg) - set(log)))
示例6: test_make_inverse_operator_loose
def test_make_inverse_operator_loose(evoked):
"""Test MNE inverse computation (precomputed and non-precomputed)."""
# Test old version of inverse computation starting from forward operator
noise_cov = read_cov(fname_cov)
inverse_operator = read_inverse_operator(fname_inv)
fwd_op = convert_forward_solution(read_forward_solution_meg(fname_fwd),
surf_ori=True, copy=False)
with catch_logging() as log:
with pytest.deprecated_call(): # limit_depth_chs
my_inv_op = make_inverse_operator(
evoked.info, fwd_op, noise_cov, loose=0.2, depth=0.8,
limit_depth_chs=False, verbose=True)
log = log.getvalue()
assert 'MEG: rank 302 computed' in log
assert 'limit = 1/%d' % fwd_op['nsource'] in log
_compare_io(my_inv_op)
assert_equal(inverse_operator['units'], 'Am')
_compare_inverses_approx(my_inv_op, inverse_operator, evoked,
rtol=1e-2, atol=1e-5, depth_atol=1e-3)
# Test MNE inverse computation starting from forward operator
with catch_logging() as log:
my_inv_op = make_inverse_operator(evoked.info, fwd_op, noise_cov,
loose='auto', depth=0.8,
fixed=False, verbose=True)
log = log.getvalue()
assert 'MEG: rank 302 computed from 305' in log
_compare_io(my_inv_op)
_compare_inverses_approx(my_inv_op, inverse_operator, evoked,
rtol=1e-3, atol=1e-5)
assert ('dev_head_t' in my_inv_op['info'])
assert ('mri_head_t' in my_inv_op)
示例7: test_chpi_subtraction
def test_chpi_subtraction():
"""Test subtraction of cHPI signals"""
raw = Raw(chpi_fif_fname, allow_maxshield='yes', preload=True)
with catch_logging() as log:
filter_chpi(raw, include_line=False, verbose=True)
assert_true('5 cHPI' in log.getvalue())
# MaxFilter doesn't do quite as well as our algorithm with the last bit
raw.crop(0, 16, copy=False)
raw_c = Raw(sss_hpisubt_fname, preload=True).crop(0, 16, copy=False)
raw_c.pick_types(meg=True, eeg=True, eog=True, ecg=True, stim=True,
misc=True, copy=False) # remove cHPI status chans
assert_meg_snr(raw, raw_c, 143, 624)
# Degenerate cases
raw_nohpi = Raw(test_fif_fname, preload=True)
assert_raises(RuntimeError, filter_chpi, raw_nohpi)
# When MaxFliter downsamples, like::
# $ maxfilter -nosss -ds 2 -f test_move_anon_raw.fif \
# -o test_move_anon_ds2_raw.fif
# it can strip out some values of info, which we emulate here:
raw = Raw(chpi_fif_fname, allow_maxshield='yes')
raw.crop(0, 1, copy=False).load_data()
raw.resample(600., npad='auto')
raw.info['buffer_size_sec'] = np.float64(2.)
raw.info['lowpass'] = 200.
del raw.info['maxshield']
del raw.info['hpi_results'][0]['moments']
del raw.info['hpi_subsystem']['event_channel']
with catch_logging() as log:
filter_chpi(raw, verbose=True)
assert_true('2 cHPI' in log.getvalue())
示例8: test_fetch_file
def test_fetch_file(url, tmpdir):
"""Test URL retrieval."""
tempdir = str(tmpdir)
archive_name = op.join(tempdir, "download_test")
with catch_logging() as log:
_fetch_file(url, archive_name, timeout=30., verbose='debug')
log = log.getvalue()
assert 'Resuming at' not in log
with open(archive_name, 'rb') as fid:
data = fid.read()
stop = len(data) // 2
assert 0 < stop < len(data)
with open(archive_name + '.part', 'wb') as fid:
fid.write(data[:stop])
with catch_logging() as log:
_fetch_file(url, archive_name, timeout=30., verbose='debug')
log = log.getvalue()
assert 'Resuming at %s' % stop in log
with pytest.raises(Exception, match='unknown url type'):
_fetch_file('NOT_AN_ADDRESS', op.join(tempdir, 'test'), verbose=False)
resume_name = op.join(tempdir, "download_resume")
# touch file
with open(resume_name + '.part', 'w'):
os.utime(resume_name + '.part', None)
_fetch_file(url, resume_name, resume=True, timeout=30.,
verbose=False)
with pytest.raises(ValueError, match='Bad hash value'):
_fetch_file(url, archive_name, hash_='a', verbose=False)
with pytest.raises(RuntimeError, match='Hash mismatch'):
_fetch_file(url, archive_name, hash_='a' * 32, verbose=False)
示例9: test_chpi_subtraction
def test_chpi_subtraction():
"""Test subtraction of cHPI signals"""
raw = Raw(chpi_fif_fname, allow_maxshield="yes", preload=True)
with catch_logging() as log:
filter_chpi(raw, include_line=False, verbose=True)
assert_true("5 cHPI" in log.getvalue())
# MaxFilter doesn't do quite as well as our algorithm with the last bit
raw.crop(0, 16, copy=False)
# remove cHPI status chans
raw_c = Raw(sss_hpisubt_fname).crop(0, 16, copy=False).load_data()
raw_c.pick_types(meg=True, eeg=True, eog=True, ecg=True, stim=True, misc=True)
assert_meg_snr(raw, raw_c, 143, 624)
# Degenerate cases
raw_nohpi = Raw(test_fif_fname, preload=True)
assert_raises(RuntimeError, filter_chpi, raw_nohpi)
# When MaxFliter downsamples, like::
# $ maxfilter -nosss -ds 2 -f test_move_anon_raw.fif \
# -o test_move_anon_ds2_raw.fif
# it can strip out some values of info, which we emulate here:
raw = Raw(chpi_fif_fname, allow_maxshield="yes")
with warnings.catch_warnings(record=True): # uint cast suggestion
raw = raw.crop(0, 1).load_data().resample(600.0, npad="auto")
raw.info["buffer_size_sec"] = np.float64(2.0)
raw.info["lowpass"] = 200.0
del raw.info["maxshield"]
del raw.info["hpi_results"][0]["moments"]
del raw.info["hpi_subsystem"]["event_channel"]
with catch_logging() as log:
filter_chpi(raw, verbose=True)
assert_true("2 cHPI" in log.getvalue())
示例10: test_head_translation
def test_head_translation():
"""Test Maxwell filter head translation."""
raw = read_crop(raw_fname, (0., 1.))
# First try with an unchanged destination
raw_sss = maxwell_filter(raw, destination=raw_fname,
origin=mf_head_origin, regularize=None,
bad_condition='ignore')
assert_meg_snr(raw_sss, read_crop(sss_std_fname, (0., 1.)), 200.)
# Now with default
with pytest.warns(RuntimeWarning, match='over 25 mm'):
with catch_logging() as log:
raw_sss = maxwell_filter(raw, destination=mf_head_origin,
origin=mf_head_origin, regularize=None,
bad_condition='ignore', verbose='warning')
assert ('over 25 mm' in log.getvalue())
assert_meg_snr(raw_sss, read_crop(sss_trans_default_fname), 125.)
destination = np.eye(4)
destination[2, 3] = 0.04
assert_allclose(raw_sss.info['dev_head_t']['trans'], destination)
# Now to sample's head pos
with pytest.warns(RuntimeWarning, match='= 25.6 mm'):
with catch_logging() as log:
raw_sss = maxwell_filter(raw, destination=sample_fname,
origin=mf_head_origin, regularize=None,
bad_condition='ignore', verbose='warning')
assert ('= 25.6 mm' in log.getvalue())
assert_meg_snr(raw_sss, read_crop(sss_trans_sample_fname), 350.)
assert_allclose(raw_sss.info['dev_head_t']['trans'],
read_info(sample_fname)['dev_head_t']['trans'])
# Degenerate cases
pytest.raises(RuntimeError, maxwell_filter, raw,
destination=mf_head_origin, coord_frame='meg')
pytest.raises(ValueError, maxwell_filter, raw, destination=[0.] * 4)
示例11: test_head_translation
def test_head_translation():
"""Test Maxwell filter head translation"""
with warnings.catch_warnings(record=True): # maxshield
raw = Raw(raw_fname, allow_maxshield=True).crop(0.0, 1.0, False)
# First try with an unchanged destination
raw_sss = maxwell_filter(raw, destination=raw_fname, origin=mf_head_origin, regularize=None, bad_condition="ignore")
assert_meg_snr(raw_sss, Raw(sss_std_fname).crop(0.0, 1.0, False), 200.0)
# Now with default
with catch_logging() as log:
raw_sss = maxwell_filter(
raw,
destination=mf_head_origin,
origin=mf_head_origin,
regularize=None,
bad_condition="ignore",
verbose="warning",
)
assert_true("over 25 mm" in log.getvalue())
assert_meg_snr(raw_sss, Raw(sss_trans_default_fname), 125.0)
# Now to sample's head pos
with catch_logging() as log:
raw_sss = maxwell_filter(
raw,
destination=sample_fname,
origin=mf_head_origin,
regularize=None,
bad_condition="ignore",
verbose="warning",
)
assert_true("= 25.6 mm" in log.getvalue())
assert_meg_snr(raw_sss, Raw(sss_trans_sample_fname), 350.0)
# Degenerate cases
assert_raises(RuntimeError, maxwell_filter, raw, destination=mf_head_origin, coord_frame="meg")
assert_raises(ValueError, maxwell_filter, raw, destination=[0.0] * 4)
示例12: test_thresholds
def test_thresholds():
"""Test automatic threshold calculations."""
# within subjects
rng = np.random.RandomState(0)
X = rng.randn(10, 1, 1) + 0.08
want_thresh = -stats.t.ppf(0.025, len(X) - 1)
assert 0.03 < stats.ttest_1samp(X[:, 0, 0], 0)[1] < 0.05
my_fun = partial(ttest_1samp_no_p)
with catch_logging() as log:
with pytest.warns(RuntimeWarning, match='threshold is only valid'):
out = permutation_cluster_1samp_test(X, stat_fun=my_fun,
verbose=True)
log = log.getvalue()
assert str(want_thresh)[:6] in log
assert len(out[1]) == 1 # 1 cluster
assert 0.03 < out[2] < 0.05
# between subjects
Y = rng.randn(10, 1, 1)
Z = rng.randn(10, 1, 1) - 0.7
X = [X, Y, Z]
want_thresh = stats.f.ppf(1. - 0.05, 2, sum(len(a) for a in X) - len(X))
p = stats.f_oneway(*X)[1]
assert 0.03 < p < 0.05
my_fun = partial(f_oneway) # just to make the check fail
with catch_logging() as log:
with pytest.warns(RuntimeWarning, match='threshold is only valid'):
out = permutation_cluster_test(X, tail=1, stat_fun=my_fun,
verbose=True)
log = log.getvalue()
assert str(want_thresh)[:6] in log
assert len(out[1]) == 1 # 1 cluster
assert 0.03 < out[2] < 0.05
with pytest.warns(RuntimeWarning, match='Ignoring argument "tail"'):
permutation_cluster_test(X, tail=0)
示例13: test_calculate_chpi_positions
def test_calculate_chpi_positions():
"""Test calculation of cHPI positions."""
# Check to make sure our fits match MF decently
mf_quats = read_head_pos(pos_fname)
raw = read_raw_fif(chpi_fif_fname, allow_maxshield='yes', preload=True)
# This is a little hack (aliasing while decimating) to make it much faster
# for testing purposes only. We can relax this later if we find it breaks
# something.
raw_dec = _decimate_chpi(raw, 15)
with catch_logging() as log:
py_quats = _calculate_chpi_positions(raw_dec, t_step_max=1.,
verbose='debug')
assert_true(log.getvalue().startswith('HPIFIT'))
_assert_quats(py_quats, mf_quats, dist_tol=0.004, angle_tol=2.5)
# degenerate conditions
raw_no_chpi = read_raw_fif(test_fif_fname)
assert_raises(RuntimeError, _calculate_chpi_positions, raw_no_chpi)
raw_bad = raw.copy()
del raw_bad.info['hpi_meas'][0]['hpi_coils'][0]['coil_freq']
assert_raises(RuntimeError, _calculate_chpi_positions, raw_bad)
raw_bad = raw.copy()
for d in raw_bad.info['dig']:
if d['kind'] == FIFF.FIFFV_POINT_HPI:
d['coord_frame'] = FIFF.FIFFV_COORD_UNKNOWN
break
assert_raises(RuntimeError, _calculate_chpi_positions, raw_bad)
for d in raw_bad.info['dig']:
if d['kind'] == FIFF.FIFFV_POINT_HPI:
d['coord_frame'] = FIFF.FIFFV_COORD_HEAD
d['r'] = np.ones(3)
raw_bad.crop(0, 1.)
picks = np.concatenate([np.arange(306, len(raw_bad.ch_names)),
pick_types(raw_bad.info, meg=True)[::16]])
raw_bad.pick_channels([raw_bad.ch_names[pick] for pick in picks])
with warnings.catch_warnings(record=True): # bad pos
with catch_logging() as log_file:
_calculate_chpi_positions(raw_bad, t_step_min=1., verbose=True)
# ignore HPI info header and [done] footer
assert_true('0/5 good' in log_file.getvalue().strip().split('\n')[-2])
# half the rate cuts off cHPI coils
raw.info['lowpass'] /= 2.
assert_raises_regex(RuntimeError, 'above the',
_calculate_chpi_positions, raw)
# test on 5k artemis data
raw = read_raw_artemis123(art_fname, preload=True)
mf_quats = read_head_pos(art_mc_fname)
with catch_logging() as log:
py_quats = _calculate_chpi_positions(raw, t_step_min=2.,
verbose='debug')
_assert_quats(py_quats, mf_quats, dist_tol=0.004, angle_tol=2.5)
示例14: test_calculate_chpi_positions
def test_calculate_chpi_positions():
"""Test calculation of cHPI positions
"""
trans, rot, t = head_pos_to_trans_rot_t(read_head_pos(pos_fname))
raw = Raw(chpi_fif_fname, allow_maxshield="yes", preload=True)
t -= raw.first_samp / raw.info["sfreq"]
quats = _calculate_chpi_positions(raw, verbose="debug")
trans_est, rot_est, t_est = head_pos_to_trans_rot_t(quats)
_compare_positions((trans, rot, t), (trans_est, rot_est, t_est), 0.003)
# degenerate conditions
raw_no_chpi = Raw(test_fif_fname)
assert_raises(RuntimeError, _calculate_chpi_positions, raw_no_chpi)
raw_bad = raw.copy()
for d in raw_bad.info["dig"]:
if d["kind"] == FIFF.FIFFV_POINT_HPI:
d["coord_frame"] = 999
break
assert_raises(RuntimeError, _calculate_chpi_positions, raw_bad)
raw_bad = raw.copy()
for d in raw_bad.info["dig"]:
if d["kind"] == FIFF.FIFFV_POINT_HPI:
d["r"] = np.ones(3)
raw_bad.crop(0, 1.0, copy=False)
with warnings.catch_warnings(record=True): # bad pos
with catch_logging() as log_file:
_calculate_chpi_positions(raw_bad, verbose=True)
# ignore HPI info header and [done] footer
for line in log_file.getvalue().strip().split("\n")[4:-1]:
assert_true("0/5 good" in line)
# half the rate cuts off cHPI coils
with warnings.catch_warnings(record=True): # uint cast suggestion
raw.resample(300.0, npad="auto")
assert_raises_regex(RuntimeError, "above the", _calculate_chpi_positions, raw)
示例15: test_notch_filters
def test_notch_filters():
"""Test notch filters
"""
# let's use an ugly, prime sfreq for fun
sfreq = 487.0
sig_len_secs = 20
t = np.arange(0, int(sig_len_secs * sfreq)) / sfreq
freqs = np.arange(60, 241, 60)
# make a "signal"
rng = np.random.RandomState(0)
a = rng.randn(int(sig_len_secs * sfreq))
orig_power = np.sqrt(np.mean(a ** 2))
# make line noise
a += np.sum([np.sin(2 * np.pi * f * t) for f in freqs], axis=0)
# only allow None line_freqs with 'spectrum_fit' mode
assert_raises(ValueError, notch_filter, a, sfreq, None, "fft")
assert_raises(ValueError, notch_filter, a, sfreq, None, "iir")
methods = ["spectrum_fit", "spectrum_fit", "fft", "fft", "iir"]
filter_lengths = [None, None, None, 8192, None]
line_freqs = [None, freqs, freqs, freqs, freqs]
tols = [2, 1, 1, 1]
for meth, lf, fl, tol in zip(methods, line_freqs, filter_lengths, tols):
with catch_logging() as log_file:
b = notch_filter(a, sfreq, lf, filter_length=fl, method=meth, verbose="INFO")
if lf is None:
out = log_file.getvalue().split("\n")[:-1]
if len(out) != 2:
raise ValueError("Detected frequencies not logged properly")
out = np.fromstring(out[1], sep=", ")
assert_array_almost_equal(out, freqs)
new_power = np.sqrt(sum_squared(b) / b.size)
assert_almost_equal(new_power, orig_power, tol)