Example #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')
Example #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
    'active': array([1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]),
    'rest':   array([0., 1., 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 nistats.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 is 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 now effects in the data.
    'active': array([1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]),
    'rest': array([0., 1., 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 nistats.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 is 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 now effects in the data.
Example #5
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 nistats.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, enstimate and plot the main contrasts"""
    design_matrix = first_level_model.design_matrices_[0]
Example #6
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,
    fig.savefig(f'{out_dir}{sub}/figures/{sub}_design_matrix.png')

    #--- defining contrasts
    trial_dummies = pd.get_dummies(design_matrix.columns)
    trial_contrasts = pd.DataFrame.to_dict(trial_dummies, orient='list')
    trial_contrasts['overall'] = [
        1 if i[0] == 'Q' else 0 for i in design_matrix.columns
    ]

    fig, ax = plt.subplots(n_trials, 1)
    fig.set_size_inches(22, 40)

    for i in range(n_trials):
        plt.figure()
        _ = plot_contrast_matrix(trial_contrasts[f'Q{i+1:02}'],
                                 design_matrix=design_matrix.iloc[:, 0:40],
                                 ax=ax[i])

    fig.savefig(f'{out_dir}{sub}/figures/{sub}_contrasts_trials.png')

    #--- trial effects estimation
    zmaps = np.zeros((89, 105, 89, n_trials))

    for i in range(n_trials):
        zmap = fmri_glm_non_smoothed.compute_contrast(np.asarray(
            trial_contrasts[f'Q{i+1:02}']),
                                                      output_type='z_score')
        zmaps[:, :, :, i] = zmap.get_fdata()
        p = plot_stat_map(zmap,
                          threshold=3,
                          display_mode='z',
Example #8
0
    display_mode='ortho')
plt.show()

from nistats.reporting import compare_niimgs
compare_niimgs([z_map], [fsl_z_map],
               model.masker_,
               ref_label='Nistats',
               src_label='FSL')
plt.show()

#############################################################################
# Simple statistical report of thresholded contrast
# -----------------------------------------------------
# We display the contrast plot and table with cluster information.
from nistats.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 nistats.reporting import get_clusters_table
print(get_clusters_table(z_map, norm.isf(0.001), 10).to_latex())

#########################################################################
# Generating a report
                                              stat_type=cont[4],
                                              output_type='z_score')
            identifier = '%s_sub-%02d_%s' % (cont, sdx, method)
            out_file = '%s/zmap_%s' % (res_path, identifier)
            z_map.to_filename('%s.nii.gz' % out_file)

        # Plot design matrices and contrasts
        plot_design_matrix(fmri_glm.design_matrices_[0],
                           output_file='%s/design_matrix_01_sub-%02d.svg' %
                           (res_path, sdx))

        plot_design_matrix(fmri_glm.design_matrices_[1],
                           output_file='%s/design_matrix_02_sub-%02d.svg' %
                           (res_path, sdx))

        plot_design_matrix(fmri_glm.design_matrices_[2],
                           output_file='%s/design_matrix_03_sub-%02d.svg' %
                           (res_path, sdx))

        plot_design_matrix(fmri_glm.design_matrices_[3],
                           output_file='%s/design_matrix_04_sub-%02d.svg' %
                           (res_path, sdx))

        # Plot contrast matrix
        for cont in contrast_list:
            plot_contrast_matrix(contrast_list[cont],
                                 design_matrix=fmri_glm.design_matrices_[0],
                                 output_file='%s/%s.svg' % (res_path, cont))

        print('Finished sub: %03d - Method: %s' % (sdx, method))
Example #10
0
        for i in range(len(contrast)):
            if design_matrix.columns[i] == label:
                contrast[i] = 1
            elif lbl in design_matrix.columns[
                    i]:  # -1 to other fingers of same hand
                contrast[i] = -1

        z_map = fmri_glm.compute_contrast(contrast, output_type='z_score')
        z_map.to_filename(output_dir + 'z_%s-all_%s_contrast.nii.gz' %
                          (label, lbl))

#compare left vs right
rl_limb = ['hand', 'leg']

for j in range(len(rl_limb)):
    contrast = np.zeros(len(
        design_matrix.columns))  # array of zeros with len = num predictors
    for i in range(len(contrast)):
        if 'r' + rl_limb[j] in design_matrix.columns[i]:
            contrast[i] = 1
        elif 'l' + rl_limb[j] in design_matrix.columns[i]:
            contrast[i] = -1

    plot_contrast_matrix(contrast, design_matrix=design_matrix)

    z_map = fmri_glm.compute_contrast(contrast, output_type='z_score')
    z_map.to_filename(output_dir + 'z_right-left_' + rl_limb[j] +
                      '_contrast.nii.gz')

print('Success!')
###############################################################################
# Detecting voxels with significant effects
# -----------------------------------------
#
# To access the estimated coefficients (Betas of the GLM model), we
# created constrast with a single '1' in each of the columns: The role
# of the contrast is to select some columns of the model --and
# potentially weight them-- to study the associated statistics. So in
# a nutshell, a contrast is a weighted combination of the estimated
# effects.  Here we can define canonical contrasts that just consider
# the two condition in isolation ---let's call them "conditions"---
# then a contrast that makes the difference between these conditions.

from nistats.reporting import plot_contrast_matrix
plot_contrast_matrix(curr_contrast,
                     design_matrix=design_matrix,
                     output_file=join(outdir, contrast_name + '_contrast.png'))

###############################################################################
# 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(curr_contrast, output_type='effect_size')

###############################################################################
# In order to get statistical significance, we form a t-statistic, and
# directly convert is 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 now effects in the data.
z_map = fmri_glm.compute_contrast(curr_contrast, output_type='z_score')
    return contrasts

#########################################################################
# So let's look at these computed contrasts
#
# * "left - right button press" probes motor activity in left versus right button presses
# * 'H-V': probes the differential activity in viewing a horizontal vs vertical checkerboard
# * "audio - video" 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 nistats.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, enstimate and plot the main contrasts"""
    design_matrix = first_level_model.design_matrices_[0]
    # Call the contrast specification within the function
Example #13
0
import matplotlib.pyplot as plt
from scipy.stats import norm
plotting.plot_glass_brain(z_map, colorbar=True, threshold=norm.isf(0.001),
                          title='Nistats Z map of "StopSuccess - Go" (unc p<0.001)',
                          plot_abs=False, display_mode='ortho')
plotting.plot_glass_brain(fsl_z_map, colorbar=True, threshold=norm.isf(0.001),
                          title='FSL Z map of "StopSuccess - Go" (unc p<0.001)',
                          plot_abs=False, display_mode='ortho')
plt.show()

from nistats.reporting import compare_niimgs
compare_niimgs([z_map], [fsl_z_map], model.masker_,
               ref_label='Nistats', src_label='FSL')
plt.show()

#############################################################################
# Simple statistical report of thresholded contrast
# -----------------------------------------------------
# We display the contrast plot and table with cluster information
from nistats.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
from nistats.reporting import get_clusters_table
print(get_clusters_table(z_map, norm.isf(0.001), 10).to_latex())