Metadata-Version: 2.4
Name: bird-dtw
Version: 0.2.0
Summary: Dynamic Time Warping for bird migration trajectories, tuned per species
Home-page: https://github.com/yvnnhong/bird-dtw
Author: Yvonne Hong
Author-email: Yvonne Hong <yvonneh.nyc@gmail.com>
License: MIT License
        
        Copyright (c) 2026 Yvonne Hong
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/yvnnhong/bird-dtw
Project-URL: Issues, https://github.com/yvnnhong/bird-dtw/issues
Keywords: dtw,ornithology,migration,trajectory-analysis,arctic-tern
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Requires-Dist: pandas>=2.0
Requires-Dist: requests>=2.28
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Requires-Dist: black; extra == "dev"
Requires-Dist: ruff; extra == "dev"
Dynamic: author
Dynamic: home-page
Dynamic: license-file
Dynamic: requires-python

# bird-dtw

Compare bird migration routes using Dynamic Time Warping.

## What is this?

`bird-dtw` measures similarity between bird migration paths using Dynamic Time Warping (DTW). DTW aligns sequences of different lengths, so a bird that flew slightly faster or slower than another can still show high similarity if the overall route is the same.

**Current species:** Arctic tern (via OBIS-SEAMAP dataset).

**Use cases:**
- Compare two birds' migration routes to find similarities
- Find anomalous birds by comparing all pairs
- Use DTW directly on your own bird GPS data

**Two workflows:**

1. **You have raw GPS data** → Use segmentation to split it into migration legs (northbound, southbound, wintering), then compare with DTW.
2. **You already know which points belong to which leg** → Skip segmentation, pass sorted (lat, lon) points directly to DTW.

**Current species:** Arctic tern (via OBIS-SEAMAP dataset).

## Installation

```bash
pip install bird-dtw
```

(Requires Python 3.10+)

## Quick Start

### Workflow 1: Compare Arctic terns using built-in data

```python
import bird_dtw

# Compare two Arctic terns' northbound routes
distance = bird_dtw.compare_birds("ARTE_371", "ARTE_373", leg="northbound")
print(f"Route similarity: {distance:.2f} km")
```

Lower distance = more similar routes.

### Workflow 2: Find anomalous birds

```python
import bird_dtw

# Get all pairwise comparisons
results = bird_dtw.compare_all_pairs(leg="northbound")

# Sort by distance to spot unusual routes
for bird_a, bird_b, distance in sorted(results, key=lambda x: x[2]):
    print(f"{bird_a} vs {bird_b}: {distance:.2f} km")
```

### Workflow 3: DTW on your own bird data

If you already know which GPS points belong to which migration leg, compare them directly:

```python
import bird_dtw

# Your sorted (lat, lon) points for two birds
bird_1_northbound = [(10.5, 20.3), (11.2, 21.1), (12.0, 22.0)]
bird_2_northbound = [(10.6, 20.4), (11.1, 21.2), (12.1, 22.1)]

# Compare directly
dtw = bird_dtw.DTW(bird_1_northbound, bird_2_northbound, window=4)
distance, matrix = dtw.dynamic_time_warping()

print(f"DTW Distance: {distance:.2f} km")

# Get the optimal alignment path
path = dtw.backtrack()
```

## API Reference

### `compare_birds(bird_a_id, bird_b_id, species="arctic_tern", leg="northbound")`

Compare two Arctic terns' migration routes. Automatically fetches, segments, and compares data.

**Parameters:**
- `bird_a_id` (str): First bird ID (e.g., "ARTE_371")
- `bird_b_id` (str): Second bird ID (e.g., "ARTE_373")
- `species` (str): Species name (default: "arctic_tern")
- `leg` (str): Migration phase — "northbound", "southbound", or "wintering" (default: "northbound")

**Returns:** DTW distance in kilometers (float).

### `compare_all_pairs(species="arctic_tern", leg="northbound")`

Compare all birds in the dataset against each other.

**Returns:** List of tuples `(bird_a_id, bird_b_id, distance)`.

### `DTW(track_a, track_b, window)`

Low-level Dynamic Time Warping for custom bird GPS sequences.

**Parameters:**
- `track_a` (list of tuples): First bird's (lat, lon) points, in chronological order
- `track_b` (list of tuples): Second bird's (lat, lon) points, in chronological order
- `window` (int): Sakoe-Chiba band window size (controls alignment flexibility)

**Methods:**
- `dynamic_time_warping()` → (distance, matrix)
- `backtrack()` → list of (row, col) indices representing the optimal alignment path

## How It Works

DTW aligns two bird migration paths by finding the lowest-cost "warping path" — a way to match points from one track to points in another. The cost is the sum of great-circle distances (haversine) between matched points.

Birds with different flight speeds but similar routes will show high similarity because DTW allows temporal flexibility.

### Segmentation (for Arctic terns)

If your data isn't pre-segmented, the built-in `segment_track()` function splits a full year of GPS fixes into migration legs using Net Squared Displacement (NSD) — the squared straight-line distance from the bird's starting point. This follows the method from Egevang et al. (2010).

See [Segmentation Details](./docs/essential_concepts.md) for how NSD-based segmentation works.

## Data Source

Arctic tern data comes from the OBIS-SEAMAP dataset (Egevang et al. 2010, PNAS). Data is fetched at runtime and is not redistributed in this repository. Non-commercial use only (CC-BY-NC 4.0).

## Testing

```bash
pytest tests/
```

## Contributing

Contributions welcome! Current priorities:
- Additional bird species implementations
- Custom distance metrics
- Visualization tools

## License

MIT

## Citation

If you use this library in research, please cite:

Egevang, C., Stenhouse, I. J., Phillips, R. A., Petersen, A., Fox, J. W., & Silk, J. R. (2010). Tracking of Arctic terns. *Proceedings of the National Academy of Sciences*, 107(43), 18640-18645.
