コード例 #1
0
ファイル: analysis.py プロジェクト: agramfort/nipype
    def _make_output_figures(self):
        """
        Generate the desired figure and save the files according to
        self.inputs.output_figure_file

        """
        
        if self.inputs.figure_type == 'matrix':
            fig_coh = viz.drawmatrix_channels(self.coherence,
                                channel_names=self.ROIs,
                                color_anchor=0)
        
            fig_coh.savefig(fname_presuffix(self.inputs.output_figure_file,
                                    suffix='_coherence'))

            fig_dt = viz.drawmatrix_channels(self.delay,
                                channel_names=self.ROIs,
                                color_anchor=0)
        
            fig_dt.savefig(fname_presuffix(self.inputs.output_figure_file,
                                    suffix='_delay'))
        else:
            fig_coh = viz.drawgraph_channels(self.coherence,
                                channel_names=self.ROIs)
        
            fig_coh.savefig(fname_presuffix(self.inputs.output_figure_file,
                                    suffix='_coherence'))

            fig_dt = viz.drawgraph_channels(self.delay,
                                channel_names=self.ROIs)
        
            fig_dt.savefig(fname_presuffix(self.inputs.output_figure_file,
                                    suffix='_delay'))
コード例 #2
0
ファイル: granger.py プロジェクト: ryanneely11/data_analysis
def analyze(data,chan_names):
	TR = 1000.0 ##sample rate
	f_ub = 100 ##upper freq bound
	f_lb = 0 ##lower freq bound
	##compute the result for each trial
	coh = []
	g1 = []
	g2 = []
	for trial in range(data.shape[0]):
		trialdata = data[trial,:,:]
		time_series = ts.TimeSeries(trialdata, sampling_rate=TR)
		G = nta.GrangerAnalyzer(input=time_series,order=2)
		C1 = nta.CoherenceAnalyzer(time_series)
		C2 = nta.CorrelationAnalyzer(time_series)
		freq_idx_G = np.where((G.frequencies > f_lb) * (G.frequencies < f_ub))[0]
		freq_idx_C = np.where((C1.frequencies > f_lb) * (C1.frequencies < f_ub))[0]
		coh.append(np.nanmean(C1.coherence[:, :, freq_idx_C], -1))  # Averaging on the last dimension
		g1.append(np.nanmean(G.causality_xy[:, :, freq_idx_G], -1))
		g2.append(np.nanmean(G.causality_xy[:, :, freq_idx_G] - G.causality_yx[:, :, freq_idx_G], -1))
	##now average across trials
	coh = np.nanmean(np.asarray(coh),axis=0)
	g1 = np.nanmean(np.asarray(g1),axis=0)
	g2 = np.nanmean(np.asarray(g2),axis=0)
	fig01 = drawmatrix_channels(coh, chan_names, size=[10., 10.], title='Coherence')
	fig02 = drawmatrix_channels(C2.corrcoef, chan_names, size=[10., 10.], title="Correlations")
	fig03 = drawmatrix_channels(g1.T, chan_names, size=[10., 10.],title="Forward causality")
	fig04 = drawmatrix_channels(g2.T, chan_names, size=[10., 10.], title="Reverse causality")
コード例 #3
0
    def _make_output_figures(self):
        """
        Generate the desired figure and save the files according to
        self.inputs.output_figure_file

        """
        if self.inputs.figure_type == 'matrix':
            fig_coh = viz.drawmatrix_channels(self.coherence,
                                              channel_names=self.ROIs,
                                              color_anchor=0)

            fig_coh.savefig(fname_presuffix(self.inputs.output_figure_file,
                                            suffix='_coherence'))

            fig_dt = viz.drawmatrix_channels(self.delay,
                                             channel_names=self.ROIs,
                                             color_anchor=0)

            fig_dt.savefig(fname_presuffix(self.inputs.output_figure_file,
                                           suffix='_delay'))
        else:
            fig_coh = viz.drawgraph_channels(self.coherence,
                                             channel_names=self.ROIs)

            fig_coh.savefig(fname_presuffix(self.inputs.output_figure_file,
                                            suffix='_coherence'))

            fig_dt = viz.drawgraph_channels(self.delay,
                                            channel_names=self.ROIs)

            fig_dt.savefig(fname_presuffix(self.inputs.output_figure_file,
                                           suffix='_delay'))
コード例 #4
0
ファイル: render.py プロジェクト: alexsavio/macuto
def slicesdir_connectivity_matrices(output_dir, cmat_list, dpi=150, lower_triangle=True, **kwargs):
    """
    @param output_dir:
    @param file_list1: list of ndarrays
    List of connectivity matrices

    @param dpi: int
    Dots per inch resolution of the plot images

    @param lower_triangle: bool
    If true, will plot a lower triangle of the matrix,
    the full matrix otherwise.

    @param kwargs: arguments to show_many_slices
    See draw_square_matrix_channels named arguments.
    """
    import os
    import skimage.io as skio
    import matplotlib.pyplot as plt
    from nitime.viz import drawmatrix_channels

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    img_files = []

    #cmap = kwargs.pop('cmap', plt.cm.rainbow)
    channel_names = kwargs.pop('channel_names', None)
    color_anchor = kwargs.pop('color_anchor', 0)
    size = kwargs.pop('size', [10., 10.])

    #CREATE separate images of each file_list2 file
    # on the corresponding file_list1 file
    for idx in list(range(len(cmat_list))):
        cmat = cmat_list[idx]

        png_fname = 'connectivity_matrix' + str(idx) + '.png'
        png_path = os.path.join(output_dir, png_fname)

        if lower_triangle:
            fig = drawmatrix_channels(cmat, channel_names, size=size,
                                      color_anchor=color_anchor, **kwargs)
        else:
            fig = draw_square_matrix_channels(cmat, channel_names, size=size,
                                              color_anchor=color_anchor, **kwargs)

        #fig  = plt.matshow(cmat, cmap=cmap)
        fig.savefig(png_path, transparent=True, dpi=dpi)

        img = autocrop_img(skio.imread(png_path))
        skio.imsave(png_path, img)

        img_files.append(os.path.basename(png_path))

        plt.close()

    #Create the index.html file with all images
    create_imglist_html(output_dir, img_files)

    return img_files
コード例 #5
0
def nitime_solution(animal, day, cutoff=True):
    # TODO: add support for custom freq bands
    import h5py
    import nitime
    import numpy as np
    import nitime.analysis as nta
    from utils_loading import encode_to_filename
    from nitime.viz import drawmatrix_channels
    import matplotlib.pyplot as plt
    folder = "/Volumes/DATA_01/NL/layerproject/processed/"
    hf = h5py.File(encode_to_filename(folder, animal, day), 'r')
    dff = np.array(hf['dff'])
    NEUR = 'ens'
    # Critical neuron pair vs general neuron gc
    if NEUR == 'ens':
        rois = dff[hf['ens_neur']]
    elif NEUR == 'neur':
        rois = dff[hf['nerden']]
    else:
        rois = dff[NEUR]

    rois_ts = nitime.TimeSeries(rois, sampling_interval=1 / hf.attrs['fr'])
    G = nta.GrangerAnalyzer(rois_ts)
    if cutoff:
        sel = np.where(G.frequencies < hf.attrs['fr'])[0]
        caus_xy = G.causality_xy[:, :, sel]
        caus_yx = G.causality_yx[:, :, sel]
        caus_sim = G.simultaneous_causality[:, :, sel]
    else:
        caus_xy = G.causality_xy
        caus_yx = G.causality_yx
        caus_sim = G.simultaneous_causality
    g1 = np.mean(caus_xy, -1)
    g2 = np.mean(caus_yx, -1)
    g3 = np.mean(caus_sim, -1)
    g4 = g1-g2
    fig03 = drawmatrix_channels(g1, ['E11', 'E12', 'E21', 'E22'], size=[10., 10.], color_anchor = 0)
    plt.colorbar()
コード例 #6
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)
コード例 #7
0
def robust_viz(g, labels):
    from nitime.viz import drawmatrix_channels
    g[np.isnan(g)] = 0
    drawmatrix_channels(g, labels, size=[10., 10.], color_anchor=0)
コード例 #8
0
ファイル: granger_fmri.py プロジェクト: Eric89GXL/nitime
freq_idx_G = np.where((G.frequencies > f_lb) * (G.frequencies < f_ub))[0]
freq_idx_C = np.where((C1.frequencies > f_lb) * (C1.frequencies < f_ub))[0]


"""

We plot the 'causality' from x to y ($F_{x \rightarrow y}$) and from y to x
($F_{y \rightarrow x}$ for the first two ROIs and compare to the coherence
between these two time-series:

"""

coh = np.mean(C1.coherence[:, :, freq_idx_C], -1)  # Averaging on the last dimension
g1 = np.mean(G.causality_xy[:, :, freq_idx_G], -1)

fig01 = drawmatrix_channels(coh, roi_names, size=[10., 10.], color_anchor=0)

"""

.. image:: fig/granger_fmri_01.png

"""

fig02 = drawmatrix_channels(C2.corrcoef, roi_names, size=[10., 10.], color_anchor=0)

"""

.. image:: fig/granger_fmri_02.png

"""
コード例 #9
0
ファイル: test_viz.py プロジェクト: derekrollend/nitime
def test_drawmatrix_channels():
    fig01 = drawmatrix_channels(C.corrcoef,
                                roi_names,
                                size=[10., 10.],
                                color_anchor=0)
コード例 #10
0
T.metadata['roi'] = roi_names
"""

First, we examine the correlations between the time-series extracted from
different parts of the brain. The following script extracts the data (using the
drawmatrix_channels function, displaying the correlation matrix with the ROIs
labeled.

"""

# Initialize the correlation analyzer
C = CorrelationAnalyzer(T)

# Display the correlation matrix
fig01 = drawmatrix_channels(C.corrcoef,
                            roi_names,
                            size=[10., 10.],
                            color_anchor=0)
"""

.. image:: fig/resting_state_fmri_01.png

Notice that setting the color_anchor input to this function to 0 makes sure
that the center of the color map (here a blue => white => red) is at 0. In this
case, positive values will be displayed as red and negative values in blue.

We notice that the left caudate nucleus (labeled 'lcau') has an interesting
pattern of correlations. It has a high correlation with both the left putamen
('lput', which is located nearby) and also with the right caudate nucleus
('lcau'), which is the homologous region in the other hemisphere. Are these two
correlation values related to each other? The right caudate and left putamen
seem to have a moderately low correlation value. One way to examine this
コード例 #11
0
ファイル: fmri5.py プロジェクト: fperez/nitime
#This part is the same as before
TR=1.89
data_rec = csv2rec('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]
data = percent_change(data)
T = TimeSeries(data,sampling_interval=TR)
T.metadata['roi'] = roi_names 
C = CoherenceAnalyzer(T)
freq_idx = np.where((C.frequencies>0.02) * (C.frequencies<0.15))[0]
idx_lcau = np.where(roi_names=='lcau')[0]
idx_rcau = np.where(roi_names=='rcau')[0]
idx_lput = np.where(roi_names=='lput')[0]
idx_rput = np.where(roi_names=='rput')[0]
idx = np.hstack([idx_lcau,idx_rcau,idx_lput,idx_rput])
idx1 = np.vstack([[idx[i]]*4 for i in range(4)]).ravel()
idx2 = np.hstack(4*[idx])

#For the third dimension, take always the index of the left caudate:
idx3 = np.hstack(16*[idx_lcau])

#Extract the partial coherence and average across the frequency bands: 
coh = C.coherence_partial[idx1,idx2,idx3].reshape(4,4,C.frequencies.shape[0])
coh = np.mean(coh[:,:,freq_idx],-1) #Averaging on the last dimension

drawgraph_channels(coh,roi_names[idx])
drawmatrix_channels(coh,roi_names[idx],color_anchor=0)
コード例 #12
0
        # reshape ROI matrix
        allROIS=reshapeTS(t_fix)
        numRuns=allROIS.shape[1]

        corr_all[subject] = np.zeros((numRuns,len(rois),len(rois))) * np.nan
        coh_all[subject] = np.zeros((numRuns,len(rois),len(rois))) * np.nan
        
        # Get roi correlations and coherence
        for runNum in range(allROIS.shape[1]):
            #need to load timeseries by run
            fixTS=ts.TimeSeries(allROIS[:,runNum,:], sampling_interval=TR)
            fixTS.metadata['roi'] = roi_names
           
            # Get plot and correlations
            C=CorrelationAnalyzer(fixTS)
            fig01 = drawmatrix_channels(C.corrcoef, roi_names, size=[10., 10.], color_anchor=0,  title='Correlation Results Run %i' % runNum)
            plt.show()
            # Save correlation
            corr_all[subject][runNum]=C.corrcoef

            # Get coherence
            Coh = CoherenceAnalyzer(fixTS)
   
            Coh.method['NFFT'] = NFFT
            Coh.method['n_overlap']=n_overlap

            # Get the index for the frequencies inside the ub and lb
            freq_idx = np.where((Coh.frequencies > f_lb) * (Coh.frequencies < f_ub))[0]
            
            # Extract coherence
            # Coher[0]= correlations for first ROI in list with others
コード例 #13
0
    coherAll_flat[ind] = np.nan
    ind = np.where( corrAll_flat == np.Infinity)
    corrAll_flat[ind] = np.nan

    # Reshape back into matrix of runs x rois x rois
    coherAll_t=coherAll_flat.reshape(numRuns, roiNames.size, roiNames.size)
    corrAll_t=corrAll_flat.reshape(numRuns, roiNames.size, roiNames.size)

    # Average over runs (the first dimension)
    coherAvg_t=np.mean(coherAll_t, 0)
    coherSTD=np.std(coherAll_t, 0)
    corrAvg_t=np.mean(corrAll_t,0)
    corrSTD=np.std(corrAll_t, 0)

    # Plot graph of coherence and correlation values
    fig1 = drawmatrix_channels(coherAvg_t, roiNames, size=coherAvg_t.shape, color_anchor=0, title='Average ' +condition+  ' Coherence Results over ' +str(numRuns) + ' runs for ' + sub)
    fig2=drawmatrix_channels(coherSTD, roiNames, size=coherSTD.shape, color_anchor=0, title='Average ' +condition+ ' Coherence STD over ' +str(numRuns) + ' runs for ' + sub)
    fig3=drawmatrix_channels(corrAvg_t, roiNames, size=corrAvg_t.shape, color_anchor=0, title='Average ' +condition+ ' Correlation Results over ' +str(numRuns) + ' runs for ' + sub)
    fig4=drawmatrix_channels(corrSTD, roiNames, size=corrSTD.shape, color_anchor=0, title='Average ' +condition+ ' Correlation STD over ' +str(numRuns) + ' runs for ' + sub)
    plt.show()

    #Plot data for 3 streams (btw for all)
    titleName=condition+" coherence "
    #get3NetworkAvg(coherAvg_t, titleName, roiNames, numRuns)
    titleName=condition+" correlation "
    #get3NetworkAvg(corrAvg_t, titleName, roiNames, numRuns)

    #Plot the data for 4 groups
    #Define the streams
    r_earlyVent=[1, 2, 3]
    r_earlyDors=[7, 8, 9]
コード例 #14
0
    tmin,
    tmax,
    proj=True,
    picks=picks,
    baseline=(None, 0),
    preload=True,
    reject=dict(grad=4000e-13, eog=150e-6),
)

# Export to NiTime
epochs_ts = epochs.to_nitime(picks=np.arange(20), collapse=True)

###############################################################################
# Now use nitime's OO-interface to compute coherence between sensors

from nitime.analysis import MTCoherenceAnalyzer
from nitime.viz import drawmatrix_channels
import matplotlib.pyplot as plt

# setup coherency analyzer
C = MTCoherenceAnalyzer(epochs_ts)

# confine analysis to 10 - 20 Hz
freq_idx = np.where((C.frequencies > 10) * (C.frequencies < 30))[0]

# compute average coherence
coh = np.mean(C.coherence[:, :, freq_idx], -1)  # Averaging on last dimension
drawmatrix_channels(coh, epochs.ch_names, color_anchor=0, title="MEG gradiometer coherence")

plt.show()
コード例 #15
0
    # stack the value to sum_'s
    stack_coh = np.dstack((stack_coh, coh))
    stack_gl = np.dstack((stack_gl, gl))
    stack_R = np.dstack((stack_R, R.corrcoef))
    # save extracted data
    np.savez(os.path.join(result_dir,s,'%s_data.npz' % (s)),G,C,R,coh,gl,g2)
    # clear the variables
    coh, gl, g2, G, C, R = (None, None, None, None, None, None)
    

# calcualte mean
mean_coh = np.mean(stack_coh, axis = 2)
mean_gl = np.mean(stack_gl, axis = 2)
mean_R = np.mean(stack_R, axis = 2)
# plot group averaged
figGroup_coh = drawmatrix_channels(mean_coh, roi_names,size=[10.,10.], color_anchor=0)
plt.title('Control pair-wise Coherence')
plt.savefig(os.path.join(result_dir,'Control_pair_wise_coherence.png'))
figGroup_gl = drawmatrix_channels(mean_gl, roi_names,size=[10.,10.], color_anchor=0)
plt.title('Control pair-wise Granger Causality')
plt.savefig(os.path.join(result_dir,'Control_pair_wise_granger_causality.png'))
figGroup_R = drawmatrix_channels(mean_R, roi_names,size=[10.,10.], color_anchor=0)
plt.title('Control pair-wise Correlation')
plt.savefig(os.path.join(result_dir,'Control_pair_wise_correlation.png'))

np.savez(os.path.join(result_dir,'Control_Group_average.npz'), stack_coh, 
         stack_gl, stack_R, mean_coh, mean_gl, mean_R)
        
    
    
    
コード例 #16
0
ファイル: render.py プロジェクト: nagyistge/neurita.cajal
def slicesdir_connectivity_matrices(output_dir,
                                    cmat_list,
                                    dpi=150,
                                    lower_triangle=True,
                                    **kwargs):
    """
    @param output_dir:
    @param file_list1: list of ndarrays
    List of connectivity matrices

    @param dpi: int
    Dots per inch resolution of the plot images

    @param lower_triangle: bool
    If true, will plot a lower triangle of the matrix,
    the full matrix otherwise.

    @param kwargs: arguments to show_many_slices
    See draw_square_matrix_channels named arguments.
    """

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    img_files = []

    #cmap = kwargs.pop('cmap', plt.cm.rainbow)
    channel_names = kwargs.pop('channel_names', None)
    color_anchor = kwargs.pop('color_anchor', 0)
    size = kwargs.pop('size', [10., 10.])

    #CREATE separate images of each file_list2 file
    # on the corresponding file_list1 file
    for idx in list(range(len(cmat_list))):
        cmat = cmat_list[idx]

        if lower_triangle:
            fig = drawmatrix_channels(cmat,
                                      channel_names,
                                      size=size,
                                      color_anchor=color_anchor,
                                      **kwargs)
        else:
            fig = draw_square_matrix_channels(cmat,
                                              channel_names,
                                              size=size,
                                              color_anchor=color_anchor,
                                              **kwargs)

        png_fname = 'connectivity_matrix' + str(idx) + '.png'
        png_path = os.path.join(output_dir, png_fname)

        export_figure(fig, png_path, dpi=dpi)

        img_files.append(os.path.basename(png_path))

        plt.close()

    #Create the index.html file with all images
    create_imglist_html(output_dir, img_files)

    return img_files
コード例 #17
0
    caus_yx = G.causality_yx[:, :, sel]
else:
    caus_xy = G.causality_xy
    caus_yx = G.causality_yx
cutoff = False
G = nta.GrangerAnalyzer(rois_ts, order=1)
if cutoff:
    sel = np.where(G.frequencies < hf.attrs['fr'])[0]
    caus_xy = G.causality_xy[:, :, sel]
    caus_yx = G.causality_yx[:, :, sel]
else:
    caus_xy = G.causality_xy
    caus_yx = G.causality_yx
g1 = np.mean(caus_xy, -1)
g2 = np.mean(caus_yx, -1)
fig03 = drawmatrix_channels(g1, ['a', 'b'], size=[10., 10.], color_anchor=0)
plt.show()
fig03 = drawmatrix_channels(g2, ['a', 'b'], size=[10., 10.], color_anchor=0)
plt.show()
fig03 = drawmatrix_channels(g1 - g2, ['a', 'b'], size=[10., 10.], color_anchor=0)
plt.show()
g1
g2


def robust_viz(g, labels):
    from nitime.viz import drawmatrix_channels
    g[np.isnan(g)] = 0
    drawmatrix_channels(g, labels, size=[10., 10.], color_anchor=0)

コード例 #18
0
                            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:
	    target_coords[0] = (volume_shape[0]-1) - (target_coords[0])
コード例 #19
0
ファイル: fmri3.py プロジェクト: sheremat/nitime
import nitime.viz

reload(nitime.viz)
from nitime.viz import drawmatrix_channels

# This time Import the coherence analyzer
from nitime.analysis import CoherenceAnalyzer

# This part is the same as before
TR = 1.89
data_rec = csv2rec("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]

data = percent_change(data)
T = TimeSeries(data, sampling_interval=TR)
T.metadata["roi"] = roi_names
C = CoherenceAnalyzer(T)

# We look only at frequencies between 0.02 and 0.15 (the physiologically
# relevant band, see http://imaging.mrc-cbu.cam.ac.uk/imaging/DesignEfficiency:
freq_idx = np.where((C.frequencies > 0.02) * (C.frequencies < 0.15))[0]

# Extract the coherence and average across these frequency bands:
coh = np.mean(C.coherence[:, :, freq_idx], -1)  # Averaging on the last dimension
drawmatrix_channels(coh, roi_names, size=[10.0, 10.0], color_anchor=0)
コード例 #20
0
                        filter=dict(lb=f_lb,
                            ub=f_ub,
                            method='boxcar'),
                        verbose=True).data

    # 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 = viz.plot_tseries(seed_T)

seed_Cor = nta.CorrelationAnalyzer(seed_T)
fig = viz.drawmatrix_channels(seed_Cor.corrcoef, seed_rois, color_anchor=0)


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

for i_target, target_name in enumerate(target_rois):
    print '\n', target_name, target_roi_type
    if target_roi_type is 'mask':
        target_file = os.path.join(mask_roi_dir, '{}.nii'.format(target_name))

        # load roi mask
        target_mask = nib.load(target_file)

        # find the coordinates of cortex voxels
コード例 #21
0
ファイル: extract_ts.py プロジェクト: MadsJensen/Hyp_MEG_MNE
for j in range(cohMatrixNormal.shape[2]):
    niTS = TimeSeries(labelTsNormal[j], sampling_rate=epochs.info["sfreq"])
    niTS.metadata["roi"] = labels_name

    C = MTCoherenceAnalyzer(niTS)

    # confine analysis to Aplha (8  12 Hz)
    freq_idx = np.where((C.frequencies > f_lw) * (C.frequencies < f_up))[0]

    # compute average coherence &  Averaging on last dimension
    cohMatrixNormal[:, :, j] = np.mean(C.coherence[:, :, freq_idx], -1)


# %%
drawmatrix_channels(bin.astype(int), labels_name, color_anchor=0,
                    title='MEG coherence')

plt.show()


# %%
thresholdLeft = np.median(cohMatrixLeft[np.nonzero(cohMatrixLeft)]) \
    + np.std(cohMatrixLeft[np.nonzero(cohMatrixLeft)])
binMatrixLeft = cohMatrixLeft > thresholdLeft

thresholdRight = np.median(cohMatrixRight[np.nonzero(cohMatrixRight)]) \
    + np.std(cohMatrixRight[np.nonzero(cohMatrixRight)])
binMatrixRight = cohMatrixRight > thresholdRight


# %%
コード例 #22
0
ファイル: multi_taper_coh.py プロジェクト: ilustreous/nitime
"""

coh = np.mean(coh_mat[:, :, freq_idx], -1)  # Averaging on the last dimension


"""

The next line calls the visualization routine which displays the data

"""


fig01 = drawmatrix_channels(coh,
                            roi_names,
                            size=[10., 10.],
                            color_anchor=0,
                            title='MTM Coherence')


"""

.. image:: fig/multi_taper_coh_01.png

Next we perform the same analysis, using the nitime object oriented interface.

We start by initializing a TimeSeries object with this data and with the
sampling_interval provided above. We set the metadata 'roi' field with the ROI
names.

コード例 #23
0
ファイル: granger_fmri.py プロジェクト: luzpaz/nitime
freq_idx_G = np.where((G.frequencies > f_lb) * (G.frequencies < f_ub))[0]
freq_idx_C = np.where((C1.frequencies > f_lb) * (C1.frequencies < f_ub))[0]
"""

We plot the 'causality' from x to y ($F_{x \rightarrow y}$) and from y to x
($F_{y \rightarrow x}$ for the first two ROIs and compare to the coherence
between these two time-series:

"""

coh = np.mean(C1.coherence[:, :, freq_idx_C],
              -1)  # Averaging on the last dimension
g1 = np.mean(G.causality_xy[:, :, freq_idx_G], -1)

fig01 = drawmatrix_channels(coh, roi_names, size=[10., 10.], color_anchor=0)
"""

.. image:: fig/granger_fmri_01.png

"""

fig02 = drawmatrix_channels(C2.corrcoef,
                            roi_names,
                            size=[10., 10.],
                            color_anchor=0)
"""

.. image:: fig/granger_fmri_02.png

"""
コード例 #24
0
                    proj=True,
                    picks=picks,
                    baseline=(None, 0),
                    preload=True,
                    reject=dict(grad=4000e-13, eog=150e-6))

# Export to NiTime
epochs_ts = epochs.to_nitime(picks=np.arange(20), collapse=True)

###############################################################################
# Now use nitime's OO-interface to compute coherence between sensors

from nitime.analysis import MTCoherenceAnalyzer
from nitime.viz import drawmatrix_channels
import matplotlib.pyplot as plt

# setup coherency analyzer
C = MTCoherenceAnalyzer(epochs_ts)

# confine analysis to 10 - 20 Hz
freq_idx = np.where((C.frequencies > 10) * (C.frequencies < 30))[0]

# compute average coherence
coh = np.mean(C.coherence[:, :, freq_idx], -1)  # Averaging on last dimension
drawmatrix_channels(coh,
                    epochs.ch_names,
                    color_anchor=0,
                    title='MEG gradiometer coherence')

plt.show()
コード例 #25
0
        numRuns = allROIS.shape[1]

        corr_all[subject] = np.zeros((numRuns, len(rois), len(rois))) * np.nan
        coh_all[subject] = np.zeros((numRuns, len(rois), len(rois))) * np.nan

        # Get roi correlations and coherence
        for runNum in range(allROIS.shape[1]):
            #need to load timeseries by run
            fixTS = ts.TimeSeries(allROIS[:, runNum, :], sampling_interval=TR)
            fixTS.metadata['roi'] = roi_names

            # Get plot and correlations
            C = CorrelationAnalyzer(fixTS)
            fig01 = drawmatrix_channels(C.corrcoef,
                                        roi_names,
                                        size=[10., 10.],
                                        color_anchor=0,
                                        title='Correlation Results Run %i' %
                                        runNum)
            plt.show()
            # Save correlation
            corr_all[subject][runNum] = C.corrcoef

            # Get coherence
            Coh = CoherenceAnalyzer(fixTS)

            Coh.method['NFFT'] = NFFT
            Coh.method['n_overlap'] = n_overlap

            # Get the index for the frequencies inside the ub and lb
            freq_idx = np.where(
                (Coh.frequencies > f_lb) * (Coh.frequencies < f_ub))[0]
コード例 #26
0
ファイル: multi_taper_coh.py プロジェクト: saifrahmed/nitime
"""

We extract the coherence and average over all these frequency bands:

"""

coh = np.mean(coh_mat[:, :, freq_idx], -1)  # Averaging on the last dimension
"""

The next line calls the visualization routine which displays the data

"""

fig01 = drawmatrix_channels(coh,
                            roi_names,
                            size=[10., 10.],
                            color_anchor=0,
                            title='MTM Coherence')
"""

.. image:: fig/multi_taper_coh_01.png

Next we perform the same analysis, using the nitime object oriented interface.

We start by initializing a TimeSeries object with this data and with the
sampling_interval provided above. We set the metadata 'roi' field with the ROI
names.


"""
コード例 #27
0
T.metadata['roi'] = roi_names


"""

First, we examine the correlations between the time-series extracted from
different parts of the brain. The following script extracts the data (using the
draw_matrix function, displaying the correlation matrix with the ROIs labeled.

"""

#Initialize the correlation analyzer
C = CorrelationAnalyzer(T)

#Display the correlation matrix
fig01 = drawmatrix_channels(C.corrcoef, roi_names, size=[10., 10.], color_anchor=0)


"""

.. image:: fig/resting_state_fmri_01.png

Notice that setting the color_anchor input to this function to 0 makes sure
that the center of the color map (here a blue => white => red) is at 0. In this
case, positive values will be displayed as red and negative values in blue.

We notice that the left caudate nucleus (labeled 'lcau') has an interesting
pattern of correlations. It has a high correlation with both the left putamen
('lput', which is located nearby) and also with the right caudate nucleus
('lcau'), which is the homologous region in the other hemisphere. Are these two
correlation values related to each other? The right caudate and left putamen
コード例 #28
0
ファイル: test_viz.py プロジェクト: ilustreous/nitime
def test_drawmatrix_channels():
    fig01 = drawmatrix_channels(C.corrcoef, roi_names, size=[10., 10.], color_anchor=0)
コード例 #29
0
ファイル: fmri1.py プロジェクト: fperez/nitime
#This information (the sampling rate) has to be known in advance:
TR=1.89

#Load the data from the csv file:
data_rec = csv2rec('data/fmri_timeseries.csv')

#Extract information:
roi_names= np.array(data_rec.dtype.names)
n_samples = data_rec.shape[0]


#Make an empty container for the data
data = np.zeros((len(roi_names),n_samples))

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

#Normalize the data:
data = percent_change(data)

#Initialize the time-series from the normalized data:
T = TimeSeries(data,sampling_interval=TR)
T.metadata['roi'] = roi_names 

#Initialize the correlation analyzer
C = CorrelationAnalyzer(T)

#Display the correlation matrix
drawmatrix_channels(C(),roi_names,size=[10.,10.],color_anchor=0)