def overview( workflow, identifiers, cut_coords=[None, [0, -4.5, -3.3]], threshold=2.5, template="~/ni_data/templates/DSURQEc_40micron_masked.nii.gz", orientation="portrait", save_as="", ): """Plot the statistical maps per-factor from a 2nd level GLM workflow result directory.""" plt.style.use('samri.conf') stat_maps_ = [ "~/ni_data/ofM.dr/l2/{0}/{1}/tstat1.nii.gz".format(workflow, i) for i in identifiers ] stat_maps_ = [i for i in stat_maps_ if path.isfile(i)] identifiers = [[i] * len(cut_coords) for i in identifiers] stat_maps = [[i] * len(cut_coords) for i in stat_maps_] stat_maps = [item for sublist in stat_maps for item in sublist] identifiers = [item for sublist in identifiers for item in sublist] cut_coords = cut_coords * len(stat_maps_) maps.stat( stat_maps, template=template, threshold=threshold, interpolation="none", figure_title=workflow, subplot_titles=identifiers, cut_coords=cut_coords, orientation=orientation, save_as=save_as, )
def multipage_plot(results, subjects, page_rows=4, template='/usr/share/mouse-brain-atlases/dsurqec_40micron_masked.nii', base_cut_coords=[None], save_as="", overlays=[], scale=0.6, threshold=0.1, dim=0.8, figure_title="", ): rcParams['axes.titlepad'] = 200 save_as_base, save_as_ext = path.splitext(save_as) valid_subjects = list(set([i['subject'] for i in results if bool(i['result']) and i['subject'] in subjects])) subjects_paginated = [valid_subjects[i:i+page_rows] for i in range(0, len(valid_subjects), page_rows)] for ix, subjects_page in enumerate(subjects_paginated): results_page = [i for i in results if i['subject'] in subjects_page] my_maps, subplot_titles, cut_coords = multiplot_matrix(results_page, 'result', base_cut_coords=base_cut_coords) save_as_page = save_as_base+str(ix)+save_as_ext maps.stat(my_maps, figure_title=figure_title, template=template, threshold=threshold, cut_coords=cut_coords, overlays=overlays, save_as=save_as_page, scale=scale, subplot_titles=subplot_titles, dim=dim, )
def multipage_plot(results, subjects, page_rows=4, template='~/ni_data/templates/DSURQEc_40micron_masked.nii.gz', base_cut_coords=[None], save_as="", overlays=[], scale=0.6, threshold=0.1, dim=0.8, figure_title="", ): rcParams['axes.titlepad'] = 200 save_as_base, save_as_ext = path.splitext(save_as) valid_subjects = list(set([i['subject'] for i in results if bool(i['result']) and i['subject'] in subjects])) subjects_paginated = [valid_subjects[i:i+page_rows] for i in range(0, len(valid_subjects), page_rows)] for ix, subjects_page in enumerate(subjects_paginated): results_page = [i for i in results if i['subject'] in subjects_page] my_maps, subplot_titles, cut_coords = multiplot_matrix(results_page, 'result', base_cut_coords=base_cut_coords) save_as_page = save_as_base+str(ix)+save_as_ext maps.stat(my_maps, figure_title=figure_title, template=template, threshold=threshold, cut_coords=cut_coords, overlays=overlays, save_as=save_as_page, scale=scale, subplot_titles=subplot_titles, dim=dim, )
def blur_kernel_compare_dr(conditions=["ofM","ofM_aF","ofM_cF1","ofM_cF2","ofM_pF"], parameters=["level2_dgamma","level2_dgamma_blurxy4","level2_dgamma_blurxy5", "level2_dgamma_blurxy6", "level2_dgamma_blurxy7"], threshold=3): from matplotlib.backends.backend_pdf import PdfPages pp = PdfPages('~/DR.pdf') for condition in conditions: stat_maps = ["~/ni_data/ofM.dr/GLM/"+parameter+"/_category_multi_"+condition+"/flameo/mapflow/_flameo0/stats/tstat1.nii.gz" for parameter in parameters] titles = [stat_map[32:-43] for stat_map in stat_maps] maps.stat(stat_maps, cut_coords=(-49,8,43), threshold=threshold, interpolation="none", template="~/ni_data/templates/hires_QBI_chr.nii.gz", save_as=pp, figure_title=condition, subplot_titles=parameters) pp.close()
def single_ts_seed_connectivity( template="~/ni_data/templates/DSURQEc_40micron_masked.nii.gz", save_as="" ): # connectivity_img = fc.seed_based_connectivity( # "~/ni_data/ofM.dr/preprocessing/as_composite/sub-5689/ses-ofM/func/sub-5689_ses-ofM_trial-EPI_CBV_chr_longSOA.nii.gz", # # "~/ni_data/ofM.dr/preprocessing/as_composite/sub-5706/ses-ofM_aF/func/sub-5706_ses-ofM_aF_trial-EPI_CBV_chr_longSOA.nii.gz", # # "~/ni_data/ofM.dr/preprocessing/as_composite/sub-5690/ses-ofM/func/sub-5690_ses-ofM_trial-EPI_CBV_chr_longSOA.nii.gz", # # "~/ni_data/ofM.dr/preprocessing/as_composite/sub-4011/ses-ofM_aF/func/sub-4011_ses-ofM_aF_trial-EPI_CBV_jb_long.nii.gz", # "~/ni_data/templates/roi/DSURQEc_dr.nii.gz", # save_as="~/fc.nii.gz" # ) # connectivity_img1 = fc.seed_based_connectivity( # # "~/ni_data/ofM.dr/preprocessing/as_composite/sub-5689/ses-ofM/func/sub-5689_ses-ofM_trial-EPI_CBV_chr_longSOA.nii.gz", # # "~/ni_data/ofM.dr/preprocessing/as_composite/sub-5706/ses-ofM_aF/func/sub-5706_ses-ofM_aF_trial-EPI_CBV_chr_longSOA.nii.gz", # "~/ni_data/ofM.dr/preprocessing/as_composite/sub-5690/ses-ofM/func/sub-5690_ses-ofM_trial-EPI_CBV_chr_longSOA.nii.gz", # # "~/ni_data/ofM.dr/preprocessing/as_composite/sub-4011/ses-ofM_aF/func/sub-4011_ses-ofM_aF_trial-EPI_CBV_jb_long.nii.gz", # "~/ni_data/templates/roi/DSURQEc_dr.nii.gz", # save_as="~/fc.nii.gz" # ) connectivity_img2 = fc.seed_based_connectivity( # "~/ni_data/ofM.dr/preprocessing/as_composite/sub-5689/ses-ofM/func/sub-5689_ses-ofM_trial-EPI_CBV_chr_longSOA.nii.gz", # "~/ni_data/ofM.dr/preprocessing/as_composite/sub-5706/ses-ofM_aF/func/sub-5706_ses-ofM_aF_trial-EPI_CBV_chr_longSOA.nii.gz", "~/ni_data/ofM.dr/preprocessing/as_composite/sub-5690/ses-ofM_aF/func/sub-5690_ses-ofM_aF_trial-EPI_CBV_chr_longSOA.nii.gz", # "~/ni_data/ofM.dr/preprocessing/as_composite/sub-4011/ses-ofM_aF/func/sub-4011_ses-ofM_aF_trial-EPI_CBV_jb_long.nii.gz", "~/ni_data/templates/roi/DSURQEc_dr.nii.gz", save_as="~/fc.nii.gz" ) stat_maps=[connectivity_img2] # stat_maps=[connectivity_img,connectivity_img,"~/fc.nii.gz",connectivity_img1,connectivity_img1, connectivity_img2,] # stat_maps=[connectivity_img,connectivity_img,] maps.stat(stat_maps, template=template, threshold=0.1, orientation="landscape", # cut_coords=[None,], cut_coords=[None,[0,-4.5,-3.3],None,[0,-4.5,-3.3],None,None], # cut_coords=[None,[0,-4.5,-3.3],], overlays=["~/ni_data/templates/roi/DSURQEc_dr.nii.gz",], save_as=save_as, scale=0.8, dim=0.8, )
def single_ts_seed_connectivity( template="/usr/share/mouse-brain-atlases/dsurqec_40micron_masked.nii", save_as="fcs.pdf" ): connectivity_img2 = fc.seed_based_connectivity( "~/ni_data/ofM.dr/preprocessing/composite/sub-6255/ses-ofM/func/sub-6255_ses-ofM_task-EPI_CBV_chr_longSOA.nii.gz", "~/ni_data/templates/roi/DSURQEc_dr.nii.gz", save_as="~/fc.nii.gz" ) stat_maps=[connectivity_img2,connectivity_img2] maps.stat(stat_maps, template=template, threshold=0.1, shape="landscape", cut_coords=[None,[0,-4.9,-3.3]], overlays=["~/ni_data/templates/roi/DSURQEc_dr.nii.gz",], save_as=save_as, scale=0.6, dim=0.8, )
import samri.plotting.maps as maps from os import path stat_map = 'data/l2/generic/acq-EPIlowcov_run-1_tstat.nii.gz' template = '/usr/share/mouse-brain-atlases/dsurqec_40micron_masked.nii' maps.stat( stat_maps=[stat_map], template=template, overlays=['data/acquisition_area_dsurqec.nii.gz'], annotate=True, scale=0.2, show_plot=False, interpolation=None, draw_colorbar=True, black_bg=False, threshold=1, dim=0.2, )
def plot_roi_per_session( df, x='Session', y='Mean t-Statistic', condition='treatment', unit='subject', ci=90, palette=["#56B4E9", "#E69F00"], dodge=True, order=[], feature_map=True, roi_left=0.02, roi_bottom=0.74, roi_width=0.3, roi_height=0.2, roi_anat="/usr/share/mouse-brain-atlases/dsurqec_40micron_masked.nii", roi_threshold=None, cut_coords=None, samri_style=True, renames=[], save_as='', ax=None, fig=None, ): """Plot a ROI t-values over the session timecourse """ if samri_style: plt.style.use(u'seaborn-darkgrid') plt.style.use('ggplot') try: df = path.abspath(path.expanduser(df)) except AttributeError: pass # definitions for the axes height = rcParams['figure.subplot.top'] bottom = rcParams['figure.subplot.bottom'] left = rcParams['figure.subplot.left'] width = rcParams['figure.subplot.right'] session_coordinates = [left, bottom, width, height] roi_coordinates = [ left + roi_left, bottom + roi_bottom, roi_width, roi_height ] if not fig: fig = plt.figure(1) if renames: for key in renames: for subkey in renames[key]: df.loc[df[key] == subkey, key] = renames[key][subkey] if not ax: ax1 = plt.axes(session_coordinates) else: ax1 = ax ax = sns.pointplot( x=x, y=y, units=unit, data=df, hue=condition, dodge=dodge, palette=sns.color_palette(palette), order=order, ax=ax1, ci=ci, ) ax.set_ylabel(y) if isinstance(feature_map, str): ax2 = plt.axes(roi_coordinates) if roi_threshold and cut_coords: maps.stat( feature, cut_coords=cut_coords, template=roi_anat, annotate=False, scale=0.3, show_plot=False, interpolation=None, threshold=roi_threshold, draw_colorbar=False, ax=ax2, ) else: maps.atlas_label( feature_map, scale=0.3, color="#E69F00", ax=ax2, annotate=False, alpha=0.8, ) elif feature_map: try: features = df['feature'].unique() except KeyError: pass else: if len(features) > 1: print( 'WARNING: The features list contains more than one feature. We will highlight the first one in the list. This may be incorrect.' ) feature = features[0] ax2 = plt.axes(roi_coordinates) if path.isfile(feature): if roi_threshold and cut_coords: maps.stat( stat_maps=feature, cut_coords=cut_coords, template=roi_anat, annotate=False, scale=0.3, show_plot=False, interpolation=None, threshold=roi_threshold, draw_colorbar=False, ax=ax2, ) else: maps.atlas_label( feature, scale=0.3, color="#E69F00", ax=ax2, annotate=False, alpha=0.8, ) else: atlas = df['atlas'].unique()[0] mapping = df['mapping'].unique()[0] if isinstance(feature, str): feature = [feature] maps.atlas_label( atlas, scale=0.3, color="#E69F00", ax=ax2, mapping=mapping, label_names=feature, alpha=0.8, annotate=False, ) if save_as: plt.savefig(path.abspath(path.expanduser(save_as)), bbox_inches='tight') return fig, ax
renames={ 'Session': { 'ofM': 'naïve', 'ofMaF': 'acute', 'ofMcF1': 'chronic (2w)', 'ofMcF2': 'chronic (4w)', 'ofMpF': 'post', }, }, ) ax2 = plt.axes(roi_coordinates) stat_map = path.abspath( path.expanduser( '~/ni_data/ofM.dr/bids/l2/best_responders/sessionofM/tstat1.nii.gz')) template = path.abspath( path.expanduser( '/usr/share/mouse-brain-atlases/dsurqec_40micron_masked.nii')) maps.stat( stat_maps=[stat_map], template=template, cut_coords=[(0, -4.3, -3.3)], annotate=False, scale=0.3, show_plot=False, interpolation=None, threshold=4, draw_colorbar=False, ax=ax2, )
def multi( timecourses, designs, stat_maps, events_dfs, subplot_titles, colors=QUALITATIVE_COLORSET, figure="maps", quantitative=True, save_as="", samri_style=True, ): if figure == "maps": maps.stat(stat_maps, template="~/ni_data/templates/ds_QBI_chr.nii.gz", threshold=0.1, interpolation="gaussian", subplot_titles=subplot_titles) elif figure == "timecourses": if len(timecourses) > 1: ncols = 2 #we use inverse floor division to get the ceiling max_rows = (len(timecourses) // ncols) + 1 min_rows = len(timecourses) % max_rows if samri_style: fig, axes = plt.subplots(figsize=(10 * max_rows, 7 * ncols), facecolor='#eeeeee', nrows=max_rows * min_rows, ncols=ncols) else: fig, axes = plt.subplots(facecolor='#eeeeee', nrows=max_rows * min_rows, ncols=ncols) xlabel_positive = [(i * max_rows) - 1 for i in range(1, ncols)] xlabel_positive.append(len(timecourses) - 1) max_ylim = [0, 0] for ix, timecourse in enumerate(timecourses): timecourse = timecourses[ix] design = designs[ix] events_df = events_dfs[ix] subplot_title = subplot_titles[ix] col = ix // max_rows row = ix % max_rows if col + 1 == ncols: ax = plt.subplot2grid((max_rows * min_rows, ncols), (row * max_rows, col), rowspan=max_rows) else: ax = plt.subplot2grid((max_rows * min_rows, ncols), (row * min_rows, col), rowspan=min_rows) for d, o in zip(events_df["duration"], events_df["onset"]): d = round(d) o = round(o) ax.axvspan(o, o + d, facecolor="cyan", alpha=0.15) ax.plot(timecourse, lw=rcParams['lines.linewidth'] / 4) ax.plot(design[0]) if not ix in xlabel_positive: plt.setp(ax.get_xticklabels(), visible=False) if not quantitative: ax.yaxis.grid(False) ax.set_yticks([]) else: ax.yaxis.set_label_position("right") ax.tick_params(axis='y', ) ax.set_xlim([0, len(timecourse)]) ax.set_ylabel(subplot_title) else: fig, ax = plt.subplots(facecolor='#eeeeee') timecourse = timecourses[0] design = designs[0] events_df = events_dfs[0] subplot_title = "Arbitrary Units" for d, o in zip(events_df["duration"], events_df["onset"]): d = round(d) o = round(o) ax.axvspan(o, o + d, facecolor="cyan", alpha=0.15) ax.plot(timecourse, lw=rcParams['lines.linewidth'] * 1.5, color=colors[0], alpha=1) for ix, i in enumerate(design): try: iteration_color = colors[ix + 1] except IndexError: pass ax.plot(design[ix], lw=rcParams['lines.linewidth'] * 2, color=iteration_color, alpha=1) if not quantitative: ax.yaxis.grid(False) ax.set_yticks([]) else: ax.yaxis.set_label_position("right") ax.set_xlim([0, len(timecourse)]) ax.set_ylabel(subplot_title) ax.set_xlabel("TR[1s]") else: print("WARNING: you must specify either 'maps' or 'timecourses'") if save_as: save_as = path.abspath(path.expanduser(save_as)) plt.savefig(save_as)