def ica_vis(subj_num): # Use the mean as a background mean_img_1 = image.mean_img(BOLD_file_1) mean_img_2 = image.mean_img(BOLD_file_2) mean_img_3 = image.mean_img(BOLD_file_3) plot_stat_map(image.index_img(component_img_1, 5), mean_img_1, output_file=os.path.join(data_path,'sub'+subj_num+'_BOLD','task001_run001'+'ica_1'+'.jpg')) plot_stat_map(image.index_img(component_img_1, 12), mean_img_1, output_file=os.path.join(data_path,'sub'+subj_num+'_BOLD','task001_run001'+'ica_2'+'.jpg')) plot_stat_map(image.index_img(component_img_2, 5), mean_img_2, output_file=os.path.join(data_path,'sub'+subj_num+'_BOLD','task002_run001'+'ica_1'+'.jpg')) plot_stat_map(image.index_img(component_img_2, 12), mean_img_2, output_file=os.path.join(data_path,'sub'+subj_num+'_BOLD','task002_run001'+'ica_2'+'.jpg'))
def test_coregister(): anat_file = os.path.join(os.path.dirname(testing_data.__file__), 'anat.nii.gz') func_file = os.path.join(os.path.dirname(testing_data.__file__), 'func.nii.gz') mean_func_file = os.path.join(tst.tmpdir, 'mean_func.nii.gz') mean_img(func_file).to_filename(mean_func_file) bunch = func.coregister(anat_file, mean_func_file, tst.tmpdir, slice_timing=False, verbose=False, reorient_only=True) assert_true( _check_same_fov(nibabel.load(bunch.coreg_func_), nibabel.load(bunch.coreg_anat_))) assert_true(_check_same_obliquity(bunch.coreg_anat_, bunch.coreg_func_)) assert_true(os.path.isfile(bunch.coreg_transform_)) assert_less(0, len(bunch.coreg_warps_)) assert_true(bunch.coreg_warps_[-1] is None) # Last slice in functional # is without signal for warp_file in bunch.coreg_warps_[:-1]: assert_true(os.path.isfile(warp_file)) # Check environement variables setting assert_raises_regex(RuntimeError, "3dcopy", func.coregister, anat_file, mean_func_file, tst.tmpdir, slice_timing=False, verbose=False, reorient_only=True, AFNI_DECONFLICT='NO') # Check caching does not change the paths bunch2 = func.coregister(anat_file, mean_func_file, tst.tmpdir, slice_timing=False, verbose=False, caching=True, reorient_only=True, AFNI_DECONFLICT='OVERWRITE') assert_equal(bunch.coreg_func_, bunch2.coreg_func_) assert_equal(bunch.coreg_anat_, bunch2.coreg_anat_) assert_equal(bunch.coreg_transform_, bunch2.coreg_transform_) for warp_file, warp_file2 in zip(bunch.coreg_warps_, bunch2.coreg_warps_): assert_equal(warp_file, warp_file2)
def init(subject,layer,filename_irm,filename_mask,filename_stimuli): #we transform the layer and subject variables in order to use them in the input path if subject < 10: subject = '0' + str(subject) else: subject = str(subject) if layer < 10: layer = '0' + str(layer) else: layer = str(layer) print("Initializing tests for subject " + subject + " and layer " + layer + " ...") #we dig out our data from these files and we create the mask in order to have a better rendering in the future plots meanepi = (mean_img(filename_irm)) loaded_stimuli = np.load(filename_stimuli) masker = NiftiMasker(mask_img=filename_mask, detrend=True,standardize=True) masker.fit() fmri_data = masker.transform(filename_irm) fmri_ready = fmri_data[17:-(fmri_data.shape[0]-17-loaded_stimuli.shape[0])] # building the encoding models middle = int(loaded_stimuli.shape[0]/2) y_train = fmri_ready[:middle] y_test = fmri_ready[middle:] X_train = (loaded_stimuli[:middle]) X_test = (loaded_stimuli[middle:]) print("Init done") return X_train,X_test,y_train,y_test,masker,meanepi
def p_map(task, run, p_values_3d, threshold=0.05): """ Generate three thresholded p-value maps. Parameters ---------- task: int Task number run: int Run number p_value_3d: 3D array of p_value. threshold: The cutoff value to determine significant voxels. Returns ------- threshold p-value images """ fmri_img = image.smooth_img('../../../data/sub001/BOLD/' + 'task00' + str(task) + '_run00' + str(run) + '/filtered_func_data_mni.nii.gz', fwhm=6) mean_img = image.mean_img(fmri_img) log_p_values = -np.log10(p_values_3d) log_p_values[np.isnan(log_p_values)] = 0. log_p_values[log_p_values > 10.] = 10. log_p_values[log_p_values < -np.log10(threshold)] = 0 plot_stat_map(nib.Nifti1Image(log_p_values, fmri_img.get_affine()), mean_img, title="Thresholded p-values", annotate=False, colorbar=True)
def _run_interface(self, runtime): import nibabel as nib from nilearn import plotting, datasets, image from nipype.interfaces.base import isdefined import numpy as np import pylab as plt import os wra_img = nib.load(self.inputs.wra_img) canonical_img = nib.load(self.inputs.canonical_img) title = self.inputs.title mean_wraimg = image.mean_img(wra_img) if title != "": filename = title.replace(" ", "_") + ".pdf" else: filename = "plot.pdf" fig = plotting.plot_anat(mean_wraimg, title="wrafunc & canonical single subject", cut_coords=range(-40, 40, 10), display_mode='z') fig.add_edges(canonical_img) fig.savefig(filename) fig.close() self._plot = filename runtime.returncode = 0 return runtime
def make_img(dataset, svc): print("Making Image.....") # Here is the image coef = svc.coef_ # reverse feature selection coef = feature_selection.inverse_transform(coef) # reverse masking weight_img = masker.inverse_transform(coef) # Use the mean image as a background to avoid relying on anatomical data from nilearn import image mean_img = image.mean_img(dataset) mean_img.to_filename( 'projects/niblab/bids_projects/Experiments/ChocoData/derivatives/code/decoding/milkshake_vs_h2O/images/exclusive/p2_mean_nimask.nii' ) # Create the figure from nilearn.plotting import plot_stat_map, show display = plot_stat_map(weight_img, mean_img, title='Milkshake vs. H2O') display.savefig( '/projects/niblab/bids_projects/Experiments/ChocoData/derivatives/code/decoding/milkshake_vs_h2O/images/exclusive/p2_SVM_nimask.png' ) # Saving the results as a Nifti file may also be important weight_img.to_filename( '/projects/niblab/bids_projects/Experiments/ChocoData/derivatives/code/decoding/milkshake_vs_h2O/images/exclusive/p2_SVM_nimask.nii' )
def plot_region_overlay(roi_img, func_img, fname, cmap): """Overlay mask/atlas on mean functional image. Parameters ---------- roi_img : str File name of atlas/mask image func_img : str File name of 4D functional image that was used in extraction. cmap : matplotlib.colors.LinearSegmentedColormap Colormap to use. Returns ------- matplotlib.pyplot.figure Atlas/mask plot """ # compute mean of functional image bg_img = mean_img(func_img) n_cuts = 7 fig, axes = plt.subplots(3, 1, figsize=(15, 6)) g = plot_roi(roi_img, bg_img=bg_img, display_mode='z', axes=axes[0], alpha=.66, cut_coords=np.linspace(-50, 60, num=n_cuts), cmap=cmap, black_bg=True, annotate=False) g.annotate(size=8) g = plot_roi(roi_img, bg_img=bg_img, display_mode='x', axes=axes[1], alpha=.66, cut_coords=np.linspace(-60, 60, num=n_cuts), cmap=cmap, black_bg=True, annotate=False) g.annotate(size=8) g = plot_roi(roi_img, bg_img=bg_img, display_mode='y', axes=axes[2], alpha=.66, cut_coords=np.linspace(-90, 60, num=n_cuts), cmap=cmap, black_bg=True, annotate=False) g.annotate(size=8) fname += '_mask_overlay.png' fig.savefig(fname, bbox_inches='tight') plt.close() # just get figure directory + file for html fig_path = os.path.basename(os.path.dirname(fname)) return os.path.join(fig_path, os.path.basename(fname))
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 t2starw(self): if self._t2starw is None: self._t2starw = image.mean_img(self.t2starw_echoes) self._t2starw = image.math_img('im / np.percentile(im, 95) * 4095', im=self._t2starw) return self._t2starw
def _run_interface(self, runtime): import matplotlib matplotlib.use('Agg') import pylab as plt wra_img = nib.load(self.inputs.wra_img) canonical_img = nib.load(self.inputs.canonical_img) title = self.inputs.title mean_wraimg = image.mean_img(wra_img) if title != "": filename = title.replace(" ", "_") + ".pdf" else: filename = "plot.pdf" fig = plotting.plot_anat(mean_wraimg, title="wrafunc & canonical single subject", cut_coords=range(-40, 40, 10), display_mode='z') fig.add_edges(canonical_img) fig.savefig(filename) fig.close() self._plot = filename runtime.returncode = 0 return runtime
def searchlight(x, y, m=None, groups=None, cv=None, write=False, logger=None, **searchlight_args): """ Wrapper to launch searchlight :param x: Data :param y: labels :param m: mask :param groups: group labels :param cv: cross validator :param write: if image for writing is desired or not :param logger: :param searchlight_args:(default) process_mask_img(None), radius(2mm), estimator(svc), n_jobs(-1), scoring(none), cv(3fold), verbose(0) :return: trained SL object and SL results """ write_to_logger("starting searchlight... ", logger) from nilearn import image, decoding, masking if m is None: m = masking.compute_epi_mask(x) write_to_logger("searchlight params: " + str(searchlight_args)) sl = decoding.SearchLight(mask_img=m, cv=cv, **searchlight_args) sl.fit(x, y, groups) if write: return sl, image.new_img_like(image.mean_img(x), sl.scores_) else: return sl
def _run_interface(self, runtime): import matplotlib matplotlib.use('Agg') import nibabel as nib from nilearn import plotting, datasets, image from nipype.interfaces.base import isdefined import numpy as np import pylab as plt import os wra_img = nib.load(self.inputs.wra_img) canonical_img = nib.load(self.inputs.canonical_img) title = self.inputs.title mean_wraimg = image.mean_img(wra_img) if title != "": filename = title.replace(" ", "_")+".pdf" else: filename = "plot.pdf" fig = plotting.plot_anat(mean_wraimg, title="wrafunc & canonical single subject", cut_coords=range(-40, 40, 10), display_mode='z') fig.add_edges(canonical_img) fig.savefig(filename) fig.close() self._plot = filename runtime.returncode=0 return runtime
def compute_subj_mask(subj): num = 0 print 'Loading BOLD subject #%i...' % subj bold = load(path.join(data_dir, 'sub%03d/BOLD/task001_run00%i/bold_dico.nii.gz' % (subj, num+1))) print 'Averaging BOLD...' avg = image.mean_img(bold) print 'Saving average EPI...' avg_path = path.join(mask_dir, 'mean_sub%03d_run00%i.nii.gz' % (subj, num+1)) affine = avg.get_affine() save(avg, avg_path) print 'Aligning the surface...' cortex.align.automatic('sub%03d' % subj, 'auto01', avg_path) m_thick = cortex.db.get_mask('sub%03d' % subj, 'auto01', type='thick') print 'Thick mask is computed: %i voxels' % m_thick.sum() m_thin = cortex.db.get_mask('sub%03d' % subj, 'auto01', type='thin') print 'Thin mask is computed: %i voxels' % m_thin.sum() # .T is important here, because pycortex and nibabel have different # assumptions about the axis order thick = Nifti1Image(np.float32(m_thick.T), affine) thin = Nifti1Image(np.float32(m_thin.T), affine) save(thick, path.join(mask_dir, 'sub%03d_mask_thick.nii.gz' % subj)) save(thin, path.join(mask_dir, 'sub%03d_mask_thin.nii.gz' % subj))
def generate_fmri_data_for_subject(subject): """ Input : Take as input each fmri file. One file = One block Load all fmri data and apply a global mask mak on it. The global mask is computed using the mask from each fmri run (block). Applying a global mask for a subject uniformize the data. Output: Output fmri_runs for a subject, corrected using a global mask """ fmri_filenames = sorted( glob.glob( os.path.join(paths.rootpath, "fmri-data/en", "sub-%03d" % subject, "func", "resample*.nii"))) masks_filenames = sorted( glob.glob( os.path.join(paths.path2Data, "en/fmri_data/masks", "sub_{}".format(subject), "resample*.pkl"))) masks = [] for file in masks_filenames: with open(file, 'rb') as f: mask = pickle.load(f) masks.append(mask) global_mask = math_img('img>0.5', img=mean_img(masks)) masker = MultiNiftiMasker(global_mask, detrend=True, standardize=True) masker.fit() fmri_runs = [masker.transform(f) for f in tqdm(fmri_filenames)] print(fmri_runs[0].shape) return fmri_runs
def _run_interface(self, runtime): import matplotlib matplotlib.use("Agg") import pylab as plt wra_img = nib.load(self.inputs.wra_img) canonical_img = nib.load(self.inputs.canonical_img) title = self.inputs.title mean_wraimg = image.mean_img(wra_img) if title != "": filename = title.replace(" ", "_") + ".pdf" else: filename = "plot.pdf" fig = plotting.plot_anat( mean_wraimg, title="wrafunc & canonical single subject", cut_coords=range(-40, 40, 10), display_mode="z" ) fig.add_edges(canonical_img) fig.savefig(filename) fig.close() self._plot = filename runtime.returncode = 0 return runtime
def spikes_mask(in_file, in_mask=None, out_file=None): """ Utility function to calculate a mask in which check for :abbr:`EM (electromagnetic)` spikes. """ import os.path as op import nibabel as nb import numpy as np from nilearn.image import mean_img from nilearn.plotting import plot_roi from scipy import ndimage as nd if out_file is None: fname, ext = op.splitext(op.basename(in_file)) if ext == '.gz': fname, ext2 = op.splitext(fname) ext = ext2 + ext out_file = op.abspath('{}_spmask{}'.format(fname, ext)) out_plot = op.abspath('{}_spmask.pdf'.format(fname)) in_4d_nii = nb.load(in_file) orientation = nb.aff2axcodes(in_4d_nii.affine) if in_mask: mask_data = nb.load(in_mask).get_data() a = np.where(mask_data != 0) bbox = np.max(a[0]) - np.min(a[0]), np.max(a[1]) - \ np.min(a[1]), np.max(a[2]) - np.min(a[2]) longest_axis = np.argmax(bbox) # Input here is a binarized and intersected mask data from previous section dil_mask = nd.binary_dilation(mask_data, iterations=int( mask_data.shape[longest_axis] / 9)) rep = list(mask_data.shape) rep[longest_axis] = -1 new_mask_2d = dil_mask.max(axis=longest_axis).reshape(rep) rep = [1, 1, 1] rep[longest_axis] = mask_data.shape[longest_axis] new_mask_3d = np.logical_not(np.tile(new_mask_2d, rep)) else: new_mask_3d = np.zeros(in_4d_nii.shape[:3]) == 1 if orientation[0] in ['L', 'R']: new_mask_3d[0:2, :, :] = True new_mask_3d[-3:-1, :, :] = True else: new_mask_3d[:, 0:2, :] = True new_mask_3d[:, -3:-1, :] = True mask_nii = nb.Nifti1Image(new_mask_3d.astype(np.uint8), in_4d_nii.get_affine(), in_4d_nii.get_header()) mask_nii.to_filename(out_file) plot_roi(mask_nii, mean_img(in_4d_nii), output_file=out_plot) return out_file, out_plot
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)
def correlation_searchlight(A, B, mask=None, radius=2, interpolate=False, n_jobs=1, data_dir=None): """ Parameters ---------- A : list list of (even_trials, odd_trials) tuples for the first condition (A); each tuple represents a subject's mean fMRI data for both trials, and even/odd_trials should be a 3D niimg or path (string) to a NIfTI file B : list list of (even_trials, odd_trials) tuples for the second condition (B); formatted the same as A mask : Niimg-like object boolean image giving location of voxels containing usable signals radius : int radius of the searchlight sphere interpolate : bool whether or not to skip every other sphere and interpolate the results; used to speed up the analysis n_jobs : int number of CPUs to split the work up between (-1 means "all CPUs") data_dir : string path to directory where MVPA results should be stored Returns ------- score_map_fpaths : list list of paths to NIfTI files representing the MVPA scores for each subject """ if not mask: niimgs = [niimg for trials in A + B for niimg in trials] mask = compute_epi_mask(mean_img(concat_imgs(niimgs))) spheres = extract_spheres(get_data(mask), radius, interpolate) _analyze_subject = partial(analyze_subject, spheres=spheres, interpolate=interpolate, mask=mask, data_dir=data_dir) if n_jobs > 1 or n_jobs == -1: score_map_fpaths = concurrent_exec( _analyze_subject, [(i, _A, _B) for i, (_A, _B) in enumerate(zip(A, B))], n_jobs) else: score_map_fpaths = [] for subject_id, (_A, _B) in enumerate(zip(A, B)): score_map_fpath = _analyze_subject(subject_id, _A, _B) score_map_fpaths.append(score_map_fpath) return score_map_fpaths
def spikes_mask(in_file, in_mask=None, out_file=None): """ Utility function to calculate a mask in which check for :abbr:`EM (electromagnetic)` spikes. """ import os.path as op import nibabel as nb import numpy as np from nilearn.image import mean_img from nilearn.plotting import plot_roi from scipy import ndimage as nd if out_file is None: fname, ext = op.splitext(op.basename(in_file)) if ext == '.gz': fname, ext2 = op.splitext(fname) ext = ext2 + ext out_file = op.abspath('{}_spmask{}'.format(fname, ext)) out_plot = op.abspath('{}_spmask.pdf'.format(fname)) in_4d_nii = nb.load(in_file) orientation = nb.aff2axcodes(in_4d_nii.affine) if in_mask: mask_data = nb.load(in_mask).get_data() a = np.where(mask_data != 0) bbox = np.max(a[0]) - np.min(a[0]), np.max(a[1]) - \ np.min(a[1]), np.max(a[2]) - np.min(a[2]) longest_axis = np.argmax(bbox) # Input here is a binarized and intersected mask data from previous section dil_mask = nd.binary_dilation( mask_data, iterations=int(mask_data.shape[longest_axis] / 9)) rep = list(mask_data.shape) rep[longest_axis] = -1 new_mask_2d = dil_mask.max(axis=longest_axis).reshape(rep) rep = [1, 1, 1] rep[longest_axis] = mask_data.shape[longest_axis] new_mask_3d = np.logical_not(np.tile(new_mask_2d, rep)) else: new_mask_3d = np.zeros(in_4d_nii.shape[:3]) == 1 if orientation[0] in ['L', 'R']: new_mask_3d[0:2, :, :] = True new_mask_3d[-3:-1, :, :] = True else: new_mask_3d[:, 0:2, :] = True new_mask_3d[:, -3:-1, :] = True mask_nii = nb.Nifti1Image(new_mask_3d.astype(np.uint8), in_4d_nii.get_affine(), in_4d_nii.get_header()) mask_nii.to_filename(out_file) plot_roi(mask_nii, mean_img(in_4d_nii), output_file=out_plot) return out_file, out_plot
def sbc_group(in_dir, out_dir): """ for each session: load sbc (z transformed) of all subjects and calculate mean & sd """ os.makedirs(out_dir, exist_ok=True) niis = glob(os.path.join(in_dir, "*.nii.gz")) sessions = list( set( map(lambda f: os.path.basename(f).split("_")[-1].split(".")[0], niis))) sessions.sort() print("calc mean sbc for {}".format(sessions)) for ses in sessions: niis = glob(os.path.join(in_dir, "*{}.nii.gz".format(ses))) niis.sort() print(niis) from nilearn import image, plotting out_filename_mean_nii = os.path.join( out_dir, "sbc_1_mean_ses-{}.nii.gz".format(ses)) out_filename_sd_nii = os.path.join( out_dir, "sbc_1_sd_ses-{}.nii.gz".format(ses)) out_filename_mean_png = os.path.join( out_dir, "sbc_2_mean_ses-{}.png".format(ses)) out_filename_sd_png = os.path.join(out_dir, "sbc_2_sd_ses-{}.png".format(ses)) out_filename_list = os.path.join(out_dir, "sbc_ses-{}_scans.txt".format(ses)) mean_sbc = image.mean_img(niis) mean_sbc.to_filename(out_filename_mean_nii) concat_img = image.concat_imgs(niis) sd_sbc = image.math_img("np.std(img, axis=-1)", img=concat_img) sd_sbc.to_filename(out_filename_sd_nii) with open(out_filename_list, "w") as fi: fi.write("\n".join(niis)) display = plotting.plot_stat_map( mean_sbc, threshold=0.5, cut_coords=(0, -52, 18), title="mean sbc {} (fisher z)".format(ses)) display.add_markers(marker_coords=[(0, -52, 18)], marker_color='g', marker_size=300) display.savefig(out_filename_mean_png) display.close() display = plotting.plot_stat_map( sd_sbc, cut_coords=(0, -52, 18), title="sd sbc {} (fisher z)".format(ses)) display.add_markers(marker_coords=[(0, -52, 18)], marker_color='g', marker_size=300) display.savefig(out_filename_sd_png) display.close()
def mean_img(in_file, out_file=None): """ Use nilearn.image.mean_img. Returns ------- out_file: str The absolute path to the output file. """ import nilearn.image as niimg return niimg.mean_img(in_file)
def glass_brain(r2_voxels, subject, current_ROI, ROI_name, name): """ Input : Masked results of r2score Take masked data and project it again in a 3D space Ouput : 3D glassbrain of r2score """ # Get one mask and fit it to the corresponding ROI if current_ROI != -1 and current_ROI <= 5: masks_ROIs_filenames = sorted( glob.glob(os.path.join(paths.path2Data, "en/ROIs_masks/", "*.nii"))) ROI_mask = masks_ROIs_filenames[current_ROI] ROI_mask = NiftiMasker(ROI_mask, detrend=True, standardize=True) ROI_mask.fit() unmasked_data = ROI_mask.inverse_transform(r2_voxels) # Get masks and fit a global mask else: masks = [] masks_filenames = sorted( glob.glob( os.path.join(paths.path2Data, "en/fmri_data/masks", "sub_{}".format(subject), "resample*.pkl"))) for file in masks_filenames: with open(file, 'rb') as f: mask = pickle.load(f) masks.append(mask) global_mask = math_img('img>0.5', img=mean_img(masks)) masker = MultiNiftiMasker(global_mask, detrend=True, standardize=True) masker.fit() unmasked_data = masker.inverse_transform(r2_voxels) display = plot_glass_brain(unmasked_data, display_mode='lzry', threshold='auto', colorbar=True, title='Sub_{}'.format(subject)) if not os.path.exists( os.path.join(paths.path2Figures, 'glass_brain', 'Sub_{}'.format(subject), ROI_name)): os.makedirs( os.path.join(paths.path2Figures, 'glass_brain', 'Sub_{}'.format(subject), ROI_name)) display.savefig( os.path.join(paths.path2Figures, 'glass_brain', 'Sub_{}'.format(subject), ROI_name, 'R_squared_test_{}.png'.format(name))) print( 'Figure Path : ', os.path.join(paths.path2Figures, 'glass_brain', 'Sub_{}'.format(subject), ROI_name, 'R_squared_test_{}.png'.format(name))) display.close()
def _make_psc(data): mean_img = image.mean_img(data) # Replace 0s for numerical reasons mean_data = mean_img.get_data() mean_data[mean_data == 0] = 1 denom = image.new_img_like(mean_img, mean_data) return image.math_img('data / denom[..., np.newaxis] * 100 - 100', data=data, denom=denom)
def mean_nodiff_fct(in_file, bval_file, nodiff_b=0): import os, numpy as np from nilearn import image bvals = np.loadtxt(bval_file) nodiff_index = bvals <= nodiff_b nodiff_img = image.index_img(in_file, nodiff_index) mean_nodiff_img = image.mean_img(nodiff_img) out_file = os.path.abspath('mean_nodiff.nii.gz') mean_nodiff_img.to_filename(out_file) return out_file
def data_to_img(d, img, copy_header=False): """ Wrapper for new_image_like :param img: Image with header you want to add :param d: data :param copy_header: Boolean :param logger: logger instance :return: Image file """ return image.new_img_like(image.mean_img(img), d, copy_header=copy_header)
def _process_second_level_input(second_level_input): """Helper function to process second_level_input.""" if isinstance(second_level_input, pd.DataFrame): return _process_second_level_input_as_dataframe(second_level_input) elif (hasattr(second_level_input, "__iter__") and isinstance(second_level_input[0], FirstLevelModel)): return _process_second_level_input_as_firstlevelmodels( second_level_input) else: return mean_img(second_level_input), None
def gm_mask(db, ref_affine, ref_shape, threshold=.25): """ Utility to create a gm mask by averaging glm images from the db """ from nilearn.image import mean_img import nibabel as nib gm_imgs = db[db.contrast == 'gm'].path.values mean_gm = mean_img(gm_imgs, target_affine=ref_affine, target_shape=ref_shape) gm_mask = nib.Nifti1Image((mean_gm.get_data() > .25).astype('uint8'), ref_affine) return mean_gm, gm_mask
def refvol(self): #create reference bold, bold mask, and mask the ref refs = [nib.load( os.path.join(self.subj.prep_dir,folder[0],file) ) for folder in os.walk(self.subj.prep_dir) for file in folder[2] if '%s_boldref.nii.gz'%(self.space) in file] ref = mean_img(refs) nib.save(ref,self.subj.refvol) masks = [nib.load( os.path.join(self.subj.prep_dir,folder[0],file) ) for folder in os.walk(self.subj.prep_dir) for file in folder[2] if '%s_desc-brain_mask.nii.gz'%(self.space) in file] mask = mean_img(masks) mask = threshold_img(mask,.1) nib.save(mask,self.subj.refvol_mask) os.system('fslmaths %s -bin %s'%(self.subj.refvol_mask,self.subj.refvol_mask)) os.system('fslmaths %s -mas %s %s'%(self.subj.refvol,self.subj.refvol_mask,self.subj.refvol_brain))
def compute_global_masker(rootdir, subjects): masks = [ compute_epi_mask( glob.glob( os.path.join(rootdir, "fmri-data/en", "sub-%03d" % s, "func", "*.nii"))) for s in subjects ] global_mask = math_img('img>0.5', img=mean_img(masks)) masker = MultiNiftiMasker(global_mask, detrend=True, standardize=True) masker.fit() return masker
def compute_global_masker(files): # [[path, path2], [path3, path4]] # return a MultiNiftiMasker object masks = [compute_epi_mask(f) for f in files] global_mask = math_img( 'img>0.5', img=mean_img(masks)) # take the average mask and threshold at 0.5 masker = MultiNiftiMasker( global_mask, detrend=True, standardize=True ) # return a object that transforms a 4D barin into a 2D matrix of voxel-time and can do the reverse action masker.fit() return masker
def create_group_mask(mask_loc, fmriprep_dir, threshold=.8, verbose=True): if verbose: print('Creating Group mask...') makedirs(path.dirname(mask_loc), exist_ok=True) brainmasks = glob( path.join(fmriprep_dir, 'sub-s???', '*', 'func', '*MNI152NLin2009cAsym_brainmask*')) mean_mask = image.mean_img(brainmasks) group_mask = image.math_img("a>=%s" % str(threshold), a=mean_mask) group_mask.to_filename(mask_loc) if verbose: print('Finished creating group mask')
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
def compute_global_masker(files, **kwargs): # [[path, path2], [path3, path4]] """Returns a NiftiMasker object from list (of list) of files. Arguments: - files: list (of list of str) Returns: - masker: NiftiMasker """ masks = [compute_epi_mask(f) for f in files] global_mask = math_img('img>0.95', img=mean_img(masks)) # take the average mask and threshold at 0.5 masker = NiftiMasker(global_mask, **kwargs) masker.fit() return masker
def dataToImg(d, img, copy_header=False, logger=None): """ Wrapper for new_image_like :param img: Image with header you want to add :param d: data :param copy_header: Boolean :param logger: logger instance :return: Image file """ from nilearn import image write_to_logger("converting data to image...", logger) return image.new_img_like(image.mean_img(img), d, copy_header=copy_header)
def plot_segmentation( img, gm_filename, wm_filename=None, csf_filename=None, output_filename=None, cut_coords=None, display_mode='ortho', cmap=None, title='GM + WM + CSF segmentation', close=False): """ Plot a contour mapping of the GM, WM, and CSF of a subject's anatomical. Parameters ---------- img_filename: string or image object path of file containing image data, or image object simply gm_filename: string path of file containing Grey Matter template wm_filename: string (optional) path of file containing White Matter template csf_filename: string (optional) path of file containing Cerebro-Spinal Fluid template """ # misc if cmap is None: cmap = plt.cm.gray if cut_coords is None: cut_coords = (-10, -28, 17) if display_mode in ['x', 'y', 'z']: cut_coords = (cut_coords['xyz'.index(display_mode)],) # plot img img = mean_img(img) img = reorder_img(img, resample="continuous") _slicer = plot_img(img, cut_coords=cut_coords, display_mode=display_mode, cmap=cmap, black_bg=True) # add TPM contours gm = nibabel.load(gm_filename) _slicer.add_contours(gm, levels=[.51], colors=["r"]) if not wm_filename is None: _slicer.add_contours(wm_filename, levels=[.51], colors=["g"]) if not csf_filename is None: _slicer.add_contours(csf_filename, levels=[.51], colors=['b']) # misc _slicer.title(title, size=12, color='w', alpha=0) if not output_filename is None: plt.savefig(output_filename, bbox_inches='tight', dpi=200, facecolor="k", edgecolor="k") if close: plt.close()
def loader(anat, downsample, target_affine, dataroot, subject, maskpath, nrun, niifilename, labels, **kwargs): ''' All parameters are submitted as cfg dictionary. Given parameters in cfg, return masked and concatenated over runs data Input anat: MNI template downsample: 1 or 0 target_affine: downsampling matrix dataroot: element of path to data subject: folder in dataroot with subject data maskpath: path to mask nrun: number of runs niifilename: how is the data file called labels: labels from load_labels function Output dict(nii_func=nii_func,nii_mean=nii_mean,masker=masker,nii_mask=nii_mask) nii_func: 4D data nii_mean: mean over 4th dimension masker: masker object from nibabel nii_mask: 3D mask ''' nii_func = list() for r in range(nrun): fname = '{0}/{1}/run{2}/{3}'.format(dataroot, subject, r+1, niifilename) # Assumption about file location nii_img = load(fname, mmap=False) nii_img.set_sform(anat.get_sform()) # Get mean over 4D nii_mean = mean_img(nii_img) # Masking nii_mask = load(maskpath) nii_mask.set_sform(anat.get_sform()) # Binarize the mask nii_mask = check_binary(nii_mask) if downsample: nii_img = resample_img(nii_img, target_affine=target_affine) nii_mask = resample_img(nii_mask, target_affine=target_affine, interpolation='nearest') masker = NiftiMasker(nii_mask, standardize=True) nii_img = masker.fit_transform(nii_img) # Drop zero timepoints, zscore nii_img = drop_labels(nii_img, labels.get('to_drop_zeros')[r]) nii_func.append(stats.zscore(nii_img, axis=0)) # zscore over time # throw data together nii_func = np.concatenate(nii_func) return dict(nii_func=nii_func, nii_mean=nii_mean, masker=masker, nii_mask=nii_mask)
def multi_session_time_slice_diffs(img_list): """ time slice difference on several 4D images Parameters ---------- img_list: list of 4D Niimg-like Input multi-session images returns ------- results : dict see time_slice_diffs docstring for details. note ---- The results are accumulated across sessions """ results = {} for i, img in enumerate(img_list): results_ = time_slice_diffs(img) if i == 0: for key, val in results_.items(): # special case for 'session_length' to make # aggregation easier later on results[key] = val if key != 'session_length' else [val] else: results['volume_mean_diff2'] = np.hstack(( results['volume_mean_diff2'], results_['volume_mean_diff2'])) results['slice_mean_diff2'] = np.vstack(( results['slice_mean_diff2'], results_['slice_mean_diff2'])) results['volume_means'] = np.hstack(( results['volume_means'], results_['volume_means'])) results['diff2_mean_vol'] = mean_img( [results['diff2_mean_vol'], results_['diff2_mean_vol']]) results['slice_diff2_max_vol'] = nib.Nifti1Image( np.maximum(results_['slice_diff2_max_vol'].get_data(), results['slice_diff2_max_vol'].get_data()), results['slice_diff2_max_vol'].get_affine() ) results['session_length'].append(results_['session_length']) return results
# 'aws' == amazon web services also OK dataset = HcpDataset(fetcher_type='aws') # only fetch anatomical files. files = dataset.fetch(n_subjects=2, data_types=['task']) # Filter subject 2 only nii_files = filter(lambda fil: fil and '100408' in fil and fil.endswith('_LR.nii.gz'), files) tasks = ['emotion', 'gambling', 'language', 'motor', 'social', 'wm'] # Compute mean images mean_imgs = dict() for task in tasks: mean_imgs[task] = mean_img(filter(lambda fil: task.upper() in fil, nii_files)[0]) # Now make a matrix. fh = plt.figure(figsize=(18, 10)) for ti1, task1 in enumerate(tasks): for ti2 in range(0, ti1 - 1): task2 = tasks[ti2] ax = fh.add_subplot(5, 5, (ti1 - 1) * 5 + ti2 + 1) img = math_img("img1 - img2", img1=mean_imgs[task1], img2=mean_imgs[task2]) plot_stat_map( img, title='%s - %s' % (task1, task2), symmetric_cbar=True, black_bg=True, display_mode='yz',
y_train=np.array(y_train.astype('double')) y_test[y_test=='scissors']=1 y_test[y_test=='scrambledpix']=-1 y_test=np.array(y_test.astype('double')) masker = NiftiMasker(mask_strategy='epi',standardize=True) X_train = masker.fit_transform(X_train) X_test = masker.transform(X_test) mask = masker.mask_img_.get_data().astype(np.bool) mask= _crop_mask(mask) background_img = mean_img(data_files.func[0]) X_train, y_train, _, y_train_mean, _ = center_data(X_train, y_train, fit_intercept=True, normalize=False,copy=False) X_test-=X_train.mean(axis=0) X_test/=np.std(X_train,axis=0) alpha=1 ratio=0.5 k=200 solver_params = dict(tol=1e-6, max_iter=5000,prox_max_iter=100) init=None w,obj,init=tvksp_solver(X_train,y_train,alpha,ratio,k,mask=mask,init=init,loss="logistic",verbose=1,**solver_params) coef=w[:-1] intercept=w[-1]
import numpy as np import pandas as pd import nibabel as nib from nilearn.plotting import plot_stat_map, show from nilearn.image import mean_img from nistats.design_matrix import make_design_matrix from nistats.glm import FirstLevelGLM from nistats.datasets import fetch_spm_auditory # fetch spm auditory data subject_data = fetch_spm_auditory() fmri_img = nib.concat_images(subject_data.func) # compute bg unto which activation will be projected mean_img = mean_img(fmri_img) # construct experimental paradigm tr = 7. n_scans = 96 epoch_duration = 6 * tr # duration in seconds conditions = ['rest', 'active'] * 8 n_blocks = len(conditions) duration = epoch_duration * np.ones(n_blocks) onset = np.linspace(0, (n_blocks - 1) * epoch_duration, n_blocks) paradigm = pd.DataFrame( {'onset': onset, 'duration': duration, 'name': conditions}) # construct design matrix frame_times = np.linspace(0, (n_scans - 1) * tr, n_scans) drift_model = 'Cosine'
from nilearn.image import mean_img import nibabel as nib from nistats.glm import FirstLevelGLM from nistats import datasets # write directory write_dir = path.join(getcwd(), 'results') if not path.exists(write_dir): mkdir(write_dir) # Data and analysis parameters data = datasets.fetch_fiac_first_level() fmri_img = [data['func1'], data['func2']] 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] # GLM specification fmri_glm = FirstLevelGLM(data['mask'], standardize=False, noise_model='ar1') # GLM fitting fmri_glm.fit(fmri_img, design_matrices) # compute fixed effects of the two runs and compute related images n_columns = design_matrices[0].shape[1] def pad_vector(contrast_, n_columns): return np.hstack((contrast_, np.zeros(n_columns - len(contrast_)))) contrasts = {'SStSSp_minus_DStDSp': pad_vector([1, 0, 0, -1], n_columns),
### Look at the SVC's discriminating weights coef = svc.coef_ # reverse feature selection coef = feature_selection.inverse_transform(coef) # reverse masking weight_img = nifti_masker.inverse_transform(coef) ### Create the figure from nilearn import image import matplotlib.pyplot as plt from nilearn.plotting import plot_stat_map # Plot the mean image because we have no anatomic data mean_img = image.mean_img(dataset_files.func) plot_stat_map(weight_img, mean_img, title='SVM weights') ### Saving the results as a Nifti file may also be important import nibabel nibabel.save(weight_img, 'haxby_face_vs_house.nii') ### Cross validation ########################################################## from sklearn.cross_validation import LeaveOneLabelOut ### Define the cross-validation scheme used for validation. # Here we use a LeaveOneLabelOut cross-validation on the session label # divided by 2, which corresponds to a leave-two-session-out cv = LeaveOneLabelOut(session // 2)
# Apply this sample mask to X (fMRI data) and y (behavioral labels) # Because the data is in one single large 4D image, we need to use # index_img to do the split easily from nilearn.image import index_img func_filenames = data_files.func[0] X_train = index_img(func_filenames, condition_mask_train) X_test = index_img(func_filenames, condition_mask_test) y_train = target[condition_mask_train] y_test = target[condition_mask_test] # Compute the mean epi to be used for the background of the plotting from nilearn.image import mean_img background_img = mean_img(func_filenames) ############################################################################## # Fit SpaceNet with a Graph-Net penalty from nilearn.decoding import SpaceNetClassifier # Fit model on train data and predict on test data decoder = SpaceNetClassifier(memory="nilearn_cache", penalty="graph-net") decoder.fit(X_train, y_train) y_pred = decoder.predict(X_test) accuracy = (y_pred == y_test).mean() * 100.0 print("Graph-net classification accuracy : %g%%" % accuracy) # Visualization from nilearn.plotting import plot_stat_map, show
memory_level=1) fmri_masked = nifti_masker.fit_transform(fmri_img) from sklearn.feature_selection import f_classif f_values, p_values = f_classif(fmri_masked, y) p_values = -np.log10(p_values) p_values[p_values > 10] = 10 p_unmasked = nifti_masker.inverse_transform(p_values).get_data() ### Visualization ############################################################# import matplotlib.pyplot as plt # Use the fmri mean image as a surrogate of anatomical data from nilearn import image from nilearn.plotting import plot_stat_map mean_fmri = image.mean_img(fmri_img) plot_stat_map(nibabel.Nifti1Image(searchlight.scores_, mean_fmri.get_affine()), mean_fmri, title="Searchlight", display_mode="z", cut_coords=[-16], colorbar=False) ### F_score results p_ma = np.ma.array(p_unmasked, mask=np.logical_not(process_mask)) plot_stat_map(nibabel.Nifti1Image(p_ma, mean_fmri.get_affine()), mean_fmri, title="F-scores", display_mode="z", cut_coords=[-16], colorbar=False) plt.show()
# Normalize estimated components, for thresholding to make sense components_masked -= components_masked.mean(axis=0) components_masked /= components_masked.std(axis=0) # Threshold components_masked[components_masked < 0.8] = 0 # Now invert the masking operation, going back to a full 3D # representation component_img = masker.inverse_transform(components_masked) components = component_img.get_data() # Using a masked array is important to have transparency in the figures components = np.ma.masked_equal(components, 0, copy=False) ### Visualize the results ##################################################### # Show some interesting components # Use the mean as a background import nibabel import pylab as plt from nilearn import image from nilearn.plotting import plot_stat_map mean_img = image.mean_img(dataset.func[0]) plot_stat_map(nibabel.Nifti1Image(component_img.get_data()[:, :, :, 5], component_img.get_affine()), mean_img) plot_stat_map(nibabel.Nifti1Image(component_img.get_data()[:, :, :, 12], component_img.get_affine()), mean_img) plt.show()
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()
contrast['SStSSp_minus_DStDSp'] = _pad_vector([1, 0, 0, -1], n_columns) contrast['DStDSp_minus_SStSSp'] = - contrast['SStSSp_minus_DStDSp'] contrast['DSt_minus_SSt'] = _pad_vector([- 1, - 1, 1, 1], n_columns) contrast['DSp_minus_SSp'] = _pad_vector([- 1, 1, - 1, 1], n_columns) contrast['DSt_minus_SSt_for_DSp'] = _pad_vector([0, - 1, 0, 1], n_columns) contrast['DSp_minus_SSp_for_DSt'] = _pad_vector([0, 0, - 1, 1], n_columns) contrast['Deactivation'] = _pad_vector([- 1, - 1, - 1, - 1, 4], n_columns) contrast['Effects_of_interest'] = np.eye(n_columns)[:5] return contrast # compute fixed effects of the two runs and compute related images n_columns = np.load(design_files[0])['X'].shape[1] contrasts = make_fiac_contrasts(n_columns) print('Computing contrasts...') mean_ = mean_img(data['func1']) for index, (contrast_id, contrast_val) in enumerate(contrasts.items()): print(' Contrast % 2i out of %i: %s' % ( index + 1, len(contrasts), contrast_id)) z_image_path = path.join(write_dir, '%s_z_map.nii' % contrast_id) z_map, = multi_session_model.transform( [contrast_val] * 2, contrast_name=contrast_id, output_z=True) nib.save(z_map, z_image_path) # make a snapshot of the contrast activation if contrast_id == 'Effects_of_interest': vmax = max(- z_map.get_data().min(), z_map.get_data().max()) vmin = - vmax display = plot_stat_map(z_map, bg_img=mean_, threshold=2.5, title=contrast_id) display.savefig(path.join(write_dir, '%s_z_map.png' % contrast_id))
############################################################################### # From already masked data from nilearn.input_data import NiftiMasker import nilearn.image as image from nilearn.plotting.img_plotting import plot_roi # Load Miyawaki dataset 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) # This time, we can use the NiftiMasker without changing the default mask # strategy, as the data has already been masked, and thus lies on a # homogeneous background masker = NiftiMasker() masker.fit(miyawaki_filename) plot_roi(masker.mask_img_, miyawaki_mean_img, title="Mask from already masked data") ############################################################################### # From raw EPI data
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()
grouped_fmri_masked, grouped_conditions_encoded) # f_regression implicitly adds intercept pvals_bonferroni *= fmri_masked.shape[1] pvals_bonferroni[np.isnan(pvals_bonferroni)] = 1 pvals_bonferroni[pvals_bonferroni > 1] = 1 neg_log_pvals_bonferroni = -np.log10(pvals_bonferroni) neg_log_pvals_bonferroni_unmasked = nifti_masker.inverse_transform( neg_log_pvals_bonferroni).get_data() ### Visualization ############################################################# import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import ImageGrid # Use the fmri mean image as a surrogate of anatomical data from nilearn import image mean_fmri = image.mean_img(dataset_files.func).get_data() # Various plotting parameters picked_slice = 27 # plotted slice vmin = -np.log10(0.1) # 10% corrected vmax = min(np.amax(neg_log_pvals), np.amax(neg_log_pvals_bonferroni)) grid = ImageGrid(plt.figure(), 111, nrows_ncols=(1, 2), direction="row", axes_pad=0.05, add_all=True, label_mode="1", share_all=True, cbar_location="right", cbar_mode="single", cbar_size="7%", cbar_pad="1%") # Plot thresholded p-values map corresponding to F-scores ax = grid[0] p_ma = np.ma.masked_less(neg_log_pvals_bonferroni_unmasked, vmin) ax.imshow(np.rot90(mean_fmri[..., picked_slice]), interpolation='nearest', cmap=plt.cm.gray)
# Smooth the data using image processing module from nilearn from nilearn import image # 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
memory_level=1) fmri_masked = nifti_masker.fit_transform(fmri_img) from sklearn.feature_selection import f_classif f_values, p_values = f_classif(fmri_masked, y) p_values = -np.log10(p_values) p_values[np.isnan(p_values)] = 0 p_values[p_values > 10] = 10 p_unmasked = nifti_masker.inverse_transform(p_values).get_data() ### Visualization ############################################################# import matplotlib.pyplot as plt # Use the fmri mean image as a surrogate of anatomical data from nilearn import image mean_fmri = image.mean_img(fmri_img).get_data() ### Searchlight results plt.figure(1) # searchlight.scores_ contains per voxel cross validation scores s_scores = np.ma.array(searchlight.scores_, mask=np.logical_not(process_mask)) plt.imshow(np.rot90(mean_fmri[..., picked_slice]), interpolation='nearest', cmap=plt.cm.gray) plt.imshow(np.rot90(s_scores[..., picked_slice]), interpolation='nearest', cmap=plt.cm.hot, vmax=1) plt.axis('off') plt.title('Searchlight') ### F_score results plt.figure(2) p_ma = np.ma.array(p_unmasked, mask=np.logical_not(process_mask))
# # First we display the labels of the clustering in the brain. # # To visualize results, we need to transform the clustering's labels back # to a neuroimaging volume. For this, we use the NiftiMasker's # inverse_transform method. from nilearn.plotting import plot_roi, plot_epi, show # Unmask the labels # Avoid 0 label labels = ward.labels_ + 1 labels_img = nifti_masker.inverse_transform(labels) from nilearn.image import mean_img mean_func_img = mean_img(func_filename) first_plot = plot_roi(labels_img, mean_func_img, title="Ward parcellation", display_mode='xz') # common cut coordinates for all plots cut_coords = first_plot.cut_coords ################################################################## # labels_img is a Nifti1Image object, it can be saved to file with the # following code: labels_img.to_filename('parcellation.nii') ##################################################################
""" Plot Haxby masks ================= Small script to plot the masks of the Haxby dataset. """ from scipy import linalg import matplotlib.pyplot as plt from nilearn import datasets data = datasets.fetch_haxby() # Build the mean image because we have no anatomic data from nilearn import image mean_img = image.mean_img(data.func[0]) z_slice = -24 from nilearn.image.resampling import coord_transform affine = mean_img.get_affine() _, _, k_slice = coord_transform(0, 0, z_slice, linalg.inv(affine)) k_slice = round(k_slice) fig = plt.figure(figsize=(4, 5.4), facecolor='k') from nilearn.plotting import plot_anat display = plot_anat(mean_img, display_mode='z', cut_coords=[z_slice], figure=fig) display.add_contours(data.mask_vt[0], contours=1, antialiased=False, linewidths=4., levels=[0], colors=['red']) display.add_contours(data.mask_house[0], contours=1, antialiased=False,
from sklearn.decomposition import FastICA n_components = 20 ica = FastICA(n_components=n_components, random_state=42) components_masked = ica.fit_transform(data_masked.T).T # Normalize estimated components, for thresholding to make sense components_masked -= components_masked.mean(axis=0) components_masked /= components_masked.std(axis=0) # Threshold components_masked[components_masked < .8] = 0 # Now invert the masking operation, going back to a full 3D # representation component_img = masker.inverse_transform(components_masked) ### Visualize the results ##################################################### # Show some interesting components import matplotlib.pyplot as plt from nilearn import image from nilearn.plotting import plot_stat_map # Use the mean as a background mean_img = image.mean_img(func_filename) plot_stat_map(image.index_img(component_img, 5), mean_img) plot_stat_map(image.index_img(component_img, 12), mean_img) plt.show()
hrf_model = 'spm + derivative' # The hemodunamic response finction is the SPM canonical one ######################################################################### # Resample the images. # # This is achieved by the concat_imgs function of Nilearn. from nilearn.image import concat_imgs, resample_img, mean_img fmri_img = [concat_imgs(subject_data.func1, auto_resample=True), concat_imgs(subject_data.func2, auto_resample=True)] affine, shape = fmri_img[0].affine, fmri_img[0].shape print('Resampling the second image (this takes time)...') fmri_img[1] = resample_img(fmri_img[1], affine, shape[:3]) ######################################################################### # Create mean image for display mean_image = mean_img(fmri_img) ######################################################################### # Make design matrices import numpy as np import pandas as pd from nistats.design_matrix import make_first_level_design_matrix design_matrices = [] ######################################################################### # loop over the two sessions for idx, img in enumerate(fmri_img, start=1): # Build experimental paradigm n_scans = img.shape[-1] events = pd.read_table(subject_data['events{}'.format(idx)]) # Define the sampling times for the design matrix