예제 #1
0
def get_nii_data_from_folder(folder, use_verbs=False):

    # inside the folder, search only for betasXX.nii files
    beta_map_regex = r'betas(\d{2}).nii$'
    beta_map_filter = re_filter(beta_map_regex)

    beta_files = filter(beta_map_filter, glob.glob(os.path.join(folder, "*")))

    beta_files = sorted(beta_files)

    # get mask file. It must be in same folder
    mask_file = os.path.join(folder, "mask.nii")
    #new_folder = '/volatile/thirion/mygit/worddecoding/brain_reading/fmri/vl100318/fmri/' ## ugly
    #mask_file = os.path.join(new_folder, "HO_epi.nii")

    masker = NiftiMasker(mask_file, smooth=3.)

    masker.fit(beta_files[0])

    masked_nii_data = [masker.transform(beta_file) for beta_file in beta_files]

    # this returns a 3D array with dimensions
    # (sessions, trials, voxels)
    masked_nii_data = np.array(masked_nii_data)

    # return only the useful values: The last 6 are
    # drift regressors and are thrown away

    masked_nii_data = masked_nii_data[:, :-6, :]

    if use_verbs:
        return masked_nii_data
    else:
        # In case we do not want the verbs (default case)
        # we need to remove the lines corresponding to verbs

        masked_nii_data = masked_nii_data.reshape(-1,
                                                  masked_nii_data.shape[-1])
        masked_nii_data = masked_nii_data[:, masked_nii_data.std(0) > 0]
        _, verbs, _, _, _ = parse_stimuli()

        return masked_nii_data[verbs == False]
예제 #2
0
Simple example of NiftiMasker use
==================================

Here is a simple example of automatic mask computation using the nifti masker.
The mask is computed and visualized.
"""

### Load nyu_rest dataset #####################################################

from nisl import datasets
from nisl.io import NiftiMasker
dataset = datasets.fetch_nyu_rest(n_subjects=1)

### Compute the mask ##########################################################

nifti_masker = NiftiMasker(memory="nisl_cache", memory_level=2)
nifti_masker.fit(dataset.func[0])
mask = nifti_masker.mask_img_.get_data()

### Visualize the mask ########################################################
import pylab as pl
import numpy as np
import nibabel
pl.figure()
pl.axis('off')
pl.imshow(np.rot90(nibabel.load(dataset.func[0]).get_data()[..., 20, 0]),
          interpolation='nearest', cmap=pl.cm.gray)
ma = np.ma.masked_equal(mask, False)
pl.imshow(np.rot90(ma[..., 20]), interpolation='nearest', cmap=pl.cm.autumn,
          alpha=0.5)
pl.title("Mask")
예제 #3
0
Simple example of NiftiMasker use
==================================

Here is a simple example of automatic mask computation using the nifti masker.
The mask is computed and visualized.
"""

### Load nyu_rest dataset #####################################################

from nisl import datasets
from nisl.io import NiftiMasker
dataset = datasets.fetch_nyu_rest(n_subjects=1)

### Compute the mask ##########################################################

nifti_masker = NiftiMasker(transpose=True,
                           memory="nisl_cache", memory_level=2)
nifti_masker.fit(dataset.func[0])
mask = nifti_masker.mask_img_.get_data()

### Visualize the mask ########################################################
import pylab as pl
import numpy as np
import nibabel
pl.figure()
pl.axis('off')
pl.imshow(np.rot90(nibabel.load(dataset.func[0]).get_data()[..., 20, 0]),
          interpolation='nearest', cmap=pl.cm.gray)
ma = np.ma.masked_equal(mask, False)
pl.imshow(np.rot90(ma[..., 20]), interpolation='nearest', cmap=pl.cm.autumn,
          alpha=0.5)
pl.title("Mask")
예제 #4
0
### Restrict to faces and houses ##############################################

# Keep only data corresponding to face or houses
condition_mask = np.logical_or(conditions == 'face', conditions == 'house')
X = fmri_data[..., condition_mask]
y = y[condition_mask]
session = session[condition_mask]
conditions = conditions[condition_mask]

# We have 2 conditions
n_conditions = np.size(np.unique(y))

### Loading step ##############################################################
from nisl.io import NiftiMasker
from nibabel import Nifti1Image
nifti_masker = NiftiMasker(mask=mask, detrend=True, sessions=session)
niimg = Nifti1Image(X, affine)
X = nifti_masker.fit_transform(niimg)

### Prediction function #######################################################

### Define the prediction function to be used.
# Here we use a Support Vector Classification, with a linear kernel and C=1
from sklearn.svm import SVC
clf = SVC(kernel='linear', C=1.)

### Dimension reduction #######################################################

from sklearn.feature_selection import SelectKBest, f_classif

### Define the dimension reduction to be used.
예제 #5
0
# For compatibility with numpy 1.3 and scikit-learn 0.12
# "return_inverse" option appeared in numpy 1.4, scikit-learn >= 0.14 supports
# text labels.
# With scikit-learn >= 0.14, replace this line by: target = labels
_, target = sklearn.utils.fixes.unique(labels, return_inverse=True)

### Remove resting state condition ############################################

no_rest_indices = (labels != 'rest')
target = target[no_rest_indices]

### Load the mask #############################################################

from nisl.io import NiftiMasker
nifti_masker = NiftiMasker(mask=dataset.mask_vt[0])

# We give to the nifti_masker a filename, and retrieve a 2D array ready
# for machine learning with scikit-learn
fmri_masked = nifti_masker.fit_transform(dataset.func[0])

### Prediction function #######################################################

# First, we remove rest condition
fmri_masked = fmri_masked[no_rest_indices]

# Here we use a Support Vector Classification, with a linear kernel and C=1
from sklearn.svm import SVC
svc = SVC(kernel='linear', C=1.)

# And we run it
# Keep only data corresponding to faces or houses
condition_mask = np.logical_or(conditions == 'face', conditions == 'house')
X = fmri_data[..., condition_mask]
y = y[condition_mask]
session = session[condition_mask]
conditions = conditions[condition_mask]

# We have 2 conditions
n_conditions = np.size(np.unique(y))

### Loading step ##############################################################
from nisl.io import NiftiMasker
from nibabel import Nifti1Image
nifti_masker = NiftiMasker(mask=mask,
                           sessions=session,
                           smooth=4,
                           memory="nisl_cache",
                           memory_level=1)
niimg = Nifti1Image(X, affine)
X = nifti_masker.fit_transform(niimg)

### Prediction function #######################################################

### Define the prediction function to be used.
# Here we use a Support Vector Classification, with a linear kernel and C=1
from sklearn.svm import SVC
clf = SVC(kernel='linear', C=1.)

### Dimension reduction #######################################################

from sklearn.feature_selection import SelectKBest, f_classif
예제 #7
0
images by mean on the parcellation.

This parcellation may be useful in a supervised learning, see for
instance: `A supervised clustering approach for fMRI-based inference of
brain states <http://hal.inria.fr/inria-00589201>`_, Michel et al,
Pattern Recognition 2011.

"""

### Load nyu_rest dataset #####################################################

from nisl import datasets
from nisl.io import NiftiMasker

dataset = datasets.fetch_nyu_rest(n_subjects=1)
nifti_masker = NiftiMasker()
fmri_masked = nifti_masker.fit_transform(dataset.func[0])
mask = nifti_masker.mask_.get_data()

### Ward ######################################################################

# Compute connectivity matrix: which voxel is connected to which
from sklearn.feature_extraction import image

shape = mask.shape
connectivity = image.grid_to_graph(n_x=shape[0],
                                   n_y=shape[1],
                                   n_z=shape[2],
                                   mask=mask)

# Computing the ward for the first time, this is long...
# Build the mean image because we have no anatomic data
mean_img = fmri_data.mean(axis=-1)

### Restrict to faces and houses ##############################################
condition_mask = np.logical_or(conditions == 'face', conditions == 'house')
X = fmri_data[..., condition_mask]
y = y[condition_mask]
session = session[condition_mask]
conditions = conditions[condition_mask]

### Loading step ##############################################################
from nisl.io import NiftiMasker
from nibabel import Nifti1Image

nifti_masker = NiftiMasker(mask=mask,
                           sessions=session,
                           memory='nisl_cache',
                           memory_level=1)
niimg = Nifti1Image(X, affine)
X_masked = nifti_masker.fit(niimg).transform(niimg)
#X_preprocessed = nifti_masker.inverse_transform(X_masked).get_data()
#X_preprocessed = np.rollaxis(X_preprocessed, axis=-1)
mask = nifti_masker.mask_img_.get_data().astype(np.bool)

### Prepare the masks #########################################################
# Here we will use several masks :
# * mask is the originalmask
# * process_mask is a subset of mask, it contains voxels that should be
#   processed (we only keep the slice z = 26 and the back of the brain to speed
#   up computation)
process_mask = mask.copy()
process_mask[..., 38:] = False