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

EventCounter([events_names])

Methods

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

Methods

Space

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, actor)

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, …])

Highly interactive 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, fib, dpy)

setup_module()

slicer_panel(renderer, iren[, data, affine, …])

Slicer panel with slicer included

Module: viz.gmem

GlobalHorizon()

Module: viz.panel

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(renderer, 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() #doctest: +IGNORE_EXCEPTION_DETAIL
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.

EventCounter

class dipy.viz.app.EventCounter(events_names=['CharEvent', 'MouseMoveEvent', 'KeyPressEvent', 'KeyReleaseEvent', 'LeftButtonPressEvent', 'LeftButtonReleaseEvent', 'RightButtonPressEvent', 'RightButtonReleaseEvent', 'MiddleButtonPressEvent', 'MiddleButtonReleaseEvent'])

Bases: object

Methods

count(i_ren, _obj, _element)

Simple callback that counts events occurences.

check_counts

load

monitor

save

__init__(events_names=['CharEvent', 'MouseMoveEvent', 'KeyPressEvent', 'KeyReleaseEvent', 'LeftButtonPressEvent', 'LeftButtonReleaseEvent', 'RightButtonPressEvent', 'RightButtonReleaseEvent', 'MiddleButtonPressEvent', 'MiddleButtonReleaseEvent'])

Initialize self. See help(type(self)) for accurate signature.

check_counts(expected)
count(i_ren, _obj, _element)

Simple callback that counts events occurences.

classmethod load(filename)
monitor(ui_component)
save(filename)

Horizon

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

Bases: object

Methods

add_actors(scene, tractograms, threshold)

Add streamline actors to the scene

build_scene

build_show

remove_actors

__init__(tractograms=None, images=None, pams=None, cluster=False, cluster_thr=15.0, random_colors=False, length_gt=0, length_lt=1000, clusters_gt=0, clusters_lt=10000, world_coords=True, interactive=True, out_png='tmp.png', recorded_events=None)

Highly interactive visualization - invert the Horizon!

Parameters
tractogramssequence of Streamlines

Sequence of Streamlines objects

imagessequence of tuples

Each tuple contains data and affine

pamssequence of PeakAndMetrics
clusterbool

Enable QuickBundlesX clustering

cluster_thrfloat

Distance threshold used for clustering

random_colorsbool
length_gtfloat
length_ltfloat
clusters_gtint
clusters_ltint
world_coordsbool
interactivebool
out_pngstring
recorded_eventsstring

File path to replay recorded events

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_actors(scene, tractograms, threshold)

Add streamline actors to the scene

build_scene()
build_show(scene)
remove_actors(scene)

Space

class dipy.viz.app.Space

Bases: enum.Enum

Enum to simplify future change to convention

__init__($self, /, *args, **kwargs)

Initialize self. See help(type(self)) for accurate signature.

RASMM = 'rasmm'
VOX = 'vox'
VOXMM = 'voxmm'

StatefulTractogram

class dipy.viz.app.StatefulTractogram(streamlines, reference, space, shifted_origin=False, 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
data_per_point

Getter for data_per_point

data_per_streamline

Getter for data_per_streamline

shifted_origin

Getter for shift

space

Getter for the current space

space_attribute

Getter for spatial attribute

streamlines

Partially safe getter for streamlines

Methods

compute_bounding_box()

Compute the bounding box of the streamlines in their current state

get_streamlines_copy()

Safe getter for streamlines (for slicing)

is_bbox_in_vox_valid()

Verify that the bounding box is valid in voxel space Will transform the streamlines for OBB, slow for big tractogram

remove_invalid_streamlines()

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_rasmm()

Safe function to transform streamlines 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, shifted_origin=False, 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 attribute. Typically a nifti-related object from the native diffusion used for streamlines generation

spacestring

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

shifted_originbool

Information on the position of the origin, False is Trackvis standard, default (corner of the voxel) True is NIFTI standard (center of the voxel)

data_per_pointdict

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

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.

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

get_streamlines_copy()

Safe getter for streamlines (for slicing)

is_bbox_in_vox_valid()

Verify that the bounding box is valid in voxel space Will transform the streamlines for OBB, slow for big tractogram

Returns
outputbool

Are the streamlines within the volume of the associated reference

remove_invalid_streamlines()

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 Returns ——- output : tuple

Tuple of two list, indices_to_remove, indices_to_keep

property shifted_origin

Getter for shift

property space

Getter for the current space

property space_attribute

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_rasmm()

Safe function to transform streamlines and update state

to_vox()

Safe function to transform streamlines and update state

to_voxmm()

Safe function to transform streamlines and update state

Streamlines

dipy.viz.app.Streamlines

alias of nibabel.streamlines.array_sequence.ArraySequence

apply_shader

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

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=False, length_gt=0, length_lt=1000, clusters_gt=0, clusters_lt=10000, world_coords=True, interactive=True, out_png='tmp.png', recorded_events=None)

Highly interactive visualization - invert the Horizon!

Parameters
tractogramssequence

Sequence of Streamlines objects

imagessequence of tuples

Each tuple contains data and affine

pamspeaks
clusterbool

Enable QuickBundlesX clustering

cluster_thrfloat

Distance threshold used for clustering

random_colorsbool
length_gtfloat
length_ltfloat
clusters_gtint
clusters_ltint
world_coordsbool
interactivebool
out_pngstring
recorded_eventsstring

File path to replay recorded events

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() #doctest: +IGNORE_EXCEPTION_DETAIL
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=True)

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

If True print information in stdout.

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, fib, dpy)

Parameters
sftStatefulTractogram

The stateful tractogram to save

filenamestring

Filename with valid extension

Returns
outputbool

Did the saving work properly

setup_module

dipy.viz.app.setup_module()

slicer_panel

dipy.viz.app.slicer_panel(renderer, iren, data=None, affine=None, world_coords=False, pam=None, mask=None)

Slicer panel with slicer included

Parameters
rendererRenderer
irenInteractor
data3d ndarray
affine4x4 ndarray
world_coordsbool

If True then the affine is applied.

peaksPeaksAndMetrics

Default None

Returns
panelPanel

GlobalHorizon

class dipy.viz.gmem.GlobalHorizon

Bases: object

__init__()

Initialize self. See help(type(self)) for accurate signature.

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() #doctest: +IGNORE_EXCEPTION_DETAIL
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(renderer, iren, data=None, affine=None, world_coords=False, pam=None, mask=None)

Slicer panel with slicer included

Parameters
rendererRenderer
irenInteractor
data3d ndarray
affine4x4 ndarray
world_coordsbool

If True then the affine is applied.

peaksPeaksAndMetrics

Default None

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() #doctest: +IGNORE_EXCEPTION_DETAIL
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))) # doctest: +SKIP

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() #doctest: +IGNORE_EXCEPTION_DETAIL
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)

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.

overlay_slices

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

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, plottet 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 title of the left image. By default, no title is displayed.

rtitlestring (optional)

the string to be written as 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.

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)

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 ploted using matplotlib, else the grids are just returned

Returns
warped_forwardarray

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

warped_backwardarray

Image with 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 apropriate default matrix.

plot_slices

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

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

Creates a figure showing the axial, coronal and sagital 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.

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 ploted

yinteger list

y-axis values to be ploted

xlabelstring

label for x-axis

ylablestring

label for y-axis