Metadata-Version: 2.5
Name: phasecurvefit
Version: 0.4.0
Summary: Walk through phase-space observations
Project-URL: Bug Tracker, https://github.com/GalacticDynamics/phasecurvefit/issues
Project-URL: Changelog, https://github.com/GalacticDynamics/phasecurvefit/releases
Project-URL: Homepage, https://github.com/GalacticDynamics/phasecurvefit
Author-email: GalacticDynamics <nstarman@users.noreply.github.com>, Nathaniel Starkman <nstarman@users.noreply.github.com>
License: MIT License
        
        Copyright (c) 2025, Nathaniel Starkman.
        All rights reserved.
        
        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.
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: equinox>=0.13.5
Requires-Dist: jax>=0.7.2
Requires-Dist: jaxknn>=0.1.1
Requires-Dist: jaxmore[tqdm]>=0.6.1
Requires-Dist: jaxtyping>=0.3.5
Requires-Dist: optax>=0.2.4
Requires-Dist: optional-dependencies>=0.4.0
Requires-Dist: plum-dispatch>=2.6.1
Requires-Dist: quax>=0.4.6
Requires-Dist: scipy>=1.11
Requires-Dist: wadler-lindig-parts>=0.3.0
Requires-Dist: zeroth>=1.0.1
Provides-Extra: all
Requires-Dist: jaxkd>=0.0.5; extra == 'all'
Requires-Dist: unxt>=2.0; extra == 'all'
Provides-Extra: interop
Requires-Dist: unxt>=2.0; extra == 'interop'
Provides-Extra: kdtree
Requires-Dist: jaxkd>=0.0.5; extra == 'kdtree'
Provides-Extra: tutorials
Requires-Dist: galax>=0.1.0; extra == 'tutorials'
Requires-Dist: jaxkd>=0.0.5; extra == 'tutorials'
Requires-Dist: matplotlib>=3.10.8; extra == 'tutorials'
Requires-Dist: unxt>=2.0; extra == 'tutorials'
Requires-Dist: unxt[interop-mpl]; extra == 'tutorials'
Description-Content-Type: text/markdown

# phasecurvefit: Construct Paths through Phase-Space Points

[![PyPI version](https://img.shields.io/pypi/v/phasecurvefit.svg)](https://pypi.org/project/phasecurvefit/)
[![Python versions](https://img.shields.io/pypi/pyversions/phasecurvefit.svg)](https://pypi.org/project/phasecurvefit/)
[![CI](https://github.com/GalacticDynamics/phasecurvefit/actions/workflows/ci.yml/badge.svg)](https://github.com/GalacticDynamics/phasecurvefit/actions/workflows/ci.yml)
[![codecov](https://codecov.io/gh/GalacticDynamics/phasecurvefit/branch/main/graph/badge.svg)](https://codecov.io/gh/GalacticDynamics/phasecurvefit)
[![Docs](https://github.com/GalacticDynamics/phasecurvefit/actions/workflows/docs.yml/badge.svg)](https://galacticdynamics.github.io/phasecurvefit/)
[![CITATION.cff](https://github.com/GalacticDynamics/phasecurvefit/actions/workflows/cff-validator.yml/badge.svg)](https://github.com/GalacticDynamics/phasecurvefit/actions/workflows/cff-validator.yml)
[![pyOpenSci Peer-Reviewed](https://pyopensci.org/badges/peer-reviewed.svg)](https://github.com/pyOpenSci/software-submission/issues/285)

Construct paths through phase-Space points, supporting many different
algorithms.

## Why phasecurvefit?

Many datasets are samples along a curve in phase space whose order along the
curve is unknown. Before fitting a model to such a curve you need two things: an
ordering coordinate for every sample, and a smooth track through them. Doing
this by hand, or with a position-only nearest-neighbor or clustering method,
breaks down in exactly the cases that matter:

- **Curves that cross or fold back on themselves.** Where two strands meet, the
  nearest point is often on the wrong strand. phasecurvefit uses velocities as
  well as positions, so the ordering stays on the right strand (see the
  [epitrochoid tutorials](https://galacticdynamics.github.io/phasecurvefit/latest/tutorials/epitrochoid_autoencoder.html)).
- **No known starting point.** The default MST | SOM pipeline finds the two ends
  of the curve itself, so no progenitor position or hand-picked start index is
  needed
  ([MST tutorial](https://galacticdynamics.github.io/phasecurvefit/latest/tutorials/stream_mst.html)).
- **Incomplete orderings.** An orderer may order only a reliable subset (the
  local-flow walk does); an autoencoder then assigns an ordering coordinate γ to
  every sample and learns a smooth mean track through them
  ([stream autoencoder tutorial](https://galacticdynamics.github.io/phasecurvefit/latest/tutorials/stream_autoencoder.html)).
- **Contamination.** A stream-plus-background mixture model gives each sample a
  calibrated membership probability, so interlopers can be down-weighted or
  removed
  ([outlier-rejection tutorial](https://galacticdynamics.github.io/phasecurvefit/latest/tutorials/outlier_rejection.html)).
- **Use inside larger models.** phasecurvefit is built on JAX: the walk, the
  distance metrics and the neural networks work with `jit`, `vmap` and `grad`
  and run on CPU or GPU. A training-free running-mean track is available when
  speed matters more than accuracy, for example inside a likelihood evaluated at
  every step of an MCMC
  ([running-mean tutorial](https://galacticdynamics.github.io/phasecurvefit/latest/tutorials/stream_runningmean.html)).

phasecurvefit is a reusable, tested library for ordering samples along a curve
in phase space, by default with an MST backbone refined by a Self-Organizing
Map, with alternative orderers (including momentum-weighted ordering), gap
filling, outlier rejection and optional physical units (via `unxt`). It was
built for stellar streams but applies to any ordered phase-space data.

## Features

- **JAX-powered**: Fully compatible with JAX transformations (`jit`, `vmap`,
  `grad`)
- **GPU-ready**: Runs on CPU, GPU, or TPU via JAX
- **Type-safe**: Comprehensive (optionally runtime checked) type hints with
  `jaxtyping`
- **Pluggable metrics**: Customizable distance metrics for different physical
  interpretations
- **Pluggable query strategies**: Choose which neighbors each step may move to
  (e.g., all points, or only the k spatially nearest via a KD-tree)
- **Pluggable orderers**: One interface over multiple ordering algorithms — by
  default an MST backbone refined by a SOM, with the velocity-following walk as
  an alternative
- **Highly customizable ML setup and training**: Well-chosen defaults with
  highly flexible customization for specific use-cases.
- **Physical units**: Optional support via `unxt` for unit-aware calculations

## Installation

Install the core package:

```bash
pip install phasecurvefit[all]
```

Or with uv:

```bash
uv add phasecurvefit[all]
```

<details>
  <summary>from source, using uv</summary>

```bash
uv add git+https://github.com/GalacticDynamics/phasecurvefit.git@main
```

You can customize the branch by replacing `main` with any other branch name.

</details>
<details>
  <summary>building from source</summary>

```bash
cd /path/to/parent
git clone https://github.com/GalacticDynamics/phasecurvefit.git
cd phasecurvefit
uv pip install -e .  # editable mode
```

</details>

### Optional Dependencies

phasecurvefit has optional dependencies for extended functionality:

- **unxt**: Physical units support for phase-space calculations
- **kdtree (jaxkd)**: KD-tree strategy that restricts each step to the k
  spatially nearest points

Install with optional dependencies:

```bash
# pip install phasecurvefit[all]  # Install with all extras
pip install phasecurvefit[interop]  # Install with unxt for unit support
pip install phasecurvefit[kdtree]  # Install with jaxkd for KD-tree strategy
```

Or with uv:

```bash
# uv add phasecurvefit --extra all  # installs all extras
uv add phasecurvefit --extra interop
uv add phasecurvefit --extra kdtree
```

### Running the Tutorials

The
[tutorial notebooks](https://galacticdynamics.github.io/phasecurvefit/latest/tutorials/index.html)
need packages beyond the runtime `[all]` extra — `matplotlib` for plotting and
`galax` for the mock-stream examples. Install them with the `tutorials` extra:

```bash
pip install phasecurvefit[tutorials]
```

```bash
uv add phasecurvefit --extra tutorials
```

Note `[all]` intentionally does not include `tutorials`: `all` covers optional
_runtime_ functionality, while `tutorials` covers packages only needed to run
the example notebooks.

### GPU Support (NVIDIA CUDA)

phasecurvefit runs on GPU through JAX, but a plain `pip install jax` (what
phasecurvefit depends on) only ships a CPU-only `jaxlib`. If you have an NVIDIA
GPU and see:

```text
An NVIDIA GPU may be present on this machine, but a CUDA-enabled jaxlib is
not installed. Falling back to cpu.
```

Install JAX's CUDA-enabled build alongside phasecurvefit:

```bash
pip install --upgrade "phasecurvefit[all]" "jax[cuda12]"
```

Or with uv:

```bash
uv add phasecurvefit --extra all
uv add "jax[cuda12]"
```

This pulls in self-contained NVIDIA CUDA/cuDNN wheels — you don't need the CUDA
toolkit installed system-wide — but you do still need a
[compatible NVIDIA driver](https://docs.jax.dev/en/latest/installation.html#nvidia-gpu)
for your GPU. `--upgrade` ensures pip actually swaps in the CUDA-enabled
`jaxlib` even if a CPU-only one is already installed. See the
[JAX GPU installation guide](https://docs.jax.dev/en/latest/installation.html#nvidia-gpu)
for other CUDA versions or platforms (TPU, ROCm), and verify the install with:

```python
import jax

print(jax.devices())  # should list a CudaDevice, not just CpuDevice
```

## Quick Start

```python
import jax
import jax.numpy as jnp
import phasecurvefit as pcf

# Create phase-space observations as dictionaries (Cartesian coordinates)
pos = {
    "x": jnp.array([0.0, 1.0, 2.0, 3.0, 4.0]),
    "y": jnp.array([0.0, 0.5, 1.0, 1.5, 2.0]),
}
vel = {
    "x": jnp.array([1.0, 1.0, 1.0, 1.0, 1.0]),
    "y": jnp.array([0.5, 0.5, 0.5, 0.5, 0.5]),
}

# Step 1: Order the observations: an MST backbone refined by a SOM. (With fewer
# than 15 points, as here, the SOM is skipped and the MST is used alone.)
result = pcf.order(pos, vel)
print(result.indices)  # Initial ordering

# Step 2: Create normalizer and autoencoder
key = jax.random.key(0)
normalizer = pcf.nn.StandardScalerNormalizer(pos, vel)
autoencoder = pcf.nn.PathAutoencoder.make(
    normalizer, gamma_range=result.gamma_range, key=key
)

# Step 3: Configure and run training
train_config = pcf.nn.TrainingConfig(
    n_epochs_encoder=100,  # Encoder-only epochs
    n_epochs_both=50,  # Joint training epochs
    show_pbar=False,  # Disable progress bar
)

# Train the autoencoder
result, _, losses = pcf.nn.train_autoencoder(
    autoencoder, result, config=train_config, key=key
)

print(result.indices)  # Post-training ordering
```

### With Physical Units

When `unxt` is installed, you can use physical units throughout the workflow:

```python
import jax
import jax.numpy as jnp
import phasecurvefit as pcf
import unxt as u

# Create phase-space observations with units
pos = {
    "x": u.Q([0.0, 1.0, 2.0, 3.0, 4.0], "kpc"),
    "y": u.Q([0.0, 0.5, 1.0, 1.5, 2.0], "kpc"),
}
vel = {
    "x": u.Q([1.0, 1.0, 1.0, 1.0, 1.0], "km/s"),
    "y": u.Q([0.5, 0.5, 0.5, 0.5, 0.5], "km/s"),
}

# Step 1: Order with units (units are preserved throughout)
metric_scale = u.Q(1.0, "kpc")
config = pcf.WalkConfig(strategy=pcf.strats.KDTree(k=3))
result = pcf.order(
    pos,
    vel,
    pcf.orderers.LocalFlowOrderer(config=config, metric_scale=metric_scale),
    metadata=pcf.StateMetadata(usys=u.unitsystems.galactic),
)

# Step 2: Create normalizer and autoencoder (handles units automatically)
key = jax.random.key(0)
normalizer = pcf.nn.StandardScalerNormalizer(pos, vel)
autoencoder = pcf.nn.PathAutoencoder.make(
    normalizer, gamma_range=result.gamma_range, key=key
)
result, _, losses = pcf.nn.train_autoencoder(
    autoencoder, result, config=train_config, key=key
)
```

## Orderers

The ordering step is pluggable. Every orderer implements the same interface —
`order(positions, velocities)` — and returns an `OrderingResult` that feeds the
autoencoder unchanged, so orderers are interchangeable. With no orderer,
`pcf.order(pos, vel)` runs the **default pipeline**, an MST backbone refined by
a SOM (`MSTOrderer() | SOMOrderer()`). The built-in orderers it is made from,
and the alternative to them, are:

- **`MSTOrderer`** — a minimum-spanning-tree backbone. It needs no start point
  (the graph diameter finds the two tips itself), which makes it ideal for
  **near-closed loops** where the velocity field reverses and a single walk
  covers only one arm.
- **`SOMOrderer`** — a Self-Organizing Map refinement. Its prototypes average
  over many tracers, so the backbone it produces is far less sensitive to local
  noise than a single walk's or MST's individual decisions.
- **`LocalFlowOrderer`** — the velocity-following walk. Follows a coherent flow
  from a start point, and is fully JAX-traceable.

```python
import jax.numpy as jnp
import phasecurvefit as pcf

# Points along a curve
t = jnp.linspace(0.0, 1.0, 60)
pos = {"x": 10.0 * t, "y": jnp.sin(3.0 * t)}
vel = {"x": jnp.ones(60), "y": 3.0 * jnp.cos(3.0 * t)}

# The default: MST backbone refined by a SOM (no start point needed)
result = pcf.order(pos, vel)

# The velocity-following walk, via the orderer interface
walk_orderer = pcf.orderers.LocalFlowOrderer(metric_scale=1.0, start_idx=0)
walk_result = walk_orderer.order(pos, vel)

# A custom chain: tune the MST, then refine with a SOM
chain = pcf.orderers.MSTOrderer(k=8, jump_cap=2.0) | pcf.orderers.SOMOrderer()
chain_result = pcf.order(pos, vel, chain)

# Either result feeds the autoencoder unchanged
print(result.gamma_range)  # (-1.0, 1.0)
```

`MSTOrderer` also has opt-in velocity mechanisms (`velocity_weight`,
`sever_cos_threshold`, `orient_by_velocity`) for self-overlapping streams. See
the
[orderer guide](https://galacticdynamics.github.io/phasecurvefit/latest/how-to/choose-orderer.html)
and the
[v0.3 → v0.4 Migration Guide](https://galacticdynamics.github.io/phasecurvefit/latest/reference/migration/v0.3-to-v0.4.html),
which covers the change of default from the walk to MST | SOM.

## Distance Metrics

The algorithm supports pluggable distance metrics to control how points are
ordered. The default metric is `AlignedMomentumDistanceMetric`, which combines
spatial proximity with velocity alignment:

```python
import jax.numpy as jnp
import phasecurvefit as pcf

# Define simple Cartesian arrays (not quantities)
pos = {"x": jnp.array([0.0, 1.0, 2.0]), "y": jnp.array([0.0, 0.5, 1.0])}
vel = {"x": jnp.array([1.0, 1.0, 1.0]), "y": jnp.array([0.5, 0.5, 0.5])}

# Use default metric (AlignedMomentumDistanceMetric)
config = pcf.WalkConfig()
result = pcf.order(pos, vel, pcf.orderers.LocalFlowOrderer(config=config))
```

### Using Different Metrics

`phasecurvefit` provides three built-in metrics:

1. **AlignedMomentumDistanceMetric** (default): Combines spatial distance with
   velocity alignment (momentum-weighted nearest neighbor)
2. **FullPhaseSpaceDistanceMetric**: True 6D Euclidean distance in phase space
3. **SpatialDistanceMetric**: Pure spatial distance, ignoring velocity

```python
import jax.numpy as jnp
import phasecurvefit as pcf

# Define simple Cartesian arrays (not quantities)
pos = {"x": jnp.array([0.0, 1.0, 2.0]), "y": jnp.array([0.0, 0.5, 1.0])}
vel = {"x": jnp.array([1.0, 1.0, 1.0]), "y": jnp.array([0.5, 0.5, 0.5])}

# Pure spatial ordering (ignores velocity)
config_spatial = pcf.WalkConfig(metric=pcf.metrics.SpatialDistanceMetric())
result = pcf.order(
    pos, vel, pcf.orderers.LocalFlowOrderer(config=config_spatial, metric_scale=0.0)
)

# Full 6D phase-space distance
config_phase = pcf.WalkConfig(metric=pcf.metrics.FullPhaseSpaceDistanceMetric())
result = pcf.order(pos, vel, pcf.orderers.LocalFlowOrderer(config=config_phase))
```

### Custom Metrics

You can define custom metrics by subclassing `AbstractDistanceMetric`:

```python
import jax
import jax.numpy as jnp
import phasecurvefit as pcf


class WeightedPhaseSpaceMetric(pcf.metrics.AbstractDistanceMetric):
    """Custom weighted phase-space metric."""

    def __call__(self, current_pos, current_vel, positions, velocities, metric_scale):
        # Compute position distance
        pos_diff = jax.tree.map(jnp.subtract, positions, current_pos)
        pos_dist_sq = sum(jax.tree.leaves(jax.tree.map(jnp.square, pos_diff)))

        # Compute velocity distance
        vel_diff = jax.tree.map(jnp.subtract, velocities, current_vel)
        vel_dist_sq = sum(jax.tree.leaves(jax.tree.map(jnp.square, vel_diff)))

        # Custom weighting scheme
        return jnp.sqrt(pos_dist_sq + (metric_scale**2) * vel_dist_sq)


# Use custom metric via WalkConfig
config = pcf.WalkConfig(metric=WeightedPhaseSpaceMetric())
result = pcf.order(pos, vel, pcf.orderers.LocalFlowOrderer(config=config))
```

See the
[metric guide](https://galacticdynamics.github.io/phasecurvefit/latest/how-to/tune-metric.html)
for more details and examples.

## Query Strategies

The algorithm supports pluggable query strategies to control how neighbors are
found. A strategy determines which points are considered as potential next steps
in the walk.

`phasecurvefit` provides two built-in strategies:

1. **BruteForce** (default): Compute distances to all remaining points and
   select the nearest one.
2. **KDTree**: Restrict each step's candidates to the `k` spatially nearest
   points, then select by the metric (requires optional `jaxkd` dependency).
   Each step costs O(k) instead of O(n), after a one-off batched KD-tree query
   that builds every point's neighbor list. On CPU that setup dominates for
   small datasets, so it beats `BruteForce` only from a few thousand points up
   (with `k=50`).

### Using Built-in Strategies

```python
import jax.numpy as jnp
import phasecurvefit as pcf

# Define simple Cartesian arrays
pos = {"x": jnp.array([0.0, 1.0, 2.0]), "y": jnp.array([0.0, 0.5, 1.0])}
vel = {"x": jnp.array([1.0, 1.0, 1.0]), "y": jnp.array([0.5, 0.5, 0.5])}

# Default strategy (brute-force — no configuration needed)
config_brute = pcf.WalkConfig(strategy=pcf.strats.BruteForce())
result = pcf.order(pos, vel, pcf.orderers.LocalFlowOrderer(config=config_brute))

# KD-tree strategy: only the k spatially nearest points are candidates
config_kdtree = pcf.WalkConfig(strategy=pcf.strats.KDTree(k=2))
result = pcf.order(pos, vel, pcf.orderers.LocalFlowOrderer(config=config_kdtree))
```

### Custom Query Strategies

You can define custom strategies by subclassing `AbstractQueryStrategy`:

```python
import jax.numpy as jnp
import phasecurvefit as pcf


class SmallestIndexStrategy(pcf.strats.AbstractQueryStrategy):
    """Custom strategy: select the smallest unvisited index.

    This is a toy example showing how to implement a custom strategy.
    By returning uniform distances, argmin selects the smallest index
    deterministically. In practice, distance-based strategies like BruteForce
    are more useful.
    """

    def init(self, positions, /, *, metadata):
        """No persistent state needed."""
        return None

    def query(
        self,
        state,
        /,
        current_pos,
        current_vel,
        positions,
        velocities,
        metric_fn,
        metric_scale,
    ):
        """Return uniform distances to all points.

        Since all distances are equal, the walk algorithm's argmin will
        deterministically select the smallest unvisited index.
        """
        # Get number of points
        n_points = len(next(iter(positions.values())))

        # Return uniform distances to all points
        # argmin will pick the smallest unvisited index
        distances = jnp.ones(n_points)

        return pcf.strats.QueryResult(distances=distances, indices=None)


# Use custom strategy via WalkConfig
config = pcf.WalkConfig(strategy=SmallestIndexStrategy())
result = pcf.order(pos, vel, pcf.orderers.LocalFlowOrderer(config=config))
```

## Citation

If you use `phasecurvefit` in published work, please cite the package via its
DOI, together with the paper behind whichever component you used.

[![DOI](https://zenodo.org/badge/1134484136.svg)](https://doi.org/10.5281/zenodo.18714340)

<details>
  <summary>component papers</summary>

- **default pipeline / SOM ordering** (`pcf.order(pos, vel)`, `SOMOrderer`,
  `phasecurvefit.som`) — Starkman et al. (2023), MNRAS 522, 5022,
  [arXiv:2212.00949](https://arxiv.org/abs/2212.00949)
- **momentum-weighted ordering** (`LocalFlowOrderer`) **or the autoencoder**
  (`PathAutoencoder`, `fit_track`) — Nibauer et al. (2022),
  [arXiv:2205.11767](https://arxiv.org/abs/2205.11767)
- **mixture-model membership / outlier rejection** — Hogg, Bovy & Lang (2010),
  [arXiv:1008.4686](https://arxiv.org/abs/1008.4686)

Machine-readable metadata for all of these is in
[`CITATION.cff`](https://github.com/GalacticDynamics/phasecurvefit/blob/main/CITATION.cff);
what to cite for which component, with BibTeX entries, is on the
[Citation page](https://galacticdynamics.github.io/phasecurvefit/latest/reference/citation.html).

</details>

## AI Usage Disclosure

Portions of this codebase (including tests and documentation) were refactored
and generated with the assistance of Language Models. Select algorithms are
implemented by AI against well-tested oracles. All AI contributions have been
and will continue to be reviewed and verified by the human maintainers.
