示例#1
0
def surface_images(out_dir, subj):
    """Plot the white, pial, and inflated surfaces to look for defects."""
    for surf in ["white", "pial", "inflated"]:
        panels = []
        for hemi in ["lh", "rh"]:

            try:
                b = Brain(subj, hemi, surf, curv=False, background="white")
            except TypeError:
                # PySurfer <= 0.5
                b = Brain(subj,
                          hemi,
                          surf,
                          curv=False,
                          config_opts=dict(background="white"))

            for view in ["lat", "med", "ven"]:
                b.show_view(view, distance="auto")
                panels.append(crop(b.screenshot()))
            b.close()

        # Make and save a figure
        f = multi_panel_brain_figure(panels)
        fname = op.join(out_dir, "{}_surface.png".format(surf))
        f.savefig(fname, bbox_inches="tight")
        plt.close(f)
示例#2
0
def contrast_loop(subj, contrasts, stat_temp, mask_temp, png_temp, args,
                  z_thresh, sign):
    """Iterate over contrasts and make surface images."""
    for contrast in contrasts:

        # Calculate where the overlay should saturate
        z_max = calculate_sat_point(stat_temp, contrast, sign, subj)
        panels = []
        for hemi in ["lh", "rh"]:

            # Initialize the brain object
            b_subj = subj if args.regspace == "epi" else "fsaverage"

            try:
                b = Brain(b_subj, hemi, args.geometry, background="white")
            except TypeError:
                # PySurfer <= v0.5
                b = Brain(b_subj,
                          hemi,
                          args.geometry,
                          config_opts={"background": "white"})

            # Plot the mask
            mask_file = mask_temp.format(contrast=contrast,
                                         hemi=hemi,
                                         subj=subj)
            add_mask_overlay(b, mask_file)

            # Plot the overlay
            stat_file = stat_temp.format(contrast=contrast,
                                         hemi=hemi,
                                         subj=subj)
            add_stat_overlay(b,
                             stat_file,
                             z_thresh,
                             z_max,
                             sign,
                             sig_to_z=args.regspace == "fsaverage")

            # Take screenshots
            for view in ["lat", "med", "ven"]:
                b.show_view(view, distance="auto")
                sleep(.1)
                panels.append(crop(b.screenshot()))
            b.close()

        # Make a single figure with all the panels
        f = multi_panel_brain_figure(panels)
        kwargs = {}
        if sign in ["pos", "abs"]:
            kwargs["pos_cmap"] = "Reds_r"
        if sign in ["neg", "abs"]:
            kwargs["neg_cmap"] = "Blues"
        add_colorbars(f, z_thresh, z_max, **kwargs)

        # Save the figure in both hemisphere outputs
        for hemi in ["lh", "rh"]:
            png_file = png_temp.format(hemi=hemi, contrast=contrast, subj=subj)
            f.savefig(png_file, bbox_inches="tight")
        plt.close(f)
示例#3
0
def curvature_normalization(data_dir, subj):
    """Normalize the curvature map and plot contour over fsaverage."""
    surf_dir = op.join(data_dir, subj, "surf")
    snap_dir = op.join(data_dir, subj, "snapshots")
    panels = []
    for hemi in ["lh", "rh"]:

        # Load the curv values and apply registration to fsaverage
        curv_fname = op.join(surf_dir, "{}.curv".format(hemi))
        curv_vals = nib.freesurfer.read_morph_data(curv_fname)
        subj_curv_vals = apply_surface_warp(data_dir, subj, hemi, curv_vals)
        subj_curv_binary = (subj_curv_vals > 0)

        # Load the template curvature
        norm_fname = op.join(data_dir, "fsaverage", "surf",
                             "{}.curv".format(hemi))
        norm_curv_vals = nib.freesurfer.read_morph_data(norm_fname)
        norm_curv_binary = (norm_curv_vals > 0)

        # Compute the curvature overlap image
        curv_overlap = np.zeros_like(norm_curv_binary, np.int)
        curv_overlap[norm_curv_binary & subj_curv_binary] = 1
        curv_overlap[norm_curv_binary ^ subj_curv_binary] = 2

        # Mask out the medial wall
        cortex_fname = op.join(data_dir, "fsaverage", "label",
                               "{}.cortex.label".format(hemi))
        cortex = nib.freesurfer.read_label(cortex_fname)
        medial_wall = ~np.in1d(np.arange(curv_overlap.size), cortex)
        curv_overlap[medial_wall] = 1

        # Plot the curvature overlap image
        try:
            b = Brain("fsaverage", hemi, "inflated", background="white")
        except TypeError:
            # PySurfer <= 0.5
            b = Brain("fsaverage",
                      hemi,
                      "inflated",
                      config_opts=dict(background="white"))

        b.add_data(curv_overlap,
                   min=0,
                   max=2,
                   colormap=[".9", ".45", "indianred"],
                   colorbar=False)

        for view in ["lat", "med", "ven"]:
            b.show_view(view, distance="auto")
            panels.append(crop(b.screenshot()))
        b.close()

    # Make and save a figure
    f = multi_panel_brain_figure(panels)
    fname = op.join(snap_dir, "surface_registration.png")
    f.savefig(fname, bbox_inches="tight")
    plt.close(f)
示例#4
0
def curvature_normalization(data_dir, subj):
    """Normalize the curvature map and plot contour over fsaverage."""
    surf_dir = op.join(data_dir, subj, "surf")
    snap_dir = op.join(data_dir, subj, "snapshots")
    panels = []
    for hemi in ["lh", "rh"]:

        # Load the curv values and apply registration to fsaverage
        curv_fname = op.join(surf_dir, "{}.curv".format(hemi))
        curv_vals = nib.freesurfer.read_morph_data(curv_fname)
        subj_curv_vals = apply_surface_warp(data_dir, subj,
                                            hemi, curv_vals)
        subj_curv_binary = (subj_curv_vals > 0)

        # Load the template curvature
        norm_fname = op.join(data_dir, "fsaverage", "surf",
                             "{}.curv".format(hemi))
        norm_curv_vals = nib.freesurfer.read_morph_data(norm_fname)
        norm_curv_binary = (norm_curv_vals > 0)

        # Compute the curvature overlap image
        curv_overlap = np.zeros_like(norm_curv_binary, np.int)
        curv_overlap[norm_curv_binary & subj_curv_binary] = 1
        curv_overlap[norm_curv_binary ^ subj_curv_binary] = 2

        # Mask out the medial wall
        cortex_fname = op.join(data_dir, "fsaverage", "label",
                               "{}.cortex.label".format(hemi))
        cortex = nib.freesurfer.read_label(cortex_fname)
        medial_wall = ~np.in1d(np.arange(curv_overlap.size), cortex)
        curv_overlap[medial_wall] = 1

        # Plot the curvature overlap image
        try:
            b = Brain("fsaverage", hemi, "inflated", background="white")
        except TypeError:
            # PySurfer <= 0.5
            b = Brain("fsaverage", hemi, "inflated",
                      config_opts=dict(background="white"))

        b.add_data(curv_overlap, min=0, max=2,
                   colormap=[".9", ".45", "indianred"], colorbar=False)

        for view in ["lat", "med", "ven"]:
            b.show_view(view, distance="auto")
            panels.append(crop(b.screenshot()))
        b.close()

    # Make and save a figure
    f = multi_panel_brain_figure(panels)
    fname = op.join(snap_dir, "surface_registration.png")
    f.savefig(fname, bbox_inches="tight")
    plt.close(f)
示例#5
0
def contrast_loop(subj, contrasts, stat_temp, mask_temp, png_temp,
                  args, z_thresh, sign):
    """Iterate over contrasts and make surface images."""
    for contrast in contrasts:

        # Calculate where the overlay should saturate
        z_max = calculate_sat_point(stat_temp, contrast, sign, subj)
        panels = []
        for hemi in ["lh", "rh"]:

            # Initialize the brain object
            b_subj = subj if args.regspace == "epi" else "fsaverage"

            try:
                b = Brain(b_subj, hemi, args.geometry, background="white")
            except TypeError:
                # PySurfer <= v0.5
                b = Brain(b_subj, hemi, args.geometry,
                          config_opts={"background": "white"})

            # Plot the mask
            mask_file = mask_temp.format(contrast=contrast,
                                         hemi=hemi, subj=subj)
            add_mask_overlay(b, mask_file)

            # Plot the overlay
            stat_file = stat_temp.format(contrast=contrast,
                                         hemi=hemi, subj=subj)
            add_stat_overlay(b, stat_file, z_thresh, z_max, sign,
                             sig_to_z=args.regspace == "fsaverage")

            # Take screenshots
            for view in ["lat", "med", "ven"]:
                b.show_view(view, distance="auto")
                sleep(.1)
                panels.append(crop(b.screenshot()))
            b.close()

        # Make a single figure with all the panels
        f = multi_panel_brain_figure(panels)
        kwargs = {}
        if sign in ["pos", "abs"]:
            kwargs["pos_cmap"] = "Reds_r"
        if sign in ["neg", "abs"]:
            kwargs["neg_cmap"] = "Blues"
        add_colorbars(f, z_thresh, z_max, **kwargs)

        # Save the figure in both hemisphere outputs
        for hemi in ["lh", "rh"]:
            png_file = png_temp.format(hemi=hemi, contrast=contrast, subj=subj)
            f.savefig(png_file, bbox_inches="tight")
        plt.close(f)
示例#6
0
def plot_brains(axes, palette):

    lat_ax, med_ax = axes
    lat_color, med_color = palette

    b = Brain("fsaverage", "lh", "pial",
              background="white", size=(1200, 1200))

    b.add_morphometry("curv", grayscale=True, min=-.5, max=.5,
                      colormap="Greys", colorbar=False)

    b.add_label("roi_labels/lh.ifs.label", alpha=.9, color="#feb308")
    b.add_label("roi_labels/lh.mfc.label", alpha=.9, color="#cf6275")

    mlab.view(160, 70)
    lat_ax.imshow(crop(b.screenshot()), rasterized=True)

    mlab.view(15, 90)
    med_ax.imshow(crop(b.screenshot()),  rasterized=True)

    b.close()

    for ax in axes:
        ax.set_axis_off()
示例#7
0
def plot_brains(subjects, axes):

    for subj, subj_axes in zip(subjects, axes):

        exp = dict(pc="dots", ti="sticks")[subj[:2]]

        data_fname = "roi_cache/{}_{}_ifs.npz".format(subj, exp)
        with np.load(data_fname) as dobj:
            vox_ijk = dobj["vox_ijk"]

        res_fname = "decoding_analysis/{}_{}_ifs.pkz".format(subj, exp)
        res = moss.load_pkl(res_fname)
        prefs = res.prefs

        surf_vals = roi_to_surf(exp, subj, prefs, vox_ijk)

        lut = get_colormap(exp, False)

        for hemi, ax in zip(["lh", "rh"], subj_axes):

            b = Brain(subj,
                      hemi,
                      "inflated",
                      background="white",
                      cortex=("binary", -4, 8, False),
                      size=(1000, 600))

            b.add_data(surf_vals.ix[hemi].fillna(-11).values,
                       colormap=lut,
                       colorbar=False,
                       thresh=-10,
                       min=-1.75,
                       max=1.75)

            mlab.view(*get_ifs_view(subj, hemi))
            img = crop(b.screenshot())
            ax.imshow(img, rasterized=True)
            ax.set(xticks=[], yticks=[])
            b.close()
示例#8
0
def surface_images(out_dir, subj):
    """Plot the white, pial, and inflated surfaces to look for defects."""
    for surf in ["white", "pial", "inflated"]:
        panels = []
        for hemi in ["lh", "rh"]:

            try:
                b = Brain(subj, hemi, surf, curv=False, background="white")
            except TypeError:
                # PySurfer <= 0.5
                b = Brain(subj, hemi, surf, curv=False,
                          config_opts=dict(background="white"))

            for view in ["lat", "med", "ven"]:
                b.show_view(view, distance="auto")
                panels.append(crop(b.screenshot()))
            b.close()

        # Make and save a figure
        f = multi_panel_brain_figure(panels)
        fname = op.join(out_dir, "{}_surface.png".format(surf))
        f.savefig(fname, bbox_inches="tight")
        plt.close(f)