def run(idx, reduction, alpha, mask, raw, n_components, init, func_filenames): output_dir = join(trace_folder, 'experiment_%i' % idx) try: os.makedirs(output_dir) except OSError: pass dict_fact = SpcaFmri(mask=mask, smoothing_fwhm=3, batch_size=40, shelve=not raw, n_components=n_components, replacement=False, dict_init=fetch_atlas_smith_2009().rsn70 if init else None, reduction=reduction, alpha=alpha, random_state=0, n_epochs=2, l1_ratio=0.5, backend='c', memory=expanduser("~/nilearn_cache"), memory_level=2, verbose=5, n_jobs=1, trace_folder=output_dir ) print('[Example] Learning maps') t0 = time.time() dict_fact.fit(func_filenames, raw=raw) t1 = time.time() - t0 print('[Example] Dumping results') # Decomposition estimator embeds their own masker masker = dict_fact.masker_ components_img = masker.inverse_transform(dict_fact.components_) components_img.to_filename(join(output_dir, 'components_final.nii.gz')) print('[Example] Run in %.2f s' % t1) # Show components from both methods using 4D plotting tools import matplotlib.pyplot as plt from nilearn.plotting import plot_prob_atlas, show print('[Example] Displaying') fig, axes = plt.subplots(2, 1) plot_prob_atlas(components_img, view_type="filled_contours", axes=axes[0]) plot_stat_map(index_img(components_img, 0), axes=axes[1], colorbar=False, threshold=0) plt.savefig(join(output_dir, 'components.pdf')) show()
def connectome_graph (fullMatrix): # here it is set to threshold 1% for matrix in fullMatrix: plotting.plot_connectome(matrix, coords, edge_threshold="99%", colorbar=True) plotting.show()
# The NiftiMasker report allows us to see the mask before and after resampling. # Simply hover over the report to see the mask from the original image. import numpy as np masker = NiftiMasker(mask_strategy='epi', target_affine=np.eye(3) * 8) masker.fit(epi_img) report = masker.generate_report() report ############################################################################### # After mask computation: extracting time series ############################################################################### # # Extract time series # trended vs detrended trended = NiftiMasker(mask_strategy='epi') detrended = NiftiMasker(mask_strategy='epi', detrend=True) trended_data = trended.fit_transform(epi_img) detrended_data = detrended.fit_transform(epi_img) # The timeseries are numpy arrays, so we can manipulate them with numpy print("Trended: mean %.2f, std %.2f" % (np.mean(trended_data), np.std(trended_data))) print("Detrended: mean %.2f, std %.2f" % (np.mean(detrended_data), np.std(detrended_data))) show()
def MCA_cm_plots(mca, MCA_components, MNIcoords, num_edge=200, title=None): vmin = -4 vmax = 4 fh = plt.figure(figsize=(10, 5)) for component in range(MCA_components): ax = fh.add_subplot(1, MCA_components, component + 1) cm = mca.edge_scores_mat[:, :, component] cm = cm + cm.T cm = matrix_threshold(cm, num_edge=num_edge) plotting.plot_connectome(cm, MNIcoords, axes=ax, node_size=0, edge_cmap='vlag', annotate=False, edge_vmin=vmin, edge_vmax=vmax, colorbar=False, display_mode='z', edge_kwargs={ 'Alpha': 0.75, 'lw': 1 }) plt.title(np.round(mca.eigenvalues_[component] * 100, 2)) if title is not None: plt.savefig(title + 'MCA_edgeweights.svg', dpi=600) plotting.show() # plot the colorbar fh = plt.figure(figsize=(2.5, 2.5)) ax = fh.add_subplot(1, 1, 1) plotting.plot_connectome(cm, MNIcoords, axes=ax, node_size=0, edge_cmap='vlag', annotate=False, edge_vmin=vmin, edge_vmax=vmax, colorbar=True, display_mode='z', edge_kwargs={ 'Alpha': 0.75, 'lw': 1 }) if title is not None: plt.savefig(title + 'MCA_colorbar.svg', dpi=600) plotting.show() # plot the individual MCA weights plt.figure(figsize=(2.5, 2.5)) plt.imshow(mca.ind_scores[:, 0:MCA_components], cmap='vlag', vmin=-1, vmax=1, aspect="auto") plt.xticks(range(MCA_components), np.arange(1, MCA_components + 1)) plt.xlabel('Components') plt.ylabel('Participants') if title is not None: plt.savefig(title + 'MCA_indweights.svg', dpi=600) plt.show()
def show_image_from_file(path): print(path) plotting.plot_img(path) plotting.show()
def map_plane(estimates, atlas, path, suffix="", plane="z", cut_coords=1, cbar=False, vmin=0.0, vmaxs=[], cmaps=[], print_fig=True, verbose=False): from nilearn import image, plotting if len(vmaxs) < len(estimates.columns): vmaxs = [round(v, 2) for v in estimates.max()] for f, feature in enumerate(estimates.columns): stat_map = image.copy_img(atlas).get_data() data = estimates[feature] if verbose: print("{:20s} Min: {:6.4f} Mean: {:6.4f} Max: {:6.4f}".format( feature, min(data), np.mean(data), max(data))) if not verbose and print_fig: print("\n{}".format(feature)) for i, value in enumerate(data): stat_map[stat_map == i + 1] = value stat_map = image.new_img_like(atlas, stat_map) if plane == "ortho": cut_coords = None display = plotting.plot_stat_map(stat_map, display_mode=plane, cut_coords=cut_coords, symmetric_cbar=False, colorbar=cbar, cmap=cmaps[f], threshold=vmin, vmax=vmaxs[f], alpha=0.5, annotate=False, draw_cross=False) file_name = "{}/{}{}.png".format(path, feature, suffix) display.savefig(file_name, dpi=250) transparent_background(file_name) if print_fig: display.close() display = plotting.plot_stat_map(stat_map, display_mode=plane, cut_coords=cut_coords, symmetric_cbar=False, colorbar=cbar, cmap=cmaps[f], threshold=vmin, vmax=vmaxs[f], alpha=0.5, annotate=True, draw_cross=False) plotting.show() display.close()
def plot_nii(nii_file): plotting.plot_img(nii_file) plotting.show()
black_bg=True, display_mode='xz', threshold=3) ############################################################################### # Plotting the sign of the activation plotting.plot_glass_brain(localizer_tmap_filename, threshold=0, colorbar=True, plot_abs=False) ############################################################################### # The sign of the activation and a colorbar plotting.plot_glass_brain(localizer_tmap_filename, threshold=3, colorbar=True, plot_abs=False) ############################################################################### # Different projections for the left and right hemispheres # --------------------------------------------------------- # # Hemispheric sagittal cuts plotting.plot_glass_brain(localizer_tmap_filename, title='plot_glass_brain with display_mode="lzr"', black_bg=True, display_mode='lzr', threshold=3) ############################################################################### plotting.plot_glass_brain(localizer_tmap_filename, threshold=0, colorbar=True, title='plot_glass_brain with display_mode="lyrz"', plot_abs=False, display_mode='lyrz') plotting.show()
def __init__(self, stat_img='path', **options): from nilearn import plotting plotting.plot_glass_brain(stat_img, **options) plotting.show()
def __init__(self, maps_img='path', **options): from nilearn import plotting plotting.plot_prob_atlas(maps_img, **options) plotting.show()
def __init__(self, atlas_filename='path', **options): from nilearn import plotting plotting.plot_roi(atlas_filename, **options) plotting.show()
def __init__(self, sourceFile='path', **options): from nilearn import plotting plotting.plot_img(sourceFile, **options) plotting.show()
def plot_connectome_threshold(cm, MNIcoords, num_edge=250, display_mode='lzr', edge_alpha=0.75, edge_lw=1, title='test'): ''' Plots the top/bottom 'num_edges' in a nilearn connectome plot as opposed to a percentage of the edges. Colors the positive and negative edges seperately using vlag ''' # create positive colormap new_cmap = sns.cm.vlag(np.arange(0.55, 1, .001), alpha=None) new_cmap = ListedColormap(new_cmap) # get positive / negative data cm, cm_pos, cm_neg = matrix_threshold(cm, num_edge=num_edge) # get vmin/vmax edge_vmin = np.min(cm_pos[cm_pos > 0]) edge_vmax = np.max(cm_pos) # plot first connectome connectome = plotting.plot_connectome(cm_pos, MNIcoords, node_size=0, node_color='black', edge_cmap=new_cmap, edge_vmin=edge_vmin, edge_vmax=edge_vmax, display_mode=display_mode, edge_kwargs={ 'Alpha': edge_alpha, 'lw': edge_lw }, node_kwargs={ 'Alpha': 0, 'lw': 0 }, alpha=0.1, annotate=False, colorbar=True) # saves the colorbar out plt.savefig(title + '1.svg') # negative plot new_cmap = sns.cm.vlag(np.arange(0, 0.45, .001), alpha=None) new_cmap = ListedColormap(np.flipud(new_cmap)) #adjust cm cm_neg = cm_neg * -1 # new vmins edge_vmin = np.min(cm_neg[cm_neg > 0]) edge_vmax = np.max(cm_neg) #add graph connectome.add_graph(cm_neg, MNIcoords, node_size=0, node_color='black', edge_cmap=new_cmap, edge_vmin=edge_vmin, edge_vmax=edge_vmax, edge_kwargs={ 'Alpha': edge_alpha, 'lw': edge_lw }, node_kwargs={ 'Alpha': 0, 'lw': 0 }, colorbar=True) plt.savefig(title + '2.svg') plotting.show()
def plot_reconstruction_diff(self, block, filename='', show=True, plot_abs=False, t=0, labeler=lambda b: None, zscore_bound=3, **kwargs): if filename == '' and t is None: filename = '%s-%s_htfa_reconstruction_diff.pdf' filename = filename % (self.common_name(), str(block)) elif filename == '': filename = '%s-%s_htfa_reconstruction_diff_tr%d.pdf' filename = filename % (self.common_name(), str(block), t) results = self.results(block) factor_centers = results['factor_centers'] factor_log_widths = results['factor_log_widths'] if block is not None: weights = results['weights'] else: block = np.random.choice(self.num_blocks, 1)[0] weights = self.enc.hyperparams.state_vardict( )['block']['weights']['mu'][block] factors = tfa_models.radial_basis(self.voxel_locations, factor_centers, factor_log_widths) times = (0, self.voxel_activations[block].shape[0]) reconstruction = weights[times[0]:times[1], :] @ factors diff = self.voxel_activations[block] - reconstruction if zscore_bound is None: zscore_bound = diff.max().item() image = utils.cmu2nii(diff.numpy()**2, self.voxel_locations.numpy(), self._templates[block]) if t is None: image_slice = nilearn.image.mean_img(image) else: image_slice = nilearn.image.index_img(image, t) plot = niplot.plot_glass_brain( image_slice, plot_abs=plot_abs, colorbar=True, symmetric_cbar=False, title=utils.title_brain_plot(block, self._blocks[block], labeler, t, 'Squared Residual'), vmin=0, vmax=zscore_bound**2, **kwargs, ) logging.info('Reconstruction Error (Frobenius Norm): %.8e out of %.8e', np.linalg.norm(diff.numpy()), np.linalg.norm(self.voxel_activations[block].numpy())) if filename is not None: plot.savefig(filename) if show: niplot.show() return plot
def main(): opts = get_parser().parse_args() # work directory if opts.workdir: WORKDIR = os.path.abspath(opts.workdir) else: WORKDIR = os.getcwd() # log name if opts.logname: BASELOGNAME = opts.logname else: BASELOGNAME = 'createFCMatrix' # create log file TIMESTAMP = datetime.datetime.now().strftime("%m%d%y%H%M%S%p") LOGFILENAME = BASELOGNAME + '_' + TIMESTAMP + '.log' LOGFILE = open(os.path.join(WORKDIR, LOGFILENAME), 'w') # functional MRI func_file = os.path.abspath(opts.func_file) parcel_file = os.path.abspath(opts.parcel_file) label_file = os.path.abspath(opts.label_file) output_file = os.path.abspath(opts.output_file) parcel = img.load_img(parcel_file) logtext( LOGFILE, "parcellation " + parcel_file + " has dimensions " + str(parcel.shape)) if opts.confound_file: confound_file = os.path.abspath(opts.confound_file) # Repetition Time if opts.TR: TR = opts.TR logtext(LOGFILE, "Repetition Time passed is " + str(TR) + " seconds") else: logtext(LOGFILE, "No repetition time passed. This is necessary for filtering.") # high pass if opts.high_pass: high_pass = opts.high_pass logtext(LOGFILE, "High pass cutoff " + str(high_pass) + " Hz") else: logtext( LOGFILE, "No high pass filter passed. This is necessary for filtering.") # low_pass if opts.low_pass: low_pass = opts.low_pass logtext(LOGFILE, "Low pass cutoff is " + str(low_pass) + " Hz") else: logtext(LOGFILE, "No low pass filter passed. This is necessary for filtering.") # skip rows if opts.skip_rows: skip_rows = opts.skip_rows logtext(LOGFILE, "skip " + str(skip_rows) + " rows in the label file") if opts.confound_cols: confound_cols = opts.confound_cols if len(confound_cols) < 2: confoundheader_file = os.path.abspath(confound_cols[0]) with open(confoundheader_file, 'r') as fd: confound_cols = fd.readlines() confound_columns = [] for substr in confound_cols: confound_columns.append(substr.replace("\n", "")) else: confound_columns = confound_cols masker = input_data.NiftiLabelsMasker(labels_img=parcel, standardize=True, memory='nilearn_cache', verbose=1, detrend=True, low_pass=low_pass, high_pass=high_pass, t_r=TR) func_img = img.load_img(func_file) logtext( LOGFILE, "func_file " + parcel_file + " has dimensions " + str(func_img.shape)) #Convert confounds file into required format logtext(LOGFILE, "Extract Confounds") confounds = extract_confounds(confound_file, confound_columns) logtext(LOGFILE, "Confounds: " + str(confounds.head())) logtext(LOGFILE, "Save Confounds") confound_out = BASELOGNAME + '_confoundsOut_' + TIMESTAMP + '.csv' confounds.to_csv(confound_out, index=False) #Apply cleaning, parcellation and extraction to functional data logtext(LOGFILE, "clean and extract functional data from parcellation") confounds_array = confounds.to_numpy() time_series = masker.fit_transform(func_img, confounds_array) logtext(LOGFILE, "Calculate correlation matrix") correlation_measure = ConnectivityMeasure(kind='correlation') correlation_matrix = correlation_measure.fit_transform([time_series])[0] logtext( LOGFILE, "parsing label file " + label_file + " by skipping " + str(skip_rows) + " rows") labelfile_df = pd.read_csv(label_file, header=None, usecols=[1], delim_whitespace=True, skiprows=skip_rows) logtext(LOGFILE, "labels: " + str(labelfile_df.head())) labels_array = labelfile_df.to_numpy() logtext(LOGFILE, "saving correlation matrix to " + output_file) np.fill_diagonal(correlation_matrix, 0) parcel_df = pd.DataFrame(correlation_matrix) parcel_df.to_csv(output_file, index=False, header=False) logtext(LOGFILE, "Displaying correlation matrix") if not (opts.batchmode): plot.plot_matrix(correlation_matrix, figure=(10, 8), labels=labels_array, vmax=0.8, vmin=-0.8, reorder=True) plot.show() LOGFILE.close()
file_name="sub001_sess1_left_cerebrum", output_dir=out_dir) ########################################################################### # Now we look at the laminar depth estimates if not skip_plots: plotting.plot_img(depth['depth'], vmin=0, vmax=1, cmap='autumn', colorbar=True, annotate=False, draw_cross=False) ############################################################################ # .. image:: ../_static/cortical_extraction4.png ############################################################################# ############################################################################# # If the example is not run in a jupyter notebook, render the plots: if not skip_plots: plotting.show() ############################################################################# # References # ----------- # .. [1] Han et al (2004) CRUISE: Cortical Reconstruction Using Implicit # Surface Evolution, NeuroImage, vol. 23, pp. 997--1012. # .. [2] Waehnert et al (2014) Anatomically motivated modeling of cortical # laminae. DOI: 10.1016/j.neuroimage.2013.03.078
grid_size = int(np.ceil(np.sqrt(subject_niimg.shape[0]))) fig, axes = plt.subplots(grid_size, grid_size, figsize=(grid_size * 10, grid_size * 10)) [axi.set_axis_off() for axi in axes.ravel()] row = -1 for i, cur_img in enumerate(nl.image.iter_img(subject_niimg)): col = i % grid_size if col == 0: row += 1 nlplt.plot_stat_map(cur_img, bg_img=smri_filename, title="IC %d" % i, axes=axes[row, col], threshold=3, colorbar=False) plt.show() print("Image shape is %s" % (str(subject_niimg.shape))) num_components = subject_niimg.shape[-1] print("Detected {num_components} spatial maps".format( num_components=num_components)) nlplt.plot_prob_atlas(subject_niimg, bg_img=smri_filename, view_type='filled_contours', draw_cross=False, title='All %d spatial maps' % num_components, threshold='auto') nlplt.show()
def plot_fmri(img): for t in range(img.shape[-1]): img_t = image.index_img(img, t) plotting.plot_stat_map(img_t) plotting.show()
# Grab extracted components umasked back to Nifti image. # Note: For older versions, less than 0.4.1. components_img_ # is not implemented. See Note section above for details. components_img = estimator.components_img_ components_img.to_filename('%s_resting_state.nii.gz' % names[estimator]) components_imgs.append(components_img) ############################################################################### # Visualize the results # ---------------------- from nilearn.plotting import (plot_prob_atlas, find_xyz_cut_coords, show, plot_stat_map) from nilearn.image import index_img # Selecting specific maps to display: maps were manually chosen to be similar indices = {dict_learning: 25, canica: 33} # We select relevant cut coordinates for displaying cut_component = index_img(components_imgs[0], indices[dict_learning]) cut_coords = find_xyz_cut_coords(cut_component) for estimator, components in zip(estimators, components_imgs): # 4D plotting plot_prob_atlas(components, view_type="filled_contours", title="%s" % names[estimator], cut_coords=cut_coords, colorbar=False) # 3D plotting plot_stat_map(index_img(components, indices[estimator]), title="%s" % names[estimator], cut_coords=cut_coords, colorbar=False) show()
def plot_excursion_sets(exc_sets, max_activation, x_coords, y_coords, z_coords): for i in range(0, len(sorted(exc_sets.items()))): if len(sorted(exc_sets.items())[i][1][1]) == 2: soft, (mask_file, (exc_set_file, exc_set_file_neg), stat_file) = sorted(exc_sets.items())[i] # Remove NaNs n = nib.load(exc_set_file) d = n.get_data() exc_set_nonan = nib.Nifti1Image(np.nan_to_num(d), n.affine, header=n.header) n = nib.load(exc_set_file_neg) d = n.get_data() exc_set_neg_nonan = nib.Nifti1Image(np.nan_to_num(d), n.affine, header=n.header) # Combine activations and deactivations in a single image to_display = math_img("img1-img2", img1=exc_set_nonan, img2=exc_set_neg_nonan) # Display statistic maps display = plotting.plot_stat_map(to_display, display_mode='x', cut_coords=x_coords, draw_cross=False, colorbar=True, title=soft.upper(), threshold=0.000001, vmax=max_activation) display = plotting.plot_stat_map(to_display, cut_coords=y_coords, draw_cross=False, display_mode='y', threshold=0.000001, colorbar=False, vmax=max_activation) # Additional plot: slices along z display = plotting.plot_stat_map(to_display, cut_coords=z_coords, draw_cross=False, display_mode='z', threshold=0.000001, colorbar=False, vmax=max_activation, title=soft.upper()) plotting.show() else: soft, (mask_file, exc_set_file, stat_file) = sorted(exc_sets.items())[i] # Remove NaNs n = nib.load(exc_set_file) d = n.get_data() exc_set_nonan = nib.Nifti1Image(np.nan_to_num(d), n.affine, header=n.header) # Combine activations and deactivations in a single image to_display = exc_set_nonan # Display statistic maps display = plotting.plot_stat_map(to_display, display_mode='x', cut_coords=x_coords, draw_cross=False, colorbar=True, title=soft.upper(), threshold=0.000001, vmax=max_activation) display = plotting.plot_stat_map(to_display, cut_coords=y_coords, draw_cross=False, display_mode='y', threshold=0.000001, colorbar=False, vmax=max_activation) # Additional plot: slices along z display = plotting.plot_stat_map(to_display, cut_coords=z_coords, draw_cross=False, display_mode='z', threshold=0.000001, colorbar=False, vmax=max_activation, title=soft.upper()) plotting.show()