@page swc_import SWC Import

# SWC Import Functionality

This document describes how to import neuronal morphology data from SWC files into the Quadrix library.

## What is SWC?

SWC (Sholl-Wig Crossover) is the standard file format for representing neuronal morphology data. It's widely used in neuroscience for storing dendritic and axonal structures.

### SWC File Format

Each line in an SWC file represents a single point (node) in the neuron's structure:

```
# Comments start with #
n type x y z radius parent
1 1 0.0 0.0 0.0 2.0 -1
2 3 1.0 0.0 0.0 0.8 1
3 3 2.0 0.0 0.0 0.7 2
...
```

**Fields:**
- `n`: Sample number (1-indexed, unique identifier for each point)
- `type`: Structure type (1=soma, 2=axon, 3=dendrite, 4=apical dendrite, etc.)
- `x, y, z`: 3D coordinates of the point
- `radius`: Radius at that point (currently not used in Quadrix)
- `parent`: Sample number of the parent point (-1 for root/soma)

## Usage

### Rust

```rust
use quadrix::swc::load_swc_file;

fn main() {
    // Load an SWC file
    match load_swc_file("data/test_neuron.swc") {
        Ok(dendrite) => {
            println!("Loaded {} vertices", dendrite.vertices.len());
            println!("Loaded {} edges", dendrite.edges.len());

            // Access vertices and edges
            for vertex in &dendrite.vertices {
                if vertex.is_root() {
                    println!("Root at: ({}, {}, {})",
                             vertex.x(), vertex.y(), vertex.z());
                }
            }
        }
        Err(e) => eprintln!("Error: {}", e),
    }
}
```

### Command Line Tool

A command-line utility is provided to inspect SWC files:

```bash
# Build the tool
cargo build --release --bin swc_info

# Run it
./target/release/swc_info data/test_neuron.swc
```

Output:
```
Successfully loaded SWC file: data/test_neuron.swc
Number of vertices: 12
Number of edges: 11
Number of root vertices: 1
Number of leaf vertices: 3

Bounding box:
  X: [0.000, 4.000]
  Y: [0.000, 4.000]
  Z: [0.000, 0.000]

Edge statistics:
  Total length: 15.234
  Average length: 1.385
  Min length: 0.500
  Max length: 2.236
```

### Python

```python
import quadrix

# Load an SWC file
dendrite = quadrix.load_swc("data/test_neuron.swc")

# Access the dendrite structure
print(f"Loaded {len(dendrite.vertices)} vertices")
print(f"Loaded {len(dendrite.edges)} edges")

# Find root and leaf vertices
roots = [v for v in dendrite.vertices if v.is_root]
leaves = [v for v in dendrite.vertices if v.is_leaf]

print(f"Roots: {len(roots)}, Leaves: {len(leaves)}")

# Get coordinates
for vertex in dendrite.vertices:
    x, y, z = vertex.x, vertex.y, vertex.z
    print(f"Vertex at ({x:.2f}, {y:.2f}, {z:.2f})")
```

## Implementation Details

### Data Structure Conversion

When loading an SWC file, the following conversions take place:

1. **Vertices**: Each SWC point becomes a `Vertex` with:
   - UUID-based ID (for efficient lookups)
   - 3D coordinates from the SWC file
   - Parent-child relationships based on the parent field

2. **Edges**: Edges are created between each point and its parent:
   - Stores vertex IDs for both endpoints
   - Caches coordinates for efficient computation
   - Can compute edge length and other geometric properties

3. **Dendrite**: The complete structure is returned as a `Dendrite` object:
   - Contains all vertices and edges
   - Supports computation of quadric matrices
   - Enables analysis of dendritic geometry

### Tree Structure

The SWC format naturally represents a tree structure:
- Points with `parent = -1` are roots (typically the soma)
- Each point can have multiple children (creating branch points)
- Leaf vertices have no children

This tree structure is preserved in the `Vertex` parent-child relationships.

## API Reference

### Rust API

```rust
// Module: quadrix::swc

/// Parse an SWC file into a vector of SWC points
pub fn parse_swc_file(path: &str) -> Result<Vec<SwcPoint>, Box<dyn Error>>

/// Build a Dendrite from SWC points
pub fn build_dendrite_from_swc(swc_points: Vec<SwcPoint>) -> Result<Dendrite, Box<dyn Error>>

/// Load an SWC file directly into a Dendrite (combines the above two)
pub fn load_swc_file(path: &str) -> Result<Dendrite, Box<dyn Error>>

/// Represents a single point in an SWC file
pub struct SwcPoint {
    pub sample_number: i32,
    pub structure_type: i32,
    pub x: f64,
    pub y: f64,
    pub z: f64,
    pub radius: f64,
    pub parent_sample: i32,
}
```

### Python API

```python
# Load an SWC file
dendrite = quadrix.load_swc(path: str) -> Dendrite

# Raises IOError if the file cannot be loaded or parsed
```

## Example Files

A test SWC file is included at `data/test_neuron.swc` with a simple dendritic structure featuring:
- 1 soma (root)
- 2 main branches
- 1 branch point
- 3 terminal points (leaves)

## Error Handling

The SWC loader performs validation and will return errors for:
- Missing or unreadable files
- Invalid SWC format (wrong number of fields)
- Invalid numeric values
- Missing parent references
- Empty SWC files (no data points)

## Future Enhancements

Potential improvements to the SWC import functionality:
- Support for radius information in analysis
- Validation of SWC structure type fields
- Support for multiple soma points
- Morphology validation (e.g., checking for cycles)
- Performance optimization for very large neuron reconstructions
