示例#1
0
def test_SeedCoherenceAnalyzer():
    """ Test the SeedCoherenceAnalyzer """
    methods = (None,
           {"this_method": 'welch', "NFFT": 256},
           {"this_method": 'multi_taper_csd'},
           {"this_method": 'periodogram_csd', "NFFT": 256})

    Fs = np.pi
    t = np.arange(256)
    seed1 = np.sin(10 * t) + np.random.rand(t.shape[-1])
    seed2 = np.sin(10 * t) + np.random.rand(t.shape[-1])
    target = np.sin(10 * t) + np.random.rand(t.shape[-1])
    T = ts.TimeSeries(np.vstack([seed1, target]), sampling_rate=Fs)
    T_seed1 = ts.TimeSeries(seed1, sampling_rate=Fs)
    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':
            C1 = nta.CoherenceAnalyzer(T, method=this_method)
            C2 = nta.SeedCoherenceAnalyzer(T_seed1, T_target,
                                           method=this_method)
            C3 = nta.SeedCoherenceAnalyzer(T_seed2, T_target,
                                           method=this_method)

            npt.assert_almost_equal(C1.coherence[0, 1], C2.coherence[1])
            npt.assert_almost_equal(C2.coherence[1], C3.coherence[0, 1])
            npt.assert_almost_equal(C1.phase[0, 1], C2.relative_phases[1])
            npt.assert_almost_equal(C1.delay[0, 1], C2.delay[1])

        else:
            with pytest.raises(ValueError) as e_info:
                nta.SeedCoherenceAnalyzer(T_seed1, T_target, this_method)
示例#2
0
    def _run_interface(self, runtime):
        lb, ub = self.inputs.frequency_range

        if self.inputs.in_TS is Undefined:
            # get TS form csv and inputs.TR
            TS = self._csv2ts()

        else:
            # get TS from inputs.in_TS
            TS = self.inputs.in_TS

        # deal with creating or storing ROI names:
        if not TS.metadata.has_key('ROIs'):
            self.ROIs = ['roi_%d' % x for x, _ in enumerate(TS.data)]
        else:
            self.ROIs = TS.metadata['ROIs']

        A = nta.CoherenceAnalyzer(TS,
                                  method=dict(this_method='welch',
                                              NFFT=self.inputs.NFFT,
                                              n_overlap=self.inputs.n_overlap))

        freq_idx = np.where(
            (A.frequencies > self.inputs.frequency_range[0]) *
            (A.frequencies < self.inputs.frequency_range[1]))[0]

        #Get the coherence matrix from the analyzer, averaging on the last
        #(frequency) dimension: (roi X roi array)
        self.coherence = np.mean(A.coherence[:, :, freq_idx], -1)
        # Get the time delay from analyzer, (roi X roi array)
        self.delay = np.mean(A.delay[:, :, freq_idx], -1)
        return runtime
示例#3
0
def test_SparseCoherenceAnalyzer():
    Fs = np.pi
    t = np.arange(256)
    x = np.sin(10 * t) + np.random.rand(t.shape[-1])
    y = np.sin(10 * t) + np.random.rand(t.shape[-1])
    T = ts.TimeSeries(np.vstack([x, y]), sampling_rate=Fs)
    C1 = nta.SparseCoherenceAnalyzer(T, ij=((0, 1), (1, 0)))
    C2 = nta.CoherenceAnalyzer(T)

    # Coherence symmetry:
    npt.assert_almost_equal(np.abs(C1.coherence[0, 1]),
                            np.abs(C1.coherence[1, 0]))
    npt.assert_almost_equal(np.abs(C1.coherency[0, 1]),
                            np.abs(C1.coherency[1, 0]))

    # Make sure you get the same answers as you would from the standard
    # CoherenceAnalyzer:

    npt.assert_almost_equal(C2.coherence[0, 1], C1.coherence[0, 1])
    # This is the PSD (for the first time-series in the object):
    npt.assert_almost_equal(C2.spectrum[0, 0], C1.spectrum[0])
    # And the second (for good measure):
    npt.assert_almost_equal(C2.spectrum[1, 1], C1.spectrum[1])

    # The relative phases should be equal
    npt.assert_almost_equal(C2.phase[0, 1], C1.relative_phases[0, 1])
    # But not the absolute phases (which have the same shape):
    npt.assert_equal(C1.phases[0].shape, C1.relative_phases[0, 1].shape)

    # The delay is equal:
    npt.assert_almost_equal(C2.delay[0, 1], C1.delay[0, 1])
    # Make sure that you would get an error if you provided a method other than
    # 'welch':
    with pytest.raises(ValueError) as e_info:
        nta.SparseCoherenceAnalyzer(T, method=dict(this_method='foo'))
示例#4
0
    def _fit(ts_set1, ts_set2, lb, ub):
        ts = concatenate_timeseries(ts_set1, ts_set2)
        coh = nta.CoherenceAnalyzer(ts)

        freq_idx_coh = np.where(
            (coh.frequencies > lb) * (coh.frequencies < ub))[0]

        mean_coh = np.mean(coh.coherence[:, :, freq_idx_coh],
                           axis=-1)  # Averaging on the last dimension
        return np.mean(mean_coh)  #average all of it
示例#5
0
def test_CoherenceAnalyzer():
    methods = (None, {
        "this_method": 'welch',
        "NFFT": 256
    }, {
        "this_method": 'multi_taper_csd'
    }, {
        "this_method": 'periodogram_csd',
        "NFFT": 256
    })

    Fs = np.pi
    t = np.arange(1024)
    x = np.sin(10 * t) + np.random.rand(t.shape[-1])
    y = np.sin(10 * t) + np.random.rand(t.shape[-1])
    # Third time-series used for calculation of partial coherence:
    z = np.sin(10 * t)
    T = ts.TimeSeries(np.vstack([x, y, z]), sampling_rate=np.pi)
    n_series = T.shape[0]
    for unwrap in [True, False]:
        for method in methods:
            C = nta.CoherenceAnalyzer(T, method, unwrap_phases=unwrap)
            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]))

            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:
                npt.assert_equal(C.coherence.shape,
                                 (n_series, n_series, len(t) // 2 + 1))

            # Coherence symmetry:
            npt.assert_equal(C.coherence[0, 1], C.coherence[1, 0])

            # Phase/delay asymmetry:
            npt.assert_equal(C.phase[0, 1], -1 * C.phase[1, 0])

            # 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)
                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)
示例#6
0
def test_coherence_analysis(tmpdir):
    """Test that the coherence analyzer works"""
    import nitime.analysis as nta
    import nitime.timeseries as ts

    tmpdir.chdir()
    # This is the nipype interface analysis:
    CA = nitime.CoherenceAnalyzer()
    CA.inputs.TR = 1.89
    CA.inputs.in_file = example_data("fmri_timeseries.csv")
    if display_available:
        tmp_png = tempfile.mkstemp(suffix=".png")[1]
        CA.inputs.output_figure_file = tmp_png
    tmp_csv = tempfile.mkstemp(suffix=".csv")[1]
    CA.inputs.output_csv_file = tmp_csv

    o = CA.run()
    assert o.outputs.coherence_array.shape == (31, 31)

    # This is the nitime analysis:
    TR = 1.89
    data_rec = np.recfromcsv(example_data("fmri_timeseries.csv"))
    roi_names = np.array(data_rec.dtype.names)
    n_samples = data_rec.shape[0]
    data = np.zeros((len(roi_names), n_samples))

    for n_idx, roi in enumerate(roi_names):
        data[n_idx] = data_rec[roi]

    T = ts.TimeSeries(data, sampling_interval=TR)

    assert (CA._csv2ts().data == T.data).all()

    T.metadata["roi"] = roi_names
    C = nta.CoherenceAnalyzer(
        T,
        method=dict(
            this_method="welch", NFFT=CA.inputs.NFFT, n_overlap=CA.inputs.n_overlap
        ),
    )

    freq_idx = np.where(
        (C.frequencies > CA.inputs.frequency_range[0])
        * (C.frequencies < CA.inputs.frequency_range[1])
    )[0]

    # Extract the coherence and average across these frequency bands:
    # Averaging is done on the last dimension
    coh = np.mean(C.coherence[:, :, freq_idx], -1)

    assert (o.outputs.coherence_array == coh).all()
示例#7
0
def test_coherence_analysis():
    """Test that the coherence analyzer works """
    import nitime.analysis as nta
    import nitime.timeseries as ts

    # This is the nipype interface analysis:
    CA = nitime.CoherenceAnalyzer()
    CA.inputs.TR = 1.89
    CA.inputs.in_file = example_data('fmri_timeseries.csv')
    if display_available:
        tmp_png = tempfile.mkstemp(suffix='.png')[1]
        CA.inputs.output_figure_file = tmp_png
    tmp_csv = tempfile.mkstemp(suffix='.csv')[1]
    CA.inputs.output_csv_file = tmp_csv

    o = CA.run()
    yield assert_equal, o.outputs.coherence_array.shape, (31, 31)

    # This is the nitime analysis:
    TR = 1.89
    data_rec = np.recfromcsv(example_data('fmri_timeseries.csv'))
    roi_names = np.array(data_rec.dtype.names)
    n_samples = data_rec.shape[0]
    data = np.zeros((len(roi_names), n_samples))

    for n_idx, roi in enumerate(roi_names):
        data[n_idx] = data_rec[roi]

    T = ts.TimeSeries(data, sampling_interval=TR)

    yield assert_equal, CA._csv2ts().data, T.data

    T.metadata['roi'] = roi_names
    C = nta.CoherenceAnalyzer(T,
                              method=dict(this_method='welch',
                                          NFFT=CA.inputs.NFFT,
                                          n_overlap=CA.inputs.n_overlap))

    freq_idx = np.where((C.frequencies > CA.inputs.frequency_range[0]) *
                        (C.frequencies < CA.inputs.frequency_range[1]))[0]

    # Extract the coherence and average across these frequency bands:
    coh = np.mean(C.coherence[:, :, freq_idx],
                  -1)  # Averaging on the last dimension

    yield assert_equal, o.outputs.coherence_array, coh
示例#8
0
def test_warn_short_tseries():
    """

    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

    """

    with warnings.catch_warnings(record=True) as w:
        # Cause all warnings to always be triggered.
        warnings.simplefilter("always")
        # 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))
        # Verify some things
        npt.assert_equal(len(w), 1)
示例#9
0
def granger_causality_analysis(time_series, f_lb, f_ub, granger_order, roi_names,result_dir, s='', c=''):
    # initialize GrangerAnalyzer object
    G = nta.GrangerAnalyzer(time_series, order = granger_order)
    # initialize CoherenceAnalyzer 
    C = nta.CoherenceAnalyzer(time_series)
    # initialize CorrelationAnalyzer
    R = nta.CorrelationAnalyzer(time_series)
    # get the index of the frequency band of interest for different analyzer
    freq_idx_G = np.where((G.frequencies > f_lb) * (G.frequencies < f_ub))[0]
    freq_idx_C = np.where((C.frequencies> f_lb) * (C.frequencies < f_ub)) [0]
    # average the last dimension
    coh = np.mean(C.coherence[:, :, freq_idx_C], -1) 
    gl = np.mean(G.causality_xy[:, :, freq_idx_G], -1)
    # Difference in HRF between ROI may result misattriution of causality
    # examine diference between x-->y and y-->x
    g2 = np.mean(G.causality_xy[:,:,freq_idx_G] - G.causality_yx[:,:,freq_idx_G],-1)
    # Figure organization:
    # causality_xy: x-->y, or roi_names[0]-->roi_names[1], roi_names[0]-->roi_names[2], etc.
    # this makes: given a column, transverse through rows. Directionality is
    # from current column label to each row label
    # plot coherence from x to y, 
    drawmatrix_channels(coh, roi_names, size=[10., 10.], color_anchor=0)
    plt.title(('%s %s pair-wise Coherence' % (s, c)).replace('  ',' '))
    plt.savefig(os.path.join(result_dir,s,('%s_%s_pairwise_coherence.png' % (s, c)).replace('__','_')))
    # plot correlation from x to y
    #drawmatrix_channels(R.corrcoef, roi_names, size=[10., 10.], color_anchor=0)
    #plt.title(('%s %s pair-wise Correlation' % (s, c)).replace('  ',' '))
    #plt.savefig(os.path.join(result_dir,s,('%s_%s_pairwise_correlation.png' % (s, c)).replace('__','_')))
    # plot granger causality from x to y
    drawmatrix_channels(gl, roi_names, size=[10., 10.], color_anchor=0)
    plt.title(('%s %s pair-wise Granger Causality' % (s, c)).replace('  ',' '))
    plt.savefig(os.path.join(result_dir,s,('%s_%s_pairwise_granger_causality.png' % (s, c)).replace('__','_')))
    # plot granger causliaty forward-backward difference
    drawmatrix_channels(g2, roi_names, size=[10., 10.], color_anchor = 0)
    plt.title(('%s %s pair-wise Granger Causality Forward-Backward Difference' % (s, c)).replace('  ',' '))
    plt.savefig(os.path.join(result_dir,s,('%s_%s_granger_causality_forward_backward_diff.png' % (s, c)).replace('__','_')))
    # close all the figures
    plt.close("all")
    return(coh, gl, g2, G, C, R)
示例#10
0
We initialize the GrangerAnalyzer object, while specifying the order of the
autoregressive model to be 1 (predict the current behavior of the time-series
based on one time-point back).

"""

G = nta.GrangerAnalyzer(time_series, order=1)
"""

For comparison, we also initialize a CoherenceAnalyzer and a
CorrelationAnalyzer, with the same TimeSeries object:

"""

C1 = nta.CoherenceAnalyzer(time_series)
C2 = nta.CorrelationAnalyzer(time_series)
"""

We are only interested in the physiologically relevant frequency band
(approximately 0.02 to 0.15 Hz).

The spectral resolution is different in these two different analyzers. In the
CoherenceAnalyzer, the spectral resolution depends on the size of the window
used for calculating the spectral density and cross-spectrum, whereas in the
GrangerAnalyzer it is derived, as determined by the user, from the MAR model
used.

For this reason, the indices used to access the relevant part of the spectrum
will be different in the different analyzers.
示例#11
0
                    (len(subjects), num_runs, len(rois), len(rois))) * np.nan
                coh_all[cond] = np.zeros(
                    (len(subjects), num_runs, len(rois), len(rois))) * np.nan

            #plt.figure(); plt.suptitle(cond)
            for nr in range(num_runs):
                #initialize a time series object
                T = nt.TimeSeries(data[cond][:, nr, :], sampling_interval=TR)
                T.metadata['roi'] = rois

                #initialize a correlation analyzer
                Corr = nta.CorrelationAnalyzer(T)
                corr_all[cond][s, nr] = Corr.corrcoef

                #initialize a coherence analyzer
                Coh = nta.CoherenceAnalyzer(T)
                Coh.method['NFFT'] = NFFT
                freq_ind = np.where(
                    (Coh.frequencies > f_lb) * (Coh.frequencies < f_ub))[0]
                coh_all[cond][s, nr] = np.mean(Coh.coherence[:, :, freq_ind],
                                               -1)  #avg over frequencies

                #For debugging, lets look at some of the spectra
                #plt.subplot(num_runs,1,nr+1)
                #S_original = nta.SpectralAnalyzer(T)
                #plt.plot(S_original.psd[0],S_original.psd[1][0],label='Welch PSD')
                #plt.plot(S_original.spectrum_fourier[0],S_original.spectrum_fourier[1][0],label='FFT')
                #plt.plot(S_original.periodogram[0],S_original.periodogram[1][0],label='Periodogram')
                #plt.plot(S_original.spectrum_multi_taper[0],S_original.spectrum_multi_taper[1][0][0],label='Multi-taper')
                #plt.xlabel('Frequency (Hz)')
                #plt.ylabel('Power')