Beispiel #1
0
def plotBrain(objIn, how='full', thr=None, **kwargs):
    """
    More complete brain plotting of a Brain_Data instance
    Args:
        obj: (Brain_Data) object to plot
        how: (str) whether to plot a glass brain 'glass', 3 view-multi-slice mni 'mni', or both 'full'
        thr: (str/float) thresholding of image. Can be string for percentage, or float for data units (see Brain_Data.threshold()
        kwargs: optionals args to nilearn plot functions (e.g. vmax)

    """
    if thr:
        obj = objIn.threshold(thr)
    else:
        obj = objIn.copy()

    views = ['x', 'y', 'z']
    coords = [range(-50, 51, 8),
              range(-80, 50, 10),
              range(-40, 71, 9)]  #[-88,-72,-58,-38,-26,8,20,34,46]
    cmap = 'RdBu_r'

    if thr is None:
        print("Plotting unthresholded image")
    elif type(thr) == str:
        print("Plotting top %s of voxels" % thr)
    elif type(thr) == float or type(thr) == int:
        print("Plotting voxels with stat value >= %s" % thr)

    if how == 'full':
        plot_glass_brain(obj.to_nifti(),
                         display_mode='lzry',
                         colorbar=True,
                         cmap=cmap,
                         plot_abs=False,
                         **kwargs)
        for v, c in zip(views, coords):
            plot_stat_map(obj.to_nifti(),
                          cut_coords=c,
                          display_mode=v,
                          cmap=cmap,
                          bg_img=resolve_mni_path(MNI_Template)['brain'],
                          **kwargs)
    elif how == 'glass':
        plot_glass_brain(obj.to_nifti(),
                         display_mode='lzry',
                         colorbar=True,
                         cmap=cmap,
                         plot_abs=False,
                         **kwargs)
    elif how == 'mni':
        for v, c in zip(views, coords):
            plot_stat_map(obj.to_nifti(),
                          cut_coords=c,
                          display_mode=v,
                          cmap=cmap,
                          bg_img=resolve_mni_path(MNI_Template)['brain'],
                          **kwargs)
    del obj  #save memory
    return
Beispiel #2
0
    def __init__(self, brain_mask=None, output_dir = None): #no scoring param
        # self.resource_folder = os.path.join(os.getcwd(),'resources')
        if output_dir is None:
            self.output_dir = os.path.join(os.getcwd())
        else:
            self.output_dir = output_dir

        if isinstance(brain_mask, str):
            brain_mask = nib.load(brain_mask)
        elif brain_mask is None:
            brain_mask = nib.load(resolve_mni_path(MNI_Template)['mask'])
        elif ~isinstance(brain_mask, nib.nifti1.Nifti1Image):
            raise ValueError("brain_mask is not a string or a nibabel instance")
        self.brain_mask = brain_mask
        self.nifti_masker = NiftiMasker(mask_img=self.brain_mask)
Beispiel #3
0
def _viewer(objIn, x, y, z, stat, figsize):
    """
    Generator function for ibrainViewer
    """
    _, ax = plt.subplots(1, figsize=figsize)
    plot_stat_map(objIn.to_nifti(),
                  display_mode='ortho',
                  bg_img=resolve_mni_path(MNI_Template)['brain'],
                  cut_coords=(x, y, z),
                  threshold=stat,
                  draw_cross=False,
                  black_bg=True,
                  dim=.25,
                  axes=ax)
    return
Beispiel #4
0
def create_sphere(coordinates, radius=5, mask=None):
    """Generate a set of spheres in the brain mask space

    Args:
        radius: vector of radius.  Will create multiple spheres if
                len(radius) > 1
        centers: a vector of sphere centers of the form [px, py, pz] or
                [[px1, py1, pz1], ..., [pxn, pyn, pzn]]

    """
    from nltools.data import Brain_Data

    if mask is not None:
        if not isinstance(mask, nib.Nifti1Image):
            if isinstance(mask, str):
                if os.path.isfile(mask):
                    mask = nib.load(mask)
            else:
                raise ValueError("mask is not a nibabel instance or a valid "
                                 "file name")

    else:
        mask = nib.load(resolve_mni_path(MNI_Template)["mask"])

    def sphere(r, p, mask):
        """create a sphere of given radius at some point p in the brain mask

        Args:
            r: radius of the sphere
            p: point (in coordinates of the brain mask) of the center of the
                sphere

        """
        dims = mask.shape
        m = [dims[0] / 2, dims[1] / 2, dims[2] / 2]
        x, y, z = np.ogrid[-m[0]:dims[0] - m[0], -m[1]:dims[1] - m[1],
                           -m[2]:dims[2] - m[2]]
        mask_r = x * x + y * y + z * z <= r * r

        activation = np.zeros(dims)
        activation[mask_r] = 1
        translation_affine = np.array([
            [1, 0, 0, p[0] - m[0]],
            [0, 1, 0, p[1] - m[1]],
            [0, 0, 1, p[2] - m[2]],
            [0, 0, 0, 1],
        ])

        return nib.Nifti1Image(activation, affine=translation_affine)

    if any(isinstance(i, list) for i in coordinates):
        if isinstance(radius, list):
            if len(radius) != len(coordinates):
                raise ValueError("Make sure length of radius list matches"
                                 "length of coordinate list.")
        elif isinstance(radius, int):
            radius = [radius] * len(coordinates)
        out = Brain_Data(
            nib.Nifti1Image(np.zeros_like(mask.get_data()),
                            affine=mask.affine),
            mask=mask,
        )
        for r, c in zip(radius, coordinates):
            out = out + Brain_Data(sphere(r, c, mask), mask=mask)
    else:
        out = Brain_Data(sphere(radius, coordinates, mask), mask=mask)
    out = out.to_nifti()
    out.get_data()[out.get_data() > 0.5] = 1
    out.get_data()[out.get_data() < 0.5] = 0
    return out
Beispiel #5
0
def plot_brain(objIn,
               how="full",
               thr_upper=None,
               thr_lower=None,
               save=False,
               **kwargs):
    """
    More complete brain plotting of a Brain_Data instance
    Args:
        obj: (Brain_Data) object to plot
        how: (str) whether to plot a glass brain 'glass', 3 view-multi-slice mni 'mni', or both 'full'
        thr_upper: (str/float) thresholding of image. Can be string for percentage, or float for data units (see Brain_Data.threshold()
        thr_lower: (str/float) thresholding of image. Can be string for percentage, or float for data units (see Brain_Data.threshold()
        save (str): if a string file name or path is provided plots will be saved into this directory appended with the orientation they belong to
        kwargs: optionals args to nilearn plot functions (e.g. vmax)

    """
    if thr_upper or thr_lower:
        obj = objIn.threshold(upper=thr_upper, lower=thr_lower)
    else:
        obj = objIn.copy()

    views = ["x", "y", "z"]
    coords = [
        range(-50, 51, 8),
        range(-80, 50, 10),
        range(-40, 71, 9),
    ]  # [-88,-72,-58,-38,-26,8,20,34,46]
    cmap = "RdBu_r"

    if thr_upper is None and thr_lower is None:
        print("Plotting unthresholded image")
    else:
        if isinstance(thr_upper, str):
            print("Plotting top %s of voxels" % thr_upper)
        elif isinstance(thr_upper, (float, int)):
            print("Plotting voxels with stat value >= %s" % thr_upper)
        if isinstance(thr_lower, str):
            print("Plotting lower %s of voxels" % thr_lower)
        elif isinstance(thr_lower, (float, int)):
            print("Plotting voxels with stat value <= %s" % thr_lower)

    if save:
        path, filename = os.path.split(save)
        filename, extension = filename.split(".")
        glass_save = os.path.join(path, filename + "_glass." + extension)
        x_save = os.path.join(path, filename + "_x." + extension)
        y_save = os.path.join(path, filename + "_y." + extension)
        z_save = os.path.join(path, filename + "_z." + extension)
    else:
        glass_save, x_save, y_save, z_save = None, None, None, None

    saves = [x_save, y_save, z_save]

    if how == "full":
        plot_glass_brain(
            obj.to_nifti(),
            display_mode="lzry",
            colorbar=True,
            cmap=cmap,
            plot_abs=False,
            **kwargs,
        )
        if save:
            plt.savefig(glass_save, bbox_inches="tight")
        for v, c, savefile in zip(views, coords, saves):
            plot_stat_map(
                obj.to_nifti(),
                cut_coords=c,
                display_mode=v,
                cmap=cmap,
                bg_img=resolve_mni_path(MNI_Template)["brain"],
                **kwargs,
            )
            if save:
                plt.savefig(savefile, bbox_inches="tight")
    elif how == "glass":
        plot_glass_brain(
            obj.to_nifti(),
            display_mode="lzry",
            colorbar=True,
            cmap=cmap,
            plot_abs=False,
            **kwargs,
        )
        if save:
            plt.savefig(glass_save, bbox_inches="tight")
    elif how == "mni":
        for v, c, savefile in zip(views, coords, saves):
            plot_stat_map(
                obj.to_nifti(),
                cut_coords=c,
                display_mode=v,
                cmap=cmap,
                bg_img=resolve_mni_path(MNI_Template)["brain"],
                **kwargs,
            )
            if save:
                plt.savefig(savefile, bbox_inches="tight")
    del obj  # save memory
    return
Beispiel #6
0
def plot_t_brain(objIn,
                 how="full",
                 thr="unc",
                 alpha=None,
                 nperm=None,
                 cut_coords=[],
                 **kwargs):
    """
    Takes a brain data object and computes a 1 sample t-test across it's first axis. If a list is provided will compute difference between brain data objects in list (i.e. paired samples t-test).
    Args:
        objIn:(list/Brain_Data) if list will compute difference map first
        how: (list) whether to plot a glass brain 'glass', 3 view-multi-slice mni 'mni', or both 'full'
        thr: (str) what method to use for multiple comparisons correction unc, fdr, or tfce
        alpha: (float) p-value threshold
        nperm: (int) number of permutations for tcfe; default 1000
        cut_coords: (list) x,y,z coords to plot brain slice
        kwargs: optionals args to nilearn plot functions (e.g. vmax)

    """
    if thr not in ["unc", "fdr", "tfce"]:
        raise ValueError("Acceptable threshold methods are 'unc','fdr','tfce'")
    views = ["x", "y", "z"]
    if len(cut_coords) == 0:
        cut_coords = [
            range(-40, 50, 10),
            [-88, -72, -58, -38, -26, 8, 20, 34, 46],
            [-34, -22, -10, 0, 16, 34, 46, 56, 66],
        ]
    else:
        if len(cut_coords) != 3:
            raise ValueError(
                "cut_coords must be a list of coordinates like [[xs],[ys],[zs]]"
            )
    cmap = "RdBu_r"

    if isinstance(objIn, list):
        if len(objIn) == 2:
            obj = objIn[0] - objIn[1]
        else:
            raise ValueError("Contrasts should contain only 2 list items!")

    thrDict = {}
    if thr == "tfce":
        thrDict["permutation"] = thr
        if nperm is None:
            nperm = 1000
        thrDict["n_permutations"] = nperm
        print("1-sample t-test corrected using: TFCE w/ %s permutations" %
              nperm)
    else:
        if thr == "unc":
            if alpha is None:
                alpha = 0.001
            thrDict[thr] = alpha
            print("1-sample t-test uncorrected at p < %.3f " % alpha)
        elif thr == "fdr":
            if alpha is None:
                alpha = 0.05
            thrDict[thr] = alpha
            print("1-sample t-test corrected at q < %.3f " % alpha)
        else:
            thrDict = None
            print("1-sample test unthresholded")

    out = objIn.ttest(threshold_dict=thrDict)
    if thrDict is not None:
        obj = out["thr_t"]
    else:
        obj = out["t"]

    if how == "full":
        plot_glass_brain(
            obj.to_nifti(),
            display_mode="lzry",
            colorbar=True,
            cmap=cmap,
            plot_abs=False,
            **kwargs,
        )
        for v, c in zip(views, cut_coords):
            plot_stat_map(
                obj.to_nifti(),
                cut_coords=c,
                display_mode=v,
                cmap=cmap,
                bg_img=resolve_mni_path(MNI_Template)["brain"],
                **kwargs,
            )
    elif how == "glass":
        plot_glass_brain(
            obj.to_nifti(),
            display_mode="lzry",
            colorbar=True,
            cmap=cmap,
            plot_abs=False,
            **kwargs,
        )
    elif how == "mni":
        for v, c in zip(views, cut_coords):
            plot_stat_map(
                obj.to_nifti(),
                cut_coords=c,
                display_mode=v,
                cmap=cmap,
                bg_img=resolve_mni_path(MNI_Template)["brain"],
                **kwargs,
            )
    del obj
    del out
    return
Beispiel #7
0
def plotTBrain(objIn,
               how='full',
               thr='unc',
               alpha=None,
               nperm=None,
               cut_coords=[],
               **kwargs):
    """
    Takes a brain data object and computes a 1 sample t-test across it's first axis. If a list is provided will compute difference between brain data objects in list (i.e. paired samples t-test).
    Args:
        objIn:(list/Brain_Data) if list will compute difference map first
        how: (list) whether to plot a glass brain 'glass', 3 view-multi-slice mni 'mni', or both 'full'
        thr: (str) what method to use for multiple comparisons correction unc, fdr, or tfce
        alpha: (float) p-value threshold
        nperm: (int) number of permutations for tcfe; default 1000
        cut_coords: (list) x,y,z coords to plot brain slice
        kwargs: optionals args to nilearn plot functions (e.g. vmax)

    """
    assert thr in ['unc', 'fdr', 'tfce'
                   ], "Acceptable threshold methods are 'unc','fdr','tfce'"
    views = ['x', 'y', 'z']
    if len(cut_coords) == 0:
        cut_coords = [
            range(-40, 50, 10), [-88, -72, -58, -38, -26, 8, 20, 34, 46],
            [-34, -22, -10, 0, 16, 34, 46, 56, 66]
        ]
    else:
        assert (
            len(cut_coords) == 3
        ), 'cut_coords must be a list of coordinates like [[xs],[ys],[zs]]'
    cmap = 'RdBu_r'

    if type(objIn) == list:
        if len(objIn) == 2:
            obj = objIn[0] - objIn[1]
        else:
            raise ValueError('Contrasts should contain only 2 list items!')

    thrDict = {}
    if thr == 'tfce':
        thrDict['permutation'] = thr
        if nperm is None:
            nperm = 1000
        thrDict['n_permutations'] = nperm
        print("1-sample t-test corrected using: TFCE w/ %s permutations" %
              nperm)
    else:
        if thr == 'unc':
            if alpha is None:
                alpha = .001
            thrDict[thr] = alpha
            print("1-sample t-test uncorrected at p < %.3f " % alpha)
        elif thr == 'fdr':
            if alpha is None:
                alpha = .05
            thrDict[thr] = alpha
            print("1-sample t-test corrected at q < %.3f " % alpha)
        else:
            thrDict = None
            print("1-sample test unthresholded")

    out = objIn.ttest(threshold_dict=thrDict)
    if thrDict is not None:
        obj = out['thr_t']
    else:
        obj = out['t']

    if how == 'full':
        plot_glass_brain(obj.to_nifti(),
                         display_mode='lzry',
                         colorbar=True,
                         cmap=cmap,
                         plot_abs=False,
                         **kwargs)
        for v, c in zip(views, cut_coords):
            plot_stat_map(obj.to_nifti(),
                          cut_coords=c,
                          display_mode=v,
                          cmap=cmap,
                          bg_img=resolve_mni_path(MNI_Template)['brain'],
                          **kwargs)
    elif how == 'glass':
        plot_glass_brain(obj.to_nifti(),
                         display_mode='lzry',
                         colorbar=True,
                         cmap=cmap,
                         plot_abs=False,
                         **kwargs)
    elif how == 'mni':
        for v, c in zip(views, cut_coords):
            plot_stat_map(obj.to_nifti(),
                          cut_coords=c,
                          display_mode=v,
                          cmap=cmap,
                          bg_img=resolve_mni_path(MNI_Template)['brain'],
                          **kwargs)
    del obj
    del out
    return