コード例 #1
0
def test_show_contrast_matrix():
    # test that the show code indeed (formally) runs
    frame_times = np.linspace(0, 127 * 1., 128)
    dmtx = make_first_level_design_matrix(
        frame_times, drift_model='polynomial', drift_order=3)
    contrast = np.ones(4)
    ax = plot_contrast_matrix(contrast, dmtx)
    assert (ax is not None)
    with InTemporaryDirectory():
        ax = plot_contrast_matrix(contrast, dmtx, output_file='contrast.png')
        assert os.path.exists('contrast.png')
        assert (ax is None)
        plot_contrast_matrix(contrast, dmtx, output_file='contrast.pdf')
        assert os.path.exists('contrast.pdf')
コード例 #2
0
def _plot_contrasts(contrasts, design_matrices):
    """
    Accepts dict of contrasts and list of design matrices and generates
    a dict of contrast titles & HTML for SVG Image data url
    for corresponding contrast plot.

    Parameters
    ----------
    contrasts: Dict[str, np.array or str]
        Contrast information, as a dict
          {'contrast_title_1, contrast_info_1/title_1, ...}

    design_matrices: List[pd.Dataframe]
        Design matrices computed in the model.

    Returns
    -------
    contrast_plots: Dict[str, svg img]
        Dict of contrast title and svg image data url
        for corresponding contrast plot.
    """
    all_contrasts_plots = {}
    contrast_template_path = os.path.join(HTML_TEMPLATE_ROOT_PATH,
                                          'contrast_template.html')
    with open(contrast_template_path) as html_template_obj:
        contrast_template_text = html_template_obj.read()

    for design_matrix in design_matrices:
        for contrast_name, contrast_data in contrasts.items():
            contrast_text_ = string.Template(contrast_template_text)
            contrast_plot = plot_contrast_matrix(contrast_data,
                                                 design_matrix,
                                                 colorbar=True)
            contrast_plot.set_xlabel(contrast_name)
            contrast_plot.figure.set_figheight(2)
            contrast_plot.figure.set_tight_layout(True)
            url_contrast_plot_svg = plot_to_svg(contrast_plot)
            # prevents sphinx-gallery & jupyter
            # from scraping & inserting plots
            plt.close()
            contrasts_for_subsitution = {
                'contrast_plot': url_contrast_plot_svg,
                'contrast_name': contrast_name,
            }
            contrast_text_ = contrast_text_.safe_substitute(
                contrasts_for_subsitution)
            all_contrasts_plots[contrast_name] = contrast_text_
    return all_contrasts_plots
コード例 #3
0
contrasts = {
    'left-right': (contrasts['visual_left_hand_button_press'] +
                   contrasts['audio_left_hand_button_press'] -
                   contrasts['visual_right_hand_button_press'] -
                   contrasts['audio_right_hand_button_press']),
    'H-V': (contrasts['horizontal_checkerboard'] -
            contrasts['vertical_checkerboard']),
    'audio-video':
    contrasts['audio'] - contrasts['video'],
    'sentences-computation':
    (contrasts['sentences'] - contrasts['computation'])
}

#########################################################################
# Take a look at the contrasts.
plot_contrast_matrix(contrasts['left-right'], design_matrix)

#########################################################################
# Take a breath.
#
# We can now  proceed by estimating the contrasts and displaying them.

import matplotlib.pyplot as plt
from nilearn.plotting import plot_stat_map

fig = plt.figure(figsize=(11, 3))
for index, (contrast_id, contrast_val) in enumerate(contrasts.items()):
    ax = plt.subplot(1, len(contrasts), 1 + index)
    z_map = first_level_model.compute_contrast(contrast_val,
                                               output_type='z_score')
    plot_stat_map(z_map,
コード例 #4
0
from nilearn.reporting import compare_niimgs

compare_niimgs([z_map], [fsl_z_map],
               model.masker_,
               ref_label='Nilearn',
               src_label='FSL')
plt.show()

#############################################################################
# Simple statistical report of thresholded contrast
# -----------------------------------------------------
# We display the contrast plot and table with cluster information
from nilearn.reporting import plot_contrast_matrix

plot_contrast_matrix('StopSuccess - Go', design_matrix)
plotting.plot_glass_brain(z_map,
                          colorbar=True,
                          threshold=norm.isf(0.001),
                          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())

#########################################################################
コード例 #5
0
    'rest':   array([0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
                     0.]),
}

###############################################################################
# We can then compare the two conditions 'active' and 'rest' by
# defining the corresponding contrast:

active_minus_rest = conditions['active'] - conditions['rest']

###############################################################################
# Let's look at it: plot the coefficients of the contrast, indexed by
# the names of the columns of the design matrix.

from nilearn.reporting import plot_contrast_matrix
plot_contrast_matrix(active_minus_rest, design_matrix=design_matrix)

###############################################################################
# Below, we compute the estimated effect. It is in BOLD signal unit,
# but has no statistical guarantees, because it does not take into
# account the associated variance.

eff_map = fmri_glm.compute_contrast(active_minus_rest,
                                    output_type='effect_size')

###############################################################################
# In order to get statistical significance, we form a t-statistic, and
# directly convert it into z-scale. The z-scale means that the values
# are scaled to match a standard Gaussian distribution (mean=0,
# variance=1), across voxels, if there were no effects in the data.
コード例 #6
0

#########################################################################
# So let's look at these computed contrasts:
#
# * 'left - right button press': probes motor activity in left versus right button presses
# * 'horizontal-vertical': probes the differential activity in viewing a horizontal vs vertical checkerboard
# * 'audio - visual': probes the difference of activity between listening to some content or reading the same type of content (instructions, stories)
# * 'computation - sentences': looks at the activity when performing a mental comptation task  versus simply reading sentences.
#
contrasts = make_localizer_contrasts(design_matrix)
plt.figure(figsize=(5, 9))
from nilearn.reporting import plot_contrast_matrix
for i, (key, values) in enumerate(contrasts.items()):
    ax = plt.subplot(len(contrasts) + 1, 1, i + 1)
    plot_contrast_matrix(values, design_matrix=design_matrix, ax=ax)

plt.show()

#########################################################################
# Contrast estimation and plotting.
#
# Since this script will be repeated several times, for the sake of readability,
# we encapsulate it in a function that we call when needed.
#
from nilearn import plotting


def plot_contrast(first_level_model):
    """ Given a first model, specify, estimate and plot the main contrasts"""
    design_matrix = first_level_model.design_matrices_[0]