Beispiel #1
0
def load_show_experimental_scans():
    from nilearn import plotting
    from src.data import experiment

    layout = experiment.get_food_temptation_data()

    # subject data is S_ID, hi-res, exp-data, events
    subject_data = experiment.get_all_subject_data(layout)

    # take first subject, exp-data
    scans = subject_data[0][2]

    scans.orthoview()

    _show_variance(scans)

    # pick a single scan to show
    single_scan = scans.slicer[:, :, :, 0]

    _show_raw(single_scan)

    plotting.plot_stat_map(
        single_scan,
        # threshold=30,
        # display_mode="z",
        # cut_coords=1,
        # colorbar=False,
    )
    plotting.plot_img(single_scan)
    plotting.plot_epi(single_scan)
    plotting.plot_roi(single_scan)
    plotting.plot_anat(single_scan)
def main(file=None, mask=True, figure=False, out_dir=None):
    """ Computes the median temporal signal-to-noise ratio (TSNR) of
    a 4D fMRI file (similar to what MRIQC does).

    Parameters
    ----------
    file : str or None
        If str, refers to the path of a 4D nifti file. If None,
        a default file is loaded.
    mask : bool
        Whether to mask the file (using Nilearn)
    figure : bool
        If False, only prints out the median TSNR value. If True,
        it will write out a figure with voxel-wise TSNR values.
    out_dir : str
        Directory to save TSNR figure to. If None, the same directory
        as `file` will be used.
    """

    if file is None:
        print("WARNING: you did not specify a file! Exiting ...")
        sys.exit()

    print(f"INFO: computing TSNR for {file}")

    # Load in image and associated data
    img = image.load_img(file)

    # Apply mask
    if mask:
        print("INFO: computing EPI mask")
        mask = masking.compute_epi_mask(img)
    else:
        # If no mask, at least remove zeros
        nonzeros = (img.get_fdata().sum(axis=3) != 0).astype(int)
        mask = nib.Nifti1Image(nonzeros, affine=img.affine)

    img_2d = masking.apply_mask(img, mask)

    # Compute TSNR
    tsnr = np.mean(img_2d, axis=0) / np.std(img_2d, axis=0)
    print(f"INFO: median TSNR = {np.median(tsnr):.3f}")

    if figure:
        # Recreate 3D nifti + plot with Nilearn
        tsnr_img = masking.unmask(tsnr, mask_img=mask)
        plotting.plot_epi(tsnr_img)

        # Save to disk
        if out_dir is None:  # set dir if necessary
            out_dir = os.path.dirname(file)

        f_name = os.path.basename(file).replace('.nii.gz', '_tsnr.png')
        f_out = os.path.join(out_dir, f_name)
        print(f"INFO: Saving figure to {f_out}")
        plt.savefig(f_out)
def compute_mean_epi(fmri_filenames, output_pathway):
    fmri_img = smooth_img(fmri_filenames, fwhm=5)
    mean_epi = mean_img(fmri_img)

    # Save
    mean_epi.to_filename(os.path.join(output_pathway, 'mean_epi.nii.gz'))

    # Plot
    plotting.plot_epi(mean_epi, title='Smoothed mean EPI',
                      output_file=os.path.join(output_pathway, 'mean_epi.png'))

    return mean_epi
Beispiel #4
0
def nii2jpg(inFile=None,
            outFile=None,
            cutCoords=(3, 3, 3),
            displayMode='ortho'):
    epiImage = image.mean_img(inFile)
    epiImage = image.smooth_img(epiImage, 'fast')
    plotting.plot_epi(epi_img=epiImage,
                      cut_coords=cutCoords,
                      output_file=outFile,
                      display_mode=displayMode,
                      annotate=False,
                      draw_cross=False)
Beispiel #5
0
def basic_plots():
    """
    Plot and save a mean EPI image and an EPI mask
    :return:
    """
    for input in glob('input/sub*'):
        sub = op.basename(input)
        func = input + '/func/{}_task-oneback_run-01_bold.nii.gz'.format(sub)
        mean = mean_img(func)
        plot_epi(mean).savefig('figures/{}_mean-epi.png'.format(sub))
        mask_img = compute_epi_mask(func)
        mask_img.to_filename('{}_brain-mask.nii.gz'.format(sub))
        plot_roi(mask_img, mean).savefig('figures/{}_brainmask.png'.format(sub))
Beispiel #6
0
    def plot(self, downsample=1, out_base="."):
        out_path = os.path.join(out_base, self.subject, self.name, self.task)
        os.makedirs(out_path, exist_ok=True)
        raw = nib.load(self.path)
        M = np.max(raw.get_data())
        n = raw.shape[3]
        mean = nimage.mean_img(raw)
        xyzcuts = nilplot.find_xyz_cut_coords(mean)
        xcuts = nilplot.find_cut_slices(mean, "x")
        ycuts = nilplot.find_cut_slices(mean, "y")
        zcuts = nilplot.find_cut_slices(mean, "z")
        del raw
        nrange = range(0, n, downsample)
        for i, img in enumerate(nimage.iter_img(self.path)):
            if i in nrange:
                nilplot.plot_epi(nimage.math_img("img / %f" % (M), img=img),
                                 colorbar=False,
                                 output_file="%s/orth_epi%0d.png" %
                                 (out_path, i),
                                 annotate=True,
                                 cut_coords=xyzcuts,
                                 cmap="gist_heat")
                nilplot.plot_epi(nimage.math_img("img / %f" % (M), img=img),
                                 colorbar=False,
                                 output_file="%s/x_epi%0d.png" % (out_path, i),
                                 annotate=True,
                                 display_mode="x",
                                 cut_coords=xcuts,
                                 cmap="gist_heat")
                nilplot.plot_epi(nimage.math_img("img / %f" % (M), img=img),
                                 colorbar=False,
                                 output_file="%s/y_epi%0d.png" % (out_path, i),
                                 annotate=True,
                                 display_mode="y",
                                 cut_coords=ycuts,
                                 cmap="gist_heat")
                nilplot.plot_epi(nimage.math_img("img / %f" % (M), img=img),
                                 colorbar=False,
                                 output_file="%s/z_epi%0d.png" % (out_path, i),
                                 annotate=True,
                                 display_mode="z",
                                 cut_coords=zcuts,
                                 cmap="gist_heat")

        slice_names = ["orth_epi", "x_epi", "y_epi", "z_epi"]
        for slic in slice_names:
            filenames = ["%s/%s%0d.png" % (out_path, slic, i) for i in nrange]
            with imageio.get_writer('%s/%s.gif' % (out_path, slic),
                                    mode='I') as writer:
                for i, filename in zip(nrange, filenames):
                    image = Image.open(filename)
                    draw = ImageDraw.Draw(image)
                    fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf',
                                             16)
                    draw.text((2, 2), str(i), font=fnt, fill=(255, 0, 0, 255))
                    image.save(filename, "PNG")
                    image = imageio.imread(filename)
                    writer.append_data(image)
Beispiel #7
0
def _save(img, root, file, coord, display_mode):
    display = None

    if mode.lower() == "anat":
        display = plotting.plot_anat(img,
                                     cut_coords=[coord],
                                     display_mode=display_mode,
                                     annotate=annotate,
                                     black_bg=black_bg)
    elif mode.lower() == "epi":
        display = plotting.plot_epi(img,
                                    cut_coords=[coord],
                                    display_mode=display_mode,
                                    annotate=annotate,
                                    black_bg=black_bg)

    (dst_dir, dst_full_path) = _create_names(root, file, coord, display_mode)

    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)

    display.savefig(dst_full_path, dpi=dpi)
    display.close()

    del display
 def predictCancer(self):
         tno=0
         img='testImage'+str(tno)+'.png'
         from nilearn import plotting
         display = plotting.plot_epi(self.fileName[0],output_file=img)
         print(tno)
         from keras.models import model_from_json
         json_file = open('model.json', 'r')
         loaded_model_json = json_file.read()
         json_file.close()
         loaded_model = model_from_json(loaded_model_json)
         # load weights into new model
         loaded_model.load_weights("model.h5")
         print("Loaded model from disk")
         import numpy as np
         from keras.preprocessing import image
         #classifier.load('file_name.h5')\n",
         test_image = image.load_img(img, target_size = (64, 64))
         test_image = image.img_to_array(test_image)
         test_image = np.expand_dims(test_image, axis = 0)
         result = loaded_model.predict(test_image)
         #training_set.class_indices
         if result == 1:
              prediction = 'LGG'
              self.label_5.setText("This MRI has non-cancerous cells")
         else:
              prediction = 'HGG'
              self.label_5.setText("This MRI has cancerous cells")
         print(result)
         print(prediction)
         
         if prediction=='LGG':
             self.label_6.setText("Lgg- They are classified as a grade 2 tumor making them slowest growing \ntype of glioma in adults. low grade gliomas would encompass grade I and \ngrade II neuro-epithelial tumours in childs. Most low-grade gliomas are \nboth highly treatable and highly curable. Low-grade cancers usually have \na better prognos is than high-grade cancers and may not need \ntreatment right away.")
         else:
             self.label_6.setText("HGG -They are classified as grade 4 tumor in most cases. High-grade cancer \ncells tend to grow and spread more quickly than low-grade cancer cells.\nCancer grade may be used to help plan treatment and determined to help \nplan treatment and determine prognosis. High-grade cancers usually have a \nworse prognosis than low-grade cancers and may need treatment \nright away or treatment that is more aggressive (intensive).")
Beispiel #9
0
def plot_compressed_samples(compressed_vol,
                            labels,
                            n_voxels,
                            masker,
                            title="",
                            memory=None):

    # Now convert those similarities back to uncompressed images
    uncompressed_images = []
    n_samples = compressed_vol.shape[0]
    for si in np.arange(n_samples):
        voxel_values = compute_voxel_values(compressed_vol[si, :],
                                            labels=labels,
                                            memory=memory)
        uncompressed_image = masker.inverse_transform(voxel_values)
        uncompressed_images.append(uncompressed_image)

    # Plot the final figure
    figure1 = plt.figure(figsize=(18, 9))
    rows_cols = len(uncompressed_images)
    for si, uncompressed_image in enumerate(uncompressed_images):

        # Stat map
        axes1 = figure1.add_subplot(rows_cols, 1, si + 1)
        data = uncompressed_image.get_data()
        stretched_data = data / np.abs(data).max()
        img = nibabel.Nifti1Image(stretched_data,
                                  affine=uncompressed_image.get_affine())
        plot_stat_map(
            img,
            display_mode='y',  # bg_img=mean_func_img,
            title="%s %d (stats)" % (title, si + 1),
            figure=figure1,
            axes=axes1)

    figure2 = plt.figure(figsize=(18, 9))
    for si, uncompressed_image in enumerate(uncompressed_images):
        # EPI map
        plot_epi(uncompressed_image,
                 figure=figure2,
                 axes=figure2.add_subplot(2, 2, si + 1),
                 title="%s %d (raw)" % (title, si),
                 display_mode='xz',
                 colorbar=True,
                 vmin=-np.abs(uncompressed_image.get_data().max()),
                 vmax=np.abs(uncompressed_image.get_data().max()),
                 cmap=cm.cold_hot)
def otherNii(filename, timepoint):
    '''
    Uses an EPI mask of the 3D image at the timepoint input as features
    '''
    DATA_PATH_FOR_NII = r"C:\Users\Ted\Desktop\CAIS_MUSIC_BRAIN\NII-Files"

    niiname2 = os.path.join(
        DATA_PATH_FOR_NII,
        "sub-01_sadln_filtered_func_200hpf_cut20_standard.nii")

    nilearn.plotting.show()
    result = nilearn.image.index_img(niiname2, timepoint)
    print(result.shape)
    plot_epi(result)
    mask_img = compute_epi_mask(result)
    nilearn.plotting.plot_roi(mask_img, result)
    masked_data = nilearn.masking.apply_mask(filename, mask_img)
    return masked_data, masked_data.shape[1]
Beispiel #11
0
    def visualizing(self):
        X_approx_rena = self.custering(self.X_masked,
                                       self.labels_rena)
        X_approx_ward = self.custering(self.X_masked,
                                       self.labels_ward)

        cut_coords = (-34, -16)
        n_image = 0

        labels_rena_img = self.visualize_labels(self.labels_rena,
                                                self.masker)
        labels_ward_img = self.visualize_labels(self.labels_ward,
                                                self.masker)

        clusters_rena_fig = plot_stat_map(labels_rena_img,
                                          bg_img=self.data,
                                          title='ReNA: clusters',
                                          display_mode='yz',
                                          cut_coords=cut_coords,
                                          colorbar=False)

        clusters_ward_fig = plot_stat_map(labels_ward_img,
                                          bg_img=self.data,
                                          title='Ward: clusters',
                                          display_mode='yz',
                                          cut_coords=cut_coords,
                                          colorbar=False)

        compress_rena_fig = plot_epi(self.masker.inverse_transform(X_approx_rena[n_image]),
                                     title='ReNA: approximated',
                                     display_mode='yz',
                                     cut_coords=cut_coords)

        compress_ward_fig = plot_epi(self.masker.inverse_transform(X_approx_ward[n_image]),
                                     title='Ward: approximated',
                                     display_mode='yz',
                                     cut_coords=cut_coords)

        original_fig = plot_epi(self.masker.inverse_transform(self.X_masked[n_image]),
                                title='original',
                                display_mode='yz',
                                cut_coords=cut_coords)

        return clusters_rena_fig, clusters_ward_fig, compress_rena_fig, compress_ward_fig, original_fig
def get_fmri_preview():
    data = {"image": ""}

    x_size = 64
    y_size = 64
    n_slice = 64
    n_volumes = 96

    if request.method == 'POST':
        f = request.files['file']
        nii_file = os.path.join(app.config['UPLOAD_FOLDER'],
                                secure_filename(f.filename))
        f.save(nii_file)
        mean_haxby = mean_img(nii_file)

        plot_epi(mean_haxby, output_file="static/img/viz.png")

        data = {'image': "static/img/viz.png"}
    return jsonify(data)
def parcel_overlay(in_file, overlay_file, out_file):
    import os.path
    import matplotlib as mpl
    mpl.use('Agg')
    from nilearn.plotting import plot_epi
    mask_display = plot_epi(in_file)
    mask_display.add_edges(overlay_file)
    #  mask_display.add_contours(overlay_file)
    #  mask_display.add_overlay(overlay_file)
    mask_display.title(out_file, x=0.01, y=0.99, size=15, color=None,
                       bgcolor=None, alpha=1)
    mask_display.savefig(out_file)
    return os.path.abspath(out_file)
def parcel_overlay(in_file, overlay_file, out_file):
    import os.path
    import matplotlib as mpl
    mpl.use('Agg')
    from nilearn.plotting import plot_epi
    mask_display = plot_epi(in_file)
    mask_display.add_edges(overlay_file)
    #  mask_display.add_contours(overlay_file)
    #  mask_display.add_overlay(overlay_file)
    mask_display.title(out_file, x=0.01, y=0.99, size=15, color=None,
                       bgcolor=None, alpha=1)
    mask_display.savefig(out_file)
    return os.path.abspath(out_file)
Beispiel #15
0
    def plot_functionals(func_file):
        # Compute the voxel_wise mean of functional images across time.
        # Basically reducing the functional image from 4D to 3D
        mean_img = image.mean_img(func_file)
        filename = func_file.split("/")[-1].split(".")[0]

        plot_filename = os.path.join(report_folder_path,
                                     "%s_mean_img.png" % filename)

        plot_img = plotting.plot_epi(mean_img,
                                     title=filename,
                                     display_mode='ortho',
                                     draw_cross=False,
                                     annotate=False,
                                     output_file=plot_filename)
Beispiel #16
0
    def _generate_report(self):
        in_img = nib.load(self.inputs.in_file)
        assert nvol(in_img) == 1

        mask_img = nib.load(self.inputs.mask_file)
        assert nvol(mask_img) == 1

        label = None
        if isdefined(self.inputs.label):
            label = self.inputs.label

        compress = self.inputs.compress_report

        n_cuts = 7
        cuts = cuts_from_bbox(mask_img, cuts=n_cuts)

        img_vals = in_img.get_fdata()[np.asanyarray(mask_img.dataobj).astype(
            np.bool)]
        vmin = img_vals.min()
        vmax = img_vals.max()

        outfiles = []
        for dimension in ["z", "y", "x"]:
            display = plot_epi(
                in_img,
                draw_cross=False,
                display_mode=dimension,
                cut_coords=cuts[dimension],
                title=label,
                vmin=vmin,
                vmax=vmax,
                colorbar=(dimension == "z"),
                cmap=plt.cm.gray,
            )
            display.add_contours(mask_img, levels=[0.5], colors="r")
            label = None  # only on first
            svg = extract_svg(display, compress=compress)
            svg = svg.replace("figure_1", str(uuid4()), 1)
            outfiles.append(fromstring(svg))

        self._out_report = op.abspath(self.inputs.out_report)
        compose_view(bg_svgs=outfiles, fg_svgs=None, out_file=self._out_report)
Beispiel #17
0
    def _generate_report(self):
        epi_img = nib.load(self.inputs.in_file)
        mask_img = nib.load(self.inputs.mask_file)
        assert nvol(epi_img) == 1
        assert nvol(mask_img) == 1

        label = None
        if isdefined(self.inputs.label):
            label = self.inputs.label

        compress = self.inputs.compress_report

        n_cuts = 7
        cuts = cuts_from_bbox(mask_img, cuts=n_cuts)

        plot_params = robust_set_limits_in_mask(epi_img, mask_img)

        outfiles = []
        for dimension in ["z", "y", "x"]:
            display = plot_epi(
                epi_img,
                draw_cross=False,
                display_mode=dimension,
                cut_coords=cuts[dimension],
                title=label,
                colorbar=(dimension == "z"),
                cmap=plt.get_cmap("gray"),
                **plot_params,
            )

            display.add_contours(mask_img, levels=[0.5], colors="r")

            label = None  # only on first

            svg = extract_svg(display, compress=compress)
            svg = svg.replace("figure_1", str(uuid4()), 1)

            outfiles.append(fromstring(svg))

        self._out_report = op.abspath(self.inputs.out_report)
        compose_view(bg_svgs=outfiles, fg_svgs=None, out_file=self._out_report)
Beispiel #18
0
print('First anatomical nifti image (3D) located is at: %s' %
      haxby_dataset.anat[0])
print('First functional nifti image (4D) is located at: %s' %
      haxby_dataset.func[0])

##############################################################################
# Visualization
# -------------
from nilearn.image.image import mean_img

# Compute the mean EPI: we do the mean along the axis 3, which is time
func_filename = haxby_dataset.func[0]
mean_haxby = mean_img(func_filename)

from nilearn.plotting import plot_epi, show
plot_epi(mean_haxby, colorbar=True, cbar_tick_format="%i")

##############################################################################
# Extracting a brain mask
# -----------------------
# Simple computation of a mask from the fMRI data
from nilearn.masking import compute_epi_mask
mask_img = compute_epi_mask(func_filename)

# Visualize it as an ROI
from nilearn.plotting import plot_roi
plot_roi(mask_img, mean_haxby)

##############################################################################
# Applying the mask to extract the corresponding time series
# ----------------------------------------------------------
Beispiel #19
0
    get_tmaps=True)
localizer_anat_filename = localizer_dataset.anats[1]
localizer_cmap_filename = localizer_dataset.cmaps[1]
localizer_tmap_filename = localizer_dataset.tmaps[1]

###############################################################################
# demo the different plotting functions

# Plotting statistical maps
plotting.plot_stat_map(localizer_cmap_filename, bg_img=localizer_anat_filename,
                       threshold=3, title="plot_stat_map",
                       cut_coords=(36, -27, 66))

# Plotting glass brain
plotting.plot_glass_brain(localizer_tmap_filename, title='plot_glass_brain',
                          threshold=3)

# Plotting anatomical maps
plotting.plot_anat(haxby_anat_filename, title="plot_anat")

# Plotting ROIs (here the mask)
plotting.plot_roi(haxby_mask_filename, bg_img=haxby_anat_filename,
                  title="plot_roi")

# Plotting EPI haxby
mean_haxby_img = image.mean_img(haxby_func_filename)
plotting.plot_epi(mean_haxby_img, title="plot_epi")

import matplotlib.pyplot as plt
plt.show()
Beispiel #20
0
sess='rest1_1'# ,'rest1_2', 'rest2_1', 'rest2_2']


create_masks = False

coords = [[10,140,11],[22,88,-69],[25,80,-74], [17,100,-66], [41,84,-26],
          [12,94,-60], [40, 91,-57], [21, 94, -73], [36, 100, -55]]

#pdb.set_trace()
###### run
os.chdir(wd)

if create_masks:
    for sub in subjects:
        masking = fs.Binarize(match = [47,48],
                          out_type = 'nii.gz')
    
        masking.inputs.in_file = glob(seg%sub)[0]
        res = masking.run()
        #wm_mask = res.outputs.binary_file
    
for s in range(len(subjects)):
    
    display = plotting.plot_epi(epi_median%(subjects[s], sess), 
                                cmap='gray', draw_cross = False,
                                annotate = False, cut_coords=coords[s])
    display.add_contours(glob(wm_mask%subjects[s])[0], levels=[.5], colors='r')
    display.savefig(pic%(subjects[s],sess))

    
"""

import func_preproc
from func_preproc import motion_correction
from func_preproc import skullstrip4d as remove_skull
from func_preproc import smoothing_scaling as normalize
from func_preproc import masking

"""
Below is an C-PAC example, which uses the default setting. This is the simplest
way of expressing serial commands/workflow, if the output of the first command
is the input of the second. Files will be stored in func/ folder. Make sure there
is already a "rest.nii.gz" file in that folder. 
"""
func_preproc.NAME_CONV = 'accumulate'
masking(normalize(remove_skull(motion_correction(motion_correction('rest')))))

"""
Below is an example imitating fcon_1000's pipeline. This time we uses more argument. 
"""
#func_preproc.NAME_CONV = 'replace'
#motion_correction('rest','rest_mc','func_2',mc_alg = 'nipy_spacerealign')
#remove_skull('rest_mc','rest_ss','func_2')
#normalize('rest_ss', func_dir='func_2', smooth=6)
#masking('rest_gms', func_dir='func_2')

from nilearn.plotting import plot_epi
from nilearn.image import mean_img
plot_epi(mean_img('func_2/rest_gms.nii.gz'), cut_coords=(-22,15,23))
plot_epi(mean_img('func_1/rest_mc_mc_ss_gms.nii.gz'), cut_coords=(-22,15,23))
plot_epi(mean_img('sample/rest_gms.nii.gz'), cut_coords=(-22,15,23))
# detect the background.
#
# With data that has already been masked, this will work well, as it lies
# on a homogeneous background

# Load Miyawaki dataset
from nilearn import datasets
miyawaki_dataset = datasets.fetch_miyawaki2008()

# print basic information on the dataset
print('First functional nifti image (4D) is located at: %s' %
      miyawaki_dataset.func[0])  # 4D data

miyawaki_filename = miyawaki_dataset.func[0]
miyawaki_mean_img = image.mean_img(miyawaki_filename)
plot_epi(miyawaki_mean_img, title='Mean EPI image')
###############################################################################
# A NiftiMasker with the default strategy
masker = NiftiMasker()
masker.fit(miyawaki_filename)

# Plot the generated mask using the mask_img_ attribute
plot_roi(masker.mask_img_,
         miyawaki_mean_img,
         title="Mask from already masked data")

###############################################################################
# Plot the generated mask using the .generate_report method
report = masker.generate_report()
report
 plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
            ncol=3, mode="expand", borderaxespad=0.,fontsize=7)
            
 y_min8, y_max8 = fig8.axes.get_ylim()
 fig8.vlines(volumeIndex,y_min8,y_max8)
            
 pdf.savefig()
 plt.close()        
 
 
 
 
 # compute regions regressors according to loaded masks
         
 for m_r in range(len(masks_reg)):    
     display=plotting.plot_epi(nilearn.image.index_img(func_img, 0),cut_coords=[0,-22,25])    
     display.add_overlay(masks_reg[m_r],cmap=plotting.cm.bwr)
     display.title(mask_regions[m_r])                
     pdf.savefig()
     plt.close()        
 
 vent = regions.img_to_signals_labels(func_img,vent_img)[0]
 surr = regions.img_to_signals_labels(func_img,surr_img)[0]
 whit = regions.img_to_signals_labels(func_img,whit_img)[0]
 beat = regions.img_to_signals_labels(func_img,beat_img)[0]
 
 plt.figure()
 plt.plot(vent,'k',label = 'ventricles')
 plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
    ncol=2, mode="expand", borderaxespad=0.)
 pdf.savefig()
_ = plt.title('rotation during scan', fontsize=20)
fig.savefig(join(img_savedir, 'motion_rotation.png'))

fig=plt.figure(figsize=(18, 4), dpi= 80, facecolor='w', edgecolor='k')
_ = plt.plot(np.full([count,1],0), 'k--', linewidth=.5)
_ = plt.plot(transx, 'b', label='transx')
_ = plt.plot(transy, 'g', label='transy')
_ = plt.plot(transz, 'r', label='transz')
_ = plt.legend(fontsize=15)
_ = plt.ylabel('translation in mm', fontsize=15)
_ = plt.xlabel('time in TRs', fontsize=15)
_ = plt.title('translation during scan', fontsize=20)
fig.savefig(join(img_savedir, 'motion_translation.png'))

# ------  Make images to check unwarping ------------------------------------------------
print('plotting unwarping images...')
img_savedir = join(warpdir_out, 'unwarp_figures')
if not exists(img_savedir):
    makedirs(img_savedir)

# mean map, before unwarping
plotting.plot_epi(image.mean_img(join(rawdir, scanInfo.loc[this_cond]['niftiName'])),
                  title=this_cond + '_mean_raw', cmap='gray',
                  output_file=join(img_savedir, this_cond + '_mean_raw.png'))
# mean map, after unwarping
plotting.plot_epi(image.mean_img(join(warpdir_out, preprocDir + '_unwarped.nii.gz')),
                  title=this_cond + '_mean_unwarp', cmap='gray',
                  output_file=join(img_savedir, this_cond + '_mean_raw.png'))

print('done and done!')
Beispiel #25
0
# Functional data
fmri_filename = haxby_dataset.func[0]
# smoothing: first argument as functional data filename and smoothing value
# (integer) in second argument. Output returns in Nifti image.
fmri_img = image.smooth_img(fmri_filename, fwhm=6)

# Visualize the mean of the smoothed EPI image using plotting function
# `plot_epi`
from nilearn.plotting import plot_epi

# First, compute the voxel-wise mean of smooth EPI image (first argument) using
# image processing module `image`
mean_img = image.mean_img(fmri_img)
# Second, we visualize the mean image with coordinates positioned manually
plot_epi(mean_img, title='Smoothed mean EPI', cut_coords=cut_coords)

##############################################################################
# Given the smoothed functional data stored in variable 'fmri_img', we then
# select two features of interest with face and house experimental conditions.
# The method we will be using is a simple Student's t-test. The below section
# gives us brief motivation example about why selecting features in high
# dimensional FMRI data setting.

##############################################################################
# Functional MRI data can be considered "high dimensional" given the p-versus-n
# ratio (e.g., p=~20,000-200,000 voxels for n=1000 samples or less). In this
# setting, machine-learning algorithms can perform poorly due to the so-called
# curse of dimensionality. However, simple means from the realms of classical
# statistics can help reducing the number of voxels.
from nilearn.image import get_data
Beispiel #26
0
# Functional data
fmri_filename = haxby_dataset.func[0]
# smoothing: first argument as functional data filename and smoothing value
# (integer) in second argument. Output returns in Nifti image.
fmri_img = image.smooth_img(fmri_filename, fwhm=6)

# Visualize the mean of the smoothed EPI image using plotting function
# `plot_epi`
from nilearn.plotting import plot_epi

# First, compute the voxel-wise mean of smooth EPI image (first argument) using
# image processing module `image`
mean_img = image.mean_img(fmri_img)
# Second, we visualize the mean image with coordinates positioned manually
plot_epi(mean_img, title='Smoothed mean EPI', cut_coords=cut_coords)

##############################################################################
# Given the smoothed functional data stored in variable 'fmri_img', we then
# select two features of interest with face and house experimental conditions.
# The method we will be using is a simple Student's t-test. The below section
# gives us brief motivation example about why selecting features in high
# dimensional FMRI data setting.

##############################################################################
# Functional MRI data can be considered "high dimensional" given the p-versus-n
# ratio (e.g., p=~20,000-200,000 voxels for n=1000 samples or less). In this
# setting, machine-learning algorithms can perform poorly due to the so-called
# curse of dimensionality. However, simple means from the realms of classical
# statistics can help reducing the number of voxels.
import matplotlib.pyplot as plt
from nilearn.plotting import plot_epi, plot_stat_map, plot_roi
from nilearn.input_data import NiftiLabelsMasker

plt.close('all')

### Find voxels of interest ###################################################

# Smooth the data
from nilearn import image
fmri_img = image.smooth_img(haxby_files.func[0], fwhm=6)

# Plot the mean image
fig_id = plt.subplot(2, 1, 1)
mean_img = image.mean_img(fmri_img)
plot_epi(mean_img, title='Smoothed mean EPI', cut_coords=(coronal, sagittal,
    axial), axes=fig_id)

# Run a T-test for face and houses
from scipy import stats
fmri_data = fmri_img.get_data()
_, p_values = stats.ttest_ind(fmri_data[..., haxby_labels == 'face'],
                              fmri_data[..., haxby_labels == 'house'],
                              axis=-1)

# Use a log scale for p-values
log_p_values = -np.log10(p_values)
log_p_values[np.isnan(log_p_values)] = 0.
log_p_values[log_p_values > 10.] = 10.
fig_id = plt.subplot(2, 1, 2)
plot_stat_map(nibabel.Nifti1Image(log_p_values, fmri_img.get_affine()), mean_img,
    title="p-values", cut_coords=(coronal, sagittal, axial), axes=fig_id)
from nilearn import datasets, plotting, image

data = datasets.fetch_adhd()

for i in range(4):
    mean_func = image.mean_img(data.func[i])
    plotting.plot_epi(mean_func)

def make_quality_control_reports(population, workspace_dir):

    for subject in population:

        print '###############################################################################'
        print ' Running Quality Control for subject %s' %subject
        print ''

        #input
        subject_dir       = os.path.join(workspace_dir, subject)

        func_native       = os.path.join(subject_dir, 'FUNC_PPROC/REST_PPROC_NATIVE_BRAIN.nii.gz')
        func_native_mask  = os.path.join(subject_dir, 'FUNC_PPROC/REST_PPROC_NATIVE_BRAIN_mask_ero.nii.gz')
        func_native_mean  = os.path.join(subject_dir, 'FUNC_PPROC/REST_PPROC_NATIVE_BRAIN_mean.nii.gz')
        func_native_gm    = os.path.join(subject_dir, 'FUNC_TRANSFORM/NATIVE_FUNC_GM.nii.gz')
        func_native_wm    = os.path.join(subject_dir, 'FUNC_TRANSFORM/NATIVE_FUNC_WM.nii.gz')
        func_native_csf   = os.path.join(subject_dir, 'FUNC_TRANSFORM/NATIVE_FUNC_CSF.nii.gz')
        func_native_first =  os.path.join(subject_dir, 'FUNC_TRANSFORM/NATIVE_FUNC_FIRST.nii.gz')

        func_mni          = os.path.join(subject_dir, 'FUNC_TRANSFORM/REST_PPROC_MNI2mm_BRAIN.nii.gz')
        func_mni_mask     = os.path.join(subject_dir, 'FUNC_TRANSFORM/REST_PPROC_MNI2mm_BRAIN_mask_ero.nii.gz')
        func_mni_mean     = os.path.join(subject_dir, 'FUNC_TRANSFORM/REST_PPROC_MNI2mm_BRAIN_mean.nii.gz')
        func_mni_gm       = os.path.join(subject_dir, 'FUNC_TRANSFORM/MNI2mm_FUNC_GM.nii.gz')
        func_mni_wm       = os.path.join(subject_dir, 'FUNC_TRANSFORM/MNI2mm_FUNC_WM.nii.gz')
        func_mni_csf      = os.path.join(subject_dir, 'FUNC_TRANSFORM/MNI2mm_FUNC_CSF.nii.gz')

        residual_compor   = os.path.join(subject_dir, 'FUNC_DENOISE/NUISANCE_MNI_COMPCOR/residual.nii.gz')
        residual_wmcsf    = os.path.join(subject_dir, 'FUNC_DENOISE/NUISANCE_MNI_WMCSF/residual.nii.gz')
        residual_global   = os.path.join(subject_dir, 'FUNC_DENOISE/NUISANCE_MNI_GLOBAL/residual.nii.gz')

        aroma_compcor     = os.path.join(subject_dir, 'FUNC_DENOISE/NUISANCE_MNI_AROMA_COMPCOR/residual.nii.gz')
        aroma_wmcsf       = os.path.join(subject_dir, 'FUNC_DENOISE/NUISANCE_MNI_AROMA_WMCSF/residual.nii.gz')
        aroma_global      = os.path.join(subject_dir, 'FUNC_DENOISE/NUISANCE_MNI_AROMA_GLOBAL/residual.nii.gz')

        movpar            = os.path.join(subject_dir,'FUNC_PPROC/MOTION_CORRECTION/REST_DISCO_MOCO_2.1D')

        qcdir =  os.path.join(subject_dir,'QUALITY_CONTROL')
        mkdir_path(qcdir)
        os.chdir(qcdir)

        print 'Creating Quality Control Report'

        ################################################################################################################
        print '1. Calculating FD'
        fd = os.path.join(qcdir, 'FD.1D')
        if not os.path.isfile(fd):
            calc_FD_power(movpar)

        population_FDs = np.genfromtxt(os.path.join(workspace_dir, 'population_fd_distributions.txt'))
        if not os.path.isfile('plot_fd_qc.png'):
           plot_FD(fd, population_FDs, subject,figsize = (8.3,8.3))

        ################################################################################################################
        print '2. Grabbing accepted frames (FD<0.2mm) '
        fd1d = np.loadtxt(fd)
        in_frames = []
        for frame, fd in enumerate(fd1d):
            if fd < 0.2:
                in_frames.append(frame)
        print '    ...Subject has %s of 417 good frames'%len(in_frames)
        np.save('in_frames', str(in_frames).replace(" ",""))
        if len(in_frames) > 150:
            in_frames_100 = in_frames[0:130]
            np.save('in_frames_100', str(in_frames_100).replace(" ",""))

        ################################################################################################################
        print '3. Calculating DVARS'
        dvars = os.path.join(qcdir, 'DVARS.npy')
        if not os.path.isfile(dvars):
            calc_DVARS(func_native, func_native_mask)
        print func_native
        print func_native_mask
        ###############################################################################################################
        print '4. TSNR'
        #get TSNR median for whole brain
        if not os.path.isfile(os.path.join(qcdir, 'REST_PPROC_NATIVE_BRAIN_tsnr.nii.gz')):
            tsnr = TSNR()
            tsnr.inputs.in_file = func_native
            tsnr.run()

        if not os.path.isfile('TSNR_data.npy'):
            tsnr_data   = nb.load('./REST_PPROC_NATIVE_BRAIN_tsnr.nii.gz').get_data()
            nan_mask    = np.logical_not(np.isnan(tsnr_data))
            mask        = nb.load(func_native_mask).get_data() > 0
            #tsnr_median = np.median(tsnr_data[np.logical_and(nan_mask, mask)])
            data        = tsnr_data[np.logical_and(nan_mask, mask)]
            tsnr_out    = os.path.join(os.getcwd(), 'TSNR_data.npy')
            np.save(tsnr_out, data)

        tsnr_median =  np.median(np.load('TSNR_data.npy'))
        print '-->',tsnr_median

        if not os.path.isfile(' plot_tsnr_mosaic.png'):
            plot_mosaic(nifti_file  = './REST_PPROC_NATIVE_BRAIN_tsnr.nii.gz',
                        output_name = 'plot_tsnr_mosaic.pdf',
                        title="tSNR",
                        overlay_mask = None,
                        figsize=(8.3, 11.7))

            os.system('convert -density 300 -trim plot_tsnr_mosaic.pdf -quality 300 -sharpen 0x1.0 -crop  2506x2570+1+470 plot_tsnr_mosaic.png')

        # whole brain plots
        if not os.path.isfile('plot_tsnr_brain_distribution.png'):
            plot_distrbution_of_values(main_file =  './REST_PPROC_NATIVE_BRAIN_tsnr.nii.gz',
                                       mask_file = func_native_mask,
                                       xlabel = "%s Whole Brain tSNR distribution" % subject,
                                       distribution=  np.genfromtxt(os.path.join(workspace_dir, 'population_tsnr_distributions.txt')),
                                       xlabel2= "%s median whole brain tSNR with respect to all subjects"%subject,
                                       figsize=(11.7,8.3),
                                       outname = 'plot_tsnr_brain_distribution.png')

            d = plotting.plot_epi(func_native_mean, cmap='gray', display_mode='y', black_bg= 1, annotate=0)
            d.add_contours(func_native_mask, colors='r')
            d.savefig('plot_func_native_mask_y.png', dpi = 130)

            d = plotting.plot_epi(func_native_mean, cmap='gray', display_mode='x', black_bg= 1, annotate=0)
            d.add_contours(func_native_mask, colors='r')
            d.savefig('plot_func_native_mask_x.png', dpi = 110)

            d = plotting.plot_epi(func_native_mean, cmap='gray', display_mode='z', black_bg= 1, annotate=0)
            d.add_contours(func_native_mask, colors='r')
            d.savefig('plot_func_native_mask_z.png', dpi = 130)

        # subcortical plots
        if not os.path.isfile('plot_tsnr_first_distribution.png'):
            plot_distrbution_of_values(main_file    =  './REST_PPROC_NATIVE_BRAIN_tsnr.nii.gz',
                                       mask_file    = func_native_first,
                                       xlabel       = "%s Subcortical tSNR distribution" % subject,
                                       distribution =  np.genfromtxt(os.path.join(workspace_dir, 'population_tsnr_first_distributions.txt')),
                                       xlabel2      = "%s median subcortical tSNR with respect to all subjects"%subject,
                                       figsize      =(11.7,8.3),
                                       outname      = 'plot_tsnr_first_distribution.png',
                                       color        = 'green')

            plot_3d_overlay(underlay_file=func_native_mean, overlay_file=func_native_first, out_filename='plot_subcortical_mask.png', dpi = 215)

        ################################################################################################################
        print '5. Plot FUNC 2 MNI Registration'

        d = plotting.plot_epi( mni_brain_2mm, cmap='gray', display_mode='x',  annotate=0, black_bg=0)
        d.add_contours(func_mni_mean, colors='r')
        d.savefig('plot_mnireg_x.png', dpi = 110)

        d = plotting.plot_epi( mni_brain_2mm, cmap='gray', display_mode='y',  annotate=0, black_bg=0)
        d.add_contours(func_mni_mean, colors='r')
        d.savefig('plot_mnireg_y.png', dpi = 130)

        d = plotting.plot_epi( mni_brain_2mm, cmap='gray', display_mode='z',  annotate=0, black_bg=1)
        d.add_contours(func_mni_mean, colors='r')
        d.savefig('plot_mnireg_z.png', dpi = 130)


        ################################################################################################################
        print '6. Plot Func GM'
        if not os.path.isfile('plot_func_native_gm.png'):
            plot_mosaic(nifti_file  = func_native_mean,
                        output_name = 'plot_func_native_gm.pdf',
                        title="Func Gray Matter",
                        overlay_mask = func_native_gm,
                        figsize=(8.3, 11.7))
            os.system('convert -density 300 -trim plot_func_native_gm.pdf -quality 300 -sharpen 0x1.0 -crop 2506x2570+1+470 plot_func_native_gm.png')


        ################################################################################################################
        print '7. Plot Nuisance Residuals'

        mni_wm_sig  = os.path.join(subject_dir, 'FUNC_DENOISE/TISSUE_SIGNALS_MNI/NUISANCE_SIGNALS_WM.npy')
        mni_gm_sig  = os.path.join(subject_dir, 'FUNC_DENOISE/TISSUE_SIGNALS_MNI/NUISANCE_SIGNALS_GM.npy')
        mni_csf_sig = os.path.join(subject_dir, 'FUNC_DENOISE/TISSUE_SIGNALS_MNI/NUISANCE_SIGNALS_CSF.npy')

        if not os.path.isfile('func_mni_detrend.nii.gz'):
           calc_residuals(subject = func_mni, selector = nuisance_detrend,wm_sig_file = mni_wm_sig,
                          csf_sig_file= mni_csf_sig, gm_sig_file = mni_gm_sig,motion_file = movpar,
                          compcor_ncomponents = 0)
           os.system('mv residual.nii.gz func_mni_detrend.nii.gz')
           os.system('rm -rf  quadratic_constant_linear.csv nuisance_regressors.mat')

        if not os.path.isfile('plot_nuisance.png'):
            plot_nuisance_residuals(mov_params                       = movpar,
                                    fd1d                             = fd1d,
                                    func_preprocessed                = func_native,
                                    func_preprocessed_mask           = func_native_mask,
                                    dvars                            = dvars,
                                    func_gm                          = func_mni_gm,
                                    residuals_dt                     = 'func_mni_detrend.nii.gz',
                                    residuals_cc                     = residual_compor ,
                                    residuals_gl                     = residual_global,
                                    aroma_cc                         = aroma_compcor ,
                                    aroma_gl                         = aroma_global,
                                    out_name                         = 'plot_nuisance.png',
                                    figsize = (8.3,8.3))

        ################################################################################################################
        print '8. Calculating Motion statistics and saving as csv'
        df = pd.DataFrame(index = [subject], columns = ['FD', 'FD_in','FD_topQua', 'FD_max', 'FD_RMS', 'DVARS', 'TSNR'])
        df.loc[subject]['FD']        = str(np.round(np.mean(fd1d), 3))
        df.loc[subject]['FD_in']     = str(np.round(len(in_frames), 3))
        quat = int(len(fd1d)/4)
        df.loc[subject]['FD_topQua'] = str(np.round(np.mean(np.sort(fd1d)[::-1][:quat]), 3))
        df.loc[subject]['FD_max']    = str(np.round(np.max(fd1d), 3))
        df.loc[subject]['FD_RMS']    = str(np.round(np.sqrt(np.mean(fd1d)), 3))
        df.loc[subject]['DVARS']     = str(np.round(np.mean(np.load(dvars)), 3))
        df.loc[subject]['TSNR']      = str(np.round(tsnr_median, 3))
        df.to_csv ('quality_paramters.csv')

        ################################################################################################################

        print 'Creating QC REPORT'

        report = canvas.Canvas('QC_REPORT.pdf', pagesize=(1280 *1.9, 1556*1.9))
        report.setFont("Helvetica", 100)
        report.drawString(inch*15, inch*39.3, '%s'%subject)
        report.setFont("Helvetica", 70)
        report.drawString(inch*15, inch*1, 'tSNR')
        report.drawImage('plot_tsnr_mosaic.png', inch*1.5, inch*2.6)
        report.showPage()

        report.setFont("Helvetica", 30)
        report.drawString(inch*31, inch*40, '%s'%subject)
        report.setFont("Helvetica", 70)
        report.drawString(inch*12, inch*1, 'Func Native Gray Matter')
        report.drawImage('plot_func_native_gm.png', inch*1.5, inch*2.6)
        report.showPage()

        report.setFont("Helvetica", 30)
        report.drawString(inch*31, inch*40, '%s'%subject)
        report.setFont("Helvetica", 50)
        report.drawString(inch*10, inch*38.5, 'Func to MNI2mm Nonlinear Registration')
        report.drawImage('plot_mnireg_x.png', inch*2.5, inch*34.5)
        report.drawImage('plot_mnireg_y.png', inch*2.5, inch*30.5)

        report.setFont("Helvetica", 30)
        report.drawString(inch*31, inch*40, '%s'%subject)
        report.setFont("Helvetica", 50)
        report.drawString(inch*13, inch*29, 'Func Native Brain Mask')
        report.drawImage('plot_func_native_mask_y.png', inch*2.5, inch*21)
        report.drawImage('plot_func_native_mask_x.png', inch*2.5, inch*25)
        report.drawImage('plot_tsnr_brain_distribution.png', inch*3.5, inch*1.7)

        brain_tsnr = get_values_inside_a_mask('REST_PPROC_NATIVE_BRAIN_tsnr.nii.gz', func_native_mask)
        tsnr_brain_check_outlier = get_outlier(brain_tsnr, np.genfromtxt(os.path.join(workspace_dir, 'population_tsnr_distributions.txt')) )
        if tsnr_brain_check_outlier is 'Accepted':
            report.setFillColorRGB(0,180,0)
        else:
             report.setFillColorRGB(250,0,0)
        report.setFont("Helvetica", 50)
        report.drawString(inch*6, inch*10, tsnr_brain_check_outlier)
        report.showPage()

        report.setFont("Helvetica", 30)
        report.drawString(inch*31, inch*40, '%s'%subject)
        report.setFont("Helvetica", 50)
        report.drawString(inch*12, inch*38.5, 'Func FIRST Subcortical Mask')
        report.drawImage('plot_subcortical_mask.png', inch*7, inch*20)
        report.drawImage('plot_tsnr_first_distribution.png', inch*3, inch*2)

        first_tsnr  = get_values_inside_a_mask('REST_PPROC_NATIVE_BRAIN_tsnr.nii.gz', func_native_first)
        tsnr_first_check_outlier = get_outlier(first_tsnr, np.genfromtxt(os.path.join(workspace_dir, 'population_tsnr_distributions.txt')) )
        if tsnr_first_check_outlier is 'Accepted':
            report.setFillColorRGB(0,180,0)
        else:
             report.setFillColorRGB(250,0,0)
        report.setFont("Helvetica", 50)
        report.drawString(inch*6, inch*10, tsnr_first_check_outlier)
        report.showPage()

        report.setFont("Helvetica", 30)
        report.drawString(inch*31, inch*40, '%s'%subject)
        report.drawImage('plot_nuisance.png', inch*3, inch*2)
        report.drawImage('plot_fd_qc.png', inch*3, inch*20)

        fd_check_outlier = get_outlier(fd1d, np.genfromtxt(os.path.join(workspace_dir, 'population_fd_distributions.txt')))
        if fd_check_outlier is 'Accepted':
            report.setFillColorRGB(0,180,0)
        else:
             report.setFillColorRGB(250,0,0)
        report.setFont("Helvetica", 50)
        report.drawString(inch*25, inch*27.5, fd_check_outlier)
        report.showPage()
        report.save()
Beispiel #30
0
def plot_epi(epi_img, **kwargs):
    nplt.plot_epi(epi_img, **kwargs)
    return
from nilearn import datasets, plotting, image

data = datasets.fetch_adhd()

mean_func = image.mean_img(data.func[0])

for smoothing in range(0, 25, 5):
    plotting.plot_epi(image.smooth_img(mean_func, smoothing),
                      title="Smoothing %imm" % smoothing)

    plt.title('Histogram of motion parameters')
    # plot the support
    for i, color in enumerate(['b', 'g', 'r', 'c', 'm', 'y']):
        plt.plot([xlist[i, left], xlist[i, right]],
                 [-0.001 - .003 * i, -.001 - .003 * i],
                 linewidth=3,
                 color=color)
    # dummy line for
    plt.plot([xlist[i, left], xlist[i, right]], [-0.018, -.018], color='w')
    plt.axis('tight')
    plt.subplots_adjust(bottom=.12, left=.14)
    plt.savefig(os.path.join(cache, 'rp_%s.png' % sufix), dpi=600)
    # plt.show()


if __name__ == '__main__':
    db = data_parser()
    mask = average_brain_mask()
    mask.to_filename('/tmp/mask.nii.gz')
    masker = NiftiMasker(mask_img=mask, memory=mem).fit()
    imgs = list(db[db.contrast == 'preprocessed'].path)
    tsnr = compute_tsnr(imgs, masker, n_jobs=1)
    tsnr_map = masker.inverse_transform(tsnr.mean(0))
    tsnr_map.to_filename(os.path.join(cache, 'average_tsnr_%s.nii.gz' % sufix))
    # Load pre-computed .nii.gz files
    # tsnr_map = os.path.join(cache, 'average_tsnr_%s.nii.gz' % sufix)
    tsnr_plot = plotting.plot_epi(tsnr_map, vmax=70, colorbar=True)
    tsnr_plot.savefig(os.path.join(cache, 'average_tsnr_%s.png' % sufix),
                      dpi=600)
    motion_histogram(db)
Beispiel #33
0
# We show the original data, and the approximation provided by the
# clustering by averaging the signal on each parcel.

# Grab number of voxels from attribute mask image (mask_img_).
original_voxels = np.sum(get_data(ward.mask_img_))

# Compute mean over time on the functional image to use the mean
# image for compressed representation comparisons
mean_func_img = mean_img(dataset.func[0])

# Compute common vmin and vmax
vmin = np.min(get_data(mean_func_img))
vmax = np.max(get_data(mean_func_img))

plotting.plot_epi(mean_func_img, cut_coords=cut_coords,
                  title='Original (%i voxels)' % original_voxels,
                  vmax=vmax, vmin=vmin, display_mode='xz')

# A reduced dataset can be created by taking the parcel-level average:
# Note that Parcellation objects with any method have the opportunity to
# use a `transform` call that modifies input features. Here it reduces their
# dimension. Note that we `fit` before calling a `transform` so that average
# signals can be created on the brain parcellations with fit call.
fmri_reduced = ward.transform(dataset.func)

# Display the corresponding data compressed using the parcellation using
# parcels=2000.
fmri_compressed = ward.inverse_transform(fmri_reduced)

plotting.plot_epi(index_img(fmri_compressed, 0),
                  cut_coords=cut_coords,
Beispiel #34
0
import matplotlib.pyplot as plt
from nilearn.plotting import plot_epi, plot_stat_map, plot_roi
from nilearn.input_data import NiftiLabelsMasker

### Find voxels of interest ###################################################

# Smooth the data
from nilearn import image
fmri_filename = haxby_dataset.func[0]
fmri_img = image.smooth_img(fmri_filename, fwhm=6)

# Plot the mean image
fig_id = plt.subplot(2, 1, 1)
mean_img = image.mean_img(fmri_img)
plot_epi(mean_img,
         title='Smoothed mean EPI',
         cut_coords=cut_coords,
         axes=fig_id)

# Run a T-test for face and houses
from scipy import stats
fmri_data = fmri_img.get_data()
_, p_values = stats.ttest_ind(fmri_data[..., haxby_labels == 'face'],
                              fmri_data[..., haxby_labels == 'house'],
                              axis=-1)

# Use a log scale for p-values
log_p_values = -np.log10(p_values)
log_p_values[np.isnan(log_p_values)] = 0.
log_p_values[log_p_values > 10.] = 10.
fig_id = plt.subplot(2, 1, 2)
plot_stat_map(nibabel.Nifti1Image(log_p_values, fmri_img.get_affine()),
Beispiel #35
0
import matplotlib.pyplot as plt
from nilearn.plotting import plot_epi, plot_stat_map, plot_roi
from nilearn.input_data import NiftiLabelsMasker

### Find voxels of interest ###################################################

# Smooth the data
from nilearn import image
fmri_filename = haxby_dataset.func[0]
fmri_img = image.smooth_img(fmri_filename, fwhm=6)

# Plot the mean image
fig_id = plt.subplot(2, 1, 1)
mean_img = image.mean_img(fmri_img)
plot_epi(mean_img, title='Smoothed mean EPI', cut_coords=cut_coords,
         axes=fig_id)

# Run a T-test for face and houses
from scipy import stats
fmri_data = fmri_img.get_data()
_, p_values = stats.ttest_ind(fmri_data[..., haxby_labels == 'face'],
                              fmri_data[..., haxby_labels == 'house'],
                              axis=-1)

# Use a log scale for p-values
log_p_values = -np.log10(p_values)
log_p_values[np.isnan(log_p_values)] = 0.
log_p_values[log_p_values > 10.] = 10.
fig_id = plt.subplot(2, 1, 2)
plot_stat_map(nibabel.Nifti1Image(log_p_values, fmri_img.get_affine()), mean_img,
              title="p-values", cut_coords=cut_coords, axes=fig_id)
###############################################################################
# Plotting ROIs (here the mask) with function `plot_roi`
# -------------------------------------------------------
#
# Visualizing ventral temporal region image from haxby dataset overlayed on
# subject specific anatomical image with coordinates positioned automatically on
# region of interest (roi)
plotting.plot_roi(haxby_mask_filename,
                  bg_img=haxby_anat_filename,
                  title="plot_roi")

###############################################################################
# Plotting EPI image with function `plot_epi`
# ---------------------------------------------

# Import image processing tool
from nilearn import image

# Compute the voxel_wise mean of functional images across time.
# Basically reducing the functional image from 4D to 3D
mean_haxby_img = image.mean_img(haxby_func_filename)

# Visualizing mean image (3D)
plotting.plot_epi(mean_haxby_img, title="plot_epi")

###############################################################################
# A call to plotting.show is needed to display the plots when running
# in script mode (ie outside IPython)
plotting.show()
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 20 21:08:28 2015

@author: Rohan Koodli
"""

from nilearn import datasets,plotting,image
import seaborn; seaborn.set()

adhd = datasets.fetch_adhd(n_subjects=1)

epi1 = adhd.func[0]

mean_func = image.mean_img(epi1)
plotting.plot_epi(mean_func,title="Original EPI")


for smoothed in range(5,30,5):
    smoothed_img = image.smooth_img(mean_func,smoothed)
    plotting.plot_epi(smoothed_img,title="Smoothing at %smm"%smoothed)
    
Beispiel #38
0
        jobtype='write')

    # Normalize EPIs
    normalize_func = mem.cache(spm.Normalize)
    out_normalize_func = normalize_func(
        parameter_file=out_segment.outputs.transformation_mat,
        apply_to_files=[
            out_realign.outputs.realigned_files,
            out_segment.outputs.native_gm_image,
            out_segment.outputs.native_wm_image,
            out_segment.outputs.native_csf_image
        ],
        write_voxel_sizes=_utils.get_voxel_dims(func_file),
        write_interp=1,
        jobtype='write')

    # Smooth EPIs
    smooth = mem.cache(spm.Smooth)
    out_smooth = smooth(
        in_files=out_normalize_func.outputs.normalized_files[0],
        fwhm=[5., 5., 5.])

    # Plot mean smoothed EPI
    average = preprocessing.Average()
    average.inputs.in_file = out_smooth.outputs.smoothed_files
    out_average = average.run()
    plotting.plot_epi(out_average.outputs.mean_image)
    plt.show()

os.chdir(current_directory)
# following code:
labels_img.to_filename('parcellation.nii')


##################################################################
# Second, we illustrate the effect that the clustering has on the
# signal. We show the original data, and the approximation provided by
# the clustering by averaging the signal on each parcel.
#
# As you can see below, this approximation is very good, although there
# are only 2000 parcels, instead of the original 60000 voxels

# Display the original data
plot_epi(nifti_masker.inverse_transform(fmri_masked[0]),
         cut_coords=cut_coords,
         title='Original (%i voxels)' % fmri_masked.shape[1],
         vmax=fmri_masked.max(), vmin=fmri_masked.min(),
         display_mode='xz')

# A reduced data can be create by taking the parcel-level average:
# Note that, as many objects in the scikit-learn, the ward object exposes
# a transform method that modifies input features. Here it reduces their
# dimension
fmri_reduced = ward.transform(fmri_masked)

# Display the corresponding data compressed using the parcellation
fmri_compressed = ward.inverse_transform(fmri_reduced)
compressed_img = nifti_masker.inverse_transform(fmri_compressed[0])

plot_epi(compressed_img, cut_coords=cut_coords,
         title='Compressed representation (2000 parcels)',
print('First anatomical nifti image (3D) located is at: %s' %
      haxby_dataset.anat[0])
print('First functional nifti image (4D) is located at: %s' %
      haxby_dataset.func[0])

##############################################################################
# Visualization
from nilearn.image.image import mean_img

# Compute the mean EPI: we do the mean along the axis 3, which is time
func_filename = haxby_dataset.func[0]
mean_haxby = mean_img(func_filename)

from nilearn.plotting import plot_epi, show

plot_epi(mean_haxby)

##############################################################################
# Extracting a brain mask

# Simple computation of a mask from the fMRI data
from nilearn.masking import compute_epi_mask

mask_img = compute_epi_mask(func_filename)

# Visualize it as an ROI
from nilearn.plotting import plot_roi

plot_roi(mask_img, mean_haxby)

##############################################################################
# clustering by averaging the signal on each parcel.

# Grab number of voxels from attribute mask image (mask_img_).
import numpy as np
original_voxels = np.sum(ward.mask_img_.get_data())

# Compute mean over time on the functional image to use the mean
# image for compressed representation comparisons
mean_func_img = mean_img(dataset.func[0])

# Compute common vmin and vmax
vmin = np.min(mean_func_img.get_data())
vmax = np.max(mean_func_img.get_data())

plotting.plot_epi(mean_func_img, cut_coords=cut_coords,
                  title='Original (%i voxels)' % original_voxels,
                  vmax=vmax, vmin=vmin, display_mode='xz')

# A reduced dataset can be created by taking the parcel-level average:
# Note that Parcellation objects with any method have the opportunity to
# use a `transform` call that modifies input features. Here it reduces their
# dimension. Note that we `fit` before calling a `transform` so that average
# signals can be created on the brain parcellations with fit call.
fmri_reduced = ward.transform(dataset.func)

# Display the corresponding data compressed using the parcellation using
# parcels=2000.
fmri_compressed = ward.inverse_transform(fmri_reduced)

plotting.plot_epi(index_img(fmri_compressed, 0),
                  cut_coords=cut_coords,
As we vary the smoothing FWHM, note how we decrease the amount of noise,
but also loose spatial details. In general, the best amount of smoothing
for a given analysis depends on the spatial extent of the effects that
are expected.

"""

from nilearn import datasets, plotting, image

data = datasets.fetch_development_fmri(n_subjects=1)

# Print basic information on the dataset
print('First subject functional nifti image (4D) are located at: %s' %
      data.func[0])

first_epi_file = data.func[0]

# First the compute the mean image, from the 4D series of image
mean_func = image.mean_img(first_epi_file)

# Then we smooth, with a varying amount of smoothing, from none to 20mm
# by increments of 5mm
for smoothing in range(0, 25, 5):
    smoothed_img = image.smooth_img(mean_func, smoothing)
    plotting.plot_epi(smoothed_img,
                      title="Smoothing %imm" % smoothing)


plotting.show()
Here we smooth a mean EPI image and plot the result

As we vary the smoothing FWHM, note how we decrease the amount of noise,
but also loose spatial details. In general, the best amount of smoothing
for a given analysis depends on the spatial extent of the effects that
are expected.

"""

from nilearn import datasets, plotting, image

data = datasets.fetch_adhd(n_subjects=1)

# Print basic information on the dataset
print('First subject functional nifti image (4D) are located at: %s' %
      data.func[0])

first_epi_file = data.func[0]

# First the compute the mean image, from the 4D series of image
mean_func = image.mean_img(first_epi_file)

# Then we smooth, with a varying amount of smoothing, from none to 20mm
# by increments of 5mm
for smoothing in range(0, 25, 5):
    smoothed_img = image.smooth_img(mean_func, smoothing)
    plotting.plot_epi(smoothed_img, title="Smoothing %imm" % smoothing)

from matplotlib import pyplot as plt
plt.show()
        write_voxel_sizes=_utils.get_voxel_dims(anat_file),
        write_interp=1,
        jobtype='write')

    # Normalize EPIs
    normalize_func = mem.cache(spm.Normalize)
    out_normalize_func = normalize_func(
        parameter_file=out_segment.outputs.transformation_mat,
        apply_to_files=[out_realign.outputs.realigned_files,
                        out_segment.outputs.native_gm_image,
                        out_segment.outputs.native_wm_image,
                        out_segment.outputs.native_csf_image],
        write_voxel_sizes=_utils.get_voxel_dims(func_file),
        write_interp=1,
        jobtype='write')

    # Smooth EPIs
    smooth = mem.cache(spm.Smooth)
    out_smooth = smooth(
        in_files=out_normalize_func.outputs.normalized_files[0],
        fwhm=[5., 5., 5.])

    # Plot mean smoothed EPI
    average = preprocessing.Average()
    average.inputs.in_file = out_smooth.outputs.smoothed_files
    out_average = average.run()
    plotting.plot_epi(out_average.outputs.mean_image)
    plt.show()

os.chdir(current_directory)
        target=out_average.outputs.mean_image,
        source=anat_file,
        apply_to_files=[out_segment.outputs.native_gm_image,
                        out_segment.outputs.native_wm_image],
        write_interp=3,
        jobtype='estwrite')

    # Normalize func
    normalize = mem.cache(spm.Normalize)
    write_voxel_sizes = np.round(_utils.get_voxel_dims(func_file), 2).tolist()
    out_normalize = normalize(
        parameter_file=out_segment.outputs.transformation_mat,
        apply_to_files=[out_realign.outputs.realigned_files,
                        out_average.outputs.mean_image],
        write_voxel_sizes=write_voxel_sizes,
        write_interp=2,
        jobtype='write')

    # Smooth func
    smooth = mem.cache(spm.Smooth)
    out_smooth = smooth(
        in_files=out_normalize.outputs.normalized_files,
        fwhm=[5., 5., 5.])

os.chdir(current_directory)

# Plot the mean func map for the last subject
from nilearn import plotting
plotting.plot_epi(out_smooth.outputs.smoothed_files[1])
plotting.show()
# print basic information on the dataset
print('First anatomical nifti image (3D) located is at: %s' %
      haxby_dataset.anat[0])
print('First functional nifti image (4D) is located at: %s' %
      haxby_dataset.func[0])

##############################################################################
# Visualization
from nilearn.image.image import mean_img

# Compute the mean EPI: we do the mean along the axis 3, which is time
func_filename = haxby_dataset.func[0]
mean_haxby = mean_img(func_filename)

from nilearn.plotting import plot_epi, show
plot_epi(mean_haxby)

##############################################################################
# Extracting a brain mask

# Simple computation of a mask from the fMRI data
from nilearn.masking import compute_epi_mask
mask_img = compute_epi_mask(func_filename)

# Visualize it as an ROI
from nilearn.plotting import plot_roi
plot_roi(mask_img, mean_haxby)

##############################################################################
# Applying the mask to extract the corresponding time series
# detect the background.
#
# With data that has already been masked, this will work well, as it lies
# on a homogeneous background

# Load Miyawaki dataset
from nilearn import datasets
miyawaki_dataset = datasets.fetch_miyawaki2008()

# print basic information on the dataset
print('First functional nifti image (4D) is located at: %s' %
      miyawaki_dataset.func[0])  # 4D data

miyawaki_filename = miyawaki_dataset.func[0]
miyawaki_mean_img = image.mean_img(miyawaki_filename)
plot_epi(miyawaki_mean_img, title='Mean EPI image')
###############################################################################
# A NiftiMasker with the default strategy
masker = NiftiMasker()
masker.fit(miyawaki_filename)

# Plot the generated mask
plot_roi(masker.mask_img_, miyawaki_mean_img,
         title="Mask from already masked data")


###############################################################################
# Computing a mask from raw EPI data
###############################################################################
#
# From raw EPI data, there is no uniform background, and a different