User Guide

This comprehensive guide covers all aspects of using MedTDA for extracting topological features from medical images.

Overview

MedTDA provides a complete pipeline for TDA feature extraction:

  1. Image Loading - Support for 2D and 3D/4D medical image formats

  2. Preprocessing - Normalization, resampling, windowing, ROI cropping

  3. Persistent Homology - Compute topological features using cubical complexes

  4. Vectorization - Convert barcodes to fixed-length feature vectors

  5. Batch Processing - Process multiple images with parallel execution

High-Level Workflow

The typical workflow with MedTDA:

from medtda import FeatureExtractor

# 1. Initialize with desired settings
extractor = FeatureExtractor(
    # Preprocessing parameters
    normalize=True,
    spacing=(1.0, 1.0, 1.0),

    # PH parameters
    filtration_type='sublevel',

    # Vectorization method
    vectorization_method='PersStats'
)

# 2. Extract features
features = extractor.execute('image.nii.gz', 'mask.nii.gz')

# 3. Use in ML pipeline
# features is a dictionary ready for pandas DataFrame

Detailed Topics

Click on any topic below for detailed information:

Preprocessing

Learn about all preprocessing options:

  • Image loading and format support

  • Intensity normalization methods

  • Resampling and spacing

  • Windowing for CT images

  • ROI cropping and masking

  • Label extraction from multi-label masks

See Preprocessing for complete details.

Persistent Homology

Understand how persistent homology is computed:

  • Filtration types (sublevel vs superlevel)

  • Cubical complex construction methods

  • Homology dimensions

  • Interpreting persistence barcodes

See Persistent Homology for complete details.

Vectorization Methods

Choose the right vectorization method for your application:

  • Persistence Statistics - Statistical summaries (fast, interpretable)

  • Betti Curves - Betti number as a function of filtration

  • Persistence Images - 2D histogram representation

  • Persistence Landscapes - Functional representation

  • Entropy Summary - Information-theoretic features

  • Persistence Silhouettes - Average persistence landscape

  • Lifespan Curves - Distribution of feature lifespans

  • Tropical Coordinates - Tropical algebra representation

See Vectorization for complete details and when to use each method.

Batch Processing

Process multiple images efficiently:

  • CSV format for batch inputs

  • Parallel processing with multiple workers

  • Error handling and logging

  • Configuration management

  • Output organization

See Batch Processing for complete details.

Complete Feature Extractor Reference

The FeatureExtractor class is the main interface for TDA feature extraction.

Initialization Parameters

Preprocessing Parameters:

  • spacing (tuple or None) - Target voxel spacing for resampling

  • window (tuple or None) - Windowing as (center, width)

  • normalize (bool) - Enable intensity normalization

  • normalize_method (str) - ‘minmax’, ‘zscore’, or ‘robust’

  • background_value (float or None) - Background pixel value

  • label (int or None) - Label to extract from multi-label mask

  • crop_to_roi (bool) - Crop to ROI bounding box

  • roi_padding (int) - Padding around ROI in pixels

Persistent Homology Parameters:

  • filtration_type (str) - ‘sublevel’ or ‘superlevel’

  • construction (str) - ‘T’ or ‘V’ cubical complex construction

  • max_dimension (int) - Maximum homology dimension (-1 for auto)

Vectorization Parameters:

  • vectorization_method (str or list) - Method(s) to apply

  • return_barcodes (bool) - Return raw barcodes with features

See FeatureExtractor for complete API documentation.

Methods

execute(image, mask=None)

Extract features from an image.

Parameters:

  • image - File path or NumPy array

  • mask - Optional mask (file path or NumPy array)

Returns:

  • Dictionary of features (or tuple of features and barcodes if return_barcodes=True)

set_vectorization_method(method, **params)

Change the vectorization method and parameters.

enable_vectorization_methods(methods)

Enable multiple vectorization methods.

set_vectorization_params(method, **params)

Configure parameters for a specific method.

Common Patterns

Progressive Refinement

Start simple and add complexity as needed:

# 1. Start with defaults
extractor = FeatureExtractor()
features = extractor.execute('image.nii.gz')

# 2. Add normalization
extractor = FeatureExtractor(normalize=True)
features = extractor.execute('image.nii.gz')

# 3. Add preprocessing
extractor = FeatureExtractor(
    normalize=True,
    spacing=(1.0, 1.0, 1.0),
    crop_to_roi=True
)
features = extractor.execute('image.nii.gz', 'mask.nii.gz')

# 4. Try different vectorization
extractor = FeatureExtractor(
    normalize=True,
    vectorization_method='PersLandscape'
)
features = extractor.execute('image.nii.gz', 'mask.nii.gz')

Comparing Vectorization Methods

Extract features using multiple methods and compare:

methods = [
    'PersStats',
    'BettiCurve',
    'PersLandscape',
    'EntropySummary'
]

results = {}
for method in methods:
    extractor = FeatureExtractor(
        normalize=True,
        vectorization_method=method
    )
    features = extractor.execute('image.nii.gz', 'mask.nii.gz')
    results[method] = features
    print(f"{method}: {len(features)} features")

Reusing Extractor for Multiple Images

Initialize once, use many times:

# Initialize extractor once
extractor = FeatureExtractor(
    normalize=True,
    spacing=(1.0, 1.0, 1.0),
    vectorization_method='PersStats'
)

# Process multiple images
images = ['scan1.nii.gz', 'scan2.nii.gz', 'scan3.nii.gz']
all_features = []

for img_path in images:
    features = extractor.execute(img_path)
    all_features.append(features)

Working with Different Image Types

2D Images

from medtda import FeatureExtractor
import numpy as np
from PIL import Image

# Load 2D image
img_2d = np.array(Image.open('slice.png').convert('L'))

# Extract features
extractor = FeatureExtractor(
    normalize=True,
    vectorization_method='PersStats'
)
features = extractor.execute(img_2d)

3D Medical Images

import SimpleITK as sitk

# Load 3D medical image
image = sitk.ReadImage('scan.nii.gz')
mask = sitk.ReadImage('mask.nii.gz')

# Extract features with preprocessing
extractor = FeatureExtractor(
    spacing=(1.0, 1.0, 1.0),  # Resample to isotropic
    normalize=True,
    crop_to_roi=True,
    vectorization_method='PersStats'
)

features = extractor.execute(image, mask)

4D Time Series

For 4D images, each time point is processed independently:

# Load 4D image (3D + time)
image_4d = sitk.ReadImage('timeseries.nii.gz')

# Process first time point
extractor = FeatureExtractor(normalize=True)
features = extractor.execute(image_4d)  # Automatically uses first volume

Multi-Label Masks

Extract features for specific labels:

# Extract features for label 2 (e.g., tumor core)
extractor = FeatureExtractor(
    label=2,              # Extract this label
    crop_to_roi=True,
    normalize=True,
    vectorization_method='PersStats'
)

features = extractor.execute('image.nii.gz', 'multilabel_mask.nii.gz')

Best Practices

  1. Always normalize for consistency

    extractor = FeatureExtractor(normalize=True, normalize_method='minmax')
    
  2. Use ROI cropping for efficiency

    extractor = FeatureExtractor(crop_to_roi=True, roi_padding=2)
    
  3. Resample to isotropic spacing for 3D images

    extractor = FeatureExtractor(spacing=(1.0, 1.0, 1.0))
    
  4. Start with PersStats for exploration

    extractor = FeatureExtractor(vectorization_method='PersStats')
    
  5. Save barcodes for later analysis

    extractor = FeatureExtractor(return_barcodes=True)
    features, barcodes = extractor.execute(image, mask)
    
  6. Use configuration files for reproducibility

    Create a config.yaml and use it consistently across your project.

Performance Tips

  • Use ROI cropping - Significantly reduces computation time

  • Limit max_dimension - Set to 1 or 2 instead of auto-detection

  • Use parallel processing - For batch processing with CLI

  • Consider image size - Downsample very large images if appropriate

  • Choose efficient vectorization - PersStats is fastest

See Frequently Asked Questions for more performance optimization tips.

Error Handling

Handle common errors gracefully:

from medtda import FeatureExtractor

extractor = FeatureExtractor(normalize=True)

try:
    features = extractor.execute('image.nii.gz', 'mask.nii.gz')
except FileNotFoundError as e:
    print(f"File not found: {e}")
except ValueError as e:
    print(f"Invalid input: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")

Next Steps