viz

fetch_viz_icons()

Download icons for fury

optional_package(name[, trip_msg])

Return package-like thing and module setup for package name

read_viz_icons([style, fname])

Read specific icon from specific style.

Module: viz.app

GlobalHorizon()

Horizon([tractograms, images, pams, ...])

Methods

Space(value)

Enum to simplify future change to convention

StatefulTractogram(streamlines, reference, space)

Class for stateful representation of collections of streamlines Object designed to be identical no matter the file format (trk, tck, vtk, fib, dpy).

Streamlines

alias of nibabel.streamlines.array_sequence.ArraySequence

apply_shader(hz, act)

Apply a shader to an actor (act) that access shared memory

build_label(text[, font_size, bold])

Simple utility function to build labels

distinguishable_colormap([bg, exclude, ...])

Generate colors that are maximally perceptually distinct.

horizon([tractograms, images, pams, ...])

Interactive medical visualization - Invert the Horizon!

length

Euclidean length of streamlines

optional_package(name[, trip_msg])

Return package-like thing and module setup for package name

qbx_and_merge(streamlines, thresholds[, ...])

Run QuickBundlesX and then run again on the centroids of the last layer

save_tractogram(sft, filename[, ...])

Save the stateful tractogram in any format (trk/tck/vtk/vtp/fib/dpy)

setup_module()

slicer_panel(scene, iren[, data, affine, ...])

Slicer panel with slicer included

Module: viz.gmem

GlobalHorizon()

Module: viz.panel

GlobalHorizon()

build_label(text[, font_size, bold])

Simple utility function to build labels

optional_package(name[, trip_msg])

Return package-like thing and module setup for package name

setup_module()

slicer_panel(scene, iren[, data, affine, ...])

Slicer panel with slicer included

Module: viz.projections

Visualization tools for 2D projections of 3D functions on the sphere, such as ODFs.

doctest_skip_parser(func)

Decorator replaces custom skip test markup in doctests.

optional_package(name[, trip_msg])

Return package-like thing and module setup for package name

setup_module()

sph_project(vertices, val[, ax, vmin, vmax, ...])

Draw a signal on a 2D projection of the sphere.

Module: viz.regtools

draw_lattice_2d(nrows, ncols, delta)

Create a regular lattice of nrows x ncols squares.

optional_package(name[, trip_msg])

Return package-like thing and module setup for package name

overlay_images(img0, img1[, title0, ...])

Plot two images one on top of the other using red and green channels.

overlay_slices(L, R[, slice_index, ...])

Plot three overlaid slices from the given volumes.

plot_2d_diffeomorphic_map(mapping[, delta, ...])

Draw the effect of warping a regular lattice by a diffeomorphic map.

plot_slices(V[, slice_indices, fname])

Plot 3 slices from the given volume: 1 sagital, 1 coronal and 1 axial

setup_module()

simple_plot(file_name, title, x, y, xlabel, ...)

Saves the simple plot with given x and y values

fetch_viz_icons

dipy.viz.fetch_viz_icons()

Download icons for fury

optional_package

dipy.viz.optional_package(name, trip_msg=None)

Return package-like thing and module setup for package name

Parameters
namestr

package name

trip_msgNone or str

message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.

Returns
pkg_likemodule or TripWire instance

If we can import the package, return it. Otherwise return an object raising an error when accessed

have_pkgbool

True if import for package was successful, false otherwise

module_setupfunction

callable usually set as setup_module in calling namespace, to allow skipping tests.

Examples

Typical use would be something like this at the top of a module using an optional package:

>>> from dipy.utils.optpkg import optional_package
>>> pkg, have_pkg, setup_module = optional_package('not_a_package')

Of course in this case the package doesn’t exist, and so, in the module:

>>> have_pkg
False

and

>>> pkg.some_function() 
Traceback (most recent call last):
    ...
TripWireError: We need package not_a_package for these functions, but
``import not_a_package`` raised an ImportError

If the module does exist - we get the module

>>> pkg, _, _ = optional_package('os')
>>> hasattr(pkg, 'path')
True

Or a submodule if that’s what we asked for

>>> subpkg, _, _ = optional_package('os.path')
>>> hasattr(subpkg, 'dirname')
True

read_viz_icons

dipy.viz.read_viz_icons(style='icomoon', fname='infinity.png')

Read specific icon from specific style.

Parameters
stylestr

Current icon style. Default is icomoon.

fnamestr

Filename of icon. This should be found in folder HOME/.fury/style/. Default is infinity.png.

Returns
pathstr

Complete path of icon.

GlobalHorizon

class dipy.viz.app.GlobalHorizon

Bases: object

__init__()

Horizon

class dipy.viz.app.Horizon(tractograms=None, images=None, pams=None, cluster=False, cluster_thr=15.0, random_colors=None, length_gt=0, length_lt=1000, clusters_gt=0, clusters_lt=10000, world_coords=True, interactive=True, out_png='tmp.png', recorded_events=None, return_showm=False, bg_color=(0, 0, 0), order_transparent=True, buan=False, buan_colors=None, roi_images=False, roi_colors=(1, 0, 0))

Bases: object

Methods

add_cluster_actors(scene, tractograms, threshold)

Add streamline actors to the scene

build_scene

build_show

remove_cluster_actors

__init__(tractograms=None, images=None, pams=None, cluster=False, cluster_thr=15.0, random_colors=None, length_gt=0, length_lt=1000, clusters_gt=0, clusters_lt=10000, world_coords=True, interactive=True, out_png='tmp.png', recorded_events=None, return_showm=False, bg_color=(0, 0, 0), order_transparent=True, buan=False, buan_colors=None, roi_images=False, roi_colors=(1, 0, 0))

Interactive medical visualization - Invert the Horizon!

Parameters
tractogramssequence of StatefulTractograms

StatefulTractograms are used for making sure that the coordinate systems are correct

imagessequence of tuples

Each tuple contains data and affine

pamssequence of PeakAndMetrics

Contains peak directions and spherical harmonic coefficients

clusterbool

Enable QuickBundlesX clustering

cluster_thrfloat

Distance threshold used for clustering. Default value 15.0 for small animal data you may need to use something smaller such as 2.0. The threshold is in mm. For this parameter to be active cluster should be enabled.

random_colorsstring, optional

Given multiple tractograms and/or ROIs then each tractogram and/or ROI will be shown with a different color. If no value is provided, both the tractograms and the ROIs will have a different random color generated from a distinguishable colormap. If the effect should only be applied to one of the 2 types, then use the options ‘tracts’ and ‘rois’ for the tractograms and the ROIs respectively.

length_gtfloat

Clusters with average length greater than length_gt amount in mm will be shown.

length_ltfloat

Clusters with average length less than length_lt amount in mm will be shown.

clusters_gtint

Clusters with size greater than clusters_gt will be shown.

clusters_ltint

Clusters with size less than clusters_lt will be shown.

world_coordsbool

Show data in their world coordinates (not native voxel coordinates) Default True.

interactivebool

Allow user interaction. If False then Horizon goes on stealth mode and just saves pictures.

out_pngstring

Filename of saved picture.

recorded_eventsstring

File path to replay recorded events

return_showmbool

Return ShowManager object. Used only at Python level. Can be used for extending Horizon’s cababilities externally and for testing purposes.

bg_colorndarray or list or tuple

Define the background color of the scene. Default is black (0, 0, 0)

order_transparentbool

Default True. Use depth peeling to sort transparent objects. If True also enables anti-aliasing.

buanbool, optional

Enables BUAN framework visualization. Default is False.

buan_colorslist, optional

List of colors for bundles.

roi_imagesbool, optional

Displays binary images as contours. Default is False.

roi_colorsndarray or list or tuple, optional

Define the colors of the roi images. Default is red (1, 0, 0)

References

Horizon_ISMRM19

Garyfallidis E., M-A. Cote, B.Q. Chandio, S. Fadnavis, J. Guaje, R. Aggarwal, E. St-Onge, K.S. Juneja, S. Koudoro, D. Reagan, DIPY Horizon: fast, modular, unified and adaptive visualization, Proceedings of: International Society of Magnetic Resonance in Medicine (ISMRM), Montreal, Canada, 2019.

add_cluster_actors(scene, tractograms, threshold, enable_callbacks=True)

Add streamline actors to the scene

Parameters
sceneScene
tractogramslist

list of tractograms

thresholdfloat

Cluster threshold

enable_callbacksbool

Enable callbacks for selecting clusters

build_scene()
build_show(scene)
remove_cluster_actors(scene)

Space

class dipy.viz.app.Space(value)

Bases: enum.Enum

Enum to simplify future change to convention

__init__(*args, **kwargs)
RASMM = 'rasmm'
VOX = 'vox'
VOXMM = 'voxmm'

StatefulTractogram

class dipy.viz.app.StatefulTractogram(streamlines, reference, space, origin=Origin.NIFTI, data_per_point=None, data_per_streamline=None)

Bases: object

Class for stateful representation of collections of streamlines Object designed to be identical no matter the file format (trk, tck, vtk, fib, dpy). Facilitate transformation between space and data manipulation for each streamline / point.

Attributes
affine

Getter for the reference affine

data_per_point

Getter for data_per_point

data_per_streamline

Getter for data_per_streamline

dimensions

Getter for the reference dimensions

origin

Getter for origin standard

space

Getter for the current space

space_attributes

Getter for spatial attribute

streamlines

Partially safe getter for streamlines

voxel_order

Getter for the reference voxel order

voxel_sizes

Getter for the reference voxel sizes

Methods

are_compatible(sft_1, sft_2)

Compatibility verification of two StatefulTractogram to ensure space, origin, data_per_point and data_per_streamline consistency

compute_bounding_box()

Compute the bounding box of the streamlines in their current state

from_sft(streamlines, sft[, data_per_point, ...])

Create an instance of StatefulTractogram from another instance of StatefulTractogram.

get_data_per_point_keys()

Return a list of the data_per_point attribute names

get_data_per_streamline_keys()

Return a list of the data_per_streamline attribute names

get_streamlines_copy()

Safe getter for streamlines (for slicing)

is_bbox_in_vox_valid()

Verify that the bounding box is valid in voxel space.

remove_invalid_streamlines([epsilon])

Remove streamlines with invalid coordinates from the object.

to_center()

Safe function to shift streamlines so the center of voxel is the origin

to_corner()

Safe function to shift streamlines so the corner of voxel is the origin

to_origin(target_origin)

Safe function to change streamlines to a particular origin standard False means NIFTI (center) and True means TrackVis (corner)

to_rasmm()

Safe function to transform streamlines and update state

to_space(target_space)

Safe function to transform streamlines to a particular space using an enum and update state

to_vox()

Safe function to transform streamlines and update state

to_voxmm()

Safe function to transform streamlines and update state

__init__(streamlines, reference, space, origin=Origin.NIFTI, data_per_point=None, data_per_streamline=None)

Create a strict, state-aware, robust tractogram

Parameters
streamlineslist or ArraySequence

Streamlines of the tractogram

referenceNifti or Trk filename, Nifti1Image or TrkFile,

Nifti1Header, trk.header (dict) or another Stateful Tractogram Reference that provides the spatial attributes. Typically a nifti-related object from the native diffusion used for streamlines generation

spaceEnum (dipy.io.stateful_tractogram.Space)

Current space in which the streamlines are (vox, voxmm or rasmm) After tracking the space is VOX, after loading with nibabel the space is RASMM

originEnum (dipy.io.stateful_tractogram.Origin), optional

Current origin in which the streamlines are (center or corner) After loading with nibabel the origin is CENTER

data_per_pointdict, optional

Dictionary in which each key has X items, each items has Y_i items X being the number of streamlines Y_i being the number of points on streamlines #i

data_per_streamlinedict, optional

Dictionary in which each key has X items X being the number of streamlines

Notes

Very important to respect the convention, verify that streamlines match the reference and are effectively in the right space.

Any change to the number of streamlines, data_per_point or data_per_streamline requires particular verification.

In a case of manipulation not allowed by this object, use Nibabel directly and be careful.

property affine

Getter for the reference affine

static are_compatible(sft_1, sft_2)

Compatibility verification of two StatefulTractogram to ensure space, origin, data_per_point and data_per_streamline consistency

compute_bounding_box()

Compute the bounding box of the streamlines in their current state

Returns
outputndarray

8 corners of the XYZ aligned box, all zeros if no streamlines

property data_per_point

Getter for data_per_point

property data_per_streamline

Getter for data_per_streamline

property dimensions

Getter for the reference dimensions

static from_sft(streamlines, sft, data_per_point=None, data_per_streamline=None)

Create an instance of StatefulTractogram from another instance of StatefulTractogram.

Parameters
streamlineslist or ArraySequence

Streamlines of the tractogram

sftStatefulTractgram,

The other StatefulTractgram to copy the space_attribute AND state from.

data_per_pointdict, optional

Dictionary in which each key has X items, each items has Y_i items X being the number of streamlines Y_i being the number of points on streamlines #i

data_per_streamlinedict, optional

Dictionary in which each key has X items X being the number of streamlines

—–
get_data_per_point_keys()

Return a list of the data_per_point attribute names

get_data_per_streamline_keys()

Return a list of the data_per_streamline attribute names

get_streamlines_copy()

Safe getter for streamlines (for slicing)

is_bbox_in_vox_valid()

Verify that the bounding box is valid in voxel space. Negative coordinates or coordinates above the volume dimensions are considered invalid in voxel space.

Returns
outputbool

Are the streamlines within the volume of the associated reference

property origin

Getter for origin standard

remove_invalid_streamlines(epsilon=0.001)

Remove streamlines with invalid coordinates from the object. Will also remove the data_per_point and data_per_streamline. Invalid coordinates are any X,Y,Z values above the reference dimensions or below zero

Parameters
epsilonfloat (optional)

Epsilon value for the bounding box verification. Default is 1e-6.

Returns
outputtuple

Tuple of two list, indices_to_remove, indices_to_keep

property space

Getter for the current space

property space_attributes

Getter for spatial attribute

property streamlines

Partially safe getter for streamlines

to_center()

Safe function to shift streamlines so the center of voxel is the origin

to_corner()

Safe function to shift streamlines so the corner of voxel is the origin

to_origin(target_origin)

Safe function to change streamlines to a particular origin standard False means NIFTI (center) and True means TrackVis (corner)

to_rasmm()

Safe function to transform streamlines and update state

to_space(target_space)

Safe function to transform streamlines to a particular space using an enum and update state

to_vox()

Safe function to transform streamlines and update state

to_voxmm()

Safe function to transform streamlines and update state

property voxel_order

Getter for the reference voxel order

property voxel_sizes

Getter for the reference voxel sizes

Streamlines

dipy.viz.app.Streamlines

alias of nibabel.streamlines.array_sequence.ArraySequence

apply_shader

dipy.viz.app.apply_shader(hz, act)

Apply a shader to an actor (act) that access shared memory

Parameters
hzGlobalHorizon instance
actfury.actor visual object

build_label

dipy.viz.app.build_label(text, font_size=18, bold=False)

Simple utility function to build labels

Parameters
textstr
font_sizeint
boldbool
Returns
labelTextBlock2D

distinguishable_colormap

dipy.viz.app.distinguishable_colormap(bg=(0, 0, 0), exclude=[], nb_colors=None)

Generate colors that are maximally perceptually distinct.

This function generates a set of colors which are distinguishable by reference to the “Lab” color space, which more closely matches human color perception than RGB. Given an initial large list of possible colors, it iteratively chooses the entry in the list that is farthest (in Lab space) from all previously-chosen entries. While this “greedy” algorithm does not yield a global maximum, it is simple and efficient. Moreover, the sequence of colors is consistent no matter how many you request, which facilitates the users’ ability to learn the color order and avoids major changes in the appearance of plots when adding or removing lines.

Parameters
bgtuple (optional)

Background RGB color, to make sure that your colors are also distinguishable from the background. Default: (0, 0, 0).

excludelist of tuples (optional)

Additional RGB colors to be distinguishable from.

nb_colorsint (optional)

Number of colors desired. Default: generate as many colors as needed.

Returns
iterable of ndarray

If nb_colors is provided, returns a list of RBG colors. Otherwise, yields the next RBG color maximally perceptually distinct from previous ones.

Notes

Code was initially in matlab and was rewritten in Python for dipy by the Dipy Team. Thank you Tim Holy for putting this online. Visit http://www.mathworks.com/matlabcentral/fileexchange/29702 for the original implementation (v1.2), 14 Dec 2010 (Updated 07 Feb 2011).

Examples

>>> from dipy.viz.colormap import distinguishable_colormap
>>> # Generate 5 colors
>>> [c for i, c in zip(range(5), distinguishable_colormap())]
[array([ 0.,  1.,  0.]),
 array([ 1.,  0.,  1.]),
 array([ 1.        ,  0.75862069,  0.03448276]),
 array([ 0.        ,  1.        ,  0.89655172]),
 array([ 0.        ,  0.17241379,  1.        ])]

horizon

dipy.viz.app.horizon(tractograms=None, images=None, pams=None, cluster=False, cluster_thr=15.0, random_colors=None, bg_color=(0, 0, 0), order_transparent=True, length_gt=0, length_lt=1000, clusters_gt=0, clusters_lt=10000, world_coords=True, interactive=True, buan=False, buan_colors=None, roi_images=False, roi_colors=(1, 0, 0), out_png='tmp.png', recorded_events=None, return_showm=False)

Interactive medical visualization - Invert the Horizon!

Parameters
tractogramssequence of StatefulTractograms

StatefulTractograms are used for making sure that the coordinate systems are correct

imagessequence of tuples

Each tuple contains data and affine

pamssequence of PeakAndMetrics

Contains peak directions and spherical harmonic coefficients

clusterbool

Enable QuickBundlesX clustering

cluster_thrfloat

Distance threshold used for clustering. Default value 15.0 for small animal data you may need to use something smaller such as 2.0. The threshold is in mm. For this parameter to be active cluster should be enabled.

random_colorsstring

Given multiple tractograms and/or ROIs then each tractogram and/or ROI will be shown with different color. If no value is provided both the tractograms and the ROIs will have a different random color generated from a distinguishable colormap. If the effect should only be applied to one of the 2 objects, then use the options ‘tracts’ and ‘rois’ for the tractograms and the ROIs respectively.

bg_colorndarray or list or tuple

Define the background color of the scene. Default is black (0, 0, 0)

order_transparentbool

Default True. Use depth peeling to sort transparent objects. If True also enables anti-aliasing.

length_gtfloat

Clusters with average length greater than length_gt amount in mm will be shown.

length_ltfloat

Clusters with average length less than length_lt amount in mm will be shown.

clusters_gtint

Clusters with size greater than clusters_gt will be shown.

clusters_ltint

Clusters with size less than clusters_lt will be shown.

world_coordsbool

Show data in their world coordinates (not native voxel coordinates) Default True.

interactivebool

Allow user interaction. If False then Horizon goes on stealth mode and just saves pictures.

buanbool, optional

Enables BUAN framework visualization. Default is False.

buan_colorslist, optional

List of colors for bundles.

roi_imagesbool, optional

Displays binary images as contours. Default is False.

roi_colorsndarray or list or tuple, optional

Define the color of the roi images. Default is red (1, 0, 0)

out_pngstring

Filename of saved picture.

recorded_eventsstring

File path to replay recorded events

return_showmbool

Return ShowManager object. Used only at Python level. Can be used for extending Horizon’s cababilities externally and for testing purposes.

References

Horizon_ISMRM19

Garyfallidis E., M-A. Cote, B.Q. Chandio, S. Fadnavis, J. Guaje, R. Aggarwal, E. St-Onge, K.S. Juneja, S. Koudoro, D. Reagan, DIPY Horizon: fast, modular, unified and adaptive visualization, Proceedings of: International Society of Magnetic Resonance in Medicine (ISMRM), Montreal, Canada, 2019.

length

dipy.viz.app.length()

Euclidean length of streamlines

Length is in mm only if streamlines are expressed in world coordinates.

Parameters
streamlinesndarray or a list or dipy.tracking.Streamlines

If ndarray, must have shape (N,3) where N is the number of points of the streamline. If list, each item must be ndarray shape (Ni,3) where Ni is the number of points of streamline i. If dipy.tracking.Streamlines, its common_shape must be 3.

Returns
lengthsscalar or ndarray shape (N,)

If there is only one streamline, a scalar representing the length of the streamline. If there are several streamlines, ndarray containing the length of every streamline.

Examples

>>> from dipy.tracking.streamline import length
>>> import numpy as np
>>> streamline = np.array([[1, 1, 1], [2, 3, 4], [0, 0, 0]])
>>> expected_length = np.sqrt([1+2**2+3**2, 2**2+3**2+4**2]).sum()
>>> length(streamline) == expected_length
True
>>> streamlines = [streamline, np.vstack([streamline, streamline[::-1]])]
>>> expected_lengths = [expected_length, 2*expected_length]
>>> lengths = [length(streamlines[0]), length(streamlines[1])]
>>> np.allclose(lengths, expected_lengths)
True
>>> length([])
0.0
>>> length(np.array([[1, 2, 3]]))
0.0

optional_package

dipy.viz.app.optional_package(name, trip_msg=None)

Return package-like thing and module setup for package name

Parameters
namestr

package name

trip_msgNone or str

message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.

Returns
pkg_likemodule or TripWire instance

If we can import the package, return it. Otherwise return an object raising an error when accessed

have_pkgbool

True if import for package was successful, false otherwise

module_setupfunction

callable usually set as setup_module in calling namespace, to allow skipping tests.

Examples

Typical use would be something like this at the top of a module using an optional package:

>>> from dipy.utils.optpkg import optional_package
>>> pkg, have_pkg, setup_module = optional_package('not_a_package')

Of course in this case the package doesn’t exist, and so, in the module:

>>> have_pkg
False

and

>>> pkg.some_function() 
Traceback (most recent call last):
    ...
TripWireError: We need package not_a_package for these functions, but
``import not_a_package`` raised an ImportError

If the module does exist - we get the module

>>> pkg, _, _ = optional_package('os')
>>> hasattr(pkg, 'path')
True

Or a submodule if that’s what we asked for

>>> subpkg, _, _ = optional_package('os.path')
>>> hasattr(subpkg, 'dirname')
True

qbx_and_merge

dipy.viz.app.qbx_and_merge(streamlines, thresholds, nb_pts=20, select_randomly=None, rng=None, verbose=False)

Run QuickBundlesX and then run again on the centroids of the last layer

Running again QuickBundles at a layer has the effect of merging some of the clusters that maybe originally devided because of branching. This function help obtain a result at a QuickBundles quality but with QuickBundlesX speed. The merging phase has low cost because it is applied only on the centroids rather than the entire dataset.

Parameters
streamlinesStreamlines
thresholdssequence

List of distance thresholds for QuickBundlesX.

nb_ptsint

Number of points for discretizing each streamline

select_randomlyint

Randomly select a specific number of streamlines. If None all the streamlines are used.

rngRandomState

If None then RandomState is initialized internally.

verbosebool, optional.

If True, log information. Default False.

Returns
clustersobj

Contains the clusters of the last layer of QuickBundlesX after merging.

References

Garyfallidis12

Garyfallidis E. et al., QuickBundles a method for tractography simplification, Frontiers in Neuroscience, vol 6, no 175, 2012.

Garyfallidis16

Garyfallidis E. et al. QuickBundlesX: Sequential clustering of millions of streamlines in multiple levels of detail at record execution time. Proceedings of the, International Society of Magnetic Resonance in Medicine (ISMRM). Singapore, 4187, 2016.

save_tractogram

dipy.viz.app.save_tractogram(sft, filename, bbox_valid_check=True)

Save the stateful tractogram in any format (trk/tck/vtk/vtp/fib/dpy)

Parameters
sftStatefulTractogram

The stateful tractogram to save

filenamestring

Filename with valid extension

bbox_valid_checkbool

Verification for negative voxel coordinates or values above the volume dimensions. Default is True, to enforce valid file.

Returns
outputbool

True if the saving operation was successful

setup_module

dipy.viz.app.setup_module()

slicer_panel

dipy.viz.app.slicer_panel(scene, iren, data=None, affine=None, world_coords=False, pam=None, mask=None, mem=<dipy.viz.gmem.GlobalHorizon object>)

Slicer panel with slicer included

Parameters
sceneScene
irenInteractor
data3d ndarray
affine4x4 ndarray
world_coordsbool

If True then the affine is applied.

peaksPeaksAndMetrics

Default None

mem
Returns
panelPanel

GlobalHorizon

class dipy.viz.gmem.GlobalHorizon

Bases: object

__init__()

GlobalHorizon

class dipy.viz.panel.GlobalHorizon

Bases: object

__init__()

build_label

dipy.viz.panel.build_label(text, font_size=18, bold=False)

Simple utility function to build labels

Parameters
textstr
font_sizeint
boldbool
Returns
labelTextBlock2D

optional_package

dipy.viz.panel.optional_package(name, trip_msg=None)

Return package-like thing and module setup for package name

Parameters
namestr

package name

trip_msgNone or str

message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.

Returns
pkg_likemodule or TripWire instance

If we can import the package, return it. Otherwise return an object raising an error when accessed

have_pkgbool

True if import for package was successful, false otherwise

module_setupfunction

callable usually set as setup_module in calling namespace, to allow skipping tests.

Examples

Typical use would be something like this at the top of a module using an optional package:

>>> from dipy.utils.optpkg import optional_package
>>> pkg, have_pkg, setup_module = optional_package('not_a_package')

Of course in this case the package doesn’t exist, and so, in the module:

>>> have_pkg
False

and

>>> pkg.some_function() 
Traceback (most recent call last):
    ...
TripWireError: We need package not_a_package for these functions, but
``import not_a_package`` raised an ImportError

If the module does exist - we get the module

>>> pkg, _, _ = optional_package('os')
>>> hasattr(pkg, 'path')
True

Or a submodule if that’s what we asked for

>>> subpkg, _, _ = optional_package('os.path')
>>> hasattr(subpkg, 'dirname')
True

setup_module

dipy.viz.panel.setup_module()

slicer_panel

dipy.viz.panel.slicer_panel(scene, iren, data=None, affine=None, world_coords=False, pam=None, mask=None, mem=<dipy.viz.gmem.GlobalHorizon object>)

Slicer panel with slicer included

Parameters
sceneScene
irenInteractor
data3d ndarray
affine4x4 ndarray
world_coordsbool

If True then the affine is applied.

peaksPeaksAndMetrics

Default None

mem
Returns
panelPanel

doctest_skip_parser

dipy.viz.projections.doctest_skip_parser(func)

Decorator replaces custom skip test markup in doctests.

Say a function has a docstring:

>>> something # skip if not HAVE_AMODULE
>>> something + else
>>> something # skip if HAVE_BMODULE

This decorator will evaluate the expresssion after skip if. If this evaluates to True, then the comment is replaced by # doctest: +SKIP. If False, then the comment is just removed. The expression is evaluated in the globals scope of func.

For example, if the module global HAVE_AMODULE is False, and module global HAVE_BMODULE is False, the returned function will have docstring:

>>> something 
>>> something + else
>>> something

optional_package

dipy.viz.projections.optional_package(name, trip_msg=None)

Return package-like thing and module setup for package name

Parameters
namestr

package name

trip_msgNone or str

message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.

Returns
pkg_likemodule or TripWire instance

If we can import the package, return it. Otherwise return an object raising an error when accessed

have_pkgbool

True if import for package was successful, false otherwise

module_setupfunction

callable usually set as setup_module in calling namespace, to allow skipping tests.

Examples

Typical use would be something like this at the top of a module using an optional package:

>>> from dipy.utils.optpkg import optional_package
>>> pkg, have_pkg, setup_module = optional_package('not_a_package')

Of course in this case the package doesn’t exist, and so, in the module:

>>> have_pkg
False

and

>>> pkg.some_function() 
Traceback (most recent call last):
    ...
TripWireError: We need package not_a_package for these functions, but
``import not_a_package`` raised an ImportError

If the module does exist - we get the module

>>> pkg, _, _ = optional_package('os')
>>> hasattr(pkg, 'path')
True

Or a submodule if that’s what we asked for

>>> subpkg, _, _ = optional_package('os.path')
>>> hasattr(subpkg, 'dirname')
True

setup_module

dipy.viz.projections.setup_module()

sph_project

dipy.viz.projections.sph_project(vertices, val, ax=None, vmin=None, vmax=None, cmap=None, cbar=True, tri=False, boundary=False, **basemap_args)

Draw a signal on a 2D projection of the sphere.

Parameters
vertices(N,3) ndarray

unit vector points of the sphere

val: (N) ndarray

Function values.

axmpl axis, optional

If specified, draw onto this existing axis instead.

vmin, vmaxfloats

Values to cut the z

cmapmpl colormap
cbar: Whether to add the color-bar to the figure
triangWhether to display the plot triangulated as a pseudo-color plot.
boundaryWhether to draw the boundary around the projection
in a black line
Returns
axaxis

Matplotlib figure axis

Examples

>>> from dipy.data import default_sphere
>>> verts = default_sphere.vertices
>>> ax = sph_project(verts.T, np.random.rand(len(verts.T))) 

draw_lattice_2d

dipy.viz.regtools.draw_lattice_2d(nrows, ncols, delta)

Create a regular lattice of nrows x ncols squares.

Creates an image (2D array) of a regular lattice of nrows x ncols squares. The size of each square is delta x delta pixels (not counting the separation lines). The lines are one pixel width.

Parameters
nrowsint

the number of squares to be drawn vertically

ncolsint

the number of squares to be drawn horizontally

deltaint

the size of each square of the grid. Each square is delta x delta pixels

Returns
latticearray, shape (R, C)

the image (2D array) of the segular lattice. The shape (R, C) of the array is given by R = 1 + (delta + 1) * nrows C = 1 + (delta + 1) * ncols

optional_package

dipy.viz.regtools.optional_package(name, trip_msg=None)

Return package-like thing and module setup for package name

Parameters
namestr

package name

trip_msgNone or str

message to give when someone tries to use the return package, but we could not import it, and have returned a TripWire object instead. Default message if None.

Returns
pkg_likemodule or TripWire instance

If we can import the package, return it. Otherwise return an object raising an error when accessed

have_pkgbool

True if import for package was successful, false otherwise

module_setupfunction

callable usually set as setup_module in calling namespace, to allow skipping tests.

Examples

Typical use would be something like this at the top of a module using an optional package:

>>> from dipy.utils.optpkg import optional_package
>>> pkg, have_pkg, setup_module = optional_package('not_a_package')

Of course in this case the package doesn’t exist, and so, in the module:

>>> have_pkg
False

and

>>> pkg.some_function() 
Traceback (most recent call last):
    ...
TripWireError: We need package not_a_package for these functions, but
``import not_a_package`` raised an ImportError

If the module does exist - we get the module

>>> pkg, _, _ = optional_package('os')
>>> hasattr(pkg, 'path')
True

Or a submodule if that’s what we asked for

>>> subpkg, _, _ = optional_package('os.path')
>>> hasattr(subpkg, 'dirname')
True

overlay_images

dipy.viz.regtools.overlay_images(img0, img1, title0='', title_mid='', title1='', fname=None, **fig_kwargs)

Plot two images one on top of the other using red and green channels.

Creates a figure containing three images: the first image to the left plotted on the red channel of a color image, the second to the right plotted on the green channel of a color image and the two given images on top of each other using the red channel for the first image and the green channel for the second one. It is assumed that both images have the same shape. The intended use of this function is to visually assess the quality of a registration result.

Parameters
img0array, shape(R, C)

the image to be plotted on the red channel, to the left of the figure

img1array, shape(R, C)

the image to be plotted on the green channel, to the right of the figure

title0string (optional)

the title to be written on top of the image to the left. By default, no title is displayed.

title_midstring (optional)

the title to be written on top of the middle image. By default, no title is displayed.

title1string (optional)

the title to be written on top of the image to the right. By default, no title is displayed.

fnamestring (optional)

the file name to write the resulting figure. If None (default), the image is not saved.

fig_kwargs: extra parameters for saving figure, e.g. `dpi=300`.

overlay_slices

dipy.viz.regtools.overlay_slices(L, R, slice_index=None, slice_type=1, ltitle='Left', rtitle='Right', fname=None, **fig_kwargs)

Plot three overlaid slices from the given volumes.

Creates a figure containing three images: the gray scale k-th slice of the first volume (L) to the left, where k=slice_index, the k-th slice of the second volume (R) to the right and the k-th slices of the two given images on top of each other using the red channel for the first volume and the green channel for the second one. It is assumed that both volumes have the same shape. The intended use of this function is to visually assess the quality of a registration result.

Parameters
Larray, shape (S, R, C)

the first volume to extract the slice from plotted to the left

Rarray, shape (S, R, C)

the second volume to extract the slice from, plotted to the right

slice_indexint (optional)

the index of the slices (along the axis given by slice_type) to be overlaid. If None, the slice along the specified axis is used

slice_typeint (optional)

the type of slice to be extracted: 0=sagital, 1=coronal (default), 2=axial.

ltitlestring (optional)

the string to be written as the title of the left image. By default, no title is displayed.

rtitlestring (optional)

the string to be written as the title of the right image. By default, no title is displayed.

fnamestring (optional)

the name of the file to write the image to. If None (default), the figure is not saved to disk.

fig_kwargs: extra parameters for saving figure, e.g. `dpi=300`.

plot_2d_diffeomorphic_map

dipy.viz.regtools.plot_2d_diffeomorphic_map(mapping, delta=10, fname=None, direct_grid_shape=None, direct_grid2world=- 1, inverse_grid_shape=None, inverse_grid2world=- 1, show_figure=True, **fig_kwargs)

Draw the effect of warping a regular lattice by a diffeomorphic map.

Draws a diffeomorphic map by showing the effect of the deformation on a regular grid. The resulting figure contains two images: the direct transformation is plotted to the left, and the inverse transformation is plotted to the right.

Parameters
mappingDiffeomorphicMap object

the diffeomorphic map to be drawn

deltaint, optional

the size (in pixels) of the squares of the regular lattice to be used to plot the warping effects. Each square will be delta x delta pixels. By default, the size will be 10 pixels.

fnamestring, optional

the name of the file the figure will be written to. If None (default), the figure will not be saved to disk.

direct_grid_shapetuple, shape (2,), optional

the shape of the grid image after being deformed by the direct transformation. By default, the shape of the deformed grid is the same as the grid of the displacement field, which is by default equal to the shape of the fixed image. In other words, the resulting deformed grid (deformed by the direct transformation) will normally have the same shape as the fixed image.

direct_grid2worldarray, shape (3, 3), optional

the affine transformation mapping the direct grid’s coordinates to physical space. By default, this transformation will correspond to the image-to-world transformation corresponding to the default direct_grid_shape (in general, if users specify a direct_grid_shape, they should also specify direct_grid2world).

inverse_grid_shapetuple, shape (2,), optional

the shape of the grid image after being deformed by the inverse transformation. By default, the shape of the deformed grid under the inverse transform is the same as the image used as “moving” when the diffeomorphic map was generated by a registration algorithm (so it corresponds to the effect of warping the static image towards the moving).

inverse_grid2worldarray, shape (3, 3), optional

the affine transformation mapping inverse grid’s coordinates to physical space. By default, this transformation will correspond to the image-to-world transformation corresponding to the default inverse_grid_shape (in general, if users specify an inverse_grid_shape, they should also specify inverse_grid2world).

show_figurebool, optional

if True (default), the deformed grids will be plotted using matplotlib, else the grids are just returned

fig_kwargs: extra parameters for saving figure, e.g. `dpi=300`.
Returns
warped_forwardarray

Image with the grid showing the effect of transforming the moving image to the static image. The shape will be direct_grid_shape if specified, otherwise the shape of the static image.

warped_backwardarray

Image with the grid showing the effect of transforming the static image to the moving image. Shape will be inverse_grid_shape if specified, otherwise the shape of the moving image.

Notes

The default value for the affine transformation is “-1” to handle the case in which the user provides “None” as input meaning “identity”. If we used None as default, we wouldn’t know if the user specifically wants to use the identity (specifically passing None) or if it was left unspecified, meaning to use the appropriate default matrix.

plot_slices

dipy.viz.regtools.plot_slices(V, slice_indices=None, fname=None, **fig_kwargs)

Plot 3 slices from the given volume: 1 sagital, 1 coronal and 1 axial

Creates a figure showing the axial, coronal and sagittal slices at the requested positions of the given volume. The requested slices are specified by slice_indices.

Parameters
Varray, shape (S, R, C)

the 3D volume to extract the slices from

slice_indicesarray, shape (3,) (optional)

the indices of the sagital (slice_indices[0]), coronal (slice_indices[1]) and axial (slice_indices[2]) slices to be displayed. If None, the middle slices along each direction are displayed.

fnamestring (optional)

the name of the file to save the figure to. If None (default), the figure is not saved to disk.

fig_kwargs: extra parameters for saving figure, e.g. `dpi=300`.

setup_module

dipy.viz.regtools.setup_module()

simple_plot

dipy.viz.regtools.simple_plot(file_name, title, x, y, xlabel, ylabel)

Saves the simple plot with given x and y values

Parameters
file_namestring

file name for saving the plot

titlestring

title of the plot

xinteger list

x-axis values to be plotted

yinteger list

y-axis values to be plotted

xlabelstring

label for x-axis

ylablestring

label for y-axis