Low level functions

The readAndFilter module contains additional functions which should not be necessary for creating applications. These functions however may be used when developing new BaseReader subclasses.

cache

Handle memory cache

class CacheContainer(max_cache=500)[source]

Class used to cache data, see cache_function()

cache

Data container

max_cache

Maximum amount of memory in Mb that should be used by the process

class LastUpdatedOrderedDict(*args, **kwds)[source]

Store items in the order the keys were last updated

cache_function(cache_container)[source]

Decorator which saves function results in memory to speed up repeated requests for the same information

The decorator uses a CacheContainer to store data, and to limit the amount of memory used. Last access time is also recorded, and in case that memory needs to be released, data with oldest access time is deleted.

Parameters:cache_container (braviz.readAndFilter.cache.CacheContainer) – Object used to store data
memo_ten(f)[source]

Simple wrapper that holds up to ten function calls in cache.

memoize(obj)[source]

A wrapper that saves the return values for a function, and returns them if the function is called again with the same arguments.

Warning

There is no limit to the size of the cache in this wrapper, consider using memo_ten(). For large data use func:cache_function.

Parameters:obj (function) – function to wrap

color_fibers

Add color and scalars to tractographies

color_by_fa(pt, fa_img)[source]

Calculates color based on an FA img

Deprecated since version 3.0: Use scalars instead

Parameters:
Returns:

(r,g,b)

color_by_z(pt)[source]

Color a point based on its ‘z’ coordinate

Parameters:pt (tuple) – Point coordinates
Returns:(r,g,b)
color_fibers_lines(fibers, polyline_color_function, *args, **kw)[source]

Applies a function to each line in a tractography to assign it a color

Parameters:
  • fibers (vtkPolyData) – Tractography
  • polyline_color_function (function) – Function that takes a vtkCell and returns a dict mapping point ids to colors
  • *args – extra positional arguments passed to polyline_color_function
  • **kwargs – extra keyword arguments passed to polyline_color_function
color_fibers_pts(fibers, color_function, *args, **kw)[source]

Apply a function to assign color for each point in a tractography

Parameters:
  • fibers (vtkPolyData) – Tractography
  • color_function (function) – Function that takes point coordinates and returns a color tuple
  • *args – extra positional arguments passed to color_function
  • **kwargs – extra keyword arguments passed to color_function
get_fa_lut()[source]

A generic FA lookuptable

Returns:vtkColorTransferFunction
get_length_lut()[source]

A generic length lookuptable

Returns:vtkColorTransferFunction
line_curvature(line)[source]

Calculates a color based on the curvature of the polyline

Implements the simple formula from http://en.wikipedia.org/wiki/Curvature

Parameters:line (vtkCell) – Polyline
Returns:Dictionary from all point ids to the random color
random_line(line)[source]

Creates a random color and maps the whole line to it

Parameters:line (vtkCell) – Polyline
Returns:Dictionary from all point ids to the random color
scalars_from_image(fibers, nifti_image)[source]

Assigns scalars taken from an image to a polydata

Parameters:
scalars_from_image_int(fibers, nifti_image)[source]

Assigns scalars taken from an image to a polydata without interpolation (nearest neighbour)

Parameters:
scalars_from_length(fibers)[source]

Assigns scalars to each line representing its length

Parameters:fibers (vtkPolyData) – Tractography
scalars_lines_from_image(fibers, nifti_image)[source]

Averages scalars along lines and assigns one scalar to each line, based on an image

Parameters:

filter_fibers

Extract fibers from tractographies

class FilterBundleWithSphere[source]

A class to interactively filter a polydata with a moving sphere

filter_bundle_with_sphere(center, radius, get_ids=False)[source]

Filter polydata to keep only the lines which have a point inside a sphere

Parameters:
  • center (tuple) – Sphere center (x,y,z)
  • radius (float) – Sphere radius
  • get_ids (bool) – get ids or filtered polydata
Returns:

If get_ids is True the ids of the satisfying cells are returned, otherwise a filtered vtkPolydata is returned

set_bundle(bundle)[source]

Set the base polydata

Parameters:bundle (vtkPolyData) – base bundle
abstract_test_lines_in_polyline(fibers, predicate)[source]

Extract lines where at least one point makes predicate True.

Parameters:
  • fibers (vtkPolyData) – Tractography
  • predicate (function) – Should take point coordinates and return a boolean
Returns:

Set of cells where the predicate is True for at least one point

boundingBoxIntesection(box1, box2)[source]

test if two bounding boxes intersect

Parameters:
  • box1 (list) – Bounding box [x0, x1, y0, y1, z0, z1]
  • box2 (list) – Bounding box [x0, x1, y0, y1, z0, z1]
Returns:

True if the bounding boxes intersect, False otherwise

extract_poly_data_subset(polydata, id_list)[source]

Extracts polylines with given ids from polydata

Parameters:
  • polydata (vtkPolyData) – Full polydata
  • id_list (list) – List of cell ids
Returns:

A vtkPolyData containing only the requested cells.

filterPolylinesWithModel(fibers, model)[source]

filters a polyline, keeps only the lines that cross a model

Parameters:
Returns:

Set of polyline ids where the line goes through the model

filter_polylines_by_scalar(fibs, scalar)[source]

Finds lines where at least one point has a scalar value in the range (scalar -0.5, scalar + 0.5)

Parameters:
  • fibs (vtkPolyData) – Full polydata with scalar data
  • scalar (float) – scalar value to look for
Returns:

Cell ids where at least one point has a scalar in the range (scalar -0.5, scalar + 0.5)

filter_polylines_with_img(polydata, img, label)[source]

Filter polydata based on labels found in an image.

For each point in the polyline the function finds the corresponding label in the image. Only lines where at least one point has the requested label are left in the output set.

Parameters:
Returns:

Set of CellIds where at least one point gets the requested label

filter_polylines_with_img_slow(polydata, img, label)[source]

Slow version of filter_polylines_with_img()

iter_id_list(id_list)[source]

Iterate over a vtkIdList

Parameters:id_list (vtkIdList) – Id List
Yields:Point ids

hierarchical fibers

Read fibers defined by a logical hierarchy

get_all_lines(subj, reader)[source]

Gets a list of the polyline ids of the whole tractography

Parameters:
get_valid_lines_from_logical(subj, tree_node, reader)[source]

Get polyline ids that match the condition in a logical node

Parameters:
get_valid_lines_from_node(subj, tree_node, reader)[source]

Get ids of polylines that match the condition described in a tree node

Parameters:
get_valid_lines_from_roi(subj, roi_id, reader)[source]

Get polyline ids that match the condition in a roi node

Parameters:
get_valid_lines_from_struct(subj, struct, reader)[source]

Get polyline ids that match the condition in a structure node

Parameters:
read_logical_fibers(subj, space, tree_dict, reader, **kwargs)[source]

Gets a vtkPolyData for a bundle described using a logical hierarchy

Parameters:

images

Work with nifti and vtk Images

nibNii2vtk(nii)[source]

Transform a nifti image read by nibabel into a vtkImageData ignoring transformations

Parameters:nii (nibabel.spatialimages.SpatialImage) – Nifti image object
Returns:vtkImageData, transformations are ignored, you should apply them afterwards see applyTransform()
nifti_rgb2vtk(nifti_rgb)[source]

Reads 4D rgb nifti images

Parameters:nifti_rgb (nibabel.spatialimages.SpatialImage) – 4D Nifti image object
Returns:vtkImageData with rgb scalars
numpy2vtk_img(d, data_type=None)[source]

Transform a 3d numpy array into a vtk image data object

Parameters:
  • d (numpy.ndarray) – Voxel data
  • data_type (str) – Data type of voxel data, if None attempts to read from the array
Returns:

vtkImageData

vtk2numpy(vtk_image)[source]

Transform a vtk image into a numpy array

Parameters:vtk_image (vtkImageData) – vtk image
Returns:A numpy array of the same shape as the image
write_nib_image(data, affine, out_file)[source]

Writes nifti image to disk

Parameters:
write_vtk_image(image_data, out_file)[source]

Write a vtkImage to disk as a nifti file

Parameters:
  • image_data (vtkImageData) – Image to write
  • out_file (str) – Path to output nifti file

named_tracts

Use custom python functions to filter tractographies

corpus_callosum(reader, subject, color, scalars, get_out_space=False)[source]

Gets the corpus callosum bundle

Parameters:
Returns:

vtkPolyData of the corpus callosum bundle

cortico_spinal_d(reader, subject, color, scalars, get_out_space=False)[source]

Gets the dominant hemisphere corticospinal tract

Parameters:
Returns:

vtkPolyData of dominant cortico-spinal tract

cortico_spinal_l(reader, subject, color, scalars=None)[source]

Gets the left cortico-spinal tract

Parameters:
Returns:

vtkPolyData of left cortico-spinal tract

cortico_spinal_n(reader, subject, color, scalars, get_out_space=False)[source]

Gets the non-dominant hemisphere corticospinal tract

Parameters:
Returns:

vtkPolyData of non-dominant cortico-spinal tract

cortico_spinal_r(reader, subject, color, scalars=None)[source]

Gets the right corticospinal tract

Parameters:
Returns:

vtkPolyData of right cortico-spinal tract

read_csv

Parse data from csv files

column_to_vtk_array(col, name='unknown')[source]

Transforms a list of values into a vtkArray, useful for feedint into vtk Data Viz functions

Parameters:
  • col (list) – List of values
  • name (str) – Name for the array
Returns:

A vtkDataArray with the values in col

get_column(file_name, name, numeric=False, nan_value=nan)[source]

Reads a column from a csv file

Deprecated since version 3.0b: Use braviz.readAndFilter.tabular_data instead

Parameters:
  • file_name (str) – csv file path
  • name (str) – header of column
  • numeric (bool) – if True cast the data to float
  • nan_value – Value to use for missing data
Returns:

A list with the values in the column

get_headers(file_name)[source]

Get the headers of a csv file

Parameters:file_name (str) – csv file path
Returns:A list of headers in the file
get_tuples_dict(file_name, key_col, columns, numeric=False, nan_value=nan)[source]

Reads multiple columns from a csv file

Deprecated since version 3.0b: Use braviz.readAndFilter.tabular_data instead

Parameters:
  • file_name (str) – csv file path
  • key_col (str) – name of column to be used as key
  • columns (list) – list of column headers to get as values
  • numeric (bool) – if True cast the data to float
  • nan_value – Value to use for missing data
Returns:

A dictionary with values from key_col as keys, and tuples from the values in columns

read_free_surfer_csv_file(file_name, row, search_col=None, col=None)[source]

Read data from freeSurfer stats file

If row is headers returns a list of file headers Otherwise: a single row will be selected based on the row value and the search_col value. The function will return the row where the value under column with header search_col matches row if col is given, only the value under the column with this header will be returned

Parameters:
  • file_name (str) – csv file path
  • row (str) – identifier for the row of interest
  • search_col (str) – header of the column where row identifiers will appear
  • col (str) – header for the column of the value of interest
Returns:

If col is None the whole row that contains row in column search_col; otherwise, the value under col for that row.

read_spm

Read data from spm.mat files

class ConditionInfo(name, onsets, durations)
__getnewargs__()

Return self as a plain tuple. Used by copy and pickle.

__getstate__()

Exclude the OrderedDict from pickling

__repr__()

Return a nicely formatted representation string

durations

Alias for field number 2

name

Alias for field number 0

onsets

Alias for field number 1

class ContrastInfo(name, design)
__getnewargs__()

Return self as a plain tuple. Used by copy and pickle.

__getstate__()

Exclude the OrderedDict from pickling

__repr__()

Return a nicely formatted representation string

design

Alias for field number 1

name

Alias for field number 0

class SpmFileReader(spm_file_path)[source]

Helper class to read data from an SPM file

conditions

Experimental conditions in the paradigm

Returns:A named tuple (see collections.namedtuple()) with condition name as first component (str), onsets (numpy.ndarray) as second argument, and durations (numpy.array) as third argument
contrasts

Existing contrast design arrays

Returns:A named tuple (see collections.namedtuple()) with contrast name as first component (str), and the contrast design array as second component (numpy.array)
get_condition_block(index)[source]

Gets a block signal representing a condition

Returns:numpy.ndarray of the same length as the one returned by get_time_vector(), it will be 1 when the condition is active, and 0 otherwise
get_contrast_names()[source]

A dictionary with contrast names

Returns:A dictionary with contrast indexes (starting at 1) for keys and contrast names for values
get_time_vector()[source]

Gets a vector containing time values for the duration of the experiment

Returns:numpy.ndarray with time values across the duration of the experiment
n_scans

The number of scans in the experiment

tr

The TR time in the experiment

get_contrasts_dict(spm_file_path)[source]

Parse information about existing contrasts from an spm file

Parameters:spm_file_path (str) – Path to spm.mat file
Returns:A dictionary with contrast indexes (starting at 1) for keys, and contrast names for values

readDartelTransform

check_matrix(m)[source]

check that the affine matrix contains only spacing and translation

Parameters:m (numpy.ndarray) – 4x4 Matrix

Returns: True if the components other than the diagonal and the last column are zero, False otherwise

dartel2GridTransform(y_file, assume_general_matrix=False)[source]

reads a dartel nifti file from disk and returns a vtkTransform, this function is very slow

Parameters:
  • y_file (str) – path to the nifti warp file
  • assume_general_matrix (bool) – If True it will be assumed that the matrix contains more than origin and spacing
Returns:

vtkGridTransform if the matrix is only spacing and origin, otherwise a vtkGeneralTransform which include the full original affine transform.

dartel2GridTransform_cached(y_file, cache_key, reader, assume_general_matrix=False)[source]

Cached version of dartel2GridTransform()

Parameters:
  • y_file (str) – Path to nifti warp file
  • cache_key (str) – Key to use for saving and reading from cache
  • reader (BaseReader) – Reader object to use for accessing cache
  • assume_general_matrix (bool) – If True it will be assumed that the matrix contains more than origin and spacing
Returns:

vtkGridTransform if the matrix is only spacing and origin, otherwise a vtkGeneralTransform which include the full original affine transform.

surfer_input

addScalars(surf_polydata, scalars)[source]

Add scalars to a vtkPolyData representation of a freesurfer surface

Parameters:
  • surf_polydata (vtkPolyData) – freesurfer surface
  • scalars (numpy.ndarray) – scalars belonging to the same freesurfer surface (same number of points)
Returns:

vtkPolyData with scalar data

apply_offset(coords, offset)[source]

applies an offset to all the coordinates in coords

Parameters:coords (numpy.ndarray) – nx3 coordinates array

Returns: nx3 coordinates array of translated coordinates

create_polydata(coords, faces)[source]

Creates a polydata using the coords and faces array (must contain only triangles)

See read_surface()

Parameters:
Returns:

vtkPolyData with same points and faces

getColorTransferLUT(start, end, midpoint, sharpness, color0, color1, color2=None)[source]

Creates a vtkLookUpTable from color0 to color1 or from color0 to color2 passing by color1

The domain of the LUT will be (start,end) midpoint and sharpness can be used to change the characteristics of the function between colors (see vtkPiecewiseFunction) if three colors are used, the resulting function will be symmetric, this means the actual midpoint for the second half will be 1-midpoint

Parameters:
  • start (float) – first value in the lookuptable domain
  • end (float) – last value in the lookuptable domain
  • midpoint (float) – Midpoint for function between colors
  • sharpness (float) – Sharpness for function between colors
  • color0 (tuple) – First color in the lookuptable
  • color1 (tuple) – Second color in the lookuptable
  • color2 (tuple) – Optional, third color in the lookuptable
Returns:

vtkColorTransferFunction

get_free_surfer_lut(name)[source]

Get standard freesurfer lookup tables

Parameters:name (str) – Name of table, available tables are - curv / avg_curv - area - thickness - volume - sulc
Returns:vtkColorTransferFunction
read_annot(filepath, orig_ids=False)[source]

Read in a Freesurfer annotation from a .annot file.

copied directly from pysurfer.io

Parameters:
  • filepath (str) – Path to annotation file
  • orig_ids (bool) – Whether to return the vertex ids as stored in the annotation file or the positional colortable ids
Returns:

  • labels (n_vtx numpy.ndarray) – Annotation id at each vertex
  • ctab (numpy.ndarray) – RGBA + label id colortable array
  • names (numpy.ndarray) – Array of region names as stored in the annot file

read_morph_data(filepath)[source]

Read a Freesurfer morphometry data file.

copied directly from pysurfer.io

This function reads in what Freesurfer internally calls “curv” file types, (e.g. ?h. curv, ?h.thickness), but as that has the potential to cause confusion where “curv” also refers to the surface curvature values, we refer to these files as “morphometry” files with PySurfer.

Parameters:filepath (str) – Path to morphometry file
Returns:curv (numpy.ndarray) – Vector representation of surface morpometry values
read_surface(filepath)[source]

reads a freesurfer wireframe structure

Parameters:filepath (str) – Path to freesurfer surface file
Returns:(coords,faces,geom), where coords are the coordinates of each point, faces are the indeces of points in each face, and geom is a dictionary containing ['cras', 'volume',  'voxelsize',  'xras',  'yras',  'zras'] which can be used to determine the affine transform required to move the surface to the MRI space
surfLUT2VTK(ctab, names=None)[source]

Transform freesurfer lookuptable into a vtkLookupTable

The index of the row will be used as label. This method is designed to work with the ctab array returned by read_annot; labels may be used to annotate values

Parameters:
  • ctab (numpy.ndarray) – 2darray with R G B [A] [X] columns.
  • names (list) – Same length as ctab, add annotations to the lookuptable
Retruns:
vtkLookupTable with colors and annotations.
surface2vtkPolyData(surf_file)[source]

read free surfer surface and transform to poly data

Parameters:surf_file (str) – Path to freesurfer surface file
Returns:vtkPolyData representation of the surface

transforms

applyTransform(img, transform, origin2=None, dimension2=None, spacing2=None, interpolate=True)[source]

Apply a linear transform to a grid which afterwards resamples the image.

Be sure to pass the inverse of the transform you would use to transform a point. Accepts linear and non linear transforms

Parameters:
  • img (vtkImageData) – Image
  • transform (vtkTransform) – Linear or nonlinear transform
  • origin2 (tuple) – If not None, the origin for the output image
  • dimension2 (tuple) – If not None, the dimension for the output image
  • spacing2 (tuple) – If not None, the spacing for the output image
  • interpolate (bool) – If True voxel values are interpolated, if False the nearest neighbour value is used. This is important for label maps.
Returns:

Resampled vtkImageData

numpy2vtkMatrix(M)[source]

Transform a 4x4 numpy array into vtk4x4 matrix

Parameters:M (numpy.ndarray) – Numpy 4x4 array
Returns
vtk4x4Matrix
readFlirtMatrix(*args, **kwargs)[source]

read a matrix in fsl flirt format

In order to apply this transformation information about the source and ref images is also requierd. The function returns the effective transform that can be applied to point data.

Parameters:
  • file_name (str) – Path to fsl transform
  • src_img_file (str) – Path to the image specifying the source image for the transform
  • ref_img_file (str) – Path to the image specifying the destination image for the transform
  • path (str) – Common path to all files, it is prepended to the other arguments
Returns:

Numpy 4x4 matrix

readFreeSurferTransform(filename)[source]

Reads a freeSurfer transform file and returns a numpy array

Parameters:filename (str) – Path to freesurfer transform
Returns:4x4 numpy array
transformGeneralData(data, transform)[source]

Use a transform or a 4x4Matrix to transform vtkPointData or poly data

Parameters:
  • data – Data to apply the transform to
  • transform (vtkTransform) – Transform to be applied
Returns:

Transformed data

transformPolyData(poly_data, transform)[source]

Kept for compatibility, it is an alias to transformGeneralData()

Deprecated since version 3.0b: Use transformGeneralData()