예제 #1
0
def test_CorrelationAnalyzer():

    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])

    T = ts.TimeSeries(np.vstack([x, y]), sampling_rate=Fs)

    C = nta.CorrelationAnalyzer(T)

    # Test the symmetry: correlation(x,y)==correlation(y,x)
    npt.assert_equal(C.corrcoef[0, 1], C.corrcoef[1, 0])
    # Test the self-sameness: correlation(x,x)==1
    npt.assert_equal(C.corrcoef[0, 0], 1)
    npt.assert_equal(C.corrcoef[1, 1], 1)

    # Test the cross-correlation:
    # First the symmetry:
    npt.assert_array_almost_equal(C.xcorr.data[0, 1], C.xcorr.data[1, 0])

    # Test the normalized cross-correlation
    # The cross-correlation should be equal to the correlation at time-lag 0
    npt.assert_equal(C.xcorr_norm.data[0, 1, C.xcorr_norm.time == 0],
                     C.corrcoef[0, 1])

    # And the auto-correlation should be equal to 1 at 0 time-lag:
    npt.assert_equal(C.xcorr_norm.data[0, 0, C.xcorr_norm.time == 0], 1)

    # Does it depend on having an even number of time-points?
    # make another time-series with an odd number of items:
    t = np.arange(1023)
    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)

    C = nta.CorrelationAnalyzer(T)

    npt.assert_equal(C.xcorr_norm.data[0, 1, C.xcorr_norm.time == 0],
                     C.corrcoef[0, 1])
예제 #2
0
def analyze_connectivity(imagelist, path_roi, roi_names, ts_param, **kwargs):
    
    TR = 1.
    for arg in kwargs:
        if arg == 'TR':
            TR = np.float(kwargs[arg])
    
    roi_list = os.listdir(path_roi)
    roi_list = [r for r in roi_list if r.find('.hdr') != -1 \
                                    or r.find('nii.gz') != -1]
    '''
    roi_list = ['lower_left_new_.nii.gz',
               'lower_right_new_.nii.gz',
               'upper_left_new_.nii.gz',
               'upper_right_new_.nii.gz',
               'roi_attention_all.4dfp.hdr',
               'roi_default_all.4dfp.hdr',
               'searchlight_separated.nii.gz'
               ]
    '''
    #roi_names = np.loadtxt('/media/DATA/fmri/learning/roi_labels', dtype=np.str)
    print('Length of image list is '+str(len(imagelist)))
    volume_shape = imagelist[0].get_data().shape[:-1]
    n_shape = list(volume_shape)
    n_shape.append(-1)
    coords = list(np.ndindex(volume_shape))
    coords = np.array(coords).reshape(n_shape)
    
    data_arr = []
    for roi in roi_list:
        r_mask = ni.load(os.path.join(path_roi, roi))
        mask = r_mask.get_data().squeeze()
        roi_filt = roi_names[roi_names.T[1] == roi]
        for label in np.unique(mask)[1:]:
            
            roi_m = np.int_(roi_filt.T[2]) == label
            if roi_m.any():
                print('Loading voxels from '+roi_filt[roi_m].T[0][0])
                time_serie = io.time_series_from_file([f.get_filename() for f in imagelist], \
                                                      coords[mask==label].T, \
                                                      TR=float(TR), \
                                                      normalize=ts_param['normalize'], \
                                                      average=ts_param['average'], \
                                                      filter=ts_param['filter'])
                data_arr.append(time_serie)
        del r_mask
    
    data = np.array(data_arr)
    ts = TimeSeries(data, sampling_interval=float(TR))
    del imagelist, time_serie
    C = nta.CorrelationAnalyzer(ts)
    
    return C, ts
예제 #3
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)
예제 #4
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.

"""
예제 #5
0
                            ub=f_ub,
                            method='boxcar'),
                        verbose=True).data
    # normalize='percent'

    # seed_ts[i_seed] = ntio.time_series_from_file(data_file,
    #                     coords=seed_coords,
    #                     TR=TR,
    #                     average=True,
    #                     verbose=True).data

seed_T = ntts.TimeSeries(seed_ts, sampling_interval=TR)
fig_seed_tseries = viz.plot_tseries(seed_T)
plt.title('seed tseries, {}'.format(fmri_file))

seed_Cor = nta.CorrelationAnalyzer(seed_T)
fig_seed_cor = viz.drawmatrix_channels(seed_Cor.corrcoef, seed_rois, color_anchor=0)
plt.title('correlation, {}'.format(fmri_file))

# Get target data
# initialize target time series
target_ts = np.zeros((len(target_rois), n_TRs))

for i_target, target_name in enumerate(target_rois):
    print '\n', target_name
    target_file = os.path.join(roi_dir, '{}.mat'.format(target_name))

    # find the coordinates of cortex voxels
    target_coords = tsv.upsample_coords(tsv.getROIcoords(target_file), upsample_factor)

    if flip_x:
예제 #6
0
    def _fit(ts_set1, ts_set2):
        ts = concatenate_timeseries(ts_set1, ts_set2)
        corr = nta.CorrelationAnalyzer(ts)

        return corr.corrcoef[0, 1]
예제 #7
0
            #initialize shape of object, but only for first subject
            if s == 0:
                corr_all[cond] = np.zeros(
                    (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')