diff options
author | Alexandre Gramfort <alexandre.gramfort@inria.fr> | 2011-08-14 20:22:45 -0400 |
---|---|---|
committer | Alexandre Gramfort <alexandre.gramfort@inria.fr> | 2011-08-14 20:22:45 -0400 |
commit | ee90362200ba8c58d08a365a2bbd45ed94838413 (patch) | |
tree | f9b76d902447c537eb740db0ea57bd24709bd588 | |
parent | 83de333b65ee5f3da656d65602e95ed701464d23 (diff) |
STY: pep8
-rw-r--r-- | doc/examples/ar_est_2vars.py | 34 | ||||
-rw-r--r-- | doc/examples/ar_model_fit.py | 24 | ||||
-rw-r--r-- | doc/examples/event_related_fmri.py | 10 | ||||
-rw-r--r-- | doc/examples/filtering_fmri.py | 4 | ||||
-rw-r--r-- | doc/examples/granger_fmri.py | 10 | ||||
-rw-r--r-- | doc/examples/grasshopper.py | 12 | ||||
-rwxr-xr-x | doc/examples/multi_taper_coh.py | 4 | ||||
-rw-r--r-- | doc/examples/resting_state_fmri.py | 4 | ||||
-rw-r--r-- | doc/examples/seed_analysis.py | 14 | ||||
-rw-r--r-- | nitime/analysis/coherence.py | 6 | ||||
-rw-r--r-- | nitime/analysis/granger.py | 47 | ||||
-rw-r--r-- | nitime/analysis/spectral.py | 12 | ||||
-rw-r--r-- | nitime/analysis/tests/test_base.py | 10 | ||||
-rw-r--r-- | nitime/analysis/tests/test_coherence.py | 27 | ||||
-rw-r--r-- | nitime/analysis/tests/test_granger.py | 21 |
15 files changed, 128 insertions, 111 deletions
diff --git a/doc/examples/ar_est_2vars.py b/doc/examples/ar_est_2vars.py index 9b54b25..334bcac 100644 --- a/doc/examples/ar_est_2vars.py +++ b/doc/examples/ar_est_2vars.py @@ -230,15 +230,15 @@ the known coefficients that generated the data: """ fig01 = plt.figure() -ax01 = fig01.add_subplot(1,1,1) +ax01 = fig01.add_subplot(1, 1, 1) # This is the estimate: -Sxx_est = np.abs(Sw[0,0]) -Syy_est = np.abs(Sw[1,1]) +Sxx_est = np.abs(Sw[0, 0]) +Syy_est = np.abs(Sw[1, 1]) # This is the 'true' value, corrected for one-sided spectral density functions -Sxx_true = Sw_true[0,0].real -Syy_true = Sw_true[1,1].real +Sxx_true = Sw_true[0, 0].real +Syy_true = Sw_true[1, 1].real """ @@ -264,8 +264,8 @@ ax01.plot(w, Sxx_true, 'b', label='true Sxx(w)') ax01.plot(w, Sxx_est, 'b--', label='estimated Sxx(w)') ax01.plot(w, Syy_true, 'g', label='true Syy(w)') ax01.plot(w, Syy_est, 'g--', label='estimated Syy(w)') -ax01.plot(w,np.mean(c_x,0),'r',label='Sxx(w) - MT PSD') -ax01.plot(w,np.mean(c_y,0),'r--',label='Syy(w) - MT PSD') +ax01.plot(w, np.mean(c_x, 0), 'r', label='Sxx(w) - MT PSD') +ax01.plot(w, np.mean(c_y, 0), 'r--', label='Syy(w) - MT PSD') ax01.legend() @@ -280,12 +280,12 @@ addition, there is the instanteaneous causality between the processes: """ fig02 = plt.figure() -ax02 = fig02.add_subplot(1,1,1) +ax02 = fig02.add_subplot(1, 1, 1) # x causes y plot -ax02.plot(w, f_x2y,label='X => Y') +ax02.plot(w, f_x2y, label='X => Y') # y causes x plot -ax02.plot(w, f_y2x,label='Y => X') +ax02.plot(w, f_y2x, label='Y => X') # instantaneous causality ax02.plot(w, f_xy, label='X:Y') @@ -309,22 +309,22 @@ processes. We also compare to the empirically calculated coherence: """ fig03 = plt.figure() -ax03 = fig03.add_subplot(1,1,1) +ax03 = fig03.add_subplot(1, 1, 1) # total causality -ax03.plot(w, f_xy + f_x2y + f_y2x,label='Total causality') +ax03.plot(w, f_xy + f_x2y + f_y2x, label='Total causality') #Interdepence: f_id = alg.interdependence_xy(Sw) -ax03.plot(w, f_id,label='Interdependence') +ax03.plot(w, f_id, label='Interdependence') -coh = np.empty((N,33)) +coh = np.empty((N, 33)) for i in xrange(N): - frex,this_coh = alg.coherence(z[i]) - coh[i] = this_coh[0,1] + frex, this_coh = alg.coherence(z[i]) + coh[i] = this_coh[0, 1] -ax03.plot(frex,np.mean(coh,0),label='Coherence') +ax03.plot(frex, np.mean(coh, axis=0), label='Coherence') ax03.legend() diff --git a/doc/examples/ar_model_fit.py b/doc/examples/ar_model_fit.py index 6d78941..527dcb7 100644 --- a/doc/examples/ar_model_fit.py +++ b/doc/examples/ar_model_fit.py @@ -7,7 +7,7 @@ Fitting an MAR model: analyzer interface In this example, we will use the Analyzer interface to fit a multi-variate auto-regressive model with two time-series influencing each other. -We start by importing 3rd party modules: +We start by importing 3rd party modules: """ @@ -26,7 +26,7 @@ import nitime.analysis.granger as gc """ The utils sub-module includes a function to generate auto-regressive processes -based on provided coefficients: +based on provided coefficients: """ @@ -37,7 +37,7 @@ import nitime.utils as utils Generate some MAR processes (according to Ding and Bressler [Ding2006]_), -""" +""" a1 = np.array([[0.9, 0], [0.16, 0.8]]) @@ -66,7 +66,7 @@ N = 500 Length of each realization: -""" +""" L = 1024 @@ -100,9 +100,9 @@ order = int(np.round(np.mean(est_order))) Once we have estimated the order, we go ahead and fit each realization of the MAR model, constraining the model order accordingly (by setting the order -key-word argument) to be always equal to the model order estimated above. +key-word argument) to be always equal to the model order estimated above. -""" +""" Rxx = np.empty((N, n_process, n_process, n_lags)) coef = np.empty((N, n_process, n_process, order)) @@ -117,25 +117,25 @@ for i in xrange(N): """ We generate a time-series from the recovered coefficients, using the same -randomization seed as the first mar. These should look pretty similar to each other: +randomization seed as the first mar. These should look pretty similar to each other: -""" +""" np.random.seed(1981) -est_ts, _ = utils.generate_mar(np.mean(coef,0), np.mean(ecov,0), L) +est_ts, _ = utils.generate_mar(np.mean(coef, axis=0), np.mean(ecov, axis=0), L) fig01 = plt.figure() -ax = fig01.add_subplot(1,1,1) +ax = fig01.add_subplot(1, 1, 1) ax.plot(est_ts[0][0:100]) -ax.plot(z[0][0][0:100],'g--') +ax.plot(z[0][0][0:100], 'g--') """ .. image:: fig/ar_model_fit_01.png -""" +""" plt.show() diff --git a/doc/examples/event_related_fmri.py b/doc/examples/event_related_fmri.py index 32ffa3e..1aaa597 100644 --- a/doc/examples/event_related_fmri.py +++ b/doc/examples/event_related_fmri.py @@ -7,9 +7,9 @@ Event-related fMRI ================== Extracting the average time-series from one signal, time-locked to the -occurence of some type of event in another signal is a very typical operation in -the analysis of time-series from neuroscience experiments. Therefore, we have -an additional example of this kind of analysis in :ref:`grasshopper` +occurence of some type of event in another signal is a very typical operation +in the analysis of time-series from neuroscience experiments. Therefore, we +have an additional example of this kind of analysis in :ref:`grasshopper` The following example is taken from an fMRI experiment in which a subject was viewing a motion stimulus, while fMRI BOLD was recorded. The time-series in @@ -44,9 +44,9 @@ Next, we load the data into a recarray from the csv file, using csv2rec """ -data_path = os.path.join(nitime.__path__[0],'data') +data_path = os.path.join(nitime.__path__[0], 'data') -data = csv2rec(os.path.join(data_path,'event_related_fmri.csv')) +data = csv2rec(os.path.join(data_path, 'event_related_fmri.csv')) """ diff --git a/doc/examples/filtering_fmri.py b/doc/examples/filtering_fmri.py index ccba94a..a15aa8a 100644 --- a/doc/examples/filtering_fmri.py +++ b/doc/examples/filtering_fmri.py @@ -58,9 +58,9 @@ the data was saved: TR = 1.89 -data_path = os.path.join(nitime.__path__[0],'data') +data_path = os.path.join(nitime.__path__[0], 'data') -data_rec = csv2rec(os.path.join(data_path,'fmri_timeseries.csv')) +data_rec = csv2rec(os.path.join(data_path, 'fmri_timeseries.csv')) # Extract ROI information from the csv file headers: roi_names = np.array(data_rec.dtype.names) diff --git a/doc/examples/granger_fmri.py b/doc/examples/granger_fmri.py index 4379dd7..dedbfef 100644 --- a/doc/examples/granger_fmri.py +++ b/doc/examples/granger_fmri.py @@ -9,8 +9,8 @@ Granger 'causality' of fMRI data Granger 'causality' analysis provides an asymmetric measure of the coupling between two time-series. When discussing this analysis method, we will put the word 'causality' in single quotes, as we believe that use of this word outside -of quotes should be reserved for particular circumstances, often not fulfilled in the -analysis of simultaneously recorder neuroscientific time-series (see +of quotes should be reserved for particular circumstances, often not fulfilled +in the analysis of simultaneously recorder neuroscientific time-series (see [Pearl2009]_ for an extensive discussion of this distinction). The central idea behind this analysis is that time-series can be described in @@ -74,9 +74,9 @@ f_lb = 0.02 We read in the resting state fMRI data into a recarray from a csv file: """ -data_path = os.path.join(nitime.__path__[0],'data') +data_path = os.path.join(nitime.__path__[0], 'data') -data_rec = csv2rec(os.path.join(data_path,'fmri_timeseries.csv')) +data_rec = csv2rec(os.path.join(data_path, 'fmri_timeseries.csv')) roi_names = np.array(data_rec.dtype.names) nseq = len(roi_names) @@ -178,7 +178,7 @@ $F_{y\rightarrow x}$ """ -g2 = np.mean(G.causality_xy[:, :, freq_idx_G] - G.causality_yx[:, :, freq_idx_G] , -1) +g2 = np.mean(G.causality_xy[:, :, freq_idx_G] - G.causality_yx[:, :, freq_idx_G], -1) fig04 = drawmatrix_channels(g2, roi_names, size=[10., 10.], color_anchor=0) """ diff --git a/doc/examples/grasshopper.py b/doc/examples/grasshopper.py index 397cbf6..38b6fff 100644 --- a/doc/examples/grasshopper.py +++ b/doc/examples/grasshopper.py @@ -42,10 +42,10 @@ spike-times are given in micro-seconds: """ -data_path = os.path.join(nitime.__path__[0],'data') +data_path = os.path.join(nitime.__path__[0], 'data') + +spike_times = np.loadtxt(os.path.join(data_path, 'grasshopper_spike_times1.txt')) -spike_times = np.loadtxt(os.path.join(data_path,'grasshopper_spike_times1.txt')) - spike_ev = ts.Events(spike_times, time_unit='us') @@ -59,7 +59,7 @@ the stimulus see [Rokem2006]_). """ -stim = np.loadtxt(os.path.join(data_path,'grasshopper_stimulus1.txt')) +stim = np.loadtxt(os.path.join(data_path, 'grasshopper_stimulus1.txt')) """ @@ -142,9 +142,9 @@ cut-off (800 Hz). """ -stim2 = np.loadtxt(os.path.join(data_path,'grasshopper_stimulus2.txt')) +stim2 = np.loadtxt(os.path.join(data_path, 'grasshopper_stimulus2.txt')) stim2 = volt2dB(stim2, maxdB=76.4286) -spike_times2 = np.loadtxt(os.path.join(data_path,'grasshopper_spike_times2.txt')) +spike_times2 = np.loadtxt(os.path.join(data_path, 'grasshopper_spike_times2.txt')) """ diff --git a/doc/examples/multi_taper_coh.py b/doc/examples/multi_taper_coh.py index 5f7ce39..a11f127 100755 --- a/doc/examples/multi_taper_coh.py +++ b/doc/examples/multi_taper_coh.py @@ -50,9 +50,9 @@ We read in the data into a recarray from a csv file: """ -data_path = os.path.join(nitime.__path__[0],'data') +data_path = os.path.join(nitime.__path__[0], 'data') -data_rec = csv2rec(os.path.join(data_path,'fmri_timeseries.csv')) +data_rec = csv2rec(os.path.join(data_path, 'fmri_timeseries.csv')) """ diff --git a/doc/examples/resting_state_fmri.py b/doc/examples/resting_state_fmri.py index e1838f9..acf29ea 100644 --- a/doc/examples/resting_state_fmri.py +++ b/doc/examples/resting_state_fmri.py @@ -53,9 +53,9 @@ We use csv2rec to read the data in from file to a recarray: """ -data_path = os.path.join(nitime.__path__[0],'data') +data_path = os.path.join(nitime.__path__[0], 'data') -data_rec = csv2rec(os.path.join(data_path,'fmri_timeseries.csv')) +data_rec = csv2rec(os.path.join(data_path, 'fmri_timeseries.csv')) """ This data structure contains in its dtype a field 'names', which contains the diff --git a/doc/examples/seed_analysis.py b/doc/examples/seed_analysis.py index dd5aeeb..9404e11 100644 --- a/doc/examples/seed_analysis.py +++ b/doc/examples/seed_analysis.py @@ -161,7 +161,7 @@ A = nta.SeedCoherenceAnalyzer(time_series_seed, time_series_target, """ Similarly, the SeedCorrelationAnalyzer receives as input seed and target -time-series: +time-series: """ @@ -194,9 +194,9 @@ for this_seed in range(n_seeds): # Extract the coherence and average across these frequency bands: coh.append(np.mean(A.coherence[this_seed][:, freq_idx], -1)) # Averaging on the # last dimension - - cor.append(B.corrcoef[this_seed]) # No need to do any additional - # computation + + cor.append(B.corrcoef[this_seed]) # No need to do any additional + # computation """ @@ -247,15 +247,15 @@ for this_vox in range(n_seeds): ax_cor[-1].matshow(vol_cor[this_vox][:, :, random_slice].squeeze()) ax_cor[-1].set_title('Seed coords: %s' % coords_seeds[:, this_vox]) -for x in zip (['Coherence', 'Correlation'],[fig01,fig02]): - suptit = '%s between all the voxels in slice: '%x[0] +for x in zip(['Coherence', 'Correlation'], [fig01, fig02]): + suptit = '%s between all the voxels in slice: ' % x[0] suptit += '%i and seed voxels' % random_slice x[1].suptitle(suptit) """ -We can now compare the results in the coherence: +We can now compare the results in the coherence: .. image:: fig/seed_analysis_01.png diff --git a/nitime/analysis/coherence.py b/nitime/analysis/coherence.py index 3f09421..241c71b 100644 --- a/nitime/analysis/coherence.py +++ b/nitime/analysis/coherence.py @@ -79,12 +79,12 @@ class CoherenceAnalyzer(BaseAnalyzer): if (self.method.get('this_method') == 'welch' or self.method.get('this_method') is None): - # If the input is shorter than NFFT, all the coherences will be 1 per - # definition. Throw a warning about that: + # If the input is shorter than NFFT, all the coherences will be + # 1 per definition. Throw a warning about that: self.method['NFFT'] = self.method.get('NFFT', tsa.default_nfft) self.method['n_overlap'] = self.method.get('n_overlap', tsa.default_n_overlap) - if (self.input.shape[-1] < + if (self.input.shape[-1] < (self.method['NFFT'] + self.method['n_overlap'])): e_s = "In nitime.analysis, the provided input time-series is" e_s += " shorter than the requested NFFT + n_overlap. All " diff --git a/nitime/analysis/granger.py b/nitime/analysis/granger.py index c537d82..68ec0a5 100644 --- a/nitime/analysis/granger.py +++ b/nitime/analysis/granger.py @@ -31,7 +31,6 @@ def fit_model(x1, x2, order=None, max_order=10, order of the model. """ - c_old = np.inf n_process = 2 Ntotal = n_process * x1.shape[-1] @@ -39,14 +38,15 @@ def fit_model(x1, x2, order=None, max_order=10, # If model order was provided as an input: if order is not None: lag = order + 1 - Rxx = utils.autocov_vector(np.vstack([x1,x2]), nlags=lag) + Rxx = utils.autocov_vector(np.vstack([x1, x2]), nlags=lag) coef, ecov = alg.lwr_recursion(np.array(Rxx).transpose(2, 0, 1)) # If the model order is not known and provided as input: else: for lag in xrange(1, max_order): - Rxx_new = utils.autocov_vector(np.vstack([x1,x2]), nlags=lag) - coef_new, ecov_new = alg.lwr_recursion(np.array(Rxx_new).transpose(2, 0, 1)) + Rxx_new = utils.autocov_vector(np.vstack([x1, x2]), nlags=lag) + coef_new, ecov_new = alg.lwr_recursion( + np.array(Rxx_new).transpose(2, 0, 1)) order_new = coef_new.shape[0] c_new = criterion(ecov_new, n_process, order_new, Ntotal) if c_new > c_old: @@ -62,11 +62,13 @@ def fit_model(x1, x2, order=None, max_order=10, coef = coef_new ecov = ecov_new else: - e_s = "Model estimation order did not converge at max_order=%s" % max_order + e_s = ("Model estimation order did not converge at max_order = %s" + % max_order) raise ValueError(e_s) return order, Rxx, coef, ecov + class GrangerAnalyzer(BaseAnalyzer): """Analyzer for computing all-to-all Granger 'causality' """ def __init__(self, input=None, ij=None, order=None, max_order=10, @@ -87,8 +89,10 @@ class GrangerAnalyzer(BaseAnalyzer): max_order: if the order is estimated, this is the maximal order to estimate for. n_freqs: int (optional) - The size of the sampling grid in the frequency domain. Defaults to 1024 + The size of the sampling grid in the frequency domain. + Defaults to 1024 criterion: + XXX """ self.data = input.data self.sampling_rate = input.sampling_rate @@ -100,9 +104,10 @@ class GrangerAnalyzer(BaseAnalyzer): if ij is None: # The following gets the full list of combinations of # non-same i's and j's: - x,y = np.meshgrid(np.arange(self._n_process), np.arange(self._n_process)) - self.ij = zip(x[np.tril_indices_from(x,-1)], - y[np.tril_indices_from(y,-1)]) + x, y = np.meshgrid(np.arange(self._n_process), + np.arange(self._n_process)) + self.ij = zip(x[np.tril_indices_from(x, -1)], + y[np.tril_indices_from(y, -1)]) else: self.ij = ij @@ -110,12 +115,12 @@ class GrangerAnalyzer(BaseAnalyzer): def _model(self): model = dict(order={}, autocov={}, model_coef={}, error_cov={}) for i, j in self.ij: - model[i, j] = {} + model[i, j] = dict() order_t, Rxx_t, coef_t, ecov_t = fit_model(self.data[i], - self.data[j], - order=self._order, - max_order=self._max_order, - criterion=self._criterion) + self.data[j], + order=self._order, + max_order=self._max_order, + criterion=self._criterion) model['order'][i, j] = order_t model['autocov'][i, j] = Rxx_t model['model_coef'][i, j] = coef_t @@ -129,7 +134,7 @@ class GrangerAnalyzer(BaseAnalyzer): return self._model['order'] else: order = {} - for i,j in self.ij: + for i, j in self.ij: order[i, j] = self._order return order @@ -150,10 +155,11 @@ class GrangerAnalyzer(BaseAnalyzer): """ This returns a dict with the values computed by :func:`granger_causality_xy`, rather than arrays, so that we can delay - the allocation of arrays as much as possible. + the allocation of arrays as much as possible. - """ - gc = dict(frequencies={}, gc_xy={}, gc_yx={}, gc_sim={}, spectral_density={}) + """ + gc = dict(frequencies={}, gc_xy={}, gc_yx={}, gc_sim={}, + spectral_density={}) for i, j in self.ij: w, f_x2y, f_y2x, f_xy, Sw = \ alg.granger_causality_xy(self.model_coef[i, j], @@ -172,7 +178,6 @@ class GrangerAnalyzer(BaseAnalyzer): def frequencies(self): return utils.get_freqs(self.sampling_rate, self._n_freqs) - def _dict2arr(self, key): """ A helper function that will generate an array with all nan's and insert @@ -184,11 +189,11 @@ class GrangerAnalyzer(BaseAnalyzer): arr = np.empty((self._n_process, self._n_process, self.frequencies.shape[0])) - + arr.fill(np.nan) # 'Translate' from dict form into matrix form: - for i,j in self.ij: + for i, j in self.ij: arr[j, i, :] = self._granger_causality[key][i, j] return arr diff --git a/nitime/analysis/spectral.py b/nitime/analysis/spectral.py index b552902..870191f 100644 --- a/nitime/analysis/spectral.py +++ b/nitime/analysis/spectral.py @@ -13,7 +13,8 @@ from .base import BaseAnalyzer class SpectralAnalyzer(BaseAnalyzer): """ Analyzer object for spectral analysis""" - def __init__(self, input=None, method=None, BW=None, adaptive=False, low_bias=False): + def __init__(self, input=None, method=None, BW=None, adaptive=False, + low_bias=False): """ The initialization of the @@ -72,7 +73,6 @@ class SpectralAnalyzer(BaseAnalyzer): self.adaptive = adaptive self.low_bias = low_bias - @desc.setattr_on_read def psd(self): """ @@ -205,10 +205,10 @@ class SpectralAnalyzer(BaseAnalyzer): low_bias=self.low_bias) else: f, spectrum_multi_taper, _ = tsa.multi_taper_psd(self.input.data, - Fs=self.input.sampling_rate, - BW=self.BW, - adaptive=self.adaptive, - low_bias=self.low_bias) + Fs=self.input.sampling_rate, + BW=self.BW, + adaptive=self.adaptive, + low_bias=self.low_bias) return f, spectrum_multi_taper diff --git a/nitime/analysis/tests/test_base.py b/nitime/analysis/tests/test_base.py index 7ee2f93..4784859 100644 --- a/nitime/analysis/tests/test_base.py +++ b/nitime/analysis/tests/test_base.py @@ -2,18 +2,20 @@ from nitime.analysis.base import BaseAnalyzer import numpy.testing as npt + def test_base(): + """Testing BaseAnalyzer""" empty_dict = {} input1 = '123' A = BaseAnalyzer(input=input1) - npt.assert_equal(A.input,input1) - npt.assert_equal(A.parameters,empty_dict) + npt.assert_equal(A.input, input1) + npt.assert_equal(A.parameters, empty_dict) input2 = '456' A.set_input(input2) - npt.assert_equal(A.input,input2) + npt.assert_equal(A.input, input2) - npt.assert_equal(A.__repr__(),'BaseAnalyzer()') + npt.assert_equal(A.__repr__(), 'BaseAnalyzer()') diff --git a/nitime/analysis/tests/test_coherence.py b/nitime/analysis/tests/test_coherence.py index 9716b35..2a22b89 100644 --- a/nitime/analysis/tests/test_coherence.py +++ b/nitime/analysis/tests/test_coherence.py @@ -8,11 +8,12 @@ import nitime.timeseries as ts import nitime.analysis as nta import platform -if float(platform.python_version()[:3])<2.5: +if float(platform.python_version()[:3]) < 2.5: old_python = True else: old_python = False + def test_CoherenceAnalyzer(): methods = (None, {"this_method": 'welch', "NFFT": 256}, @@ -33,11 +34,11 @@ def test_CoherenceAnalyzer(): if method is None: # This is the default behavior (grab the NFFT from the number # of frequencies): - npt.assert_equal(C.coherence.shape,(n_series, n_series, - C.frequencies.shape[0])) + npt.assert_equal(C.coherence.shape, (n_series, n_series, + C.frequencies.shape[0])) - elif (method['this_method']=='welch' or - method['this_method']=='periodogram_csd'): + elif (method['this_method'] == 'welch' or + method['this_method'] == 'periodogram_csd'): npt.assert_equal(C.coherence.shape, (n_series, n_series, method['NFFT'] // 2 + 1)) else: @@ -53,14 +54,15 @@ def test_CoherenceAnalyzer(): # The very first one is a nan, test from second and onwards: npt.assert_almost_equal(C.delay[0, 1][1:], -1 * C.delay[1, 0][1:]) - if method is not None and method['this_method']=='welch': - S = nta.SpectralAnalyzer(T , method) + if method is not None and method['this_method'] == 'welch': + S = nta.SpectralAnalyzer(T, method) npt.assert_almost_equal(S.cpsd[0], C.frequencies) npt.assert_almost_equal(S.cpsd[1], C.spectrum) # Test that partial coherence runs through and has the right number # of dimensions: npt.assert_equal(len(C.coherence_partial.shape), 4) + def test_SparseCoherenceAnalyzer(): Fs = np.pi t = np.arange(256) @@ -93,7 +95,7 @@ def test_SparseCoherenceAnalyzer(): # Make sure that you would get an error if you provided a method other than # 'welch': npt.assert_raises(ValueError, nta.SparseCoherenceAnalyzer, T, - method=dict(this_method='foo')) + method=dict(this_method='foo')) def test_MTCoherenceAnalyzer(): @@ -118,7 +120,8 @@ def test_MTCoherenceAnalyzer(): def test_warn_short_tseries(): """ - A warning is provided when the time-series is shorter than the NFFT + n_overlap. + A warning is provided when the time-series is shorter than + the NFFT + n_overlap. The implementation of this test is based on this: http://docs.python.org/library/warnings.html#testing-warnings @@ -131,7 +134,8 @@ def test_warn_short_tseries(): # Trigger a warning. # The following should throw a warning, because 70 is smaller than the # default NFFT=64 + n_overlap=32: - nta.CoherenceAnalyzer(ts.TimeSeries(np.random.rand(2,70),sampling_rate=1)) + nta.CoherenceAnalyzer(ts.TimeSeries(np.random.rand(2, 70), + sampling_rate=1)) # Verify some things npt.assert_equal(len(w), 1) @@ -153,7 +157,7 @@ def test_SeedCoherenceAnalyzer(): T_seed2 = ts.TimeSeries(np.vstack([seed1, seed2]), sampling_rate=Fs) T_target = ts.TimeSeries(np.vstack([seed1, target]), sampling_rate=Fs) for this_method in methods: - if this_method is None or this_method['this_method']=='welch': + if this_method is None or this_method['this_method'] == 'welch': C1 = nta.CoherenceAnalyzer(T, method=this_method) C2 = nta.SeedCoherenceAnalyzer(T_seed1, T_target, method=this_method) @@ -169,6 +173,7 @@ def test_SeedCoherenceAnalyzer(): npt.assert_raises(ValueError, nta.SeedCoherenceAnalyzer, T_seed1, T_target, this_method) + def test_SeedCoherenceAnalyzer_same_Fs(): """ diff --git a/nitime/analysis/tests/test_granger.py b/nitime/analysis/tests/test_granger.py index 9deb5ca..b9921b6 100644 --- a/nitime/analysis/tests/test_granger.py +++ b/nitime/analysis/tests/test_granger.py @@ -5,11 +5,12 @@ Testing the analysis.granger submodule import numpy as np +import numpy.testing as npt + import nitime.analysis.granger as gc import nitime.utils as utils import nitime.timeseries as ts -import numpy.testing as npt def test_model_fit(): """ @@ -53,22 +54,26 @@ def test_model_fit(): ecov = np.empty((N, n_process, n_process)) for i in xrange(N): - this_order, this_Rxx, this_coef, this_ecov = gc.fit_model(z[i][0], z[i][1], order=2) + this_order, this_Rxx, this_coef, this_ecov = gc.fit_model(z[i][0], + z[i][1], + order=2) Rxx[i] = this_Rxx coef[i] = this_coef ecov[i] = this_ecov - npt.assert_almost_equal(cov, np.mean(ecov,0), decimal=1) - npt.assert_almost_equal(am, np.mean(coef,0), decimal=1) + npt.assert_almost_equal(cov, np.mean(ecov, axis=0), decimal=1) + npt.assert_almost_equal(am, np.mean(coef, axis=0), decimal=1) # Next we test that the automatic model order estimation procedure works: est_order = [] for i in xrange(N): - this_order, this_Rxx, this_coef, this_ecov = gc.fit_model(z[i][0], z[i][1]) + this_order, this_Rxx, this_coef, this_ecov = gc.fit_model(z[i][0], + z[i][1]) est_order.append(this_order) npt.assert_almost_equal(order, np.mean(est_order), decimal=1) + def test_GrangerAnalyzer(): """ Testing the GrangerAnalyzer class, which simplifies calculations of related @@ -98,11 +103,11 @@ def test_GrangerAnalyzer(): g1 = gc.GrangerAnalyzer(ts1) # Check that things have the right shapes: - npt.assert_equal(g1.frequencies.shape[-1], g1._n_freqs//2 + 1) - npt.assert_equal(g1.causality_xy[0,1].shape, g1.causality_yx[0,1].shape) + npt.assert_equal(g1.frequencies.shape[-1], g1._n_freqs // 2 + 1) + npt.assert_equal(g1.causality_xy[0, 1].shape, g1.causality_yx[0, 1].shape) # Test inputting ij: - g2 = gc.GrangerAnalyzer(ts1, ij = [(0, 1), (1, 0)]) + g2 = gc.GrangerAnalyzer(ts1, ij=[(0, 1), (1, 0)]) # x => y for one is like y => x for the other: npt.assert_almost_equal(g1.causality_yx[1, 0], g2.causality_xy[0, 1]) |