CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-dipy

Comprehensive Python library for diffusion MRI analysis including tensor imaging, tractography, and visualization

Pending
Overview
Eval results
Files

tractography.mddocs/

Tractography and Fiber Tracking

Deterministic and probabilistic tractography algorithms with various direction selection methods, streamline generation, and tracking utilities. DIPY provides comprehensive tools for reconstructing white matter pathways from diffusion MRI data.

Capabilities

Direction Selection

Direction getter classes that determine fiber orientations for tractography algorithms.

class DeterministicMaximumDirectionGetter:
    """Deterministic direction selection using peak maxima."""
    def __init__(self, from_shm, max_angle=60.0, sphere=None):
        """
        Initialize deterministic direction getter.
        
        Parameters:
            from_shm (array): spherical harmonic coefficients
            max_angle (float): maximum turning angle in degrees
            sphere (Sphere): sphere for direction sampling
        """

class ProbabilisticDirectionGetter:
    """Probabilistic direction selection with angular uncertainty."""
    def __init__(self, from_shm, max_angle=60.0, sphere=None, sh_to_pmf=False):
        """
        Initialize probabilistic direction getter.
        
        Parameters:
            from_shm (array): spherical harmonic coefficients  
            max_angle (float): maximum turning angle in degrees
            sphere (Sphere): sphere for direction sampling
            sh_to_pmf (bool): convert SH to probability mass function
        """

class ClosestPeakDirectionGetter:
    """Direction selection using closest peak to previous direction."""
    def __init__(self, from_shm, max_angle=60.0, sphere=None):
        """Initialize closest peak direction getter."""

class BootDirectionGetter:
    """Bootstrap direction selection for uncertainty estimation."""
    def __init__(self, from_shm, max_angle=60.0, sphere=None, sh_order=None):
        """Initialize bootstrap direction getter."""

class PTTDirectionGetter:
    """Particle Tracking Tractography direction getter."""
    def __init__(self, ptt_interp, vertices, mode='prob'):
        """Initialize PTT direction getter."""

Peak Extraction

Functions for extracting directional peaks from orientation distribution functions.

def peaks_from_model(model, data, sphere, *, relative_peak_threshold=0.5, min_separation_angle=25, mask=None, return_odf=False, return_sh=False, gfa_thr=0.0, normalize_peaks=False, sh_order_max=8, sh_basis_type=None, npeaks=5, B=None, invB=None, parallel=None, num_processes=None):
    """
    Generate peaks from fitted model.
    
    Parameters:
        model: fitted reconstruction model (e.g., CSD)
        data (array): diffusion data
        sphere (Sphere): sphere for peak extraction
        relative_peak_threshold (float): minimum peak height relative to max
        min_separation_angle (float): minimum angle between peaks (degrees)
        mask (array): binary mask for processing
        return_odf (bool): return orientation distribution function
        return_sh (bool): return spherical harmonic coefficients  
        gfa_thr (float): generalized fractional anisotropy threshold
        normalize_peaks (bool): normalize peak magnitudes
        sh_order_max (int): maximum spherical harmonic order
        sh_basis_type (str): spherical harmonic basis type
        npeaks (int): maximum number of peaks per voxel
        B (array): spherical harmonic matrix
        invB (array): inverse spherical harmonic matrix
        parallel (bool): use parallel processing
        num_processes (int): number of processes for parallel execution
        
    Returns:
        PeaksAndMetrics: container with peaks, values, and metrics
    """

def peak_directions(odf, sphere, *, relative_peak_threshold=0.5, min_separation_angle=25, **kwargs):
    """
    Extract peak directions from ODF.
    
    Parameters:
        odf (array): orientation distribution function values
        sphere (Sphere): sphere defining ODF sampling
        relative_peak_threshold (float): peak detection threshold
        min_separation_angle (float): minimum peak separation angle
        
    Returns:
        tuple: (peaks, peak_values) directions and magnitudes
    """

def reshape_peaks_for_visualization(peaks):
    """
    Reshape peak data for visualization.
    
    Parameters:
        peaks (PeaksAndMetrics): peak data container
        
    Returns:
        array: reshaped peak directions for rendering
    """

class PeaksAndMetrics:
    """Container for peak directions and associated metrics."""
    def __init__(self):
        """Initialize peaks and metrics container."""
    
    @property  
    def peak_dirs(self):
        """array: peak directions (4D: x, y, z, directions)"""
    
    @property
    def peak_values(self):
        """array: peak magnitudes"""
    
    @property
    def peak_indices(self):
        """array: sphere indices of peaks"""
    
    @property
    def gfa(self):
        """array: generalized fractional anisotropy"""
    
    @property
    def qa(self):
        """array: quantitative anisotropy"""
    
    @property
    def shm_coeff(self):
        """array: spherical harmonic coefficients"""

Streamline Container

Main container class for streamline data with iteration and manipulation methods.

class Streamlines:
    """Container for streamline data."""
    def __init__(self, streamlines=None):
        """
        Initialize streamlines container.
        
        Parameters:
            streamlines (list): list of streamline arrays
        """
    
    def __len__(self):
        """Number of streamlines."""
    
    def __getitem__(self, key):
        """Access streamlines by index or slice."""
    
    def __iter__(self):
        """Iterate over streamlines."""
    
    def append(self, streamline):
        """Add streamline to container."""
    
    def extend(self, streamlines):
        """Add multiple streamlines."""

Tracking Algorithms

Core tractography algorithms for deterministic and probabilistic fiber tracking.

def LocalTracking(direction_getter, classifier, seeds, affine, step_size=0.5, max_cross=None, maxlen=1000000, fixedstep=True, return_all=True):
    """
    Local streamline tracking algorithm.
    
    Parameters:
        direction_getter: direction selection object
        classifier: tissue classifier for tracking
        seeds (array): seed point coordinates  
        affine (array): voxel-to-world transformation matrix
        step_size (float): tracking step size in mm
        max_cross (int): maximum fiber crossings per voxel
        maxlen (int): maximum streamline length
        fixedstep (bool): use fixed step size
        return_all (bool): return all streamlines including short ones
        
    Returns:
        generator: streamline generator
    """

def ParticleFilteringTracking(direction_getter, classifier, seeds, affine, max_cross=None, step_size=0.5, maxlen=1000000, pft_back_tracking_dist=2.0, pft_front_tracking_dist=1.0, particle_count=15, return_all=True):
    """
    Particle Filtering Tractography algorithm.
    
    Parameters:
        direction_getter: direction selection object
        classifier: tissue classifier
        seeds (array): seed coordinates
        affine (array): affine transformation  
        max_cross (int): maximum crossings
        step_size (float): step size in mm
        maxlen (int): maximum length
        pft_back_tracking_dist (float): back tracking distance
        pft_front_tracking_dist (float): front tracking distance  
        particle_count (int): number of particles per streamline
        return_all (bool): return all streamlines
        
    Returns:
        generator: streamline generator
    """

Tissue Classification

Classifiers that determine tracking behavior based on tissue properties.

class ThresholdClassifier:
    """Binary classifier based on scalar threshold."""
    def __init__(self, metric_map, threshold):
        """
        Initialize threshold classifier.
        
        Parameters:
            metric_map (array): scalar map (e.g., FA)
            threshold (float): classification threshold
        """

class BinaryClassifier:
    """Binary tissue classifier."""
    def __init__(self, mask):
        """Initialize with binary mask."""

class ACTClassifier:
    """Anatomically Constrained Tractography classifier."""
    def __init__(self, include_map, exclude_map=None):
        """
        Initialize ACT classifier.
        
        Parameters:
            include_map (array): inclusion probability map
            exclude_map (array): exclusion probability map
        """

Streamline Utilities

Utility functions for streamline processing and analysis.

def set_number_of_points(streamlines, nb_points=3):
    """
    Resample streamlines to fixed number of points.
    
    Parameters:
        streamlines: input streamlines
        nb_points (int): target number of points
        
    Returns:
        list: resampled streamlines
    """

def length(streamlines):
    """
    Calculate streamline lengths.
    
    Parameters:
        streamlines: input streamlines
        
    Returns:
        array: streamline lengths in mm
    """

def transform_streamlines(streamlines, mat, in_place=False):
    """
    Transform streamlines by affine matrix.
    
    Parameters:
        streamlines: input streamlines
        mat (array): 4x4 transformation matrix
        in_place (bool): modify streamlines in place
        
    Returns:
        list: transformed streamlines
    """

def select_random_set_of_streamlines(streamlines, select):
    """
    Randomly select subset of streamlines.
    
    Parameters:
        streamlines: input streamlines
        select (int): number to select
        
    Returns:
        list: selected streamlines
    """

Usage Examples

# Complete tractography workflow
from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel, auto_response_ssst
from dipy.direction import DeterministicMaximumDirectionGetter
from dipy.tracking.local import LocalTracking, ThresholdClassifier
from dipy.tracking.streamline import Streamlines
from dipy.data import read_stanford_hardi, get_sphere
import numpy as np

# Load and prepare data
img, gtab = read_stanford_hardi()
data = img.get_fdata()

# Fit CSD model for fiber orientations
response, ratio = auto_response_ssst(gtab, data)
csd_model = ConstrainedSphericalDeconvModel(gtab, response)
csd_fit = csd_model.fit(data)

# Extract peaks for direction getting
sphere = get_sphere('symmetric724')
from dipy.direction import peaks_from_model

peaks = peaks_from_model(csd_model, data, sphere, 
                        relative_peak_threshold=0.5,
                        min_separation_angle=25,
                        npeaks=2)

# Set up direction getter and classifier
dg = DeterministicMaximumDirectionGetter.from_shm(peaks.shm_coeff, 
                                                  max_angle=30, 
                                                  sphere=sphere)

# Use FA for tracking termination
from dipy.reconst.dti import TensorModel
tensor_model = TensorModel(gtab)
tensor_fit = tensor_model.fit(data)
fa = tensor_fit.fa

classifier = ThresholdClassifier(fa, 0.1)

# Generate seeds throughout the brain
from dipy.tracking import utils
seeds = utils.seeds_from_mask(fa > 0.3, affine=img.affine, density=1)

# Perform tractography
streamlines = LocalTracking(dg, classifier, seeds, img.affine, 
                           step_size=0.5, return_all=False)

# Convert to streamlines object
streamlines = Streamlines(streamlines)

print(f"Generated {len(streamlines)} streamlines")

# Filter by length
from dipy.tracking.streamline import length
lengths = length(streamlines)
long_streamlines = [s for s, l in zip(streamlines, lengths) if l > 20]

print(f"Kept {len(long_streamlines)} streamlines longer than 20mm")

# Probabilistic tractography
from dipy.direction import ProbabilisticDirectionGetter

prob_dg = ProbabilisticDirectionGetter.from_shm(peaks.shm_coeff,
                                               max_angle=30,
                                               sphere=sphere)

prob_streamlines = LocalTracking(prob_dg, classifier, seeds[:1000], 
                                img.affine, step_size=0.5)

prob_streamlines = Streamlines(prob_streamlines)
print(f"Probabilistic tracking generated {len(prob_streamlines)} streamlines")

Install with Tessl CLI

npx tessl i tessl/pypi-dipy

docs

core-utilities.md

data-access.md

image-processing.md

index.md

neural-networks.md

registration.md

segmentation.md

signal-reconstruction.md

simulations.md

statistics.md

tractography.md

visualization.md

workflows.md

tile.json