Esempio n. 1
0
def test_dics_connectivity():
    """ Test dics_connectivity function"""
    source_vertno1 = 146374  # Somewhere on the frontal lobe
    source_vertno2 = 33830
    # Load restricted forwards
    fwd, fwd_fixed = _load_restricted_forward(source_vertno1, source_vertno2)
    csd = _simulate_data(fwd_fixed, source_vertno1, source_vertno2)
    # Take subset of pairs to make calculations faster
    pairs = all_to_all_connectivity_pairs(fwd, 0.05)

    # CSD not averaged
    with pytest.raises(ValueError):
        con = dics_connectivity(pairs, fwd, csd)
    csd = csd.mean()
    # Fixed forward
    with pytest.raises(ValueError):
        dics_connectivity(pairs, fwd_fixed, csd)
    # Incorrect pairs
    with pytest.raises(ValueError):
        dics_connectivity([[0, 1, 3], [2, 4]], fwd, csd)

    con = dics_connectivity(pairs, fwd, csd, reg=1)
    max_ind = np.argmax(con.data)
    vertices = np.concatenate(con.vertices)
    assert len(con.data) == len(pairs[0])
    assert con.n_sources == fwd['nsource']
    assert vertices[pairs[0][max_ind]] == source_vertno1
    assert vertices[pairs[1][max_ind]] == source_vertno2
    # Check result is the same with tangential
    fwd_tan = forward_to_tangential(fwd)
    con2 = dics_connectivity(pairs, fwd_tan, csd, reg=1)
    assert_array_equal(con2.data, con.data)
Esempio n. 2
0
def test_forward_to_tangential(fwd):
    # Test tangential forward solution
    fwd_tan = forward_to_tangential(fwd)
    # Check shapes
    assert fwd_tan['sol']['ncol'] == fwd['nsource'] * 2
    assert fwd_tan['sol']['data'].shape == (fwd['sol']['nrow'],
                                            fwd['nsource'] * 2)
    assert fwd_tan['source_nn'].shape == (fwd['nsource'] * 2, 3)

    # Forward operator already tangential
    with pytest.raises(ValueError):
        forward_to_tangential(fwd_tan)
    # Fixed forward operator
    fwd_fixed = mne.convert_forward_solution(fwd,
                                             force_fixed=True,
                                             use_cps=True)
    with pytest.raises(ValueError):
        forward_to_tangential(fwd_fixed)
Esempio n. 3
0
def test_restrict_forward_to_vertices(fwd):
    fwd_r = restrict_forward_to_vertices(fwd, ([1170, 1609], [2159]))
    assert_array_equal(fwd_r['src'][0]['vertno'], [1170, 1609])
    assert_array_equal(fwd_r['src'][1]['vertno'], [2159])
    assert fwd_r['sol']['ncol'] == 3 * 3  # Free orientation
    assert fwd_r['sol']['nrow'] == fwd['sol']['nrow']
    assert fwd_r['sol']['data'].shape == (fwd['sol']['nrow'], 3 * 3)

    fwd_r = restrict_forward_to_vertices(fwd, ([], []))
    assert_array_equal(fwd_r['src'][0]['vertno'], [])
    assert_array_equal(fwd_r['src'][1]['vertno'], [])

    # Test fixed orientation forward solution
    fwd_fixed = mne.forward.convert_forward_solution(fwd,
                                                     force_fixed=True,
                                                     use_cps=True)
    fwd_r = restrict_forward_to_vertices(fwd_fixed, ([1170, 1609], [2159]))
    assert fwd_r['sol']['ncol'] == 3
    assert fwd_r['sol']['data'].shape == (fwd['sol']['nrow'], 3)

    # Test tangential forward solution
    fwd_tan = forward_to_tangential(fwd)
    fwd_r = restrict_forward_to_vertices(fwd_tan, ([1170, 1609], [2159]))
    assert fwd_r['sol']['ncol'] == 3 * 2
    assert fwd_r['sol']['data'].shape == (fwd['sol']['nrow'], 3 * 2)

    # Vertices not present in src
    with pytest.raises(IndexError):
        restrict_forward_to_vertices(fwd, ([30, 1609], [2159]))

    # Use indices
    fwd_r = restrict_forward_to_vertices(fwd, [0, 1, 3732])
    assert fwd_r['sol']['ncol'] == 3 * 3
    assert_array_equal(fwd_r['src'][0]['vertno'], fwd['src'][0]['vertno'][:2])
    assert_array_equal(fwd_r['src'][1]['vertno'], fwd['src'][1]['vertno'][:1])

    # Test in place operation
    restrict_forward_to_vertices(fwd, ([1170, 1609], [2159]), copy=False)
    assert_array_equal(fwd['src'][0]['vertno'], [1170, 1609])
    assert_array_equal(fwd['src'][1]['vertno'], [2159])
Esempio n. 4
0
import conpy, mne  # Import required Python modules

# Define source space on average brain, morph to subject
src_avg = mne.setup_source_space('fsaverage', spacing='ico4')
src_sub = mne.morph_source_spaces(src_avg, subject='sub002')

# Discard deep sources
info = mne.io.read_info('sub002-epo.fif')  # Read information about the sensors
verts = conpy.select_vertices_in_sensor_range(src_sub, dist=0.07, info=info)
src_sub = conpy.restrict_src_to_vertices(src_sub, verts)

# Create a one-layer BEM model
bem_model = mne.make_bem_model('sub002', ico=4, conductivity=(0.3, ))
bem = mne.make_bem_solution(bem_model)

# Make the forward model
trans = 'sub002-trans.fif'  # File containing the MRI<->Head transformation
fwd = mne.make_forward_solution(info, trans, src_sub, bem, meg=True, eeg=False)

# Only retain orientations tangential to a sphere approximation of the head
fwd = conpy.forward_to_tangential(fwd)
Esempio n. 5
0
bas_conds = ["rest", "ton"]

# load the fsaverage ico4 source space
fs_src = mne.read_source_spaces("{}fsaverage_ico4-src.fif".format(meg_dir))

# now calculate connectivity for each subject
for meg, mri in sub_dict.items():
    print("Doing Connectivities for Subject: ", meg)

    # for the experimental conditions:
    print("Running Experimental Conditions")
    fwd_r = mne.read_forward_solution(
        "{dir}nc_{meg}_from-fs_ico4_exp-r-fwd.fif".format(dir=meg_dir,
                                                          meg=meg))
    # convert the forward model to one that defines two orthogonal dipoles at each source, that are tangential to a sphere
    fwd_tan = conpy.forward_to_tangential(fwd_r)
    # get pairs for connectivity calculation
    pairs = np.load("{}NEMO_ico4_connectivity_pairs.npy".format(meg_dir))
    # pairs are defined in fsaverage space, map them to the source space of the current subject
    fsaverage_to_subj = conpy.utils.get_morph_src_mapping(
        fs_src, fwd_tan['src'], indices=True, subjects_dir=mri_dir)[0]
    pairs = [[fsaverage_to_subj[v] for v in pairs[0]],
             [fsaverage_to_subj[v] for v in pairs[1]]]
    for cond in exp_conds:
        print("Calculations for Condition: ", cond)
        for freq, vals in freqs.items():
            print("Calculations for Frequency: ", freq)
            csd = read_csd("{dir}nc_{meg}-csd_{cond}_{freq}.h5".format(
                dir=meg_dir, meg=meg, cond=cond, freq=freq))
            csd = csd.mean()
            csd = pick_channels_csd(csd, fwd_tan['info']['ch_names'])
Esempio n. 6
0
# One-to-all connectivity
# -----------------------
# Let's try to estimate coherence between the two sources. One way to do it is
# to compute "one-to-all" connectivity. We pick one point on the cortex where
# we know (or assume) that there is an active source. Then, we compute
# coherence between all points on the cortex and this reference point to see
# which parts of the cortex have a signal that is coherent with our reference
# source. Hopefully, we'll find the other source.

# Our reference point is the point with maximum power (roughly the location of
# our second simulated source signal).
ref_point = np.argmax(power.data)

# Compute one-to-all coherence between each point and the reference point.
pairs = one_to_all_connectivity_pairs(fwd, ref_point)
fwd_tan = forward_to_tangential(fwd)
con = dics_connectivity(pairs, fwd_tan, csd_signal, reg=1)

###############################################################################
# To plot the result, we transform the :class:`conpy.VertexConnectivity` object
# to an :class:`mne.SourceEstimate` object, where the "signal" at each point is
# the coherence value.
one_to_all = con.make_stc('sum', weight_by_degree=True)

# Plot the coherence values on the cortex
brain = one_to_all.plot('sample',
                        subjects_dir=subjects_dir,
                        hemi='both',
                        figure=3,
                        size=400)
Esempio n. 7
0
import conpy, mne  # Import required Python modules

# Read and convert a forward model to one that defines two orthogonal dipoles
# at each source, that are tangential to a sphere.
fwd = mne.read_forward_solution('sub002-fwd.fif')  # Read forward model
fwd_tan = conpy.forward_to_tangential(fwd_r)  # Convert to tangential model

# Pairs for which to compute connectivity. Use a distance threshold of 4 cm.
pairs = conpy.all_to_all_connectivity_pairs(fwd_tan, min_dist=0.04)

# Load CSD matrix
csd = conpy.read_csd('sub002-csd-face.h5')  # Read CSD for 'face' condition
csd = csd.mean(fmin=31, fmax=40)  # Obtain CSD for frequency band 31-40 Hz.

# Compute source connectivity using DICS. Try 50 orientations for each source
# point to find the orientation that maximizes coherence.
con = conpy.dics_connectivity(pairs, fwd_tan, csd, reg=0.05, n_angles=50)