def report_slm_oasis():  # pragma: no cover
    n_subjects = 5  # more subjects requires more memory
    oasis_dataset = nilearn.datasets.fetch_oasis_vbm(n_subjects=n_subjects)
    # Resample the images, since this mask has a different resolution
    mask_img = resample_to_img(
        nilearn.datasets.fetch_icbm152_brain_gm_mask(),
        oasis_dataset.gray_matter_maps[0],
        interpolation='nearest',
    )
    design_matrix = _make_design_matrix_slm_oasis(oasis_dataset, n_subjects)
    second_level_model = SecondLevelModel(smoothing_fwhm=2.0,
                                          mask_img=mask_img)
    second_level_model.fit(oasis_dataset.gray_matter_maps,
                           design_matrix=design_matrix)

    contrast = [[1, 0, 0], [0, 1, 0]]
    report = make_glm_report(
        model=second_level_model,
        contrasts=contrast,
        bg_img=nilearn.datasets.fetch_icbm152_2009()['t1'],
        height_control=None,
    )
    output_filename = 'generated_report_slm_oasis.html'
    output_filepath = os.path.join(REPORTS_DIR, output_filename)
    report.save_as_html(output_filepath)
    report.get_iframe()
def report_flm_fiac():  # pragma: no cover
    data = datasets.func.fetch_fiac_first_level()
    fmri_img = [data['func1'], data['func2']]

    from nilearn.image import mean_img
    mean_img_ = mean_img(fmri_img[0])

    design_files = [data['design_matrix1'], data['design_matrix2']]
    design_matrices = [pd.DataFrame(np.load(df)['X']) for df in design_files]

    fmri_glm = FirstLevelModel(mask_img=data['mask'], minimize_memory=True)
    fmri_glm = fmri_glm.fit(fmri_img, design_matrices=design_matrices)

    n_columns = design_matrices[0].shape[1]

    contrasts = {
        'SStSSp_minus_DStDSp': _pad_vector([1, 0, 0, -1], n_columns),
        'DStDSp_minus_SStSSp': _pad_vector([-1, 0, 0, 1], n_columns),
        'DSt_minus_SSt': _pad_vector([-1, -1, 1, 1], n_columns),
        'DSp_minus_SSp': _pad_vector([-1, 1, -1, 1], n_columns),
        'DSt_minus_SSt_for_DSp': _pad_vector([0, -1, 0, 1], n_columns),
        'DSp_minus_SSp_for_DSt': _pad_vector([0, 0, -1, 1], n_columns),
        'Deactivation': _pad_vector([-1, -1, -1, -1, 4], n_columns),
        'Effects_of_interest': np.eye(n_columns)[:5]
    }
    report = make_glm_report(
        fmri_glm,
        contrasts,
        bg_img=mean_img_,
        height_control='fdr',
    )
    output_filename = 'generated_report_flm_fiac.html'
    output_filepath = os.path.join(REPORTS_DIR, output_filename)
    report.save_as_html(output_filepath)
    report.get_iframe()
def report_flm_bids_features():  # pragma: no cover
    data_dir = _fetch_bids_data()
    model, subject = _make_flm(data_dir)
    title = 'FLM Bids Features Stat maps'
    report = make_glm_report(
        model=model,
        contrasts='StopSuccess - Go',
        title=title,
        cluster_threshold=3,
    )
    output_filename = 'generated_report_flm_bids_features.html'
    output_filepath = os.path.join(REPORTS_DIR, output_filename)
    report.save_as_html(output_filepath)
    report.get_iframe()
def report_flm_adhd_dmn():  # pragma: no cover
    t_r = 2.
    slice_time_ref = 0.
    n_scans = 176
    pcc_coords = (0, -53, 26)
    adhd_dataset = nilearn.datasets.fetch_adhd(n_subjects=1)
    seed_masker = NiftiSpheresMasker([pcc_coords],
                                     radius=10,
                                     detrend=True,
                                     standardize=True,
                                     low_pass=0.1,
                                     high_pass=0.01,
                                     t_r=2.,
                                     memory='nilearn_cache',
                                     memory_level=1,
                                     verbose=0)
    seed_time_series = seed_masker.fit_transform(adhd_dataset.func[0])
    frametimes = np.linspace(0, (n_scans - 1) * t_r, n_scans)
    design_matrix = make_first_level_design_matrix(frametimes,
                                                   hrf_model='spm',
                                                   add_regs=seed_time_series,
                                                   add_reg_names=["pcc_seed"])
    dmn_contrast = np.array([1] + [0] * (design_matrix.shape[1] - 1))
    contrasts = {'seed_based_glm': dmn_contrast}

    first_level_model = FirstLevelModel(t_r=t_r, slice_time_ref=slice_time_ref)
    first_level_model = first_level_model.fit(run_imgs=adhd_dataset.func[0],
                                              design_matrices=design_matrix)

    report = make_glm_report(
        first_level_model,
        contrasts=contrasts,
        title='ADHD DMN Report',
        cluster_threshold=15,
        height_control='bonferroni',
        min_distance=8.,
        plot_type='glass',
        report_dims=(1200, 'a'),
    )
    output_filename = 'generated_report_flm_adhd_dmn.html'
    output_filepath = os.path.join(REPORTS_DIR, output_filename)
    report.save_as_html(output_filepath)
    report.get_iframe()
Exemple #5
0
                          plot_abs=False,
                          display_mode='z',
                          figure=plt.figure(figsize=(4, 4)))
plt.show()

###############################################################################
# We can get a latex table from a Pandas Dataframe for display and publication purposes
from nilearn.reporting import get_clusters_table

print(get_clusters_table(z_map, norm.isf(0.001), 10).to_latex())

#########################################################################
# Generating a report
# -------------------
# Using the computed FirstLevelModel and contrast information,
# we can quickly create a summary report.

from nilearn.reporting import make_glm_report

report = make_glm_report(
    model=model,
    contrasts='StopSuccess - Go',
)

#########################################################################
# We have several ways to access the report:

# report  # This report can be viewed in a notebook
# report.save_as_html('report.html')
# report.open_in_browser()
plotting.plot_stat_map(
    z_map, threshold=threshold, colorbar=True,
    title='sex effect on grey matter density (FDR = .05)')

###########################################################################
# Note that there does not seem to be any significant effect of sex on
# grey matter density on that dataset.

###########################################################################
# Generating a report
# -------------------
# It can be useful to quickly generate a
# portable, ready-to-view report with most of the pertinent information.
# This is easy to do if you have a fitted model and the list of contrasts,
# which we do here.

from nilearn.reporting import make_glm_report

icbm152_2009 = datasets.fetch_icbm152_2009()
report = make_glm_report(model=second_level_model,
                         contrasts=['age', 'sex'],
                         bg_img=icbm152_2009['t1'],
                         )

#########################################################################
# We have several ways to access the report:

# report  # This report can be viewed in a notebook
# report.save_as_html('report.html')
# report.open_in_browser()
Exemple #7
0
def first_level(subject_dic,
                additional_regressors=None,
                compcorr=False,
                smooth=None,
                mesh=False,
                mask_img=None):
    """ Run the first-level analysis (GLM fitting + statistical maps)
    in a given subject

    Parameters
    ----------
    subject_dic: dict,
                 exhaustive description of an individual acquisition
    additional_regressors: dict or None,
                 additional regressors provided as an already sampled
                 design_matrix
                 dictionary keys are session_ids
    compcorr: Bool, optional,
              whether confound estimation and removal should be done or not
    smooth: float or None, optional,
            how much the data should spatially smoothed during masking
    """
    start_time = time.ctime()
    # experimental paradigm meta-params
    motion_names = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz']
    hrf_model = subject_dic['hrf_model']
    high_pass = subject_dic['high_pass']
    drift_model = subject_dic['drift_model']
    tr = subject_dic['TR']
    slice_time_ref = 1.

    if not mesh and (mask_img is None):
        mask_img = masking(subject_dic['func'], subject_dic['output_dir'])

    if additional_regressors is None:
        additional_regressors = dict([
            (session_id, None) for session_id in subject_dic['session_id']
        ])

    for session_id, fmri_path, onset, motion_path in zip(
            subject_dic['session_id'], subject_dic['func'],
            subject_dic['onset'], subject_dic['realignment_parameters']):

        task_id = _session_id_to_task_id([session_id])[0]

        if mesh is not False:
            from nibabel.gifti import read
            n_scans = np.array(
                [darrays.data for darrays in read(fmri_path).darrays]).shape[0]
        else:
            n_scans = nib.load(fmri_path).shape[3]

        # motion parameters
        motion = np.loadtxt(motion_path)
        # define the time stamps for different images
        frametimes = np.linspace(slice_time_ref,
                                 (n_scans - 1 + slice_time_ref) * tr, n_scans)
        if task_id == 'audio':
            mask = np.array([1, 0, 1, 1, 0, 1, 1, 0, 1, 1])
            n_cycles = 28
            cycle_duration = 20
            t_r = 2
            cycle = np.arange(0, cycle_duration, t_r)[mask > 0]
            frametimes = np.tile(cycle, n_cycles) +\
                np.repeat(np.arange(n_cycles) * cycle_duration, mask.sum())
            frametimes = frametimes[:-2]  # for some reason...

        if mesh is not False:
            compcorr = False  # XXX Fixme

        if compcorr:
            confounds = high_variance_confounds(fmri_path, mask_img=mask_img)
            confounds = np.hstack((confounds, motion))
            confound_names = ['conf_%d' % i for i in range(5)] + motion_names
        else:
            confounds = motion
            confound_names = motion_names

        if onset is None:
            warnings.warn('Onset file not provided. Trying to guess it')
            task = os.path.basename(fmri_path).split('task')[-1][4:]
            onset = os.path.join(
                os.path.split(os.path.dirname(fmri_path))[0], 'model001',
                'onsets', 'task' + task + '_run001', 'task%s.csv' % task)

        if not os.path.exists(onset):
            warnings.warn('non-existant onset file. proceeding without it')
            paradigm = None
        else:
            paradigm = make_paradigm(onset, task_id)

        # handle manually supplied regressors
        add_reg_names = []
        if additional_regressors[session_id] is None:
            add_regs = confounds
        else:
            df = read_csv(additional_regressors[session_id])
            add_regs = []
            for regressor in df:
                add_reg_names.append(regressor)
                add_regs.append(df[regressor])
            add_regs = np.array(add_regs).T
            add_regs = np.hstack((add_regs, confounds))

        add_reg_names += confound_names

        # create the design matrix
        design_matrix = make_first_level_design_matrix(
            frametimes,
            paradigm,
            hrf_model=hrf_model,
            drift_model=drift_model,
            high_pass=high_pass,
            add_regs=add_regs,
            add_reg_names=add_reg_names)
        _, dmtx, names = check_design_matrix(design_matrix)

        # create the relevant contrasts
        contrasts = make_contrasts(task_id, names)

        if mesh == 'fsaverage5':
            # this is low-resolution data
            subject_session_output_dir = os.path.join(
                subject_dic['output_dir'], 'res_fsaverage5_%s' % session_id)
        elif mesh == 'fsaverage7':
            subject_session_output_dir = os.path.join(
                subject_dic['output_dir'], 'res_fsaverage7_%s' % session_id)
        elif mesh == 'individual':
            subject_session_output_dir = os.path.join(
                subject_dic['output_dir'], 'res_individual_%s' % session_id)
        else:
            subject_session_output_dir = os.path.join(
                subject_dic['output_dir'], 'res_stats_%s' % session_id)

        if not os.path.exists(subject_session_output_dir):
            os.makedirs(subject_session_output_dir)
        np.savez(os.path.join(subject_session_output_dir, 'design_matrix.npz'),
                 design_matrix=design_matrix)

        if mesh is not False:
            run_surface_glm(design_matrix, contrasts, fmri_path,
                            subject_session_output_dir)
        else:
            z_maps, fmri_glm = run_glm(design_matrix,
                                       contrasts,
                                       fmri_path,
                                       mask_img,
                                       subject_dic,
                                       subject_session_output_dir,
                                       tr=tr,
                                       slice_time_ref=slice_time_ref,
                                       smoothing_fwhm=smooth)

            # do stats report
            anat_img = nib.load(subject_dic['anat'])
            stats_report_filename = os.path.join(subject_session_output_dir,
                                                 'report_stats.html')

            report = make_glm_report(
                fmri_glm,
                contrasts,
                threshold=3.0,
                bg_img=anat_img,
                cluster_threshold=15,
                title="GLM for subject %s" % session_id,
            )
            report.save_as_html(stats_report_filename)
Exemple #8
0
    def generate_report(self,
                        contrasts,
                        title=None,
                        bg_img="MNI152TEMPLATE",
                        threshold=3.09,
                        alpha=0.001,
                        cluster_threshold=0,
                        height_control='fpr',
                        min_distance=8.,
                        plot_type='slice',
                        display_mode=None,
                        report_dims=(1600, 800)):
        """ Returns HTMLDocument object
        for a report which shows all important aspects of a fitted GLM.
        The object can be opened in a browser, displayed in a notebook,
        or saved to disk as a standalone HTML file.

        The GLM must be fitted and have the computed design matrix(ces).

        Parameters
        ----------
            A fitted first or second level model object.

        contrasts: Dict[string, ndarray] or String or List[String] or ndarray or
            List[ndarray]

            Contrasts information for a first or second level model.

            Example:

                Dict of contrast names and coefficients,
                or list of contrast names
                or list of contrast coefficients
                or contrast name
                or contrast coefficient

                Each contrast name must be a string.
                Each contrast coefficient must be a list or numpy array of ints.

            Contrasts are passed to ``contrast_def`` for FirstLevelModel
            (:func:`nilearn.glm.first_level.FirstLevelModel.compute_contrast`)
            & second_level_contrast for SecondLevelModel
            (:func:`nilearn.glm.second_level.SecondLevelModel.compute_contrast`)

        title: String, optional
            If string, represents the web page's title and primary heading,
            model type is sub-heading.
            If None, page titles and headings are autogenerated
            using contrast names.

        bg_img: Niimg-like object
            Default is the MNI152 template
            See http://nilearn.github.io/manipulating_images/input_output.html
            The background image for mask and stat maps to be plotted on upon.
            To turn off background image, just pass "bg_img=None".

        threshold: float
            Default is 3.09
            Cluster forming threshold in same scale as `stat_img` (either a
            t-scale or z-scale value). Used only if height_control is None.

        alpha: float
            Default is 0.001
            Number controlling the thresholding (either a p-value or q-value).
            Its actual meaning depends on the height_control parameter.
            This function translates alpha to a z-scale threshold.

        cluster_threshold: int, optional
            Default is 0
            Cluster size threshold, in voxels.

        height_control: string or None
            false positive control meaning of cluster forming
            threshold: 'fpr' (default) or 'fdr' or 'bonferroni' or None

        min_distance: `float`
            For display purposes only.
            Minimum distance between subpeaks in mm. Default is 8 mm.

        plot_type: String. ['slice' (default) or  'glass']
            Specifies the type of plot to be drawn for the statistical maps.

        display_mode: string
            Default is 'z' if plot_type is 'slice'; '
            ortho' if plot_type is 'glass'.

            Choose the direction of the cuts:
            'x' - sagittal, 'y' - coronal, 'z' - axial,
            'l' - sagittal left hemisphere only,
            'r' - sagittal right hemisphere only,
            'ortho' - three cuts are performed in orthogonal directions.

            Possible values are:
            'ortho', 'x', 'y', 'z', 'xz', 'yx', 'yz',
            'l', 'r', 'lr', 'lzr', 'lyr', 'lzry', 'lyrz'.

        report_dims: Sequence[int, int]
            Default is (1600, 800) pixels.
            Specifies width, height (in pixels) of report window within a notebook.
            Only applicable when inserting the report into a Jupyter notebook.
            Can be set after report creation using report.width, report.height.

        Returns
        -------
        report_text: HTMLDocument Object
            Contains the HTML code for the GLM Report.
        """
        from nilearn.reporting import make_glm_report
        return make_glm_report(self,
                               contrasts,
                               title=title,
                               bg_img=bg_img,
                               threshold=threshold,
                               alpha=alpha,
                               cluster_threshold=cluster_threshold,
                               height_control=height_control,
                               min_distance=min_distance,
                               plot_type=plot_type,
                               display_mode=display_mode,
                               report_dims=report_dims)
plotting.plot_stat_map(
    z_map, bg_img=mean_img_, threshold=3.0,
    title='%s, fixed effects' % contrast_id)

plotting.show()

#########################################################################
# Not unexpectedly, the fixed effects version displays higher peaks than the
# input sessions. Computing fixed effects enhances the signal-to-noise ratio of
# the resulting brain maps.


#########################################################################
# Generating a report
# -------------------
# Since we have already computed the FirstLevelModel and
# and have the contrast, we can quickly create a summary report.
from nilearn.reporting import make_glm_report

report = make_glm_report(fmri_glm,
                         contrasts,
                         bg_img=mean_img_,
                         )

#########################################################################
# We have several ways to access the report:

# report  # This report can be viewed in a notebook
# report.save_as_html('report.html')
# report.open_in_browser()
    for condition_ in conditions:
        z_maps.append(glm.compute_contrast(condition_))
        condition_idx.append(condition_)
        session_idx.append(session)

#########################################################################
# Generating a report
# -------------------
# Since we have already computed the FirstLevelModel
# and have the contrast, we can quickly create a summary report.
from nilearn.image import mean_img
from nilearn.reporting import make_glm_report

mean_img_ = mean_img(func_filename)
report = make_glm_report(glm,
                         contrasts=conditions,
                         bg_img=mean_img_,
                         )

#############################################################################
# In a jupyter notebook, the report will be automatically inserted, as above.
# We have several other ways to access the report:

# report  # This report can be viewed in a notebook
# report.save_as_html('report.html')
# report.open_in_browser()

#############################################################################
# Transform the maps to an array of values
# ----------------------------------------
from nilearn.input_data import NiftiMasker
                    marker_color='g',
                    marker_size=300)
display.savefig(filename)
print("Save z-map in '{0}'.".format(filename))

###########################################################################
# Generating a report
# -------------------
# It can be useful to quickly generate a
# portable, ready-to-view report with most of the pertinent information.
# This is easy to do if you have a fitted model and the list of contrasts,
# which we do here.

from nilearn.reporting import make_glm_report

report = make_glm_report(
    first_level_model,
    contrasts=contrasts,
    title='ADHD DMN Report',
    cluster_threshold=15,
    min_distance=8.,
    plot_type='glass',
)

#########################################################################
# We have several ways to access the report:

# report  # This report can be viewed in a notebook
# report.save_as_html('report.html')
# report.open_in_browser()