Ejemplo n.º 1
0
def check_mask(epi_data):
    """
    Create the data mask and check that the volume is reasonable

    Parameters
    ----------
    data: string: path of some input data

    returns
    -------
    mask_array: array of shape nibabel.load(data).get_shape(),
                the binary mask

    """
    mask_array = compute_mask_files(epi_data[0])
    affine = nibabel.load(epi_data[0]).get_affine()
    vol = np.abs(np.linalg.det(affine)) * mask_array.sum() / 1000
    print 'The estimated brain volume is: %f cm^3, should be 1000< <2000' % vol

    return mask_array
Ejemplo n.º 2
0
def load_vol_bold_and_mask(bold_files, mask_file):

    from pyhrf.tools._io import read_volume, discard_bad_data

    # Handle mask
    if not op.exists(mask_file):
        logger.warning('Mask file %s does not exist. Mask is '
                       'computed from BOLD ...', mask_file)

        bold_file = 'subj0_bold_session0.nii.gz'
        # HACK
        if bold_files[0] == pyhrf.get_data_file_name(bold_file):
            max_frac = .99999  # be sure to keep non zero voxels
            connect_component = False  # default BOLD vol has 2 ROIs
        else:
            max_frac = .9
            connect_component = True
        compute_mask_files(bold_files[0], mask_file, False, .4,
                           max_frac, cc=connect_component)
        mask_loaded_from_file = False
    else:
        mask_loaded_from_file = True
        logger.info('Assuming orientation for mask file: ' +
                    string.join(MRI3Daxes, ','))

    logger.info('Read mask from: %s', mask_file)
    mask, mask_meta_obj = read_volume(mask_file)

    if not np.allclose(np.round(mask), mask):
        raise Exception("Mask is not n-ary (%s)" % mask_file)
    mask = np.round(mask).astype(np.int32)

    logger.info('Mask has shape %s\nMask min value: %d\n'
                'Mask max value: %d\nMask has %d parcels',
                str(mask.shape), mask.min(), mask.max(), len(np.unique(mask)))

    if mask.min() == -1:
        mask += 1

    # Load BOLD:
    last_scan = 0
    session_scans = []
    bolds = []
    logger.info('Assuming orientation for BOLD files: ' +
                string.join(MRI4Daxes, ','))

    if type(bold_files[0]) is list:
        bold_files = bold_files[0]

    for bold_file in bold_files:
        if not op.exists(bold_file):
            raise Exception('File not found: ' + bold_file)

        bold, _ = read_volume(bold_file)
        bolds.append(bold)
        session_scans.append(np.arange(last_scan,
                                       last_scan + bold.shape[TIME_AXIS],
                                       dtype=int))
        last_scan += bold.shape[TIME_AXIS]

    bold = np.concatenate(tuple(bolds), axis=TIME_AXIS)

    logger.info('BOLD has shape %s', str(bold.shape))
    discard_bad_data(bold, mask)

    return mask, mask_meta_obj, mask_loaded_from_file, bold, session_scans
Ejemplo n.º 3
0
                          drift_model=drift_model, hfcut=hfcut)

ax = design_matrix.show()
ax.set_position([.05, .25, .9, .65])
ax.set_title('Design matrix')

pylab.savefig(op.join(swd, 'design_matrix.png'))
# design_matrix.write_csv(...)

########################################
# Mask the data
########################################

print 'Computing a brain mask...'
mask_path = op.join(swd, 'mask.nii') 
mask_array = compute_mask_files( data_path, mask_path, False, 0.4, 0.9)

#########################################
# Specify the contrasts
#########################################

# simplest ones
contrasts = {}
contrast_id = conditions
for i in range(len(conditions)):
    contrasts['%s' % conditions[i]]= np.eye(len(design_matrix.names))[2 * i]

# and more complex/ interesting ones
contrasts["audio"] = contrasts["clicDaudio"] + contrasts["clicGaudio"] +\
                     contrasts["calculaudio"] + contrasts["phraseaudio"]
contrasts["video"] = contrasts["clicDvideo"] + contrasts["clicGvideo"] + \
Ejemplo n.º 4
0
        # get the images
        fmri_series = [os.path.join(fmri_dir, '%s_series_%s.nii' %
                                    (subject, session)) for session in sessions]
        if side == 'left':
            fmri_series = [
                os.path.join(fmri_dir, '%s_series_%s_lh_smooth5.gii' %
                             (subject, session)) for session in sessions]
        elif side == 'right':
            fmri_series = [
                os.path.join(fmri_dir, '%s_series_%s_rh_smooth5.gii' %
                             (subject, session)) for session in sessions]

        # compute the mask
        if side == False:
            mean_img = glob.glob(os.path.join(fmri_dir, 'mean*.nii'))[0]
            mask_array = compute_mask_files(mean_img, epi_mask, True,
                                            inf_threshold, sup_threshold)[0]

        # get the contrasts
        n_reg = make_dmtx(frametimes, add_regs=reg_matrix,
                          drift_model=drift_model, hfcut=hfcut).matrix.shape[1]

        contrasts, all_reg = make_contrasts(sessions, n_reg)
        contrast_obj = {}

        for (sess, (session, fmri_data)) in enumerate(zip(
                sessions, fmri_series)):
            # create design matrices
            reg = all_reg[2 * sess: 2 * sess + 2] # fixme
            design_matrix = make_dmtx(
                frametimes, add_regs=reg_matrix, add_reg_names=reg,
                drift_model=drift_model, hfcut=hfcut)
Ejemplo n.º 5
0
def load_vol_bold_and_mask(bold_files, mask_file):

    from pyhrf.tools._io import read_volume, discard_bad_data

    # Handle mask
    if not op.exists(mask_file):
        logger.warning(
            'Mask file %s does not exist. Mask is '
            'computed from BOLD ...', mask_file)

        bold_file = 'subj0_bold_session0.nii.gz'
        # HACK
        if bold_files[0] == pyhrf.get_data_file_name(bold_file):
            max_frac = .99999  # be sure to keep non zero voxels
            connect_component = False  # default BOLD vol has 2 ROIs
        else:
            max_frac = .9
            connect_component = True
        compute_mask_files(bold_files[0],
                           mask_file,
                           False,
                           .4,
                           max_frac,
                           cc=connect_component)
        mask_loaded_from_file = False
    else:
        mask_loaded_from_file = True
        logger.info('Assuming orientation for mask file: ' +
                    string.join(MRI3Daxes, ','))

    logger.info('Read mask from: %s', mask_file)
    mask, mask_meta_obj = read_volume(mask_file)

    if not np.allclose(np.round(mask), mask):
        raise Exception("Mask is not n-ary (%s)" % mask_file)
    mask = np.round(mask).astype(np.int32)

    logger.info(
        'Mask has shape %s\nMask min value: %d\n'
        'Mask max value: %d\nMask has %d parcels', str(mask.shape), mask.min(),
        mask.max(), len(np.unique(mask)))

    if mask.min() == -1:
        mask += 1

    # Load BOLD:
    last_scan = 0
    session_scans = []
    bolds = []
    logger.info('Assuming orientation for BOLD files: ' +
                string.join(MRI4Daxes, ','))

    if type(bold_files[0]) is list:
        bold_files = bold_files[0]

    for bold_file in bold_files:
        if not op.exists(bold_file):
            raise Exception('File not found: ' + bold_file)

        bold, _ = read_volume(bold_file)
        bolds.append(bold)
        session_scans.append(
            np.arange(last_scan, last_scan + bold.shape[TIME_AXIS], dtype=int))
        last_scan += bold.shape[TIME_AXIS]

    bold = np.concatenate(tuple(bolds), axis=TIME_AXIS)

    logger.info('BOLD has shape %s', str(bold.shape))
    discard_bad_data(bold, mask)

    return mask, mask_meta_obj, mask_loaded_from_file, bold, session_scans
Ejemplo n.º 6
0
def plot_cv_tc(epi_data, session_ids, subject_id,
               do_plot=True,
               write_image=True, mask=True, bg_image=False,
               plot_diff=True,
               _output_dir=None,
               cv_tc_plot_outfile=None):
    """ Compute coefficient of variation of the data and plot it

    Parameters
    ----------
    epi_data: list of strings, input fMRI 4D images
    session_ids: list of strings of the same length as epi_data,
                 session indexes (for figures)
    subject_id: string, id of the subject (for figures)
    do_plot: bool, optional,
             should we plot the resulting time course
    write_image: bool, optional,
                 should we write the cv image
    mask: bool or string, optional,
          (string) path of a mask or (bool)  should we mask the data
    bg_image: bool or string, optional,
              (string) pasth of a background image for display or (bool)
              should we compute such an image as the mean across inputs.
              if no, an MNI template is used (works for normalized data)
    """

    if _output_dir is None:
        if not cv_tc_plot_outfile is None:
            _output_dir = os.path.dirname(cv_tc_plot_outfile)
        else:
            _output_dir = tempfile.mkdtemp()

    cv_tc_ = []
    if isinstance(mask, basestring):
        mask_array = nibabel.load(mask).get_data() > 0
    elif mask == True:
        mask_array = compute_mask_files(epi_data[0])
    else:
        mask_array = None
    for (session_id, fmri_file) in zip(session_ids, epi_data):
        nim = do_3Dto4D_merge(fmri_file, output_dir=_output_dir)
        affine = nim.get_affine()
        if len(nim.shape) == 4:
            # get the data
            data = nim.get_data()
        else:
            raise TypeError("Expecting 4D image!")
            pass

        # compute the CV for the session
        cache_dir = os.path.join(_output_dir, "CV")
        if not os.path.exists(cache_dir):
            os.makedirs(cache_dir)
        mem = joblib.Memory(cachedir=cache_dir, verbose=5)
        cv = mem.cache(compute_cv)(data, mask_array=mask_array)

        if write_image:
            # write an image
            nibabel.save(nibabel.Nifti1Image(cv, affine),
                         os.path.join(_output_dir, 'cv_%s.nii' % session_id))
            if bg_image == False:
                try:
                    viz.plot_map(
                        cv, affine, threshold=.01, cmap=viz.cm.cold_hot)
                except IndexError:
                    print traceback.format_exc()
            else:
                if isinstance(bg_image, basestring):
                    _tmp = nibabel.load(bg_image)
                    anat, anat_affine = (
                        _tmp.get_data(),
                        _tmp.get_affine())
                else:
                    anat, anat_affine = data.mean(-1), affine
                try:
                    viz.plot_map(
                        cv, affine, threshold=.01, cmap=viz.cm.cold_hot,
                             anat=anat, anat_affine=anat_affine)
                except IndexError:
                    print traceback.format_exc()
        # compute the time course of cv
        cv_tc_sess = np.median(
            np.sqrt((data[mask_array > 0].T /
                     data[mask_array > 0].mean(-1) - 1) ** 2), 1)

        cv_tc_.append(cv_tc_sess)
    cv_tc = np.concatenate(cv_tc_)

    if do_plot:
        # plot the time course of cv for different subjects
        pl.figure()
        pl.plot(cv_tc, label=subject_id)
        pl.legend()
        pl.xlabel('time(scans)')
        pl.ylabel('Median coefficient of variation')
        pl.axis('tight')

        if not cv_tc_plot_outfile is None:
            pl.savefig(cv_tc_plot_outfile,
                       bbox_inches="tight", dpi=200)

    return cv_tc
Ejemplo n.º 7
0
        elif side == 'right':
            wild_card = '*rh_smooth5.gii' # '*rh.gii' #

        print "Subject : %s, side : %s" % (subject, side)
        # get the images
        fmri_series = [glob.glob(
                os.path.join(fmri_dir, session, wild_card))
                       for session in sessions]

        # warning: glob returns the files in random order
        for f in fmri_series:
            f.sort()

        if side == False:
            # in the volume, compute a mask o fthe brain
            mask_array = compute_mask_files(fmri_series[0], epi_mask, True,
                                            inf_threshold, sup_threshold)[0]

        # Specify the contrasts
        contrasts = make_contrasts(sessions, odd=subject in
                                   ['sujet10', 'sujet12'])

        contrast_obj = {}
        for (sess, (session, fmri_data)) in enumerate(zip(
            sessions, fmri_series)):
            # create design matrices
            reg = all_reg[4 * sess: 4 * sess + 4] # fixme
            design_matrix = make_dmtx(
                frametimes, add_regs=reg_matrix, add_reg_names=reg,
                drift_model=drift_model, hfcut=hf_cut)

            # plot the design matrix
Ejemplo n.º 8
0
Archivo: core.py Proyecto: Solvi/pyhrf
def load_vol_bold_and_mask(bold_files, mask_file):

    # Handle mask
    if not op.exists(mask_file):
        pyhrf.verbose(1,'Mask file %s does not exist. Mask is '\
                          ' computed from BOLD ...' %mask_file)
        bf = 'subj0_bold_session0.nii.gz'
        # HACK
        if bold_files[0] == pyhrf.get_data_file_name(bf):
            max_frac = .99999 #be sure to keep non zero voxels
            cc = 0 # default BOLD vol has 2 ROIs
        else:
            max_frac = .9
            cc = 1
        compute_mask_files(bold_files[0], mask_file, False, .4,
                           max_frac, cc=cc)
        mask_loaded_from_file = False
    else:
        mask_loaded_from_file = True
        pyhrf.verbose(1,'Assuming orientation for mask file: ' + \
                          string.join(MRI3Daxes, ','))

    pyhrf.verbose(2,'Read mask from: %s' %mask_file)
    mask, mask_meta_obj = read_volume(mask_file)

    if not np.allclose(np.round(mask),mask):
        raise Exception("Mask is not n-ary (%s)" %mask_file)
    mask = mask.astype(np.int32)

    pyhrf.verbose(1,'Mask has shape %s' %str(mask.shape))
    pyhrf.verbose(1,'Mask min value: %d' %mask.min())
    pyhrf.verbose(1,'Mask max value: %d' %mask.max())
    mshape = mask.shape
    if mask.min() == -1:
        mask += 1

    #Load BOLD:
    lastScan = 0
    sessionScans = []
    bolds = []
    pyhrf.verbose(1,'Assuming orientation for BOLD files: ' + \
                      string.join(MRI4Daxes, ','))

    #print 'type of bold_files[0]:', type(bold_files[0])
    #print 'bold_files:', bold_files
    if type(bold_files[0]) is list:
        bold_files = bold_files[0]

    for bold_file in bold_files:
        if not op.exists(bold_file):
            raise Exception('File not found: ' + bold_file)

        b, bold_meta = read_volume(bold_file)
        bolds.append(b)
        sessionScans.append(np.arange(lastScan,
                                      lastScan+b.shape[TIME_AXIS],
                                      dtype=int))
        lastScan += b.shape[TIME_AXIS]

    bold = np.concatenate(tuple(bolds), axis=TIME_AXIS)

    pyhrf.verbose(1,'BOLD has shape %s' %str(bold.shape))
    discard_bad_data(bold, mask)

    # #HACK
    # if mask_file != DEFAULT_MASK_VOL_FILE:
    #     write_volume(mask,'./treated_mask.nii')
    #     sys.exit(0)


    return mask, mask_meta_obj, mask_loaded_from_file, bold, sessionScans
Ejemplo n.º 9
0
                    fmri_dir,
                    '%s_series_%s_lh_smooth5.gii' % (subject, session))
                for session in sessions
            ]
        elif side == 'right':
            fmri_series = [
                os.path.join(
                    fmri_dir,
                    '%s_series_%s_rh_smooth5.gii' % (subject, session))
                for session in sessions
            ]

        # compute the mask
        if side == False:
            mean_img = glob.glob(os.path.join(fmri_dir, 'mean*.nii'))[0]
            mask_array = compute_mask_files(mean_img, epi_mask, True,
                                            inf_threshold, sup_threshold)[0]

        # get the contrasts
        n_reg = make_dmtx(frametimes,
                          add_regs=reg_matrix,
                          drift_model=drift_model,
                          hfcut=hfcut).matrix.shape[1]

        contrasts, all_reg = make_contrasts(sessions, n_reg)
        contrast_obj = {}

        for (sess, (session,
                    fmri_data)) in enumerate(zip(sessions, fmri_series)):
            # create design matrices
            reg = all_reg[2 * sess:2 * sess + 2]  # fixme
            design_matrix = make_dmtx(frametimes,
Ejemplo n.º 10
0
                          hfcut=hfcut)

ax = design_matrix.show()
ax.set_position([.05, .25, .9, .65])
ax.set_title('Design matrix')

plt.savefig(path.join(write_dir, 'design_matrix.png'))
# design_matrix.write_csv(...)

########################################
# Mask the data
########################################

print 'Computing a brain mask...'
mask_path = path.join(write_dir, 'mask.nii')
mask_array = compute_mask_files(data_path, mask_path, False, 0.4, 0.9)

#########################################
# Specify the contrasts
#########################################

# simplest ones
contrasts = {}
n_columns = len(design_matrix.names)
for i in range(paradigm.n_conditions):
    contrasts['%s' % design_matrix.names[2 * i]] = np.eye(n_columns)[2 * i]

# and more complex/ interesting ones
contrasts["audio"] = contrasts["clicDaudio"] + contrasts["clicGaudio"] +\
                     contrasts["calculaudio"] + contrasts["phraseaudio"]
contrasts["video"] = contrasts["clicDvideo"] + contrasts["clicGvideo"] + \