Exemple #1
0
def test_nifti_maps_masker_report_displayed_maps_errors(
        niftimapsmasker_inputs, displayed_maps):
    """Tests that a TypeError is raised when the argument `displayed_maps`
    of `generate_report()` is not valid.
    """
    masker = NiftiMapsMasker(**niftimapsmasker_inputs)
    masker.fit()
    with pytest.raises(TypeError, match=("Parameter ``displayed_maps``")):
        masker.generate_report(displayed_maps)
Exemple #2
0
def test_nifti_maps_masker_report_image_in_fit(niftimapsmasker_inputs):
    """"""
    masker = NiftiMapsMasker(**niftimapsmasker_inputs)
    image, _ = generate_random_img((13, 11, 12), affine=np.eye(4), length=3)
    masker.fit(image)
    html = masker.generate_report(2)
    assert masker._report_content['report_id'] == 0
    assert masker._report_content['number_of_maps'] == 9
    assert masker._report_content['warning_message'] is None
    assert html.body.count("<img") == 2
Exemple #3
0
def test_nifti_maps_masker_report_maps_number_errors(niftimapsmasker_inputs,
                                                     displayed_maps):
    """Tests that a ValueError is raised when the argument `displayed_maps`
    contains invalid map numbers.
    """
    masker = NiftiMapsMasker(**niftimapsmasker_inputs)
    masker.fit()
    with pytest.raises(ValueError,
                       match="Report cannot display the following maps"):
        masker.generate_report(displayed_maps)
Exemple #4
0
def test_nifti_maps_masker_report_list_and_arrays_maps_number(
        niftimapsmasker_inputs, displayed_maps):
    """Tests report generation for NiftiMapsMasker with displayed_maps
    passed as a list of a Numpy arrays.
    """
    masker = NiftiMapsMasker(**niftimapsmasker_inputs)
    masker.fit()
    html = masker.generate_report(displayed_maps)
    assert masker._report_content['report_id'] == 0
    assert masker._report_content['number_of_maps'] == 9
    assert (masker._report_content['displayed_maps'] == list(displayed_maps))
    msg = ("No image provided to fit in NiftiMapsMasker. "
           "Plotting only spatial maps for reporting.")
    assert masker._report_content['warning_message'] == msg
    assert html.body.count("<img") == len(displayed_maps)
Exemple #5
0
def test_nifti_maps_masker_report_integer_and_all_displayed_maps(
        niftimapsmasker_inputs, displayed_maps):
    """Tests NiftiMapsMasker reporting with no image provided to fit
    and displayed_maps provided as an integer or as 'all'.
    """
    masker = NiftiMapsMasker(**niftimapsmasker_inputs)
    masker.fit()
    expected_n_maps = 9 if displayed_maps == 'all' else min(9, displayed_maps)
    if displayed_maps != 'all' and displayed_maps > 9:
        with pytest.warns(UserWarning, match="masker only has 9 maps."):
            html = masker.generate_report(displayed_maps)
    else:
        html = masker.generate_report(displayed_maps)
    assert masker._report_content['report_id'] == 0
    assert masker._report_content['number_of_maps'] == 9
    assert (masker._report_content['displayed_maps'] == list(
        range(expected_n_maps)))
    msg = ("No image provided to fit in NiftiMapsMasker. "
           "Plotting only spatial maps for reporting.")
    assert masker._report_content['warning_message'] == msg
    assert html.body.count("<img") == expected_n_maps
Exemple #6
0
def get_data(subj, mask, sessions=None, dtype='jacobian'):
    """
    Parameters
    ----------
    subj : (N,) list of img_like
    mask : Niimg_like
    sessions : list of str


    Returns
    -------
    data : (N x M) np.ndarray
        Data extracted from ``imgs``, where ``M`` is the number of parcels in
        ``mask``
    """

    # check mask is correct
    if not isinstance(mask, BaseMasker):
        if not isinstance(mask, str):
            raise ValueError('Mask must be a mask object or filepath.')
        if 'probabilistic' in mask:
            mask = NiftiMapsMasker(mask, resampling_target='maps')
        else:
            mask = NiftiLabelsMasker(mask, resampling_target='labels')

    # only fit mask if it hasn't been fitted to save time
    if not hasattr(mask, 'maps_img_'):
        mask = mask.fit()

    # get images for supplied sessions (or all images)
    subj_dir = pjoin(DERIV_DIR, subj)
    if sessions is not None:
        imgs = list(
            itertools.chain.from_iterable(
                [glob.glob(pjoin(subj_dir, f'*_ses-{ses}_*_{dtype}.nii.gz'))
                 for ses in sorted(sessions)]
            )
        )
    else:
        imgs = sorted(glob.glob(pjoin(subj_dir, '*{dtype}.nii.gz')))

    # extract subject / session information from data (BIDS format)
    demo = np.row_stack([REGEX.findall(i) for i in imgs])
    # fit mask to data and stack across sessions
    data = np.row_stack([mask.transform(check_niimg(img, atleast_4d=True))
                         for img in imgs])
    return data, demo
Exemple #7
0
    print('% rs images: %.2f GB' % (cur_shape[-1], size_in_GB))

    ###############################################################################
    # dump network projections
    ###############################################################################

    # retrieve network projections
    from nilearn import datasets as ds
    smith_pkg = ds.fetch_atlas_smith_2009()
    icas_path = smith_pkg['rsn20']

    from nilearn.input_data import NiftiMapsMasker
    nmm = NiftiMapsMasker(
        mask_img=mask_file, maps_img=icas_path, resampling_target='mask',
        standardize=True, detrend=True)
    nmm.fit()
    nmm.maps_img_.to_filename('dbg_ica_maps.nii.gz')

    FS_netproj = nmm.transform(all_sub_rs_maps)
    np.save('%i_nets_timeseries' % sub_id, FS_netproj)

    # compute network sparse inverse covariance
    from sklearn.covariance import GraphLassoCV
    from nilearn.image import index_img
    from nilearn import plotting

    try:
        gsc_nets = GraphLassoCV(verbose=2, alphas=20)
        gsc_nets.fit(FS_netproj)

        np.save('%i_nets_cov' % sub_id, gsc_nets.covariance_)
Exemple #8
0
# Loading atlas data stored in 'labels'
labels = atlas['labels']

# Load the functional datasets
data = datasets.fetch_development_fmri(n_subjects=1)

print('First subject resting-state nifti image (4D) is located at: %s' %
      data.func[0])

############################################################################
# Extract the time series
# ------------------------
from nilearn.input_data import NiftiMapsMasker
masker = NiftiMapsMasker(maps_img=atlas_filename, standardize=True,
                         memory='nilearn_cache', verbose=5)
masker.fit(data.func[0])
time_series = masker.transform(data.func[0],
                               confounds=data.confounds)

############################################################################
# We can generate an HTML report and visualize the components of the
# :class:`~nilearn.input_data.NiftiMapsMasker`.
# You can pass the indices of the spatial maps you want to include in the
# report in the order you want them to appear.
# Here, we only include maps 2, 6, 7, 16, and 21 in the report:
report = masker.generate_report(displayed_maps=[2, 6, 7, 16, 21])
report

############################################################################
# `time_series` is now a 2D matrix, of shape (number of time points x
# number of regions)
Exemple #9
0
            map(
                lambda subject_pref: '_session_id_' + str(session) +
                subject_pref, subjects_pref)), session_list))
#flattened all filenames
input_dirs = list(
    map(
        lambda session: list(map(lambda subj: op.join(data_dir, subj), session)
                             ), sessions_subjects_dir))

#functional images and components confounds
func_filenames = list(
    flatmap(
        lambda session: map(lambda subj: op.join(data_dir, subj, ts_image),
                            session), sessions_subjects_dir))
confounds_components = list(
    flatmap(
        lambda session: map(lambda subj: op.join(data_dir, subj, cf_file),
                            session), sessions_subjects_dir))

masker = NiftiMapsMasker(maps_img=atlas_filename,
                         memory_level=1,
                         detrend=True,
                         verbose=args.verbose,
                         t_r=TR)
masker.fit()

for i, (filename,
        confound) in enumerate(zip(func_filenames, confounds_components)):
    extract_cbl(filename, confound, masker,
                op.join(data_dir, "cbl", subject_list[i]))
                                          preprocessing_folder='pipeline_1')[ind])
dyn_fc = np.asarray(dyn_fc)


##############################################################################
# NYU rs-fMRI
##############################################################################
nyu_func = fetch_nyu_rest()['func']
masker = NiftiMapsMasker(maps_img=roi_imgs, 
                         low_pass=.1,
                         high_pass=.01,
                         t_r=2.,
                         smoothing_fwhm=6., detrend=True, standardize=False,
                         resampling_target='maps', memory_level=0,
                         verbose=5)
masker.fit()

def mask_and_covariance(f):
    x = masker.transform(f)
    return np.corrcoef(x.T)[ind]
#    gl = GraphLassoCV(verbose=2)
#    gl.fit(x)
#    return gl.covariance_[ind]

from joblib import delayed, Parallel

nyu_fc = Parallel(n_jobs=20, verbose=5)(delayed(mask_and_covariance)(f)
                                        for f in nyu_func)
nyu_fc = np.asarray(nyu_fc)