---
name: vortex-detect
description: Detect and analyze vortex patterns in the Sphere-Vortex Framework. Use when identifying emergent vortex structures, computing vorticity, analyzing angular momentum, or working with spherical harmonic decomposition. Covers M5-M8 (wave.rs, momentum.rs, harmonics.rs, detection.rs).
---

# Vortex Detection & Analysis

This skill provides expertise for detecting and analyzing vortex patterns in the Sphere-Vortex Framework (L02 - Vortex Dynamics).

## Quick Reference

### Vortex Characteristics
| Property | Symbol | Range | Description |
|----------|--------|-------|-------------|
| Vorticity | ω | 0-∞ | Rotation intensity |
| Circulation | Γ | varies | Line integral of velocity |
| Core Radius | r₀ | > 0 | Vortex core size |
| Angular Momentum | L | varies | Rotational momentum |

### Detection Thresholds
```rust
MIN_VORTICITY: 0.1      // Minimum ω for detection
MIN_CIRCULATION: 0.05   // Minimum Γ for classification
CORE_RADIUS_MAX: 0.5    // Maximum normalized core radius
```

### Vortex Types
```rust
enum VortexType {
    Point,      // Idealized point vortex
    Rankine,    // Solid body rotation core
    Lamb,       // Exponential decay profile
    Burgers,    // Viscous diffusing vortex
}
```

## When to Use This Skill

1. **Detecting emergent patterns** in oscillator phase fields
2. **Computing vorticity** from velocity/phase gradients
3. **Analyzing angular momentum** for conservation checks
4. **Harmonic decomposition** of vortex structures
5. **Classifying vortex types** by profile characteristics

## Tier 1: Quick Operations

### Detect Vortices
```rust
let vortices = detector.detect_vortices(&phase_field);
for v in &vortices {
    println!("Vortex at ({:.2}, {:.2}), ω = {:.3}",
        v.center.0, v.center.1, v.vorticity);
}
```

### Compute Vorticity
```rust
let omega = detector.compute_vorticity(x, y, &velocity_field);
println!("Vorticity at ({}, {}): {:.3}", x, y, omega);
```

### Angular Momentum
```rust
let L = compute_angular_momentum(&positions, &velocities, &masses);
println!("Total angular momentum: {:.4}", L.magnitude());
```

## Tier 2: Detailed Reference

For detailed documentation on:
- Vortex detection algorithms
- Phase field analysis
- Spherical harmonic basis functions
- Momentum conservation laws

→ See [reference.md](./reference.md)

## Tier 3: Implementation Code

For implementing new vortex detection or analysis methods:

→ See [code/vortex_extensions.rs](./code/vortex_extensions.rs)

## Common Patterns

### Pattern 1: Phase Gradient Vorticity
```rust
fn compute_phase_vorticity(
    phases: &[Vec<f64>],
    dx: f64, dy: f64,
) -> Vec<Vec<f64>> {
    let n = phases.len();
    let m = phases[0].len();
    let mut omega = vec![vec![0.0; m]; n];

    for i in 1..(n-1) {
        for j in 1..(m-1) {
            let dphi_dx = (phases[i+1][j] - phases[i-1][j]) / (2.0 * dx);
            let dphi_dy = (phases[i][j+1] - phases[i][j-1]) / (2.0 * dy);
            // Vorticity is curl of phase gradient
            omega[i][j] = dphi_dy - dphi_dx;
        }
    }
    omega
}
```

### Pattern 2: Find Vortex Centers
```rust
fn find_vortex_centers(
    omega: &[Vec<f64>],
    threshold: f64,
) -> Vec<(usize, usize)> {
    let mut centers = Vec::new();
    let n = omega.len();
    let m = omega[0].len();

    for i in 1..(n-1) {
        for j in 1..(m-1) {
            // Local maximum detection
            let val = omega[i][j].abs();
            if val > threshold
                && val >= omega[i-1][j].abs()
                && val >= omega[i+1][j].abs()
                && val >= omega[i][j-1].abs()
                && val >= omega[i][j+1].abs()
            {
                centers.push((i, j));
            }
        }
    }
    centers
}
```

### Pattern 3: Circulation Integral
```rust
fn compute_circulation(
    velocity: &impl Fn(f64, f64) -> (f64, f64),
    center: (f64, f64),
    radius: f64,
    n_points: usize,
) -> f64 {
    let mut gamma = 0.0;
    let d_theta = 2.0 * PI / n_points as f64;

    for i in 0..n_points {
        let theta = i as f64 * d_theta;
        let x = center.0 + radius * theta.cos();
        let y = center.1 + radius * theta.sin();
        let (vx, vy) = velocity(x, y);

        // Tangent vector
        let tx = -theta.sin();
        let ty = theta.cos();

        gamma += (vx * tx + vy * ty) * radius * d_theta;
    }
    gamma
}
```

## Spherical Harmonics Reference

### Basis Functions Yₗᵐ(θ, φ)
```
Y₀⁰ = 1/(2√π)
Y₁⁰ = √(3/4π) cos(θ)
Y₁±¹ = ∓√(3/8π) sin(θ) e^(±iφ)
Y₂⁰ = √(5/16π) (3cos²θ - 1)
```

### Decomposition
```rust
fn harmonic_decompose(
    field: &SphericalField,
    l_max: usize,
) -> Vec<HarmonicCoefficient> {
    let mut coeffs = Vec::new();
    for l in 0..=l_max {
        for m in -(l as i32)..=(l as i32) {
            let c = field.project_onto(l, m);
            coeffs.push(HarmonicCoefficient { l, m, coeff: c });
        }
    }
    coeffs
}
```

## Integration Points

| Module | Connection |
|--------|------------|
| M4 (kuramoto.rs) | Phase field source |
| M5 (wave.rs) | Wave-vortex coupling |
| M6 (momentum.rs) | Angular momentum |
| M7 (harmonics.rs) | Spherical decomposition |

## Cognitive Tools Using This Module

- `detect_vortex` (P2)
- `compute_interior_field` (P2)
- `compute_angular_momentum` (P3)
- `analyze_harmonics` (P3)

## Database Schema

From `migrations/001_initial_schema.sql`:
```sql
CREATE TABLE detected_vortices (
    id INTEGER PRIMARY KEY,
    center_x REAL, center_y REAL,
    vorticity REAL,
    circulation REAL,
    core_radius REAL,
    vortex_type TEXT,
    detected_at TEXT
);
```

From `migrations/006_module_tensors.sql`:
```sql
CREATE TABLE harmonic_coefficients (
    entity_id TEXT,
    l INTEGER CHECK (l >= 0),
    m INTEGER CHECK (m >= -l AND m <= l),
    coefficient_real REAL,
    coefficient_imag REAL,
    magnitude REAL
);
```
