Ejemplo n.º 1
0
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Example of activation image vizualization
with nipy.neurospin vizualization tools
"""
print __doc__

import os.path
import pylab as pl
from nipy.io.imageformats import load
from nipy.neurospin import viz
import get_data_light

# get the data
data_dir = get_data_light.get_it()

img     = load(os.path.join(data_dir, 'spmT_0029.nii.gz'))
data    = img.get_data()
affine  = img.get_affine()

viz.plot_map(data, affine, cut_coords=(-52, 10, 22), 
                        threshold=2.0, cmap=viz.cm.cold_hot)
pl.show()
Ejemplo n.º 2
0
def plot_ics(maps3d, affine, output_dir, titles=None, 
            format='png', cmap=viz.cm.cold_hot, mean_img=None,
            report=True, 
            parameters=None,
            **kwargs):
    """ Save the ics to image file, and to a report.

        Parameters
        ----------
        titles: None, string or list of strings.
            Titles to be used for each ICs
        format: {'png', 'pdf', 'svg', 'jpg', ...}
            The format used to save a preview.
        cmap: matplotlib colormap
            The colormap to be used for the independant compnents, for 
            example pylab.cm.hot
        report: boolean, optional
            If report is True, an html report is saved.
        parameters: None or dictionnary, optional
            Extra parameters to put in the report.
        kwargs:
            Extra keyword arguments are passed to plot_map_2d.
    """
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    if mean_img is not None:
        img = VolumeImg(mean_img, affine=affine, world_space='mine')
        try:
            img = img.xyz_ordered()
        except CompositionError:
            # That's fine, we'll just take it in diagonal
            pass
        kwargs['anat'] = img.get_data()
        kwargs['anat_affine'] = img.affine

    img_files = list()
    maps3d = np.rollaxis(maps3d, -1)
    for index, map3d in enumerate(maps3d):
        img_base_file = 'map_%02i.%s' % (index, format)
        img_file = pjoin(output_dir, img_base_file)
        print 'Outputing image for map %2i out of % 2i:  %s' \
            % (index+1, len(maps3d), img_file)
        # XYZ order the images, this should be done in the viz
        # code.
        img = VolumeImg(map3d, affine=affine, world_space='mine')
        try:
            img = img.xyz_ordered()
        except CompositionError:
            # That's fine, we'll just take it in diagonal
            pass
        map3d = img.get_data()
        this_affine = img.affine
        x, y, z = viz.find_cut_coords(map3d, activation_threshold=1e-10)
        x, y, z = viz.coord_transform(x, y, z, this_affine)
        if np.any(map3d != 0):
            # Force the colormap to be symetric:
            map_max = max(-map3d.min(), map3d.max())
            kwargs['vmin'] = -map_max
            kwargs['vmax'] =  map_max
            map3d = np.ma.masked_equal(map3d, 0, copy=False)
            if titles is not None:
                if isinstance(titles, basestring):
                    title = titles % locals()
                else:
                    title = titles[index]
            else:
                title = None
            viz.plot_map(map3d, this_affine, (x, y, z), figure=512,
                                                    title=title,
                                                    cmap=cmap,
                                                    **kwargs)
        pl.savefig(img_file)
        pl.clf()
        img_files.append(img_base_file)

    if format in ('png', 'jpg'):
        report = markup.page()
        report.init(title='CanICA report')

        report.p(""" CanICA run, %s.""" % time.asctime())
        report.h1("Independent components")

        report.img(src=img_files)
        if parameters is not None:
            report.h1("Parameters")
            for name, value in parameters.iteritems():
                if isinstance(value, list) or isinstance(value, tuple):
                    report.p(r'<strong>%s</strong>: %s(' % 
                                (name, value.__class__.__name__))
                    report.ul()
                    descriptions = list()
                    for item in value:
                        description = pprint.pformat(item)
                        if len(description) > 1000:
                            description = ('%s...<br>&nbsp;&nbsp;&nbsp;...%s' 
                                    % (description[:200], description[-200:]))
                        descriptions.append(description)
                    report.li(descriptions)
                    report.ul.close()
                    report.p(')')
                else:
                    description = pprint.pformat(value)
                    if len(description) > 1500:
                        description = ('%s...<br>&nbsp;...%s' 
                                % (description[:500], description[-500:]))
                    report.p(r'<strong>%s</strong>: %s' % 
                                        (name, description))
        report_file = pjoin(output_dir, 'canica.html')
        file(report_file, 'w').write(str(report))
        print 80*'_'
        print 'CanICA: report in %s' % report_file
Ejemplo n.º 3
0
def plot_ics(maps3d,
             affine,
             output_dir,
             titles=None,
             format='png',
             cmap=viz.cm.cold_hot,
             mean_img=None,
             report=True,
             parameters=None,
             **kwargs):
    """ Save the ics to image file, and to a report.

        Parameters
        ----------
        titles: None, string or list of strings.
            Titles to be used for each ICs
        format: {'png', 'pdf', 'svg', 'jpg', ...}
            The format used to save a preview.
        cmap: matplotlib colormap
            The colormap to be used for the independant compnents, for 
            example pylab.cm.hot
        report: boolean, optional
            If report is True, an html report is saved.
        parameters: None or dictionnary, optional
            Extra parameters to put in the report.
        kwargs:
            Extra keyword arguments are passed to plot_map_2d.
    """
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    if mean_img is not None:
        img = VolumeImg(mean_img, affine=affine, world_space='mine')
        try:
            img = img.xyz_ordered()
        except CompositionError:
            # That's fine, we'll just take it in diagonal
            pass
        kwargs['anat'] = img.get_data()
        kwargs['anat_affine'] = img.affine

    img_files = list()
    maps3d = np.rollaxis(maps3d, -1)
    for index, map3d in enumerate(maps3d):
        img_base_file = 'map_%02i.%s' % (index, format)
        img_file = pjoin(output_dir, img_base_file)
        print 'Outputing image for map %2i out of % 2i:  %s' \
            % (index+1, len(maps3d), img_file)
        # XYZ order the images, this should be done in the viz
        # code.
        img = VolumeImg(map3d, affine=affine, world_space='mine')
        try:
            img = img.xyz_ordered()
        except CompositionError:
            # That's fine, we'll just take it in diagonal
            pass
        map3d = img.get_data()
        this_affine = img.affine
        x, y, z = viz.find_cut_coords(map3d, activation_threshold=1e-10)
        x, y, z = viz.coord_transform(x, y, z, this_affine)
        if np.any(map3d != 0):
            # Force the colormap to be symetric:
            map_max = max(-map3d.min(), map3d.max())
            kwargs['vmin'] = -map_max
            kwargs['vmax'] = map_max
            map3d = np.ma.masked_equal(map3d, 0, copy=False)
            if titles is not None:
                if isinstance(titles, basestring):
                    title = titles % locals()
                else:
                    title = titles[index]
            else:
                title = None
            viz.plot_map(map3d,
                         this_affine, (x, y, z),
                         figure=512,
                         title=title,
                         cmap=cmap,
                         **kwargs)
        pl.savefig(img_file)
        pl.clf()
        img_files.append(img_base_file)

    if format in ('png', 'jpg'):
        report = markup.page()
        report.init(title='CanICA report')

        report.p(""" CanICA run, %s.""" % time.asctime())
        report.h1("Independent components")

        report.img(src=img_files)
        if parameters is not None:
            report.h1("Parameters")
            for name, value in parameters.iteritems():
                if isinstance(value, list) or isinstance(value, tuple):
                    report.p(r'<strong>%s</strong>: %s(' %
                             (name, value.__class__.__name__))
                    report.ul()
                    descriptions = list()
                    for item in value:
                        description = pprint.pformat(item)
                        if len(description) > 1000:
                            description = (
                                '%s...<br>&nbsp;&nbsp;&nbsp;...%s' %
                                (description[:200], description[-200:]))
                        descriptions.append(description)
                    report.li(descriptions)
                    report.ul.close()
                    report.p(')')
                else:
                    description = pprint.pformat(value)
                    if len(description) > 1500:
                        description = ('%s...<br>&nbsp;...%s' %
                                       (description[:500], description[-500:]))
                    report.p(r'<strong>%s</strong>: %s' % (name, description))
        report_file = pjoin(output_dir, 'canica.html')
        file(report_file, 'w').write(str(report))
        print 80 * '_'
        print 'CanICA: report in %s' % report_file
Ejemplo n.º 4
0
                                             len(contrasts), contrast_id)
    lcontrast = my_glm.contrast(contrasts[contrast_id])
    # 
    contrast_path = op.join(swd, '%s_z_map.nii'% contrast_id)
    write_array = mask_array.astype(np.float)
    write_array[mask_array] = lcontrast.zscore()
    contrast_image = Nifti1Image(write_array, fmri_image.get_affine() )
    save(contrast_image, contrast_path)
    affine = fmri_image.get_affine()

    
    vmax = max(-write_array.min(), write_array.max())
    plot_map(write_array, affine, 
             cmap=cm.cold_hot, 
             vmin=-vmax,
             vmax=vmax,
             anat=None,
             figure=10,
             threshold=2.5)
    pylab.savefig(op.join(swd, '%s_z_map.png' % contrast_id))
    pylab.clf()
    


#########################################
# End
#########################################

print "All the  results were witten in %s" %swd

plot_map(write_array, affine, 
Ejemplo n.º 5
0
"""
Example of activation image vizualization
with nip.neurospin vizualization tools
"""

print __doc__

import os.path as op
import pylab as pl
from nipy.io.imageformats import load
from nipy.neurospin.viz import plot_map
import get_data_light

# get the data
data_dir = op.expanduser(op.join('~', '.nipy', 'tests', 'data'))
data_path = op.join(data_dir,'spmT_0029.nii.gz')
if op.exists(data_path)==False:
    get_data_light.getIt()
fim = load(data_path)
fmap = fim.get_data()
affine = fim.get_affine()

#vizualization parameters
x, y, z = -52, 10, 22
threshold = 2.0
kwargs={'cmap':pl.cm.hot,'alpha':0.7,'vmin':threshold,'anat':None}


plot_map(fmap, affine, cut_coords=(x, y, z), **kwargs)
pl.show()