.. _examples:

========
Examples
========

This section provides practical examples demonstrating how to use MedTDA for various tasks.

.. contents:: Contents
   :local:
   :depth: 2

Overview
========

The examples are organized by complexity and use case:

1. **Basic Usage** - Get started with simple feature extraction
2. **Advanced Preprocessing** - Custom preprocessing workflows
3. **Batch Workflows** - Process multiple images efficiently
4. **CLI Workflows** - Command-line usage patterns
5. **Tutorial Notebook** - Interactive Jupyter notebook

All examples use realistic medical imaging scenarios and follow best practices.

Quick Links
===========

.. list-table::
   :widths: 30 70
   :header-rows: 1

   * - Example
     - Description
   * - :doc:`basic_usage`
     - Simple feature extraction, masks, different formats
   * - :doc:`advanced_preprocessing`
     - Custom pipelines, ROI analysis, multi-step workflows
   * - :doc:`batch_workflow`
     - CSV batch processing, parallel execution, result analysis
   * - :doc:`cli_workflows`
     - CLI patterns, scripting, pipeline integration
   * - :doc:`../tutorials/notebook`
     - Interactive Jupyter notebook tutorial

Example Gallery
===============

.. toctree::
   :maxdepth: 2

   basic_usage
   advanced_preprocessing
   batch_workflow
   cli_workflows
   ../tutorials/notebook

Getting Started
===============

If you're new to MedTDA, start with:

1. :doc:`basic_usage` - Learn the fundamentals
2. :doc:`../quickstart` - 5-minute quick start guide
3. :doc:`advanced_preprocessing` - More control over preprocessing

For Production Use
==================

When deploying MedTDA:

1. :doc:`batch_workflow` - Efficient batch processing
2. :doc:`cli_workflows` - Integrate with existing pipelines

Example Data
============

Most examples use placeholder paths. To run them:

**Option 1: Use your own data**

Replace paths with your medical images:

::

    # Replace this
    image_path = 'data/patient001.nii.gz'
    
    # With your actual path
    image_path = '/path/to/your/scan.nii.gz'

**Option 2: Generate synthetic data**

For testing purposes:

::

    import numpy as np
    from medtda.loaders import save_image
    
    # Create synthetic 3D image
    synthetic_image = np.random.rand(64, 64, 64)
    save_image(synthetic_image, 'test_image.nii.gz')
    
    # Create synthetic mask
    synthetic_mask = (np.random.rand(64, 64, 64) > 0.5).astype(np.uint8)
    save_image(synthetic_mask, 'test_mask.nii.gz')

**Option 3: Download sample data**

See :doc:`../installation` for links to public medical imaging datasets.

Example Categories
==================

By Task
-------

**Classification:**

* :doc:`basic_usage` - Extract features for ML
* :doc:`batch_workflow` - Process training/test sets

**Regression:**

* :doc:`basic_usage` - Continuous outcome prediction
* :doc:`advanced_preprocessing` - Optimize preprocessing

**Exploratory Analysis:**

* :doc:`basic_usage` - Quick feature inspection

**Large-Scale Processing:**

* :doc:`batch_workflow` - Hundreds/thousands of images
* :doc:`cli_workflows` - Automation and scripting

By Image Type
--------------

**CT Scans:**

* :doc:`advanced_preprocessing` - CT windowing examples
* :doc:`basic_usage` - CT-specific workflows

**MRI:**

* :doc:`basic_usage` - Multi-sequence MRI
* :doc:`advanced_preprocessing` - Normalization strategies

**Microscopy:**

* :doc:`basic_usage` - 2D image analysis

**Multi-Modal:**

* :doc:`batch_workflow` - Process different modalities
* :doc:`advanced_preprocessing` - Modality-specific preprocessing

Code Patterns
=============

Common Import Pattern
---------------------

Most examples start with::

    from medtda import FeatureExtractor, Preprocessor, BarcodeExtractor
    from medtda.loaders import load_image, load_mask
    from medtda.vectorizers import persistence_image
    import numpy as np

Basic Workflow
--------------

Standard processing pattern::

    # 1. Load data
    image, metadata = load_image('scan.nii.gz')
    mask, _ = load_mask('mask.nii.gz')
    
    # 2. Configure extractor
    extractor = FeatureExtractor(
        normalize=True,
        vectorization_method='PersImage'
    )
    
    # 3. Extract features
    features = extractor.execute(image, mask)
    
    # 4. Use features
    # ... machine learning, analysis, etc.

Error Handling
--------------

Robust processing::

    from medtda import FeatureExtractor
    
    try:
        extractor = FeatureExtractor()
        features = extractor.execute(image_path, mask_path)
    except FileNotFoundError as e:
        print(f"File not found: {e}")
    except ValueError as e:
        print(f"Invalid data: {e}")
    except Exception as e:
        print(f"Unexpected error: {e}")

Next Steps
==========

After exploring examples:

* :doc:`../user_guide` - Comprehensive user guide
* :doc:`../api/index` - Detailed API reference
* :doc:`../theory/index` - Understand the theory
* :doc:`../faq` - Common questions

Contributing Examples
=====================

Have a useful example? Contribute!

See :doc:`../contributing` for guidelines on:

* Submitting new examples
* Improving existing examples
* Adding tutorial notebooks
* Sharing use cases

Tips for Using Examples
========================

1. **Start Simple**
   
   Begin with :doc:`basic_usage` before complex workflows

2. **Adapt to Your Data**
   
   Modify paths, parameters, and methods for your specific case

3. **Experiment**
   
   Try different preprocessing and vectorization options

4. **Check Performance**
   
   Monitor computation time for large datasets

5. **Validate Results**
   
   Always verify that features make sense for your application

See Also
========

* :doc:`../quickstart` - 5-minute tutorial
* :doc:`../user_guide` - Complete user guide
* :doc:`../cli` - CLI reference
* :doc:`../api/index` - API documentation
