コード例 #1
0
ファイル: test_coherence.py プロジェクト: Raniac/NEURO-LEARN
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 _fit(ts_set1, ts_set2, lb, ub, **kwargs):
        import nitime.analysis as nta

        fft_par = kwargs.pop('NFFT', None)
        if fft_par is not None:
            analyzer = nta.SeedCoherenceAnalyzer(ts_set1,
                                                 ts_set2,
                                                 lb=lb,
                                                 ub=ub,
                                                 method={'NFFT': fft_par})
        else:
            analyzer = nta.SeedCoherenceAnalyzer(ts_set1,
                                                 ts_set2,
                                                 lb=lb,
                                                 ub=ub)

        n_seeds = ts_set1.data.shape[0] if ts_set1.data.ndim > 1 else 1
        if n_seeds == 1:
            coh = np.mean(analyzer.coherence, -1)
        else:
            coh = []
            for seed in range(n_seeds):
                # Averaging on the last dimension
                coh.append(np.mean(analyzer.coherence[seed], -1))

        return coh
コード例 #3
0
ファイル: test_coherence.py プロジェクト: Raniac/NEURO-LEARN
def test_SeedCoherenceAnalyzer_same_Fs():
    """

    Providing two time-series with different sampling rates throws an error

    """

    Fs1 = np.pi
    Fs2 = 2 * np.pi
    t = np.arange(256)

    T1 = ts.TimeSeries(np.random.rand(t.shape[-1]),
                       sampling_rate=Fs1)

    T2 = ts.TimeSeries(np.random.rand(t.shape[-1]),
                       sampling_rate=Fs2)
    with pytest.raises(ValueError) as e_info:
        nta.SeedCoherenceAnalyzer(T1, T2)
コード例 #4
0
volume_shape = fmri_data.shape[:-1]

coords = list(np.ndindex(volume_shape))

n_seeds = 3

seeds = np.random.randint(0, len(coords), n_seeds)
coords_seeds = np.array(coords)[seeds].T

coords_target = np.array(coords).T

time_series_seed = io.time_series_from_file(fmri_file, coords_seeds, TR=TR, normalize='percent', filter=dict(lb=f_lb, ub=f_ub, method='boxcar'))

time_series_target = io.time_series_from_file(fmri_file, coords_target, TR=TR, normalize='percent',filter=dict(lb=f_lb, ub=f_ub, method='boxcar'))

A = nta.SeedCoherenceAnalyzer(time_series_seed, time_series_target, method=dict(NFFT=20))

B = nta.SeedCorrelationAnalyzer(time_series_seed, time_series_target)

freq_idx = np.where((A.frequencies > f_lb) * (A.frequencies < f_ub))[0]

cor = []
coh = []
for this_seed in range(n_seeds):
  coh.append(np.mean(A.coherence[this_seed][:, freq_idx], -1))  
  cor.append(B.corrcoef[this_seed])

coords_indices = list(coords_target)

vol_coh = []
vol_cor = []
コード例 #5
0
    print '\n', nan_targets.sum(), 'voxels with nan values ... removing'
    target_ts[i_target] = np.mean(target_data[~nan_targets,:],0) # take average across voxels

target_T = ntts.TimeSeries(target_ts, sampling_interval=TR)
fig_target_tseries = viz.plot_tseries(target_T)
plt.title('target tseries, {}'.format(fmri_file))

target_Cor = nta.CorrelationAnalyzer(target_T)
fig_target_cor = viz.drawmatrix_channels(target_Cor.corrcoef, target_rois, color_anchor=0)
plt.title('correlation, {}'.format(fmri_file))

# correlation analyzer
seed_target_Cor = nta.SeedCorrelationAnalyzer(seed_T, target_T)

# coherence analyzer
seed_target_Coh = nta.SeedCoherenceAnalyzer(seed_T, target_T,
            method=dict(NFFT=nfft))

# select frequency band
freq_idx = np.where((seed_target_Coh.frequencies > f_lb) * (seed_target_Coh.frequencies < f_ub))[0]

# extract correlation and coherence values
print 'Calculating correlation and coherence'
cor = seed_target_Cor.corrcoef
coh = np.mean(seed_target_Coh.coherence[:, :, freq_idx], -1)

# show correlation matrix
visualize.display_matrix(cor, 
    xlabels=target_rois, ylabels=seed_rois, cmap=plt.cm.RdBu_r,color_anchor=0)
fig_cor = plt.gcf()
plt.title('correlation, {}'.format(fmri_file), y=1.25)
コード例 #6
0
def seed_coherence_timeseries(seed_ts,
                              target_ts,
                              f_ub,
                              f_lb,
                              method=dict(NFFT=32)):
    conn_analyzer = nta.SeedCoherenceAnalyzer(seed_ts,
                                              target_ts,
                                              method=method)
    freq_idx = np.where((conn_analyzer.frequencies > f_lb) *
                        (conn_analyzer.frequencies < f_ub))[0]
    logger.debug(
        f"Seed timeseries has shape: {seed_ts.shape}\nLooking at freq bins centered on: {conn_analyzer.frequencies[freq_idx]}"
    )
    # mean coherence across voxels in each freq bin
    mean_coh = np.mean(conn_analyzer.coherence, axis=0)
    # mean coherence across voxels in freq bins of interest
    mean_coh_bandpass = np.mean(mean_coh[freq_idx])
    # coherence in freq band of interest for each voxel
    coh_by_voxel = np.mean(conn_analyzer.coherence[:, freq_idx], axis=1)
    phase_by_voxel = np.mean(conn_analyzer.relative_phases[:, freq_idx],
                             axis=1)

    # plots of interest
    fig, ax = plt.subplots(3, figsize=(10, 12))
    ax[0].set_title(
        "Mean coherence with seed across voxels at different frequencies")
    if len(seed_ts.shape) > 1:
        ax[0].plot(conn_analyzer.frequencies, np.mean(mean_coh, axis=0))
    else:
        ax[0].plot(conn_analyzer.frequencies, mean_coh)
    ax[0].axvline(x=f_lb)
    ax[0].axvline(x=f_ub)
    ax[0].set_xlabel("Frequency (Hz)")
    ax[0].set_ylabel("Coherence")

    # ax[1].set_title("Coherence of each voxel with seed at different frequencies")
    # for i in range(conn_analyzer.coherence.shape[0]):
    #     ax[1].plot(conn_analyzer.frequencies, conn_analyzer.coherence[i, :])
    # ax[1].axvline(x=f_lb)
    # ax[1].axvline(x=f_ub)
    # ax[1].set_xlabel("Frequency (Hz)")
    # ax[1].set_ylabel("Coherence")

    ax[1].set_title(
        f"Histogram of voxel coherence values within band {f_lb} < f < {f_ub} (N={coh_by_voxel.shape[0]})"
    )
    ax[1].hist(coh_by_voxel)
    ax[1].set_xlabel("Coherence")
    ax[1].set_ylabel("# voxels")

    ax[2].set_title(
        f"Histogram of voxel phase values within band {f_lb} < f < {f_ub} (N={coh_by_voxel.shape[0]})"
    )
    ax[2].hist(phase_by_voxel)
    ax[2].set_xlabel("Relative phase")
    ax[2].set_ylabel("# voxels")

    plt.subplots_adjust(hspace=.3)
    plt.show()
    plt.close('all')
    logger.debug((
        f"seed_ts: {seed_ts.data.shape}\n"
        f"target_ts: {target_ts.data.shape}\n{conn_analyzer.coherence.shape}\n{conn_analyzer.relative_phases.shape},"
        f"{mean_coh.shape}, {mean_coh_bandpass.shape}, {coh_by_voxel.shape}"))
    return conn_analyzer, (coh_by_voxel, phase_by_voxel)