From 9ece6a11ed6e5b31e9eaf821e3cd337d9f82ff39 Mon Sep 17 00:00:00 2001 From: Tom Donoghue Date: Thu, 21 Jan 2021 23:00:49 -0500 Subject: [PATCH 1/2] doc updates within tests --- neurodsp/tests/aperiodic/test_autocorr.py | 2 +- neurodsp/tests/aperiodic/test_dfa.py | 5 ++-- neurodsp/tests/aperiodic/test_irasa.py | 7 ++--- neurodsp/tests/burst/test_dualthresh.py | 2 +- neurodsp/tests/burst/test_utils.py | 5 ++-- neurodsp/tests/conftest.py | 2 +- neurodsp/tests/filt/test_checks.py | 9 +++--- neurodsp/tests/filt/test_filter.py | 2 +- neurodsp/tests/filt/test_fir.py | 26 +++++++++-------- neurodsp/tests/filt/test_iir.py | 2 +- neurodsp/tests/filt/test_utils.py | 8 +++-- neurodsp/tests/plts/test_filt.py | 2 +- neurodsp/tests/plts/test_rhythm.py | 2 +- neurodsp/tests/plts/test_spectral.py | 3 +- neurodsp/tests/plts/test_style.py | 6 ++-- neurodsp/tests/plts/test_time_series.py | 6 ++-- neurodsp/tests/plts/test_utils.py | 4 +-- neurodsp/tests/rhythm/test_lc.py | 4 +-- neurodsp/tests/rhythm/test_swm.py | 2 +- neurodsp/tests/settings.py | 6 ++-- neurodsp/tests/sim/test_aperiodic.py | 3 +- neurodsp/tests/sim/test_combined.py | 2 +- neurodsp/tests/sim/test_cycles.py | 2 +- neurodsp/tests/sim/test_info.py | 2 +- neurodsp/tests/sim/test_periodic.py | 2 +- neurodsp/tests/sim/test_transients.py | 2 +- neurodsp/tests/spectral/test_checks.py | 2 +- neurodsp/tests/spectral/test_power.py | 29 +++++++++---------- neurodsp/tests/spectral/test_utils.py | 4 +-- neurodsp/tests/spectral/test_variance.py | 2 +- neurodsp/tests/timefrequency/test_hilbert.py | 13 +++++---- neurodsp/tests/timefrequency/test_wavelets.py | 2 +- neurodsp/tests/utils/test_checks.py | 2 +- neurodsp/tests/utils/test_core.py | 2 +- neurodsp/tests/utils/test_data.py | 18 +++++------- neurodsp/tests/utils/test_decorators.py | 2 +- neurodsp/tests/utils/test_download.py | 2 +- neurodsp/tests/utils/test_norm.py | 10 +++---- neurodsp/tests/utils/test_outliers.py | 6 ++-- neurodsp/tests/utils/test_sim.py | 2 +- 40 files changed, 108 insertions(+), 106 deletions(-) diff --git a/neurodsp/tests/aperiodic/test_autocorr.py b/neurodsp/tests/aperiodic/test_autocorr.py index a3fd9260..9f6aa408 100644 --- a/neurodsp/tests/aperiodic/test_autocorr.py +++ b/neurodsp/tests/aperiodic/test_autocorr.py @@ -1,4 +1,4 @@ -"""Tests for autocorrelation measures.""" +"""Tests for neurodsp.aperiodic.autocorr.""" from neurodsp.aperiodic.autocorr import * diff --git a/neurodsp/tests/aperiodic/test_dfa.py b/neurodsp/tests/aperiodic/test_dfa.py index cc8d8132..3e721286 100644 --- a/neurodsp/tests/aperiodic/test_dfa.py +++ b/neurodsp/tests/aperiodic/test_dfa.py @@ -1,10 +1,11 @@ -"""Tests for fractal analysis using fluctuation measures.""" +"""Tests neurodsp.aperiodic.dfa.""" from pytest import raises import numpy as np from neurodsp.sim import sim_powerlaw + from neurodsp.tests.settings import FS, FS_HIGH from neurodsp.aperiodic.dfa import (compute_fluctuations, compute_rescaled_range, @@ -18,7 +19,7 @@ def test_compute_fluctuations(tsig): t_scales, flucs, exp = compute_fluctuations(tsig, 500) assert len(t_scales) == len(flucs) - # Check error for if the settings create window lengths that are too short + # Check error if the settings create window lengths that are too short with raises(ValueError): t_scales, flucs, exp = compute_fluctuations(tsig, 100) diff --git a/neurodsp/tests/aperiodic/test_irasa.py b/neurodsp/tests/aperiodic/test_irasa.py index d1a53441..47b68024 100644 --- a/neurodsp/tests/aperiodic/test_irasa.py +++ b/neurodsp/tests/aperiodic/test_irasa.py @@ -1,12 +1,12 @@ -"""Tests for IRASA functions.""" +"""Tests for neurodsp.aperiodic.irasa.""" import numpy as np -from neurodsp.tests.settings import FS, N_SECONDS_LONG, EXP1 - from neurodsp.sim import sim_combined from neurodsp.spectral import compute_spectrum, trim_spectrum +from neurodsp.tests.settings import FS, N_SECONDS_LONG, EXP1 + from neurodsp.aperiodic.irasa import * ################################################################################################### @@ -17,7 +17,6 @@ def test_compute_irasa(tsig_comb): # Estimate periodic and aperiodic components with IRASA f_range = [1, 30] freqs, psd_ap, psd_pe = compute_irasa(tsig_comb, FS, f_range, noverlap=int(2*FS)) - assert len(freqs) == len(psd_ap) == len(psd_pe) # Compute r-squared for the full model, comparing to a standard power spectrum diff --git a/neurodsp/tests/burst/test_dualthresh.py b/neurodsp/tests/burst/test_dualthresh.py index f3127a92..d9bc76a6 100644 --- a/neurodsp/tests/burst/test_dualthresh.py +++ b/neurodsp/tests/burst/test_dualthresh.py @@ -1,4 +1,4 @@ -"""Tests for burst detection functions.""" +"""Tests for neurodsp.burst.dualthresh.""" from neurodsp.tests.settings import FS diff --git a/neurodsp/tests/burst/test_utils.py b/neurodsp/tests/burst/test_utils.py index 38765b4a..049e2879 100644 --- a/neurodsp/tests/burst/test_utils.py +++ b/neurodsp/tests/burst/test_utils.py @@ -1,8 +1,9 @@ -"""Tests for burst detection functions.""" +"""Tests for neurodsp.burst.utils.""" -from neurodsp.burst.utils import * import pytest +from neurodsp.burst.utils import * + ################################################################################################### ################################################################################################### diff --git a/neurodsp/tests/conftest.py b/neurodsp/tests/conftest.py index eadd8c7b..4227d4c6 100644 --- a/neurodsp/tests/conftest.py +++ b/neurodsp/tests/conftest.py @@ -1,4 +1,4 @@ -"""Configuration file for pytest for NDSP.""" +"""Pytest configuration file for testing neurodsp.""" import os import shutil diff --git a/neurodsp/tests/filt/test_checks.py b/neurodsp/tests/filt/test_checks.py index 32b5776e..5c9d260b 100644 --- a/neurodsp/tests/filt/test_checks.py +++ b/neurodsp/tests/filt/test_checks.py @@ -1,4 +1,4 @@ -"""Tests for filter check functions.""" +"""Tests for neurodsp.filt.checks.""" from pytest import raises @@ -12,12 +12,11 @@ def test_check_filter_definition(): - # Check that error catching works for bad pass_type definition + # Check error for bad pass_type definition with raises(ValueError): check_filter_definition('not_a_filter', (12, 12)) # Check that filter definitions that are legal evaluate as expected - # Float or partially filled tuple for f_range should work passable f_lo, f_hi = check_filter_definition('bandpass', f_range=(8, 12)) assert f_lo == 8; assert f_hi == 12 f_lo, f_hi = check_filter_definition('bandstop', f_range=(58, 62)) @@ -31,7 +30,7 @@ def test_check_filter_definition(): f_lo, f_hi = check_filter_definition('highpass', f_range=(58, 100)) assert f_lo == 58 ; assert f_hi == None - # Check that a bandpass & bandstop definitions fail without proper definitions + # Check that bandpass & bandstop definitions fail without proper definitions with raises(ValueError): f_lo, f_hi = check_filter_definition('bandpass', f_range=8) with raises(ValueError): @@ -46,7 +45,7 @@ def test_check_filter_definition(): def test_check_filter_properties(): filter_coefs = design_fir_filter(FS, 'bandpass', (8, 12)) - + passes = check_filter_properties(filter_coefs, 1, FS, 'bandpass', (8, 12)) assert passes is True diff --git a/neurodsp/tests/filt/test_filter.py b/neurodsp/tests/filt/test_filter.py index d29b32d8..140f9dcf 100644 --- a/neurodsp/tests/filt/test_filter.py +++ b/neurodsp/tests/filt/test_filter.py @@ -1,4 +1,4 @@ -"""Test filtering functions.""" +"""Tests for neurodsp.filt.filter.""" from pytest import raises, warns diff --git a/neurodsp/tests/filt/test_fir.py b/neurodsp/tests/filt/test_fir.py index 55fd6488..9da9a83f 100644 --- a/neurodsp/tests/filt/test_fir.py +++ b/neurodsp/tests/filt/test_fir.py @@ -1,6 +1,7 @@ -"""Tests for FIR filters.""" +"""Tests for neurodsp.filt.fir.""" from pytest import raises + import numpy as np from neurodsp.tests.settings import FS, EPS_FILT @@ -15,20 +16,19 @@ def test_filter_signal_fir(tsig, tsig_sine): out = filter_signal_fir(tsig, FS, 'bandpass', (8, 12)) assert out.shape == tsig.shape - # Apply lowpass to low-frequency sine. There should be little attenuation. + # Apply lowpass to low-frequency sine, which should should give little attenuation sig_filt_lp = filter_signal_fir(tsig_sine, FS, pass_type='lowpass', f_range=(None, 10)) - # Compare the two signals only at those times where the filtered signal is not nan. + # Compare the two signals at timepoints where the filtered signal is not nan not_nan = ~np.isnan(sig_filt_lp) assert np.allclose(tsig_sine[not_nan], sig_filt_lp[not_nan], atol=EPS_FILT) - # Now apply a high pass filter. The signal should be significantly attenuated. + # Apply a highpass filter, which should significantly attenuate the signal sig_filt_hp = filter_signal_fir(tsig_sine, FS, pass_type='highpass', f_range=(30, None)) - # Get rid of nans. + # Compare the two signals at timepoints where the filtered signal is not nan not_nan = ~np.isnan(sig_filt_hp) sig_filt_hp = sig_filt_hp[not_nan] - expected_answer = np.zeros_like(sig_filt_hp) assert np.allclose(sig_filt_hp, expected_answer, atol=EPS_FILT) @@ -58,23 +58,25 @@ def test_compute_filter_length(): f_lo, f_hi = 4, 8 # Check filt_len, if defined using n_seconds - n_seconds = 1.75 # Number chosen to create odd expected filt_len (not needing rounding up) + # n_seconds here is chosen to create expected odd filt_len, without needing rounding up + n_seconds = 1.75 expected_filt_len = n_seconds * fs - filt_len = compute_filter_length(fs, 'bandpass', f_lo, f_hi, n_cycles=None, n_seconds=n_seconds) + filt_len = compute_filter_length(fs, 'bandpass', f_lo, f_hi, + n_cycles=None, n_seconds=n_seconds) assert filt_len == expected_filt_len # Check filt_len, if defined using n_cycles n_cycles = 5 expected_filt_len = int(np.ceil(fs * n_cycles / f_lo)) - filt_len = compute_filter_length(fs, 'bandpass', f_lo, f_hi, n_cycles=n_cycles, n_seconds=None) + filt_len = compute_filter_length(fs, 'bandpass', f_lo, f_hi, + n_cycles=n_cycles, n_seconds=None) assert filt_len == expected_filt_len # Check filt_len, if expected to be rounded up to be odd n_cycles = 4 expected_filt_len = int(np.ceil(fs * n_cycles / f_lo)) + 1 - filt_len = compute_filter_length(fs, 'bandpass', f_lo, f_hi, n_cycles=n_cycles, n_seconds=None) + filt_len = compute_filter_length(fs, 'bandpass', f_lo, f_hi, + n_cycles=n_cycles, n_seconds=None) assert filt_len == expected_filt_len - with raises(ValueError): filt_len = compute_filter_length(fs, 'bandpass', f_lo, f_hi) - diff --git a/neurodsp/tests/filt/test_iir.py b/neurodsp/tests/filt/test_iir.py index 4b209035..ac17c438 100644 --- a/neurodsp/tests/filt/test_iir.py +++ b/neurodsp/tests/filt/test_iir.py @@ -1,4 +1,4 @@ -"""Tests for IIR filters.""" +"""Tests for neurodsp.filt.iir.""" import numpy as np diff --git a/neurodsp/tests/filt/test_utils.py b/neurodsp/tests/filt/test_utils.py index c839a75d..44539d10 100644 --- a/neurodsp/tests/filt/test_utils.py +++ b/neurodsp/tests/filt/test_utils.py @@ -1,11 +1,13 @@ -"""Tests for filter utilities.""" +"""Tests for neurodsp.filt.utils.""" from pytest import raises + from neurodsp.tests.settings import FS -from neurodsp.filt.utils import * from neurodsp.filt.fir import design_fir_filter, compute_filter_length +from neurodsp.filt.utils import * + ################################################################################################### ################################################################################################### @@ -42,7 +44,7 @@ def test_compute_nyquist(): def test_remove_filter_edges(): - # Get the length for a possible filter & calculate # of values should be dropped for it + # Get the length for a possible filter & calculate # of values that should be dropped for it sig_len = 1000 sig = np.ones(sig_len) filt_len = compute_filter_length(FS, 'bandpass', f_lo=4, f_hi=8, n_cycles=3, n_seconds=None) diff --git a/neurodsp/tests/plts/test_filt.py b/neurodsp/tests/plts/test_filt.py index b75bca31..11e1ad3e 100644 --- a/neurodsp/tests/plts/test_filt.py +++ b/neurodsp/tests/plts/test_filt.py @@ -1,4 +1,4 @@ -"""Test filtering plots.""" +"""Tests for neurodsp.plts.filt.""" from neurodsp.filt.filter import filter_signal from neurodsp.filt.fir import design_fir_filter diff --git a/neurodsp/tests/plts/test_rhythm.py b/neurodsp/tests/plts/test_rhythm.py index 706a182c..bc428445 100644 --- a/neurodsp/tests/plts/test_rhythm.py +++ b/neurodsp/tests/plts/test_rhythm.py @@ -1,4 +1,4 @@ -"""Test rhythm plots.""" +"""Tests for neurodsp.plts.rhythm.""" import numpy as np diff --git a/neurodsp/tests/plts/test_spectral.py b/neurodsp/tests/plts/test_spectral.py index 646bbc64..48e89bbf 100644 --- a/neurodsp/tests/plts/test_spectral.py +++ b/neurodsp/tests/plts/test_spectral.py @@ -1,9 +1,10 @@ -"""Test spectral plots.""" +"""Tests for neurodsp.plts.spectral.""" import numpy as np from neurodsp.spectral.variance import compute_spectral_hist from neurodsp.spectral.power import compute_spectrum + from neurodsp.tests.settings import TEST_PLOTS_PATH from neurodsp.tests.tutils import plot_test diff --git a/neurodsp/tests/plts/test_style.py b/neurodsp/tests/plts/test_style.py index 768a6390..d45ed0bb 100644 --- a/neurodsp/tests/plts/test_style.py +++ b/neurodsp/tests/plts/test_style.py @@ -1,4 +1,4 @@ -"""Test plot style related functionality.""" +"""Tests for neurodsp.plts.style.""" import matplotlib.pyplot as plt @@ -40,7 +40,7 @@ def test_apply_line_style(): assert ax.get_lines()[0].get_lw() == lw - # Check applying style across multiple lines + # Check applying style to multiple lines _, ax = plt.subplots() ax.plot([1, 2], [[3, 4], [5, 6]]) @@ -71,7 +71,7 @@ def test_plot_style(): def my_custom_styler(ax, **kwargs): ax.set_title('DATA!') - # Apply plot style using all defaults + # Apply plot style using defaults plot_style(ax) # Apply plot style passing in a styler diff --git a/neurodsp/tests/plts/test_time_series.py b/neurodsp/tests/plts/test_time_series.py index e1e13762..581fe9ef 100644 --- a/neurodsp/tests/plts/test_time_series.py +++ b/neurodsp/tests/plts/test_time_series.py @@ -1,4 +1,4 @@ -"""Test time series plots.""" +"""Tests for neurodsp.plts.time_series.""" from pytest import raises @@ -15,10 +15,10 @@ def test_plot_time_series(tsig): times = np.arange(0, len(tsig), 1) - # Run single time series plot + # Check single time series plot plot_time_series(times, tsig) - # Run multi time series plot, with colors & labels + # Check multi time series plot, with colors & labels plot_time_series(times, [tsig, tsig[::-1]], labels=['signal', 'signal reversed'], colors=['k', 'r'], save_fig=True, file_name='test_plot_time_series.png', file_path=TEST_PLOTS_PATH) diff --git a/neurodsp/tests/plts/test_utils.py b/neurodsp/tests/plts/test_utils.py index 0aaf0369..511a1ec9 100644 --- a/neurodsp/tests/plts/test_utils.py +++ b/neurodsp/tests/plts/test_utils.py @@ -1,4 +1,4 @@ -"""Test plot utilities.""" +"""Tests for neurodsp.plts.utils.""" import os import tempfile @@ -10,7 +10,7 @@ def test_check_ax(): - # Check running will None Input + # Check running with None Input ax = check_ax(None) # Check running with pre-created axis diff --git a/neurodsp/tests/rhythm/test_lc.py b/neurodsp/tests/rhythm/test_lc.py index f4a0e61b..318745da 100644 --- a/neurodsp/tests/rhythm/test_lc.py +++ b/neurodsp/tests/rhythm/test_lc.py @@ -1,4 +1,4 @@ -"""Test lagged coherence code.""" +"""Tests for neurodsp.rhythm.lc (lagged coherence).""" from pytest import warns @@ -22,7 +22,7 @@ def test_compute_lagged_coherence(tsig): # Check using a list of n_cycles definitions lc = compute_lagged_coherence(tsig, FS, FREQS_ARR, n_cycles=[3, 4, 5]) - # Test the warning if can't estimate some values + # Test the warning if some values can't be estimated with warns(UserWarning): compute_lagged_coherence(tsig, 100, np.array([1, 2]), n_cycles=10) diff --git a/neurodsp/tests/rhythm/test_swm.py b/neurodsp/tests/rhythm/test_swm.py index 88073330..53e3260c 100644 --- a/neurodsp/tests/rhythm/test_swm.py +++ b/neurodsp/tests/rhythm/test_swm.py @@ -1,4 +1,4 @@ -"""Test the sliding window matching function.""" +"""Tests for neurodsp.rhythm.swm (sliding window matching).""" from neurodsp.tests.settings import FS diff --git a/neurodsp/tests/settings.py b/neurodsp/tests/settings.py index 4fa4aca6..783a2a8f 100644 --- a/neurodsp/tests/settings.py +++ b/neurodsp/tests/settings.py @@ -8,13 +8,13 @@ ################################################################################################### ################################################################################################### -# Define general settings for simulations & tests +# Define general settings for test simulations FS = 100 FS_HIGH = 1000 N_SECONDS = 1.0 N_SECONDS_LONG = 10.0 -# Define parameter options for simulations +# Define parameter options for test simulations FREQ1 = 10 FREQ2 = 25 FREQ_SINE = 1 @@ -28,6 +28,6 @@ EPS = 10**(-10) EPS_FILT = 10**(-3) -# Path Settings +# Set paths for test files BASE_TEST_FILE_PATH = pkg.resource_filename(__name__, 'test_files') TEST_PLOTS_PATH = os.path.join(BASE_TEST_FILE_PATH, 'plots') diff --git a/neurodsp/tests/sim/test_aperiodic.py b/neurodsp/tests/sim/test_aperiodic.py index d78e4482..4cfde617 100644 --- a/neurodsp/tests/sim/test_aperiodic.py +++ b/neurodsp/tests/sim/test_aperiodic.py @@ -1,4 +1,4 @@ -"""Test aperiodic simulation functions.""" +"""Tests for neurodsp.sim.aperiodic.""" import numpy as np from scipy.optimize import curve_fit @@ -60,7 +60,6 @@ def _estimate_single_knee(xs, offset, knee, chi2): assert -round(chi2_hat) == EXP2 - def test_sim_random_walk(): sig = sim_random_walk(N_SECONDS, FS) diff --git a/neurodsp/tests/sim/test_combined.py b/neurodsp/tests/sim/test_combined.py index 6f4a0751..f05d27de 100644 --- a/neurodsp/tests/sim/test_combined.py +++ b/neurodsp/tests/sim/test_combined.py @@ -1,4 +1,4 @@ -"""Test combined simulation functions.""" +"""Tests for neurodsp.sim.combined.""" from pytest import raises diff --git a/neurodsp/tests/sim/test_cycles.py b/neurodsp/tests/sim/test_cycles.py index d2d7f5e3..fcbc51e1 100644 --- a/neurodsp/tests/sim/test_cycles.py +++ b/neurodsp/tests/sim/test_cycles.py @@ -1,4 +1,4 @@ -"""Test cycle simulation functions.""" +"""Tests for neurodsp.sim.cycle.""" from pytest import raises diff --git a/neurodsp/tests/sim/test_info.py b/neurodsp/tests/sim/test_info.py index 2bf27311..87e3e5df 100644 --- a/neurodsp/tests/sim/test_info.py +++ b/neurodsp/tests/sim/test_info.py @@ -1,4 +1,4 @@ -"""Tests for simulation info functions.""" +"""Tests for neurodsp.sim.info.""" from pytest import raises diff --git a/neurodsp/tests/sim/test_periodic.py b/neurodsp/tests/sim/test_periodic.py index 43f72aad..9c9be4e5 100644 --- a/neurodsp/tests/sim/test_periodic.py +++ b/neurodsp/tests/sim/test_periodic.py @@ -1,4 +1,4 @@ -"""Test periodic simulation functions.""" +"""Tests for neurodsp.sim.periodic.""" from neurodsp.tests.tutils import check_sim_output from neurodsp.tests.settings import FS, N_SECONDS, FREQ1 diff --git a/neurodsp/tests/sim/test_transients.py b/neurodsp/tests/sim/test_transients.py index 169b8373..eb7cc77f 100644 --- a/neurodsp/tests/sim/test_transients.py +++ b/neurodsp/tests/sim/test_transients.py @@ -1,4 +1,4 @@ -"""Test transient simulation functions.""" +"""Tests for neurodsp.sim.transients.""" import numpy as np diff --git a/neurodsp/tests/spectral/test_checks.py b/neurodsp/tests/spectral/test_checks.py index ed9528eb..4b94ed01 100644 --- a/neurodsp/tests/spectral/test_checks.py +++ b/neurodsp/tests/spectral/test_checks.py @@ -1,4 +1,4 @@ -"""Test spectral checker functions.""" +"""Tests neurodsp.spectral.checks.""" import numpy as np diff --git a/neurodsp/tests/spectral/test_power.py b/neurodsp/tests/spectral/test_power.py index ab75e863..84e65e57 100644 --- a/neurodsp/tests/spectral/test_power.py +++ b/neurodsp/tests/spectral/test_power.py @@ -1,13 +1,11 @@ -"""Test spectral power functions.""" +"""Tests for neurodsp.spectral.power.""" + +import numpy as np from neurodsp.tests.settings import FS, FREQS_LST, FREQS_ARR, EPS, FREQ_SINE from neurodsp.spectral.power import * -from neurodsp.sim import sim_oscillation - -import numpy as np - ################################################################################################### ################################################################################################### @@ -44,19 +42,20 @@ def test_compute_spectrum_welch(tsig, tsig_sine_long): freqs, spectrum = compute_spectrum_welch(tsig, FS, avg_type='median') assert freqs.shape == spectrum.shape - # Use a rectangular window with a width of one period/cycle and no overlap. - # The specturm should just be a dirac spike at the first frequency. + # Use a rectangular window with a width of one period/cycle and no overlap + # The spectrum should just be a dirac spike at the first frequency window = np.ones(FS) - _, psd_welch = compute_spectrum(tsig_sine_long, FS, method='welch', nperseg=FS, noverlap=0, window=window) + _, psd_welch = compute_spectrum(tsig_sine_long, FS, method='welch', + nperseg=FS, noverlap=0, window=window) - # Spike at frequency 1. + # Spike at frequency 1 assert np.abs(psd_welch[FREQ_SINE] - 0.5) < EPS - # PSD at higher frequencies are essentially zero. + # PSD at higher frequencies are essentially zero expected_answer = np.zeros_like(psd_welch[FREQ_SINE+1:]) assert np.allclose(psd_welch[FREQ_SINE+1:], expected_answer, atol=EPS) - # No DC component or frequencies below the sine frequency. + # No DC component or frequencies below the sine frequency expected_answer = np.zeros_like(psd_welch[0:FREQ_SINE]) assert np.allclose(psd_welch[0:FREQ_SINE], expected_answer, atol=EPS) @@ -73,14 +72,14 @@ def test_compute_spectrum_medfilt(tsig, tsig_sine_long): freqs, spectrum = compute_spectrum_medfilt(tsig, FS) assert freqs.shape == spectrum.shape - # Compute raw estimate of psd using fourier transform. Only look at the spectrum up to the Nyquist frequency. + # Compute raw estimate of psd using fourier transform + # Only look at the spectrum up to the Nyquist frequency sig_len = len(tsig_sine_long) nyq_freq = sig_len//2 sig_ft = np.fft.fft(tsig_sine_long)[:nyq_freq] psd = np.abs(sig_ft)**2/(FS * sig_len) - # The medfilt here should only be taking the median of a window of one sample, - # so it should agree with our estimate of psd above. + # The medfilt here should be taking the median of a window with one sample + # Therefore, it should match the estimate of psd from above _, psd_medfilt = compute_spectrum(tsig_sine_long, FS, method='medfilt', filt_len=0.1) - assert np.allclose(psd, psd_medfilt, atol=EPS) diff --git a/neurodsp/tests/spectral/test_utils.py b/neurodsp/tests/spectral/test_utils.py index 09730798..e7022470 100644 --- a/neurodsp/tests/spectral/test_utils.py +++ b/neurodsp/tests/spectral/test_utils.py @@ -1,4 +1,4 @@ -"""Test the utility function from spectral.""" +"""Tests for neurodsp.spectral.utils.""" import numpy as np from numpy.testing import assert_equal @@ -31,7 +31,7 @@ def test_trim_spectrogram(): assert_equal(t_ext, np.array([0, 1])) assert_equal(p_ext, np.array([[4, 5], [7, 8], [10, 11]])) - # Check extraction across only specific axes + # Check extraction across specified axis f_ext, t_ext, p_ext = trim_spectrogram(freqs, times, pows, f_range=None, t_range=[0, 1]) assert_equal(f_ext, freqs) assert_equal(t_ext, np.array([0, 1])) diff --git a/neurodsp/tests/spectral/test_variance.py b/neurodsp/tests/spectral/test_variance.py index b8b48b9a..012a8c07 100644 --- a/neurodsp/tests/spectral/test_variance.py +++ b/neurodsp/tests/spectral/test_variance.py @@ -1,4 +1,4 @@ -"""Test spectral variance functions.""" +"""Tests for neurodsp.spectral.variance.""" from neurodsp.tests.settings import FS diff --git a/neurodsp/tests/timefrequency/test_hilbert.py b/neurodsp/tests/timefrequency/test_hilbert.py index 9840e622..8e938f20 100644 --- a/neurodsp/tests/timefrequency/test_hilbert.py +++ b/neurodsp/tests/timefrequency/test_hilbert.py @@ -1,4 +1,4 @@ -"""Test functions for time-frequency Hilbert analyses.""" +"""Tests for neurodsp.timefrequency.hilbert.""" import numpy as np @@ -47,11 +47,12 @@ def test_phase_by_time(tsig, tsig_sine): # Create a time axis, scaled to the range of [0, 2pi] times = 2 * np.pi * create_times(N_SECONDS, FS) - # Generate the expected instantaneous phase of the given signal. Phase is defined in - # [-pi, pi]. Since sin(t) = cos(t - pi/2), the phase should begin at -pi/2 and increase with a slope - # of 1 until phase hits pi, or when t=3pi/2. Phase then wraps around to -pi and again increases - # linearly with a slope of 1. - expected_answer = np.array([time-np.pi/2 if time <= 3*np.pi/2 else time-5*np.pi/2 for time in times]) + # Generate the expected instantaneous phase of the given signal + # Phase is defined in [-pi, pi]. Since sin(t) = cos(t - pi/2), the phase should begin at + # -pi/2 and increase with a slope of 1 until phase hits pi, or when t=3pi/2. Phase then + # wraps around to -pi and again increases linearly with a slope of 1 + expected_answer = np.array(\ + [time-np.pi/2 if time <= 3*np.pi/2 else time-5*np.pi/2 for time in times]) assert np.allclose(expected_answer, phase, atol=EPS) diff --git a/neurodsp/tests/timefrequency/test_wavelets.py b/neurodsp/tests/timefrequency/test_wavelets.py index 3f31ddc4..702dfca3 100644 --- a/neurodsp/tests/timefrequency/test_wavelets.py +++ b/neurodsp/tests/timefrequency/test_wavelets.py @@ -1,4 +1,4 @@ -"""Tests for time-frequency estimations using wavelets.""" +"""Tests for neurodsp.timefrequency.wavelets.""" from neurodsp.tests.settings import FS, FREQ1, FREQS_ARR diff --git a/neurodsp/tests/utils/test_checks.py b/neurodsp/tests/utils/test_checks.py index 3d79dfab..966183c3 100644 --- a/neurodsp/tests/utils/test_checks.py +++ b/neurodsp/tests/utils/test_checks.py @@ -1,4 +1,4 @@ -"""Tests for checker utility functions.""" +"""Tests for neurodsp.utils.checks.""" from pytest import raises diff --git a/neurodsp/tests/utils/test_core.py b/neurodsp/tests/utils/test_core.py index 2c1e00b6..851bc757 100644 --- a/neurodsp/tests/utils/test_core.py +++ b/neurodsp/tests/utils/test_core.py @@ -1,4 +1,4 @@ -"""Tests for core / internal utility functions.""" +"""Tests for neurodsp.utils.core.""" from pytest import raises diff --git a/neurodsp/tests/utils/test_data.py b/neurodsp/tests/utils/test_data.py index 9e4ced51..e3bb960d 100644 --- a/neurodsp/tests/utils/test_data.py +++ b/neurodsp/tests/utils/test_data.py @@ -1,7 +1,9 @@ -"""Tests for data related utility functions.""" +"""Tests for neurodsp.utils.data.""" from numpy.testing import assert_equal +from neurodsp.tests.settings import FS, N_SECONDS + from neurodsp.utils.data import * ################################################################################################### @@ -17,17 +19,13 @@ def test_create_freqs(): def test_create_times(): - fs = 10 - - n_seconds = 1 - times = create_times(n_seconds, fs) - assert_equal(times, np.arange(0, n_seconds, 1/fs)) + times = create_times(N_SECONDS, FS) + assert_equal(times, np.arange(0, N_SECONDS, 1/FS)) - n_seconds = 2 - start_val = 1 - times = create_times(n_seconds, fs, start_val=start_val) + start_val = 0.5 + times = create_times(N_SECONDS, FS, start_val=start_val) assert times[0] == start_val - assert len(times) == n_seconds * fs + assert len(times) == N_SECONDS * FS def test_create_samples(): diff --git a/neurodsp/tests/utils/test_decorators.py b/neurodsp/tests/utils/test_decorators.py index 9e11be53..1ad4b543 100644 --- a/neurodsp/tests/utils/test_decorators.py +++ b/neurodsp/tests/utils/test_decorators.py @@ -1,4 +1,4 @@ -"""Tests for decorator functions.""" +"""Tests for neurodsp.utils.decorators.""" from neurodsp.utils.decorators import * diff --git a/neurodsp/tests/utils/test_download.py b/neurodsp/tests/utils/test_download.py index 64efe22a..522cefee 100644 --- a/neurodsp/tests/utils/test_download.py +++ b/neurodsp/tests/utils/test_download.py @@ -1,4 +1,4 @@ -"""Test functions for neurodsp.utils.download.""" +"""Tests for for neurodsp.utils.download.""" import os import shutil diff --git a/neurodsp/tests/utils/test_norm.py b/neurodsp/tests/utils/test_norm.py index 62e69347..4c3ce4e5 100644 --- a/neurodsp/tests/utils/test_norm.py +++ b/neurodsp/tests/utils/test_norm.py @@ -1,4 +1,4 @@ -"""Tests for normalization related utility functions.""" +"""Tests for neurodsp.utils.norm.""" import numpy as np @@ -25,11 +25,11 @@ def test_demean(): d1 = np.array([1, 2, 3]) d2 = np.array([0, 1, 2, 3, 0]) - # Check default - demean to 0 + # Check default, which demeans to 0 out1 = demean(d1) assert np.isclose(out1.mean(), 0.) - # Check demeaning and adding specific mean + # Check demeaning with specified mean new_mean = 1. out2 = demean(d1, mean=new_mean) assert np.isclose(out2.mean(), new_mean) @@ -39,10 +39,10 @@ def test_normalize_variance(): d1 = np.array([1, 2, 3]) d2 = np.array([0, 1, 2, 3, 0]) - # Check default - normalize variance to 1 + # Check default, which normalizes variance to 1 out1 = normalize_variance(d1) np.isclose(out1.var(), 1.) - # Check normalizing and add specific variance + # Check normalizing with specified variance out2 = normalize_variance(d1, 2.) np.isclose(out2.var(), 2.) diff --git a/neurodsp/tests/utils/test_outliers.py b/neurodsp/tests/utils/test_outliers.py index e685ab4a..6cfc05ca 100644 --- a/neurodsp/tests/utils/test_outliers.py +++ b/neurodsp/tests/utils/test_outliers.py @@ -1,4 +1,4 @@ -"""Tests for outlier related utility functions.""" +"""Tests for neurodsp.utils.outliers.""" import numpy as np from numpy.testing import assert_equal @@ -10,13 +10,13 @@ def test_remove_nans(): - # Test with equal # of NaNs on either edge + # Test with an equal number of NaNs on either edge arr = np.array([np.NaN, np.NaN, 1, 2, 3, np.NaN, np.NaN]) arr_no_nans, arr_nans = remove_nans(arr) assert_equal(arr_no_nans, np.array([1, 2, 3])) assert_equal(arr_nans, np.array([True, True, False, False, False, True, True])) - # Test with different # of NaNs on either edge + # Test with a different number of NaNs on either edge arr = np.array([np.NaN, np.NaN, 1, 2, 3, 4, np.NaN,]) arr_no_nans, arr_nans = remove_nans(arr) assert_equal(arr_no_nans, np.array([1, 2, 3, 4])) diff --git a/neurodsp/tests/utils/test_sim.py b/neurodsp/tests/utils/test_sim.py index 63a4a184..4868beeb 100644 --- a/neurodsp/tests/utils/test_sim.py +++ b/neurodsp/tests/utils/test_sim.py @@ -1,4 +1,4 @@ -"""Tests for simulation related utility functions.""" +"""Tests for neurodsp.utils.sim.""" from neurodsp.utils.sim import * From 4e0985eb41fd7bf4a919da07fd9c2baa1e425e25 Mon Sep 17 00:00:00 2001 From: Tom Donoghue Date: Thu, 21 Jan 2021 23:19:08 -0500 Subject: [PATCH 2/2] add tests for decorators --- neurodsp/tests/utils/test_decorators.py | 21 +++++++++++++++++++-- neurodsp/utils/decorators.py | 10 +++++++--- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/neurodsp/tests/utils/test_decorators.py b/neurodsp/tests/utils/test_decorators.py index 1ad4b543..353098e3 100644 --- a/neurodsp/tests/utils/test_decorators.py +++ b/neurodsp/tests/utils/test_decorators.py @@ -1,12 +1,29 @@ """Tests for neurodsp.utils.decorators.""" +import numpy as np + from neurodsp.utils.decorators import * ################################################################################################### ################################################################################################### def test_normalize(): - pass + + @normalize + def func(): + return np.array([1, 2, 3, 4, 5]) + + # Check that output of function gets normalized + out = func() + assert np.isclose(out.mean(), 0.) + assert np.isclose(out.var(), 1.) def test_multidim(): - pass + + @multidim(select=[]) + def func(sig): + return np.sum(sig) + + # Check that the output of the func gets applied across dimensions + out = func(np.array([[1, 2], [1, 2]])) + assert np.array_equal(out, np.array([3, 3])) diff --git a/neurodsp/utils/decorators.py b/neurodsp/utils/decorators.py index 2bb50e0b..0c4eeddb 100644 --- a/neurodsp/utils/decorators.py +++ b/neurodsp/utils/decorators.py @@ -39,6 +39,10 @@ def multidim(select=[]): ---------- select : list of int, optional List of indices of outputs to sub-select a single instance from. + + Notes + ----- + This decorator assumes the wrapped function has the data input 'sig' as the first argument. """ def decorator(func, *args, **kwargs): @@ -52,17 +56,17 @@ def wrapper(sig, *args, **kwargs): elif sig.ndim == 2: # Apply func across rows of the input data - outs = [func(dat, *args, **kwargs) for dat in sig] + outs = [func(data, *args, **kwargs) for data in sig] if isinstance(outs[0], tuple): # Collect together associated outputs from each, # in case there are multiple outputs - out = [np.stack([dat[n_out] for dat in outs]) \ + out = [np.stack([data[n_out] for data in outs]) \ for n_out in range(len(outs[0]))] # Sub-select single instance of collection for requested outputs - out = [dat[0] if ind in select else dat for ind, dat in enumerate(out)] + out = [data[0] if ind in select else data for ind, data in enumerate(out)] else: out = np.stack(outs)